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