1 //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the entry point to the clang -cc1as functionality, which implements
11 // the direct interface to the LLVM MC based assembler.
13 //===----------------------------------------------------------------------===//
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/MCParser/MCAsmParser.h"
33 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCTargetOptions.h"
38 #include "llvm/Option/Arg.h"
39 #include "llvm/Option/ArgList.h"
40 #include "llvm/Option/OptTable.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
55 #include <system_error>
56 using namespace clang;
57 using namespace clang::driver;
58 using namespace clang::driver::options;
60 using namespace llvm::opt;
64 /// \brief Helper class for representing a single invocation of the assembler.
65 struct AssemblerInvocation {
66 /// @name Target Options
69 /// The name of the target triple to assemble for.
72 /// If given, the name of the target CPU to determine which instructions
76 /// The list of target specific features to enable or disable -- this should
77 /// be a list of strings starting with '+' or '-'.
78 std::vector<std::string> Features;
80 /// The list of symbol definitions.
81 std::vector<std::string> SymbolDefs;
84 /// @name Language Options
87 std::vector<std::string> IncludePaths;
88 unsigned NoInitialTextSection : 1;
89 unsigned SaveTemporaryLabels : 1;
90 unsigned GenDwarfForAssembly : 1;
91 unsigned CompressDebugSections : 1;
92 unsigned RelaxELFRelocations : 1;
93 unsigned DwarfVersion;
94 std::string DwarfDebugFlags;
95 std::string DwarfDebugProducer;
96 std::string DebugCompilationDir;
97 std::string MainFileName;
100 /// @name Frontend Options
103 std::string InputFile;
104 std::vector<std::string> LLVMArgs;
105 std::string OutputPath;
107 FT_Asm, ///< Assembly (.s) output, transliterate mode.
108 FT_Null, ///< No output, for timing purposes.
109 FT_Obj ///< Object file output.
112 unsigned ShowHelp : 1;
113 unsigned ShowVersion : 1;
116 /// @name Transliterate Options
119 unsigned OutputAsmVariant;
120 unsigned ShowEncoding : 1;
121 unsigned ShowInst : 1;
124 /// @name Assembler Options
127 unsigned RelaxAll : 1;
128 unsigned NoExecStack : 1;
129 unsigned FatalWarnings : 1;
130 unsigned IncrementalLinkerCompatible : 1;
132 /// The name of the relocation model to use.
133 std::string RelocationModel;
138 AssemblerInvocation() {
140 NoInitialTextSection = 0;
144 OutputAsmVariant = 0;
150 IncrementalLinkerCompatible = 0;
154 static bool CreateFromArgs(AssemblerInvocation &Res,
155 ArrayRef<const char *> Argv,
156 DiagnosticsEngine &Diags);
161 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
162 ArrayRef<const char *> Argv,
163 DiagnosticsEngine &Diags) {
166 // Parse the arguments.
167 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
169 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
170 unsigned MissingArgIndex, MissingArgCount;
171 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
172 IncludedFlagsBitmask);
174 // Check for missing argument error.
175 if (MissingArgCount) {
176 Diags.Report(diag::err_drv_missing_argument)
177 << Args.getArgString(MissingArgIndex) << MissingArgCount;
181 // Issue errors on unknown arguments.
182 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
183 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
187 // Construct the invocation.
190 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
191 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
192 Opts.Features = Args.getAllArgValues(OPT_target_feature);
194 // Use the default target triple if unspecified.
195 if (Opts.Triple.empty())
196 Opts.Triple = llvm::sys::getDefaultTargetTriple();
199 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
200 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
201 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
202 // Any DebugInfoKind implies GenDwarfForAssembly.
203 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
204 Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
205 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
206 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
207 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
208 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
209 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
210 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
213 if (Args.hasArg(OPT_INPUT)) {
215 for (const Arg *A : Args.filtered(OPT_INPUT)) {
217 Opts.InputFile = A->getValue();
220 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
225 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
226 Opts.OutputPath = Args.getLastArgValue(OPT_o);
227 if (Arg *A = Args.getLastArg(OPT_filetype)) {
228 StringRef Name = A->getValue();
229 unsigned OutputType = StringSwitch<unsigned>(Name)
231 .Case("null", FT_Null)
234 if (OutputType == ~0U) {
235 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
238 Opts.OutputType = FileType(OutputType);
240 Opts.ShowHelp = Args.hasArg(OPT_help);
241 Opts.ShowVersion = Args.hasArg(OPT_version);
243 // Transliterate Options
244 Opts.OutputAsmVariant =
245 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
246 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
247 Opts.ShowInst = Args.hasArg(OPT_show_inst);
250 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
251 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
252 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
253 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
254 Opts.IncrementalLinkerCompatible =
255 Args.hasArg(OPT_mincremental_linker_compatible);
256 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
261 static std::unique_ptr<raw_fd_ostream>
262 getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
264 if (Opts.OutputPath.empty())
265 Opts.OutputPath = "-";
267 // Make sure that the Out file gets unlinked from the disk if we get a
269 if (Opts.OutputPath != "-")
270 sys::RemoveFileOnSignal(Opts.OutputPath);
273 auto Out = llvm::make_unique<raw_fd_ostream>(
274 Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
276 Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
284 static bool ExecuteAssembler(AssemblerInvocation &Opts,
285 DiagnosticsEngine &Diags) {
286 // Get the target specific parser.
288 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
290 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
292 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
293 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
295 if (std::error_code EC = Buffer.getError()) {
296 Error = EC.message();
297 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
302 // Tell SrcMgr about this buffer, which is what the parser will pick up.
303 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
305 // Record the location of the include directories so that the lexer can find
307 SrcMgr.setIncludeDirs(Opts.IncludePaths);
309 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
310 assert(MRI && "Unable to create target register info!");
312 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
313 assert(MAI && "Unable to create target asm info!");
315 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
316 // may be created with a combination of default and explicit settings.
317 if (Opts.CompressDebugSections)
318 MAI->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
320 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
322 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
323 std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
327 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
328 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
329 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
331 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
334 if (Opts.RelocationModel == "static") {
336 } else if (Opts.RelocationModel == "pic") {
339 assert(Opts.RelocationModel == "dynamic-no-pic" &&
340 "Invalid PIC model!");
344 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, CodeModel::Default, Ctx);
345 if (Opts.SaveTemporaryLabels)
346 Ctx.setAllowTemporaryLabels(false);
347 if (Opts.GenDwarfForAssembly)
348 Ctx.setGenDwarfForAssembly(true);
349 if (!Opts.DwarfDebugFlags.empty())
350 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
351 if (!Opts.DwarfDebugProducer.empty())
352 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
353 if (!Opts.DebugCompilationDir.empty())
354 Ctx.setCompilationDir(Opts.DebugCompilationDir);
355 if (!Opts.MainFileName.empty())
356 Ctx.setMainFileName(StringRef(Opts.MainFileName));
357 Ctx.setDwarfVersion(Opts.DwarfVersion);
359 // Build up the feature string from the target feature list.
361 if (!Opts.Features.empty()) {
362 FS = Opts.Features[0];
363 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
364 FS += "," + Opts.Features[i];
367 std::unique_ptr<MCStreamer> Str;
369 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
370 std::unique_ptr<MCSubtargetInfo> STI(
371 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
373 raw_pwrite_stream *Out = FDOS.get();
374 std::unique_ptr<buffer_ostream> BOS;
376 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
377 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
378 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
379 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
380 MCCodeEmitter *CE = nullptr;
381 MCAsmBackend *MAB = nullptr;
382 if (Opts.ShowEncoding) {
383 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
384 MCTargetOptions Options;
385 MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU, Options);
387 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
388 Str.reset(TheTarget->createAsmStreamer(
389 Ctx, std::move(FOut), /*asmverbose*/ true,
390 /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst));
391 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
392 Str.reset(createNullStreamer(Ctx));
394 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
395 "Invalid file type!");
396 if (!FDOS->supportsSeeking()) {
397 BOS = make_unique<buffer_ostream>(*FDOS);
401 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
402 MCTargetOptions Options;
403 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
405 Triple T(Opts.Triple);
406 Str.reset(TheTarget->createMCObjectStreamer(
407 T, Ctx, *MAB, *Out, CE, *STI, Opts.RelaxAll,
408 Opts.IncrementalLinkerCompatible,
409 /*DWARFMustBeAtTheEnd*/ true));
410 Str.get()->InitSections(Opts.NoExecStack);
415 std::unique_ptr<MCAsmParser> Parser(
416 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
418 // FIXME: init MCTargetOptions from sanitizer flags here.
419 MCTargetOptions Options;
420 std::unique_ptr<MCTargetAsmParser> TAP(
421 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
423 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
425 // Set values for symbols, if any.
426 for (auto &S : Opts.SymbolDefs) {
427 auto Pair = StringRef(S).split('=');
428 auto Sym = Pair.first;
429 auto Val = Pair.second;
431 // We have already error checked this in the driver.
432 Val.getAsInteger(0, Value);
433 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
437 Parser->setTargetParser(*TAP.get());
438 Failed = Parser->Run(Opts.NoInitialTextSection);
441 // Close Streamer first.
442 // It might have a reference to the output stream.
444 // Close the output stream early.
448 // Delete output file if there were errors.
449 if (Failed && Opts.OutputPath != "-")
450 sys::fs::remove(Opts.OutputPath);
455 static void LLVMErrorHandler(void *UserData, const std::string &Message,
457 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
459 Diags.Report(diag::err_fe_error_backend) << Message;
461 // We cannot recover from llvm errors.
465 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
466 // Initialize targets and assembly printers/parsers.
467 InitializeAllTargetInfos();
468 InitializeAllTargetMCs();
469 InitializeAllAsmParsers();
471 // Construct our diagnostic client.
472 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
473 TextDiagnosticPrinter *DiagClient
474 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
475 DiagClient->setPrefix("clang -cc1as");
476 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
477 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
479 // Set an error handler, so that any LLVM backend diagnostics go through our
481 ScopedFatalErrorHandler FatalErrorHandler
482 (LLVMErrorHandler, static_cast<void*>(&Diags));
484 // Parse the arguments.
485 AssemblerInvocation Asm;
486 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
490 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
491 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
492 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
498 // FIXME: Use a better -version message?
499 if (Asm.ShowVersion) {
500 llvm::cl::PrintVersionMessage();
506 // FIXME: Remove this, one day.
507 if (!Asm.LLVMArgs.empty()) {
508 unsigned NumArgs = Asm.LLVMArgs.size();
509 const char **Args = new const char*[NumArgs + 2];
510 Args[0] = "clang (LLVM option parsing)";
511 for (unsigned i = 0; i != NumArgs; ++i)
512 Args[i + 1] = Asm.LLVMArgs[i].c_str();
513 Args[NumArgs + 1] = nullptr;
514 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
517 // Execute the invocation, unless there were parsing errors.
518 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
520 // If any timers were active but haven't been destroyed yet, print their
522 TimerGroup::printAll(errs());