Coverage Report

Created: 2022-01-18 06:27

/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/MC/TargetRegistry.h"
40
#include "llvm/Option/Arg.h"
41
#include "llvm/Option/ArgList.h"
42
#include "llvm/Option/OptTable.h"
43
#include "llvm/Support/CommandLine.h"
44
#include "llvm/Support/ErrorHandling.h"
45
#include "llvm/Support/FileSystem.h"
46
#include "llvm/Support/FormattedStream.h"
47
#include "llvm/Support/Host.h"
48
#include "llvm/Support/MemoryBuffer.h"
49
#include "llvm/Support/Path.h"
50
#include "llvm/Support/Process.h"
51
#include "llvm/Support/Signals.h"
52
#include "llvm/Support/SourceMgr.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
53
  AssemblerInvocation() {
151
53
    Triple = "";
152
53
    NoInitialTextSection = 0;
153
53
    InputFile = "-";
154
53
    OutputPath = "-";
155
53
    OutputType = FT_Asm;
156
53
    OutputAsmVariant = 0;
157
53
    ShowInst = 0;
158
53
    ShowEncoding = 0;
159
53
    RelaxAll = 0;
160
53
    NoExecStack = 0;
161
53
    FatalWarnings = 0;
162
53
    NoWarn = 0;
163
53
    IncrementalLinkerCompatible = 0;
164
53
    Dwarf64 = 0;
165
53
    DwarfVersion = 0;
166
53
    EmbedBitcode = 0;
167
53
  }
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
53
                                         DiagnosticsEngine &Diags) {
179
53
  bool Success = true;
180
181
  // Parse the arguments.
182
53
  const OptTable &OptTbl = getDriverOptTable();
183
184
53
  const unsigned IncludedFlagsBitmask = options::CC1AsOption;
185
53
  unsigned MissingArgIndex, MissingArgCount;
186
53
  InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount,
187
53
                                       IncludedFlagsBitmask);
188
189
  // Check for missing argument error.
190
53
  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
53
  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
53
  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
212
53
  Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
213
53
  Opts.Features = Args.getAllArgValues(OPT_target_feature);
214
215
  // Use the default target triple if unspecified.
216
53
  if (Opts.Triple.empty())
217
0
    Opts.Triple = llvm::sys::getDefaultTargetTriple();
218
219
  // Language Options
220
53
  Opts.IncludePaths = Args.getAllArgValues(OPT_I);
221
53
  Opts.NoInitialTextSection = Args.hasArg(OPT_n);
222
53
  Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
223
  // Any DebugInfoKind implies GenDwarfForAssembly.
224
53
  Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
225
226
53
  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
53
  Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
236
53
  if (auto *DwarfFormatArg = Args.getLastArg(OPT_gdwarf64, OPT_gdwarf32))
237
2
    Opts.Dwarf64 = DwarfFormatArg->getOption().matches(OPT_gdwarf64);
238
53
  Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
239
53
  Opts.DwarfDebugFlags =
240
53
      std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
241
53
  Opts.DwarfDebugProducer =
242
53
      std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
243
53
  if (const Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
244
53
                                     options::OPT_fdebug_compilation_dir_EQ))
245
41
    Opts.DebugCompilationDir = A->getValue();
246
53
  Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
247
248
53
  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
53
  if (Args.hasArg(OPT_INPUT)) {
256
52
    bool First = true;
257
52
    for (const Arg *A : Args.filtered(OPT_INPUT)) {
258
52
      if (First) {
259
52
        Opts.InputFile = A->getValue();
260
52
        First = false;
261
52
      } else {
262
0
        Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
263
0
        Success = false;
264
0
      }
265
52
    }
266
52
  }
267
53
  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
268
53
  Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
269
53
  Opts.SplitDwarfOutput =
270
53
      std::string(Args.getLastArgValue(OPT_split_dwarf_output));
271
53
  if (Arg *A = Args.getLastArg(OPT_filetype)) {
272
50
    StringRef Name = A->getValue();
273
50
    unsigned OutputType = StringSwitch<unsigned>(Name)
274
50
      .Case("asm", FT_Asm)
275
50
      .Case("null", FT_Null)
276
50
      .Case("obj", FT_Obj)
277
50
      .Default(~0U);
278
50
    if (OutputType == ~0U) {
279
0
      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
280
0
      Success = false;
281
0
    } else
282
50
      Opts.OutputType = FileType(OutputType);
283
50
  }
284
53
  Opts.ShowHelp = Args.hasArg(OPT_help);
285
53
  Opts.ShowVersion = Args.hasArg(OPT_version);
286
287
  // Transliterate Options
288
53
  Opts.OutputAsmVariant =
289
53
      getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
290
53
  Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
291
53
  Opts.ShowInst = Args.hasArg(OPT_show_inst);
292
293
  // Assemble Options
294
53
  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
295
53
  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
296
53
  Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
297
53
  Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
298
53
  Opts.RelocationModel =
299
53
      std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
300
53
  Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
301
53
  Opts.IncrementalLinkerCompatible =
302
53
      Args.hasArg(OPT_mincremental_linker_compatible);
303
53
  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
53
  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
53
  return Success;
316
53
}
317
318
static std::unique_ptr<raw_fd_ostream>
319
53
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
53
  if (Path != "-")
323
43
    sys::RemoveFileOnSignal(Path);
324
325
53
  std::error_code EC;
326
53
  auto Out = std::make_unique<raw_fd_ostream>(
327
53
      Path, EC, (Binary ? 
sys::fs::OF_None48
:
sys::fs::OF_TextWithCRLF5
));
328
53
  if (EC) {
329
0
    Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
330
0
    return nullptr;
331
0
  }
332
333
53
  return Out;
334
53
}
335
336
static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts,
337
52
                                 DiagnosticsEngine &Diags) {
338
  // Get the target specific parser.
339
52
  std::string Error;
340
52
  const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
341
52
  if (!TheTarget)
342
0
    return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
343
344
52
  ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
345
52
      MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true);
346
347
52
  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
52
  SourceMgr SrcMgr;
353
354
  // Tell SrcMgr about this buffer, which is what the parser will pick up.
355
52
  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
52
  SrcMgr.setIncludeDirs(Opts.IncludePaths);
360
361
52
  std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
362
52
  assert(MRI && "Unable to create target register info!");
363
364
0
  MCTargetOptions MCOptions;
365
52
  std::unique_ptr<MCAsmInfo> MAI(
366
52
      TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
367
52
  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
52
  MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
374
375
52
  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
376
52
  if (Opts.OutputPath.empty())
377
2
    Opts.OutputPath = "-";
378
52
  std::unique_ptr<raw_fd_ostream> FDOS =
379
52
      getOutputStream(Opts.OutputPath, Diags, IsBinary);
380
52
  if (!FDOS)
381
0
    return true;
382
52
  std::unique_ptr<raw_fd_ostream> DwoOS;
383
52
  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
52
  std::string FS = llvm::join(Opts.Features, ",");
388
389
52
  std::unique_ptr<MCSubtargetInfo> STI(
390
52
      TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
391
52
  assert(STI && "Unable to create subtarget info!");
392
393
0
  MCContext Ctx(Triple(Opts.Triple), MAI.get(), MRI.get(), STI.get(), &SrcMgr,
394
52
                &MCOptions);
395
396
52
  bool PIC = false;
397
52
  if (Opts.RelocationModel == "static") {
398
31
    PIC = false;
399
31
  } else 
if (21
Opts.RelocationModel == "pic"21
) {
400
21
    PIC = true;
401
21
  } 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
52
      TheTarget->createMCObjectFileInfo(Ctx, PIC));
411
52
  Ctx.setObjectFileInfo(MOFI.get());
412
413
52
  if (Opts.SaveTemporaryLabels)
414
0
    Ctx.setAllowTemporaryLabels(false);
415
52
  if (Opts.GenDwarfForAssembly)
416
6
    Ctx.setGenDwarfForAssembly(true);
417
52
  if (!Opts.DwarfDebugFlags.empty())
418
0
    Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
419
52
  if (!Opts.DwarfDebugProducer.empty())
420
31
    Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
421
52
  if (!Opts.DebugCompilationDir.empty())
422
41
    Ctx.setCompilationDir(Opts.DebugCompilationDir);
423
11
  else {
424
    // If no compilation dir is set, try to use the current directory.
425
11
    SmallString<128> CWD;
426
11
    if (!sys::fs::current_path(CWD))
427
11
      Ctx.setCompilationDir(CWD);
428
11
  }
429
52
  if (!Opts.DebugPrefixMap.empty())
430
0
    for (const auto &KV : Opts.DebugPrefixMap)
431
0
      Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
432
52
  if (!Opts.MainFileName.empty())
433
41
    Ctx.setMainFileName(StringRef(Opts.MainFileName));
434
52
  Ctx.setDwarfFormat(Opts.Dwarf64 ? 
dwarf::DWARF641
:
dwarf::DWARF3251
);
435
52
  Ctx.setDwarfVersion(Opts.DwarfVersion);
436
52
  if (Opts.GenDwarfForAssembly)
437
6
    Ctx.setGenDwarfRootFile(Opts.InputFile,
438
6
                            SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
439
440
52
  std::unique_ptr<MCStreamer> Str;
441
442
52
  std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
443
52
  assert(MCII && "Unable to create instruction info!");
444
445
0
  raw_pwrite_stream *Out = FDOS.get();
446
52
  std::unique_ptr<buffer_ostream> BOS;
447
448
52
  MCOptions.MCNoWarn = Opts.NoWarn;
449
52
  MCOptions.MCFatalWarnings = Opts.FatalWarnings;
450
52
  MCOptions.ABIName = Opts.TargetABI;
451
452
  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
453
52
  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
47
  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
469
0
    Str.reset(createNullStreamer(Ctx));
470
47
  } else {
471
47
    assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
472
47
           "Invalid file type!");
473
47
    if (!FDOS->supportsSeeking()) {
474
8
      BOS = std::make_unique<buffer_ostream>(*FDOS);
475
8
      Out = BOS.get();
476
8
    }
477
478
47
    std::unique_ptr<MCCodeEmitter> CE(
479
47
        TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
480
47
    std::unique_ptr<MCAsmBackend> MAB(
481
47
        TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
482
47
    assert(MAB && "Unable to create asm backend!");
483
484
0
    std::unique_ptr<MCObjectWriter> OW =
485
47
        DwoOS ? 
MAB->createDwoObjectWriter(*Out, *DwoOS)1
486
47
              : 
MAB->createObjectWriter(*Out)46
;
487
488
47
    Triple T(Opts.Triple);
489
47
    Str.reset(TheTarget->createMCObjectStreamer(
490
47
        T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
491
47
        Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
492
47
        /*DWARFMustBeAtTheEnd*/ true));
493
47
    Str.get()->initSections(Opts.NoExecStack, *STI);
494
47
  }
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
52
  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
52
  Str->setUseAssemblerInfoForParsing(true);
507
508
52
  bool Failed = false;
509
510
52
  std::unique_ptr<MCAsmParser> Parser(
511
52
      createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
512
513
  // FIXME: init MCTargetOptions from sanitizer flags here.
514
52
  std::unique_ptr<MCTargetAsmParser> TAP(
515
52
      TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
516
52
  if (!TAP)
517
0
    Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
518
519
  // Set values for symbols, if any.
520
52
  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
52
  if (!Failed) {
531
52
    Parser->setTargetParser(*TAP.get());
532
52
    Failed = Parser->Run(Opts.NoInitialTextSection);
533
52
  }
534
535
52
  return Failed;
536
52
}
537
538
static bool ExecuteAssembler(AssemblerInvocation &Opts,
539
52
                             DiagnosticsEngine &Diags) {
540
52
  bool Failed = ExecuteAssemblerImpl(Opts, Diags);
541
542
  // Delete output file if there were errors.
543
52
  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
52
  return Failed;
551
52
}
552
553
static void LLVMErrorHandler(void *UserData, const char *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
53
int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
564
  // Initialize targets and assembly printers/parsers.
565
53
  InitializeAllTargetInfos();
566
53
  InitializeAllTargetMCs();
567
53
  InitializeAllAsmParsers();
568
569
  // Construct our diagnostic client.
570
53
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
571
53
  TextDiagnosticPrinter *DiagClient
572
53
    = new TextDiagnosticPrinter(errs(), &*DiagOpts);
573
53
  DiagClient->setPrefix("clang -cc1as");
574
53
  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
575
53
  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
576
577
  // Set an error handler, so that any LLVM backend diagnostics go through our
578
  // error handler.
579
53
  ScopedFatalErrorHandler FatalErrorHandler
580
53
    (LLVMErrorHandler, static_cast<void*>(&Diags));
581
582
  // Parse the arguments.
583
53
  AssemblerInvocation Asm;
584
53
  if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
585
1
    return 1;
586
587
52
  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
52
  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
52
  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
52
  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
52
  TimerGroup::printAll(errs());
623
52
  TimerGroup::clearAll();
624
625
52
  return !!Failed;
626
52
}