Coverage Report

Created: 2021-09-21 08:58

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