Coverage Report

Created: 2018-12-11 17:59

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