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/MCRegisterInfo.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/MC/MCTargetAsmParser.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/ManagedStatic.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/PrettyStackTrace.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"
57 #include <system_error>
58 using namespace clang;
59 using namespace clang::driver;
60 using namespace clang::driver::options;
62 using namespace llvm::opt;
66 /// \brief Helper class for representing a single invocation of the assembler.
67 struct AssemblerInvocation {
68 /// @name Target Options
71 /// The name of the target triple to assemble for.
74 /// If given, the name of the target CPU to determine which instructions
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;
83 /// @name Language Options
86 std::vector<std::string> IncludePaths;
87 unsigned NoInitialTextSection : 1;
88 unsigned SaveTemporaryLabels : 1;
89 unsigned GenDwarfForAssembly : 1;
90 unsigned CompressDebugSections : 1;
91 unsigned DwarfVersion;
92 std::string DwarfDebugFlags;
93 std::string DwarfDebugProducer;
94 std::string DebugCompilationDir;
95 std::string MainFileName;
98 /// @name Frontend Options
101 std::string InputFile;
102 std::vector<std::string> LLVMArgs;
103 std::string OutputPath;
105 FT_Asm, ///< Assembly (.s) output, transliterate mode.
106 FT_Null, ///< No output, for timing purposes.
107 FT_Obj ///< Object file output.
110 unsigned ShowHelp : 1;
111 unsigned ShowVersion : 1;
114 /// @name Transliterate Options
117 unsigned OutputAsmVariant;
118 unsigned ShowEncoding : 1;
119 unsigned ShowInst : 1;
122 /// @name Assembler Options
125 unsigned RelaxAll : 1;
126 unsigned NoExecStack : 1;
127 unsigned FatalWarnings : 1;
132 AssemblerInvocation() {
134 NoInitialTextSection = 0;
138 OutputAsmVariant = 0;
147 static bool CreateFromArgs(AssemblerInvocation &Res,
148 ArrayRef<const char *> Argv,
149 DiagnosticsEngine &Diags);
154 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
155 ArrayRef<const char *> Argv,
156 DiagnosticsEngine &Diags) {
159 // Parse the arguments.
160 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
162 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
163 unsigned MissingArgIndex, MissingArgCount;
164 std::unique_ptr<InputArgList> Args(
165 OptTbl->ParseArgs(Argv.begin(), Argv.end(), MissingArgIndex, MissingArgCount,
166 IncludedFlagsBitmask));
168 // Check for missing argument error.
169 if (MissingArgCount) {
170 Diags.Report(diag::err_drv_missing_argument)
171 << Args->getArgString(MissingArgIndex) << MissingArgCount;
175 // Issue errors on unknown arguments.
176 for (const Arg *A : Args->filtered(OPT_UNKNOWN)) {
177 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
181 // Construct the invocation.
184 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
185 Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
186 Opts.Features = Args->getAllArgValues(OPT_target_feature);
188 // Use the default target triple if unspecified.
189 if (Opts.Triple.empty())
190 Opts.Triple = llvm::sys::getDefaultTargetTriple();
193 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
194 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
195 Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
196 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g_Flag);
197 Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
198 if (Args->hasArg(OPT_gdwarf_2))
199 Opts.DwarfVersion = 2;
200 if (Args->hasArg(OPT_gdwarf_3))
201 Opts.DwarfVersion = 3;
202 if (Args->hasArg(OPT_gdwarf_4))
203 Opts.DwarfVersion = 4;
204 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
205 Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
206 Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
207 Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
210 if (Args->hasArg(OPT_INPUT)) {
212 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
213 ie = Args->filtered_end(); it != ie; ++it, First=false) {
216 Opts.InputFile = A->getValue();
218 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
223 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
224 Opts.OutputPath = Args->getLastArgValue(OPT_o);
225 if (Arg *A = Args->getLastArg(OPT_filetype)) {
226 StringRef Name = A->getValue();
227 unsigned OutputType = StringSwitch<unsigned>(Name)
229 .Case("null", FT_Null)
232 if (OutputType == ~0U) {
233 Diags.Report(diag::err_drv_invalid_value)
234 << A->getAsString(*Args) << Name;
237 Opts.OutputType = FileType(OutputType);
239 Opts.ShowHelp = Args->hasArg(OPT_help);
240 Opts.ShowVersion = Args->hasArg(OPT_version);
242 // Transliterate Options
243 Opts.OutputAsmVariant =
244 getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
245 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
246 Opts.ShowInst = Args->hasArg(OPT_show_inst);
249 Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
250 Opts.NoExecStack = Args->hasArg(OPT_mno_exec_stack);
251 Opts.FatalWarnings = Args->hasArg(OPT_massembler_fatal_warnings);
256 static std::unique_ptr<raw_fd_ostream>
257 getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
259 if (Opts.OutputPath.empty())
260 Opts.OutputPath = "-";
262 // Make sure that the Out file gets unlinked from the disk if we get a
264 if (Opts.OutputPath != "-")
265 sys::RemoveFileOnSignal(Opts.OutputPath);
268 auto Out = llvm::make_unique<raw_fd_ostream>(
269 Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
271 Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
279 static bool ExecuteAssembler(AssemblerInvocation &Opts,
280 DiagnosticsEngine &Diags) {
281 // Get the target specific parser.
283 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
285 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
287 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
288 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
290 if (std::error_code EC = Buffer.getError()) {
291 Error = EC.message();
292 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
297 // Tell SrcMgr about this buffer, which is what the parser will pick up.
298 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
300 // Record the location of the include directories so that the lexer can find
302 SrcMgr.setIncludeDirs(Opts.IncludePaths);
304 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
305 assert(MRI && "Unable to create target register info!");
307 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
308 assert(MAI && "Unable to create target asm info!");
310 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
311 // may be created with a combination of default and explicit settings.
312 if (Opts.CompressDebugSections)
313 MAI->setCompressDebugSections(true);
315 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
316 std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
320 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
321 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
322 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
324 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
325 // FIXME: Assembler behavior can change with -static.
326 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), Reloc::Default,
327 CodeModel::Default, Ctx);
328 if (Opts.SaveTemporaryLabels)
329 Ctx.setAllowTemporaryLabels(false);
330 if (Opts.GenDwarfForAssembly)
331 Ctx.setGenDwarfForAssembly(true);
332 if (!Opts.DwarfDebugFlags.empty())
333 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
334 if (!Opts.DwarfDebugProducer.empty())
335 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
336 if (!Opts.DebugCompilationDir.empty())
337 Ctx.setCompilationDir(Opts.DebugCompilationDir);
338 if (!Opts.MainFileName.empty())
339 Ctx.setMainFileName(StringRef(Opts.MainFileName));
340 Ctx.setDwarfVersion(Opts.DwarfVersion);
342 // Build up the feature string from the target feature list.
344 if (!Opts.Features.empty()) {
345 FS = Opts.Features[0];
346 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
347 FS += "," + Opts.Features[i];
350 std::unique_ptr<MCStreamer> Str;
352 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
353 std::unique_ptr<MCSubtargetInfo> STI(
354 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
356 raw_pwrite_stream *Out = FDOS.get();
357 std::unique_ptr<buffer_ostream> BOS;
359 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
360 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
361 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
362 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
363 MCCodeEmitter *CE = nullptr;
364 MCAsmBackend *MAB = nullptr;
365 if (Opts.ShowEncoding) {
366 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
367 MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
369 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
370 Str.reset(TheTarget->createAsmStreamer(
371 Ctx, std::move(FOut), /*asmverbose*/ true,
372 /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst));
373 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
374 Str.reset(createNullStreamer(Ctx));
376 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
377 "Invalid file type!");
378 if (!FDOS->supportsSeeking()) {
379 BOS = make_unique<buffer_ostream>(*FDOS);
383 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
384 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
386 Triple T(Opts.Triple);
387 Str.reset(TheTarget->createMCObjectStreamer(T, Ctx, *MAB, *Out, CE, *STI,
389 /*DWARFMustBeAtTheEnd*/ true));
390 Str.get()->InitSections(Opts.NoExecStack);
395 std::unique_ptr<MCAsmParser> Parser(
396 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
398 // FIXME: init MCTargetOptions from sanitizer flags here.
399 MCTargetOptions Options;
400 std::unique_ptr<MCTargetAsmParser> TAP(
401 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
403 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
406 Parser->setTargetParser(*TAP.get());
407 Failed = Parser->Run(Opts.NoInitialTextSection);
410 // Close the output stream early.
414 // Delete output file if there were errors.
415 if (Failed && Opts.OutputPath != "-")
416 sys::fs::remove(Opts.OutputPath);
421 static void LLVMErrorHandler(void *UserData, const std::string &Message,
423 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
425 Diags.Report(diag::err_fe_error_backend) << Message;
427 // We cannot recover from llvm errors.
431 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
432 // Print a stack trace if we signal out.
433 sys::PrintStackTraceOnErrorSignal();
434 PrettyStackTraceProgram X(Argv.size(), Argv.data());
435 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
437 // Initialize targets and assembly printers/parsers.
438 InitializeAllTargetInfos();
439 InitializeAllTargetMCs();
440 InitializeAllAsmParsers();
442 // Construct our diagnostic client.
443 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
444 TextDiagnosticPrinter *DiagClient
445 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
446 DiagClient->setPrefix("clang -cc1as");
447 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
448 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
450 // Set an error handler, so that any LLVM backend diagnostics go through our
452 ScopedFatalErrorHandler FatalErrorHandler
453 (LLVMErrorHandler, static_cast<void*>(&Diags));
455 // Parse the arguments.
456 AssemblerInvocation Asm;
457 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
461 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
462 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
463 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
469 // FIXME: Use a better -version message?
470 if (Asm.ShowVersion) {
471 llvm::cl::PrintVersionMessage();
477 // FIXME: Remove this, one day.
478 if (!Asm.LLVMArgs.empty()) {
479 unsigned NumArgs = Asm.LLVMArgs.size();
480 const char **Args = new const char*[NumArgs + 2];
481 Args[0] = "clang (LLVM option parsing)";
482 for (unsigned i = 0; i != NumArgs; ++i)
483 Args[i + 1] = Asm.LLVMArgs[i].c_str();
484 Args[NumArgs + 1] = nullptr;
485 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
488 // Execute the invocation, unless there were parsing errors.
489 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
491 // If any timers were active but haven't been destroyed yet, print their
493 TimerGroup::printAll(errs());