Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/driver/cc1as_main.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- cc1as_main.cpp - Clang Assembler  ---------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This is the entry point to the clang -cc1as functionality, which implements
10
// the direct interface to the LLVM MC based assembler.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/DiagnosticOptions.h"
16
#include "clang/Driver/DriverDiagnostic.h"
17
#include "clang/Driver/Options.h"
18
#include "clang/Frontend/FrontendDiagnostic.h"
19
#include "clang/Frontend/TextDiagnosticPrinter.h"
20
#include "clang/Frontend/Utils.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/ADT/Triple.h"
24
#include "llvm/IR/DataLayout.h"
25
#include "llvm/MC/MCAsmBackend.h"
26
#include "llvm/MC/MCAsmInfo.h"
27
#include "llvm/MC/MCCodeEmitter.h"
28
#include "llvm/MC/MCContext.h"
29
#include "llvm/MC/MCInstrInfo.h"
30
#include "llvm/MC/MCObjectFileInfo.h"
31
#include "llvm/MC/MCObjectWriter.h"
32
#include "llvm/MC/MCParser/MCAsmParser.h"
33
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
34
#include "llvm/MC/MCRegisterInfo.h"
35
#include "llvm/MC/MCSectionMachO.h"
36
#include "llvm/MC/MCStreamer.h"
37
#include "llvm/MC/MCSubtargetInfo.h"
38
#include "llvm/MC/MCTargetOptions.h"
39
#include "llvm/Option/Arg.h"
40
#include "llvm/Option/ArgList.h"
41
#include "llvm/Option/OptTable.h"
42
#include "llvm/Support/CommandLine.h"
43
#include "llvm/Support/ErrorHandling.h"
44
#include "llvm/Support/FileSystem.h"
45
#include "llvm/Support/FormattedStream.h"
46
#include "llvm/Support/Host.h"
47
#include "llvm/Support/MemoryBuffer.h"
48
#include "llvm/Support/Path.h"
49
#include "llvm/Support/Process.h"
50
#include "llvm/Support/Signals.h"
51
#include "llvm/Support/SourceMgr.h"
52
#include "llvm/Support/TargetRegistry.h"
53
#include "llvm/Support/TargetSelect.h"
54
#include "llvm/Support/Timer.h"
55
#include "llvm/Support/raw_ostream.h"
56
#include <memory>
57
#include <system_error>
58
using namespace clang;
59
using namespace clang::driver;
60
using namespace clang::driver::options;
61
using namespace llvm;
62
using namespace llvm::opt;
63
64
namespace {
65
66
/// Helper class for representing a single invocation of the assembler.
67
struct AssemblerInvocation {
68
  /// @name Target Options
69
  /// @{
70
71
  /// The name of the target triple to assemble for.
72
  std::string Triple;
73
74
  /// If given, the name of the target CPU to determine which instructions
75
  /// are legal.
76
  std::string CPU;
77
78
  /// The list of target specific features to enable or disable -- this should
79
  /// be a list of strings starting with '+' or '-'.
80
  std::vector<std::string> Features;
81
82
  /// The list of symbol definitions.
83
  std::vector<std::string> SymbolDefs;
84
85
  /// @}
86
  /// @name Language Options
87
  /// @{
88
89
  std::vector<std::string> IncludePaths;
90
  unsigned NoInitialTextSection : 1;
91
  unsigned SaveTemporaryLabels : 1;
92
  unsigned GenDwarfForAssembly : 1;
93
  unsigned RelaxELFRelocations : 1;
94
  unsigned DwarfVersion;
95
  std::string DwarfDebugFlags;
96
  std::string DwarfDebugProducer;
97
  std::string DebugCompilationDir;
98
  std::map<const std::string, const std::string> DebugPrefixMap;
99
  llvm::DebugCompressionType CompressDebugSections =
100
      llvm::DebugCompressionType::None;
101
  std::string MainFileName;
102
  std::string SplitDwarfOutput;
103
104
  /// @}
105
  /// @name Frontend Options
106
  /// @{
107
108
  std::string InputFile;
109
  std::vector<std::string> LLVMArgs;
110
  std::string OutputPath;
111
  enum FileType {
112
    FT_Asm,  ///< Assembly (.s) output, transliterate mode.
113
    FT_Null, ///< No output, for timing purposes.
114
    FT_Obj   ///< Object file output.
115
  };
116
  FileType OutputType;
117
  unsigned ShowHelp : 1;
118
  unsigned ShowVersion : 1;
119
120
  /// @}
121
  /// @name Transliterate Options
122
  /// @{
123
124
  unsigned OutputAsmVariant;
125
  unsigned ShowEncoding : 1;
126
  unsigned ShowInst : 1;
127
128
  /// @}
129
  /// @name Assembler Options
130
  /// @{
131
132
  unsigned RelaxAll : 1;
133
  unsigned NoExecStack : 1;
134
  unsigned FatalWarnings : 1;
135
  unsigned NoWarn : 1;
136
  unsigned IncrementalLinkerCompatible : 1;
137
  unsigned EmbedBitcode : 1;
138
139
  /// The name of the relocation model to use.
140
  std::string RelocationModel;
141
142
  /// The ABI targeted by the backend. Specified using -target-abi. Empty
143
  /// otherwise.
144
  std::string TargetABI;
145
146
  /// @}
147
148
public:
149
40
  AssemblerInvocation() {
150
40
    Triple = "";
151
40
    NoInitialTextSection = 0;
152
40
    InputFile = "-";
153
40
    OutputPath = "-";
154
40
    OutputType = FT_Asm;
155
40
    OutputAsmVariant = 0;
156
40
    ShowInst = 0;
157
40
    ShowEncoding = 0;
158
40
    RelaxAll = 0;
159
40
    NoExecStack = 0;
160
40
    FatalWarnings = 0;
161
40
    NoWarn = 0;
162
40
    IncrementalLinkerCompatible = 0;
163
40
    DwarfVersion = 0;
164
40
    EmbedBitcode = 0;
165
40
  }
166
167
  static bool CreateFromArgs(AssemblerInvocation &Res,
168
                             ArrayRef<const char *> Argv,
169
                             DiagnosticsEngine &Diags);
170
};
171
172
}
173
174
bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
175
                                         ArrayRef<const char *> Argv,
176
40
                                         DiagnosticsEngine &Diags) {
177
40
  bool Success = true;
178
40
179
40
  // Parse the arguments.
180
40
  const OptTable &OptTbl = getDriverOptTable();
181
40
182
40
  const unsigned IncludedFlagsBitmask = options::CC1AsOption;
183
40
  unsigned MissingArgIndex, MissingArgCount;
184
40
  InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount,
185
40
                                       IncludedFlagsBitmask);
186
40
187
40
  // Check for missing argument error.
188
40
  if (MissingArgCount) {
189
0
    Diags.Report(diag::err_drv_missing_argument)
190
0
        << Args.getArgString(MissingArgIndex) << MissingArgCount;
191
0
    Success = false;
192
0
  }
193
40
194
40
  // Issue errors on unknown arguments.
195
40
  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
196
2
    auto ArgString = A->getAsString(Args);
197
2
    std::string Nearest;
198
2
    if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
199
0
      Diags.Report(diag::err_drv_unknown_argument) << ArgString;
200
2
    else
201
2
      Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
202
2
          << ArgString << Nearest;
203
2
    Success = false;
204
2
  }
205
40
206
40
  // Construct the invocation.
207
40
208
40
  // Target Options
209
40
  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
210
40
  Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
211
40
  Opts.Features = Args.getAllArgValues(OPT_target_feature);
212
40
213
40
  // Use the default target triple if unspecified.
214
40
  if (Opts.Triple.empty())
215
0
    Opts.Triple = llvm::sys::getDefaultTargetTriple();
216
40
217
40
  // Language Options
218
40
  Opts.IncludePaths = Args.getAllArgValues(OPT_I);
219
40
  Opts.NoInitialTextSection = Args.hasArg(OPT_n);
220
40
  Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
221
40
  // Any DebugInfoKind implies GenDwarfForAssembly.
222
40
  Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
223
40
224
40
  if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
225
2
                                     OPT_compress_debug_sections_EQ)) {
226
2
    if (A->getOption().getID() == OPT_compress_debug_sections) {
227
2
      // TODO: be more clever about the compression type auto-detection
228
2
      Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
229
2
    } else {
230
0
      Opts.CompressDebugSections =
231
0
          llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
232
0
              .Case("none", llvm::DebugCompressionType::None)
233
0
              .Case("zlib", llvm::DebugCompressionType::Z)
234
0
              .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
235
0
              .Default(llvm::DebugCompressionType::None);
236
0
    }
237
2
  }
238
40
239
40
  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
240
40
  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
241
40
  Opts.DwarfDebugFlags =
242
40
      std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
243
40
  Opts.DwarfDebugProducer =
244
40
      std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
245
40
  Opts.DebugCompilationDir =
246
40
      std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
247
40
  Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
248
40
249
40
  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
250
0
    auto Split = StringRef(Arg).split('=');
251
0
    Opts.DebugPrefixMap.insert(
252
0
        {std::string(Split.first), std::string(Split.second)});
253
0
  }
254
40
255
40
  // Frontend Options
256
40
  if (Args.hasArg(OPT_INPUT)) {
257
39
    bool First = true;
258
39
    for (const Arg *A : Args.filtered(OPT_INPUT)) {
259
39
      if (First) {
260
39
        Opts.InputFile = A->getValue();
261
39
        First = false;
262
39
      } else {
263
0
        Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
264
0
        Success = false;
265
0
      }
266
39
    }
267
39
  }
268
40
  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
269
40
  Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
270
40
  Opts.SplitDwarfOutput =
271
40
      std::string(Args.getLastArgValue(OPT_split_dwarf_output));
272
40
  if (Arg *A = Args.getLastArg(OPT_filetype)) {
273
39
    StringRef Name = A->getValue();
274
39
    unsigned OutputType = StringSwitch<unsigned>(Name)
275
39
      .Case("asm", FT_Asm)
276
39
      .Case("null", FT_Null)
277
39
      .Case("obj", FT_Obj)
278
39
      .Default(~0U);
279
39
    if (OutputType == ~0U) {
280
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
281
0
      Success = false;
282
0
    } else
283
39
      Opts.OutputType = FileType(OutputType);
284
39
  }
285
40
  Opts.ShowHelp = Args.hasArg(OPT_help);
286
40
  Opts.ShowVersion = Args.hasArg(OPT_version);
287
40
288
40
  // Transliterate Options
289
40
  Opts.OutputAsmVariant =
290
40
      getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
291
40
  Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
292
40
  Opts.ShowInst = Args.hasArg(OPT_show_inst);
293
40
294
40
  // Assemble Options
295
40
  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
296
40
  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
297
40
  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
298
40
  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
299
40
  Opts.RelocationModel =
300
40
      std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
301
40
  Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
302
40
  Opts.IncrementalLinkerCompatible =
303
40
      Args.hasArg(OPT_mincremental_linker_compatible);
304
40
  Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
305
40
306
40
  // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
307
40
  // EmbedBitcode behaves the same for all embed options for assembly files.
308
40
  if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
309
1
    Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
310
1
                            .Case("all", 1)
311
1
                            .Case("bitcode", 1)
312
1
                            .Case("marker", 1)
313
1
                            .Default(0);
314
1
  }
315
40
316
40
  return Success;
317
40
}
318
319
static std::unique_ptr<raw_fd_ostream>
320
40
getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
321
40
  // Make sure that the Out file gets unlinked from the disk if we get a
322
40
  // SIGINT.
323
40
  if (Path != "-")
324
37
    sys::RemoveFileOnSignal(Path);
325
40
326
40
  std::error_code EC;
327
40
  auto Out = std::make_unique<raw_fd_ostream>(
328
40
      Path, EC, (Binary ? 
sys::fs::OF_None35
:
sys::fs::OF_Text5
));
329
40
  if (EC) {
330
0
    Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
331
0
    return nullptr;
332
0
  }
333
40
334
40
  return Out;
335
40
}
336
337
static bool ExecuteAssembler(AssemblerInvocation &Opts,
338
39
                             DiagnosticsEngine &Diags) {
339
39
  // Get the target specific parser.
340
39
  std::string Error;
341
39
  const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
342
39
  if (!TheTarget)
343
0
    return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
344
39
345
39
  ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
346
39
      MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
347
39
348
39
  if (std::error_code EC = Buffer.getError()) {
349
0
    Error = EC.message();
350
0
    return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
351
0
  }
352
39
353
39
  SourceMgr SrcMgr;
354
39
355
39
  // Tell SrcMgr about this buffer, which is what the parser will pick up.
356
39
  unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
357
39
358
39
  // Record the location of the include directories so that the lexer can find
359
39
  // it later.
360
39
  SrcMgr.setIncludeDirs(Opts.IncludePaths);
361
39
362
39
  std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
363
39
  assert(MRI && "Unable to create target register info!");
364
39
365
39
  MCTargetOptions MCOptions;
366
39
  std::unique_ptr<MCAsmInfo> MAI(
367
39
      TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
368
39
  assert(MAI && "Unable to create target asm info!");
369
39
370
39
  // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
371
39
  // may be created with a combination of default and explicit settings.
372
39
  MAI->setCompressDebugSections(Opts.CompressDebugSections);
373
39
374
39
  MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
375
39
376
39
  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
377
39
  if (Opts.OutputPath.empty())
378
3
    Opts.OutputPath = "-";
379
39
  std::unique_ptr<raw_fd_ostream> FDOS =
380
39
      getOutputStream(Opts.OutputPath, Diags, IsBinary);
381
39
  if (!FDOS)
382
0
    return true;
383
39
  std::unique_ptr<raw_fd_ostream> DwoOS;
384
39
  if (!Opts.SplitDwarfOutput.empty())
385
1
    DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
386
39
387
39
  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
388
39
  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
389
39
  std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
390
39
391
39
  MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions);
392
39
393
39
  bool PIC = false;
394
39
  if (Opts.RelocationModel == "static") {
395
23
    PIC = false;
396
23
  } else 
if (16
Opts.RelocationModel == "pic"16
) {
397
16
    PIC = true;
398
16
  } else {
399
0
    assert(Opts.RelocationModel == "dynamic-no-pic" &&
400
0
           "Invalid PIC model!");
401
0
    PIC = false;
402
0
  }
403
39
404
39
  MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
405
39
  if (Opts.SaveTemporaryLabels)
406
0
    Ctx.setAllowTemporaryLabels(false);
407
39
  if (Opts.GenDwarfForAssembly)
408
3
    Ctx.setGenDwarfForAssembly(true);
409
39
  if (!Opts.DwarfDebugFlags.empty())
410
0
    Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
411
39
  if (!Opts.DwarfDebugProducer.empty())
412
22
    Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
413
39
  if (!Opts.DebugCompilationDir.empty())
414
22
    Ctx.setCompilationDir(Opts.DebugCompilationDir);
415
17
  else {
416
17
    // If no compilation dir is set, try to use the current directory.
417
17
    SmallString<128> CWD;
418
17
    if (!sys::fs::current_path(CWD))
419
17
      Ctx.setCompilationDir(CWD);
420
17
  }
421
39
  if (!Opts.DebugPrefixMap.empty())
422
0
    for (const auto &KV : Opts.DebugPrefixMap)
423
0
      Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
424
39
  if (!Opts.MainFileName.empty())
425
30
    Ctx.setMainFileName(StringRef(Opts.MainFileName));
426
39
  Ctx.setDwarfVersion(Opts.DwarfVersion);
427
39
  if (Opts.GenDwarfForAssembly)
428
3
    Ctx.setGenDwarfRootFile(Opts.InputFile,
429
3
                            SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
430
39
431
39
  // Build up the feature string from the target feature list.
432
39
  std::string FS;
433
39
  if (!Opts.Features.empty()) {
434
12
    FS = Opts.Features[0];
435
106
    for (unsigned i = 1, e = Opts.Features.size(); i != e; 
++i94
)
436
94
      FS += "," + Opts.Features[i];
437
12
  }
438
39
439
39
  std::unique_ptr<MCStreamer> Str;
440
39
441
39
  std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
442
39
  std::unique_ptr<MCSubtargetInfo> STI(
443
39
      TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
444
39
445
39
  raw_pwrite_stream *Out = FDOS.get();
446
39
  std::unique_ptr<buffer_ostream> BOS;
447
39
448
39
  MCOptions.MCNoWarn = Opts.NoWarn;
449
39
  MCOptions.MCFatalWarnings = Opts.FatalWarnings;
450
39
  MCOptions.ABIName = Opts.TargetABI;
451
39
452
39
  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
453
39
  if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
454
5
    MCInstPrinter *IP = TheTarget->createMCInstPrinter(
455
5
        llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
456
5
457
5
    std::unique_ptr<MCCodeEmitter> CE;
458
5
    if (Opts.ShowEncoding)
459
0
      CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
460
5
    std::unique_ptr<MCAsmBackend> MAB(
461
5
        TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
462
5
463
5
    auto FOut = std::make_unique<formatted_raw_ostream>(*Out);
464
5
    Str.reset(TheTarget->createAsmStreamer(
465
5
        Ctx, std::move(FOut), /*asmverbose*/ true,
466
5
        /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
467
5
        Opts.ShowInst));
468
34
  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
469
0
    Str.reset(createNullStreamer(Ctx));
470
34
  } else {
471
34
    assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
472
34
           "Invalid file type!");
473
34
    if (!FDOS->supportsSeeking()) {
474
1
      BOS = std::make_unique<buffer_ostream>(*FDOS);
475
1
      Out = BOS.get();
476
1
    }
477
34
478
34
    std::unique_ptr<MCCodeEmitter> CE(
479
34
        TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
480
34
    std::unique_ptr<MCAsmBackend> MAB(
481
34
        TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
482
34
    std::unique_ptr<MCObjectWriter> OW =
483
34
        DwoOS ? 
MAB->createDwoObjectWriter(*Out, *DwoOS)1
484
34
              : 
MAB->createObjectWriter(*Out)33
;
485
34
486
34
    Triple T(Opts.Triple);
487
34
    Str.reset(TheTarget->createMCObjectStreamer(
488
34
        T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
489
34
        Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
490
34
        /*DWARFMustBeAtTheEnd*/ true));
491
34
    Str.get()->InitSections(Opts.NoExecStack);
492
34
  }
493
39
494
39
  // When -fembed-bitcode is passed to clang_as, a 1-byte marker
495
39
  // is emitted in __LLVM,__asm section if the object file is MachO format.
496
39
  if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
497
1
                               MCObjectFileInfo::IsMachO) {
498
1
    MCSection *AsmLabel = Ctx.getMachOSection(
499
1
        "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
500
1
    Str.get()->SwitchSection(AsmLabel);
501
1
    Str.get()->EmitZeros(1);
502
1
  }
503
39
504
39
  // Assembly to object compilation should leverage assembly info.
505
39
  Str->setUseAssemblerInfoForParsing(true);
506
39
507
39
  bool Failed = false;
508
39
509
39
  std::unique_ptr<MCAsmParser> Parser(
510
39
      createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
511
39
512
39
  // FIXME: init MCTargetOptions from sanitizer flags here.
513
39
  std::unique_ptr<MCTargetAsmParser> TAP(
514
39
      TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
515
39
  if (!TAP)
516
0
    Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
517
39
518
39
  // Set values for symbols, if any.
519
39
  for (auto &S : Opts.SymbolDefs) {
520
0
    auto Pair = StringRef(S).split('=');
521
0
    auto Sym = Pair.first;
522
0
    auto Val = Pair.second;
523
0
    int64_t Value;
524
0
    // We have already error checked this in the driver.
525
0
    Val.getAsInteger(0, Value);
526
0
    Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
527
0
  }
528
39
529
39
  if (!Failed) {
530
39
    Parser->setTargetParser(*TAP.get());
531
39
    Failed = Parser->Run(Opts.NoInitialTextSection);
532
39
  }
533
39
534
39
  // Close Streamer first.
535
39
  // It might have a reference to the output stream.
536
39
  Str.reset();
537
39
  // Close the output stream early.
538
39
  BOS.reset();
539
39
  FDOS.reset();
540
39
541
39
  // Delete output file if there were errors.
542
39
  if (Failed) {
543
12
    if (Opts.OutputPath != "-")
544
12
      sys::fs::remove(Opts.OutputPath);
545
12
    if (!Opts.SplitDwarfOutput.empty() && 
Opts.SplitDwarfOutput != "-"0
)
546
0
      sys::fs::remove(Opts.SplitDwarfOutput);
547
12
  }
548
39
549
39
  return Failed;
550
39
}
551
552
static void LLVMErrorHandler(void *UserData, const std::string &Message,
553
0
                             bool GenCrashDiag) {
554
0
  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
555
0
556
0
  Diags.Report(diag::err_fe_error_backend) << Message;
557
0
558
0
  // We cannot recover from llvm errors.
559
0
  sys::Process::Exit(1);
560
0
}
561
562
40
int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
563
40
  // Initialize targets and assembly printers/parsers.
564
40
  InitializeAllTargetInfos();
565
40
  InitializeAllTargetMCs();
566
40
  InitializeAllAsmParsers();
567
40
568
40
  // Construct our diagnostic client.
569
40
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
570
40
  TextDiagnosticPrinter *DiagClient
571
40
    = new TextDiagnosticPrinter(errs(), &*DiagOpts);
572
40
  DiagClient->setPrefix("clang -cc1as");
573
40
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
574
40
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
575
40
576
40
  // Set an error handler, so that any LLVM backend diagnostics go through our
577
40
  // error handler.
578
40
  ScopedFatalErrorHandler FatalErrorHandler
579
40
    (LLVMErrorHandler, static_cast<void*>(&Diags));
580
40
581
40
  // Parse the arguments.
582
40
  AssemblerInvocation Asm;
583
40
  if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
584
1
    return 1;
585
39
586
39
  if (Asm.ShowHelp) {
587
0
    getDriverOptTable().PrintHelp(
588
0
        llvm::outs(), "clang -cc1as [options] file...",
589
0
        "Clang Integrated Assembler",
590
0
        /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
591
0
        /*ShowAllAliases=*/false);
592
0
    return 0;
593
0
  }
594
39
595
39
  // Honor -version.
596
39
  //
597
39
  // FIXME: Use a better -version message?
598
39
  if (Asm.ShowVersion) {
599
0
    llvm::cl::PrintVersionMessage();
600
0
    return 0;
601
0
  }
602
39
603
39
  // Honor -mllvm.
604
39
  //
605
39
  // FIXME: Remove this, one day.
606
39
  if (!Asm.LLVMArgs.empty()) {
607
14
    unsigned NumArgs = Asm.LLVMArgs.size();
608
14
    auto Args = std::make_unique<const char*[]>(NumArgs + 2);
609
14
    Args[0] = "clang (LLVM option parsing)";
610
28
    for (unsigned i = 0; i != NumArgs; 
++i14
)
611
14
      Args[i + 1] = Asm.LLVMArgs[i].c_str();
612
14
    Args[NumArgs + 1] = nullptr;
613
14
    llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
614
14
  }
615
39
616
39
  // Execute the invocation, unless there were parsing errors.
617
39
  bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
618
39
619
39
  // If any timers were active but haven't been destroyed yet, print their
620
39
  // results now.
621
39
  TimerGroup::printAll(errs());
622
39
  TimerGroup::clearAll();
623
39
624
39
  return !!Failed;
625
39
}