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/CC1AsOptions.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "clang/Frontend/TextDiagnosticPrinter.h"
22 #include "clang/Frontend/Utils.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/Option/Arg.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Option/OptTable.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/PrettyStackTrace.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 "llvm/Support/system_error.h"
56 #include <memory>
57 using namespace clang;
58 using namespace clang::driver;
59 using namespace llvm;
60 using namespace llvm::opt;
61 
62 namespace {
63 
64 /// \brief Helper class for representing a single invocation of the assembler.
65 struct AssemblerInvocation {
66   /// @name Target Options
67   /// @{
68 
69   /// The name of the target triple to assemble for.
70   std::string Triple;
71 
72   /// If given, the name of the target CPU to determine which instructions
73   /// are legal.
74   std::string CPU;
75 
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;
79 
80   /// @}
81   /// @name Language Options
82   /// @{
83 
84   std::vector<std::string> IncludePaths;
85   unsigned NoInitialTextSection : 1;
86   unsigned SaveTemporaryLabels : 1;
87   unsigned GenDwarfForAssembly : 1;
88   unsigned CompressDebugSections : 1;
89   std::string DwarfDebugFlags;
90   std::string DwarfDebugProducer;
91   std::string DebugCompilationDir;
92   std::string MainFileName;
93 
94   /// @}
95   /// @name Frontend Options
96   /// @{
97 
98   std::string InputFile;
99   std::vector<std::string> LLVMArgs;
100   std::string OutputPath;
101   enum FileType {
102     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
103     FT_Null, ///< No output, for timing purposes.
104     FT_Obj   ///< Object file output.
105   };
106   FileType OutputType;
107   unsigned ShowHelp : 1;
108   unsigned ShowVersion : 1;
109 
110   /// @}
111   /// @name Transliterate Options
112   /// @{
113 
114   unsigned OutputAsmVariant;
115   unsigned ShowEncoding : 1;
116   unsigned ShowInst : 1;
117 
118   /// @}
119   /// @name Assembler Options
120   /// @{
121 
122   unsigned RelaxAll : 1;
123   unsigned NoExecStack : 1;
124 
125   /// @}
126 
127 public:
128   AssemblerInvocation() {
129     Triple = "";
130     NoInitialTextSection = 0;
131     InputFile = "-";
132     OutputPath = "-";
133     OutputType = FT_Asm;
134     OutputAsmVariant = 0;
135     ShowInst = 0;
136     ShowEncoding = 0;
137     RelaxAll = 0;
138     NoExecStack = 0;
139   }
140 
141   static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
142                              const char **ArgEnd, DiagnosticsEngine &Diags);
143 };
144 
145 }
146 
147 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
148                                          const char **ArgBegin,
149                                          const char **ArgEnd,
150                                          DiagnosticsEngine &Diags) {
151   using namespace clang::driver::cc1asoptions;
152   bool Success = true;
153 
154   // Parse the arguments.
155   std::unique_ptr<OptTable> OptTbl(createCC1AsOptTable());
156   unsigned MissingArgIndex, MissingArgCount;
157   std::unique_ptr<InputArgList> Args(
158       OptTbl->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount));
159 
160   // Check for missing argument error.
161   if (MissingArgCount) {
162     Diags.Report(diag::err_drv_missing_argument)
163       << Args->getArgString(MissingArgIndex) << MissingArgCount;
164     Success = false;
165   }
166 
167   // Issue errors on unknown arguments.
168   for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
169          ie = Args->filtered_end(); it != ie; ++it) {
170     Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
171     Success = false;
172   }
173 
174   // Construct the invocation.
175 
176   // Target Options
177   Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
178   Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
179   Opts.Features = Args->getAllArgValues(OPT_target_feature);
180 
181   // Use the default target triple if unspecified.
182   if (Opts.Triple.empty())
183     Opts.Triple = llvm::sys::getDefaultTargetTriple();
184 
185   // Language Options
186   Opts.IncludePaths = Args->getAllArgValues(OPT_I);
187   Opts.NoInitialTextSection = Args->hasArg(OPT_n);
188   Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
189   Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
190   Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
191   Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
192   Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
193   Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
194   Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
195 
196   // Frontend Options
197   if (Args->hasArg(OPT_INPUT)) {
198     bool First = true;
199     for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
200            ie = Args->filtered_end(); it != ie; ++it, First=false) {
201       const Arg *A = it;
202       if (First)
203         Opts.InputFile = A->getValue();
204       else {
205         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
206         Success = false;
207       }
208     }
209   }
210   Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
211   Opts.OutputPath = Args->getLastArgValue(OPT_o);
212   if (Arg *A = Args->getLastArg(OPT_filetype)) {
213     StringRef Name = A->getValue();
214     unsigned OutputType = StringSwitch<unsigned>(Name)
215       .Case("asm", FT_Asm)
216       .Case("null", FT_Null)
217       .Case("obj", FT_Obj)
218       .Default(~0U);
219     if (OutputType == ~0U) {
220       Diags.Report(diag::err_drv_invalid_value)
221         << A->getAsString(*Args) << Name;
222       Success = false;
223     } else
224       Opts.OutputType = FileType(OutputType);
225   }
226   Opts.ShowHelp = Args->hasArg(OPT_help);
227   Opts.ShowVersion = Args->hasArg(OPT_version);
228 
229   // Transliterate Options
230   Opts.OutputAsmVariant =
231       getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
232   Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
233   Opts.ShowInst = Args->hasArg(OPT_show_inst);
234 
235   // Assemble Options
236   Opts.RelaxAll = Args->hasArg(OPT_mrelax_all);
237   Opts.NoExecStack =  Args->hasArg(OPT_mno_exec_stack);
238 
239   return Success;
240 }
241 
242 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
243                                               DiagnosticsEngine &Diags,
244                                               bool Binary) {
245   if (Opts.OutputPath.empty())
246     Opts.OutputPath = "-";
247 
248   // Make sure that the Out file gets unlinked from the disk if we get a
249   // SIGINT.
250   if (Opts.OutputPath != "-")
251     sys::RemoveFileOnSignal(Opts.OutputPath);
252 
253   std::string Error;
254   raw_fd_ostream *Out =
255       new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
256                          (Binary ? sys::fs::F_None : sys::fs::F_Text));
257   if (!Error.empty()) {
258     Diags.Report(diag::err_fe_unable_to_open_output)
259       << Opts.OutputPath << Error;
260     return 0;
261   }
262 
263   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
264 }
265 
266 static bool ExecuteAssembler(AssemblerInvocation &Opts,
267                              DiagnosticsEngine &Diags) {
268   // Get the target specific parser.
269   std::string Error;
270   const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
271   if (!TheTarget) {
272     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
273     return false;
274   }
275 
276   std::unique_ptr<MemoryBuffer> BufferPtr;
277   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
278     Error = ec.message();
279     Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
280     return false;
281   }
282   MemoryBuffer *Buffer = BufferPtr.release();
283 
284   SourceMgr SrcMgr;
285 
286   // Tell SrcMgr about this buffer, which is what the parser will pick up.
287   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
288 
289   // Record the location of the include directories so that the lexer can find
290   // it later.
291   SrcMgr.setIncludeDirs(Opts.IncludePaths);
292 
293   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
294   assert(MRI && "Unable to create target register info!");
295 
296   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
297   assert(MAI && "Unable to create target asm info!");
298 
299   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
300   // may be created with a combination of default and explicit settings.
301   if (Opts.CompressDebugSections)
302     MAI->setCompressDebugSections(true);
303 
304   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
305   formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
306   if (!Out)
307     return false;
308 
309   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
310   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
311   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
312 
313   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
314   // FIXME: Assembler behavior can change with -static.
315   MOFI->InitMCObjectFileInfo(Opts.Triple,
316                              Reloc::Default, CodeModel::Default, Ctx);
317   if (Opts.SaveTemporaryLabels)
318     Ctx.setAllowTemporaryLabels(false);
319   if (Opts.GenDwarfForAssembly)
320     Ctx.setGenDwarfForAssembly(true);
321   if (!Opts.DwarfDebugFlags.empty())
322     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
323   if (!Opts.DwarfDebugProducer.empty())
324     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
325   if (!Opts.DebugCompilationDir.empty())
326     Ctx.setCompilationDir(Opts.DebugCompilationDir);
327   if (!Opts.MainFileName.empty())
328     Ctx.setMainFileName(StringRef(Opts.MainFileName));
329 
330   // Build up the feature string from the target feature list.
331   std::string FS;
332   if (!Opts.Features.empty()) {
333     FS = Opts.Features[0];
334     for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
335       FS += "," + Opts.Features[i];
336   }
337 
338   std::unique_ptr<MCStreamer> Str;
339 
340   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
341   std::unique_ptr<MCSubtargetInfo> STI(
342       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
343 
344   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
345   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
346     MCInstPrinter *IP =
347       TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
348                                      *STI);
349     MCCodeEmitter *CE = 0;
350     MCAsmBackend *MAB = 0;
351     if (Opts.ShowEncoding) {
352       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
353       MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
354     }
355     Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
356                                            /*useCFI*/ true,
357                                            /*useDwarfDirectory*/ true,
358                                            IP, CE, MAB,
359                                            Opts.ShowInst));
360   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
361     Str.reset(createNullStreamer(Ctx));
362   } else {
363     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
364            "Invalid file type!");
365     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
366     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
367                                                       Opts.CPU);
368     Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
369                                                 CE, *STI, Opts.RelaxAll,
370                                                 Opts.NoExecStack));
371     Str.get()->InitSections();
372   }
373 
374   std::unique_ptr<MCAsmParser> Parser(
375       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
376   std::unique_ptr<MCTargetAsmParser> TAP(
377       TheTarget->createMCAsmParser(*STI, *Parser, *MCII));
378   if (!TAP) {
379     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
380     return false;
381   }
382 
383   Parser->setTargetParser(*TAP.get());
384 
385   bool Success = !Parser->Run(Opts.NoInitialTextSection);
386 
387   // Close the output.
388   delete Out;
389 
390   // Delete output on errors.
391   if (!Success && Opts.OutputPath != "-")
392     sys::fs::remove(Opts.OutputPath);
393 
394   return Success;
395 }
396 
397 static void LLVMErrorHandler(void *UserData, const std::string &Message,
398                              bool GenCrashDiag) {
399   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
400 
401   Diags.Report(diag::err_fe_error_backend) << Message;
402 
403   // We cannot recover from llvm errors.
404   exit(1);
405 }
406 
407 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
408                const char *Argv0, void *MainAddr) {
409   // Print a stack trace if we signal out.
410   sys::PrintStackTraceOnErrorSignal();
411   PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
412   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
413 
414   // Initialize targets and assembly printers/parsers.
415   InitializeAllTargetInfos();
416   InitializeAllTargetMCs();
417   InitializeAllAsmParsers();
418 
419   // Construct our diagnostic client.
420   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
421   TextDiagnosticPrinter *DiagClient
422     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
423   DiagClient->setPrefix("clang -cc1as");
424   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
425   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
426 
427   // Set an error handler, so that any LLVM backend diagnostics go through our
428   // error handler.
429   ScopedFatalErrorHandler FatalErrorHandler
430     (LLVMErrorHandler, static_cast<void*>(&Diags));
431 
432   // Parse the arguments.
433   AssemblerInvocation Asm;
434   if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
435     return 1;
436 
437   // Honor -help.
438   if (Asm.ShowHelp) {
439     std::unique_ptr<OptTable> Opts(driver::createCC1AsOptTable());
440     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
441     return 0;
442   }
443 
444   // Honor -version.
445   //
446   // FIXME: Use a better -version message?
447   if (Asm.ShowVersion) {
448     llvm::cl::PrintVersionMessage();
449     return 0;
450   }
451 
452   // Honor -mllvm.
453   //
454   // FIXME: Remove this, one day.
455   if (!Asm.LLVMArgs.empty()) {
456     unsigned NumArgs = Asm.LLVMArgs.size();
457     const char **Args = new const char*[NumArgs + 2];
458     Args[0] = "clang (LLVM option parsing)";
459     for (unsigned i = 0; i != NumArgs; ++i)
460       Args[i + 1] = Asm.LLVMArgs[i].c_str();
461     Args[NumArgs + 1] = 0;
462     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
463   }
464 
465   // Execute the invocation, unless there were parsing errors.
466   bool Success = false;
467   if (!Diags.hasErrorOccurred())
468     Success = ExecuteAssembler(Asm, Diags);
469 
470   // If any timers were active but haven't been destroyed yet, print their
471   // results now.
472   TimerGroup::printAll(errs());
473 
474   return !Success;
475 }
476