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/Arg.h"
18 #include "clang/Driver/ArgList.h"
19 #include "clang/Driver/CC1AsOptions.h"
20 #include "clang/Driver/DriverDiagnostic.h"
21 #include "clang/Driver/OptTable.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/TextDiagnosticPrinter.h"
25 #include "llvm/ADT/OwningPtr.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/MC/MCAsmBackend.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCCodeEmitter.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCParser/MCAsmParser.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCTargetAsmParser.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/ManagedStatic.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/PrettyStackTrace.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"
54 #include "llvm/Support/system_error.h"
55 using namespace clang;
56 using namespace clang::driver;
61 /// \brief Helper class for representing a single invocation of the assembler.
62 struct AssemblerInvocation {
63 /// @name Target Options
66 /// The name of the target triple to assemble for.
69 /// If given, the name of the target CPU to determine which instructions
73 /// The list of target specific features to enable or disable -- this should
74 /// be a list of strings starting with '+' or '-'.
75 std::vector<std::string> Features;
78 /// @name Language Options
81 std::vector<std::string> IncludePaths;
82 unsigned NoInitialTextSection : 1;
83 unsigned SaveTemporaryLabels : 1;
84 unsigned GenDwarfForAssembly : 1;
85 std::string DwarfDebugFlags;
86 std::string DwarfDebugProducer;
87 std::string DebugCompilationDir;
88 std::string MainFileName;
91 /// @name Frontend Options
94 std::string InputFile;
95 std::vector<std::string> LLVMArgs;
96 std::string OutputPath;
98 FT_Asm, ///< Assembly (.s) output, transliterate mode.
99 FT_Null, ///< No output, for timing purposes.
100 FT_Obj ///< Object file output.
103 unsigned ShowHelp : 1;
104 unsigned ShowVersion : 1;
107 /// @name Transliterate Options
110 unsigned OutputAsmVariant;
111 unsigned ShowEncoding : 1;
112 unsigned ShowInst : 1;
115 /// @name Assembler Options
118 unsigned RelaxAll : 1;
119 unsigned NoExecStack : 1;
124 AssemblerInvocation() {
126 NoInitialTextSection = 0;
130 OutputAsmVariant = 0;
137 static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
138 const char **ArgEnd, DiagnosticsEngine &Diags);
143 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
144 const char **ArgBegin,
146 DiagnosticsEngine &Diags) {
147 using namespace clang::driver::cc1asoptions;
150 // Parse the arguments.
151 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
152 unsigned MissingArgIndex, MissingArgCount;
153 OwningPtr<InputArgList> Args(
154 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
156 // Check for missing argument error.
157 if (MissingArgCount) {
158 Diags.Report(diag::err_drv_missing_argument)
159 << Args->getArgString(MissingArgIndex) << MissingArgCount;
163 // Issue errors on unknown arguments.
164 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
165 ie = Args->filtered_end(); it != ie; ++it) {
166 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
170 // Construct the invocation.
173 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
174 Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
175 Opts.Features = Args->getAllArgValues(OPT_target_feature);
177 // Use the default target triple if unspecified.
178 if (Opts.Triple.empty())
179 Opts.Triple = llvm::sys::getDefaultTargetTriple();
182 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
183 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
184 Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
185 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
186 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
187 Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
188 Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
189 Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
192 if (Args->hasArg(OPT_INPUT)) {
194 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
195 ie = Args->filtered_end(); it != ie; ++it, First=false) {
198 Opts.InputFile = A->getValue();
200 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
205 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
206 if (Args->hasArg(OPT_fatal_warnings))
207 Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
208 Opts.OutputPath = Args->getLastArgValue(OPT_o);
209 if (Arg *A = Args->getLastArg(OPT_filetype)) {
210 StringRef Name = A->getValue();
211 unsigned OutputType = StringSwitch<unsigned>(Name)
213 .Case("null", FT_Null)
216 if (OutputType == ~0U) {
217 Diags.Report(diag::err_drv_invalid_value)
218 << A->getAsString(*Args) << Name;
221 Opts.OutputType = FileType(OutputType);
223 Opts.ShowHelp = Args->hasArg(OPT_help);
224 Opts.ShowVersion = Args->hasArg(OPT_version);
226 // Transliterate Options
227 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
229 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
230 Opts.ShowInst = Args->hasArg(OPT_show_inst);
233 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
234 Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
239 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
240 DiagnosticsEngine &Diags,
242 if (Opts.OutputPath.empty())
243 Opts.OutputPath = "-";
245 // Make sure that the Out file gets unlinked from the disk if we get a
247 if (Opts.OutputPath != "-")
248 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
251 raw_fd_ostream *Out =
252 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
253 (Binary ? raw_fd_ostream::F_Binary : 0));
254 if (!Error.empty()) {
255 Diags.Report(diag::err_fe_unable_to_open_output)
256 << Opts.OutputPath << Error;
260 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
263 static bool ExecuteAssembler(AssemblerInvocation &Opts,
264 DiagnosticsEngine &Diags) {
265 // Get the target specific parser.
267 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
269 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
273 OwningPtr<MemoryBuffer> BufferPtr;
274 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
275 Error = ec.message();
276 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
279 MemoryBuffer *Buffer = BufferPtr.take();
283 // Tell SrcMgr about this buffer, which is what the parser will pick up.
284 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
286 // Record the location of the include directories so that the lexer can find
288 SrcMgr.setIncludeDirs(Opts.IncludePaths);
290 OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));
291 assert(MAI && "Unable to create target asm info!");
293 OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
294 assert(MRI && "Unable to create target register info!");
296 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
297 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
301 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
302 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
303 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
304 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
305 // FIXME: Assembler behavior can change with -static.
306 MOFI->InitMCObjectFileInfo(Opts.Triple,
307 Reloc::Default, CodeModel::Default, Ctx);
308 if (Opts.SaveTemporaryLabels)
309 Ctx.setAllowTemporaryLabels(false);
310 if (Opts.GenDwarfForAssembly)
311 Ctx.setGenDwarfForAssembly(true);
312 if (!Opts.DwarfDebugFlags.empty())
313 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
314 if (!Opts.DwarfDebugProducer.empty())
315 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
316 if (!Opts.DebugCompilationDir.empty())
317 Ctx.setCompilationDir(Opts.DebugCompilationDir);
318 if (!Opts.MainFileName.empty())
319 Ctx.setMainFileName(StringRef(Opts.MainFileName));
321 // Build up the feature string from the target feature list.
323 if (!Opts.Features.empty()) {
324 FS = Opts.Features[0];
325 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
326 FS += "," + Opts.Features[i];
329 OwningPtr<MCStreamer> Str;
331 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
332 OwningPtr<MCSubtargetInfo>
333 STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
335 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
336 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
338 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
340 MCCodeEmitter *CE = 0;
341 MCAsmBackend *MAB = 0;
342 if (Opts.ShowEncoding) {
343 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
344 MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
346 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
349 /*useDwarfDirectory*/ true,
352 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
353 Str.reset(createNullStreamer(Ctx));
355 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
356 "Invalid file type!");
357 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
358 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
359 Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
362 Str.get()->InitSections();
365 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
367 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
369 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
373 Parser->setTargetParser(*TAP.get());
375 bool Success = !Parser->Run(Opts.NoInitialTextSection);
380 // Delete output on errors.
381 if (!Success && Opts.OutputPath != "-")
382 sys::Path(Opts.OutputPath).eraseFromDisk();
387 static void LLVMErrorHandler(void *UserData, const std::string &Message,
389 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
391 Diags.Report(diag::err_fe_error_backend) << Message;
393 // We cannot recover from llvm errors.
397 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
398 const char *Argv0, void *MainAddr) {
399 // Print a stack trace if we signal out.
400 sys::PrintStackTraceOnErrorSignal();
401 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
402 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
404 // Initialize targets and assembly printers/parsers.
405 InitializeAllTargetInfos();
406 InitializeAllTargetMCs();
407 InitializeAllAsmParsers();
409 // Construct our diagnostic client.
410 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
411 TextDiagnosticPrinter *DiagClient
412 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
413 DiagClient->setPrefix("clang -cc1as");
414 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
415 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
417 // Set an error handler, so that any LLVM backend diagnostics go through our
419 ScopedFatalErrorHandler FatalErrorHandler
420 (LLVMErrorHandler, static_cast<void*>(&Diags));
422 // Parse the arguments.
423 AssemblerInvocation Asm;
424 if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
429 OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
430 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
436 // FIXME: Use a better -version message?
437 if (Asm.ShowVersion) {
438 llvm::cl::PrintVersionMessage();
444 // FIXME: Remove this, one day.
445 if (!Asm.LLVMArgs.empty()) {
446 unsigned NumArgs = Asm.LLVMArgs.size();
447 const char **Args = new const char*[NumArgs + 2];
448 Args[0] = "clang (LLVM option parsing)";
449 for (unsigned i = 0; i != NumArgs; ++i)
450 Args[i + 1] = Asm.LLVMArgs[i].c_str();
451 Args[NumArgs + 1] = 0;
452 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
455 // Execute the invocation, unless there were parsing errors.
456 bool Success = false;
457 if (!Diags.hasErrorOccurred())
458 Success = ExecuteAssembler(Asm, Diags);
460 // If any timers were active but haven't been destroyed yet, print their
462 TimerGroup::printAll(errs());