]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/tools/driver/cc1as_main.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.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/Driver/Arg.h"
17 #include "clang/Driver/ArgList.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/CC1AsOptions.h"
20 #include "clang/Driver/OptTable.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Frontend/DiagnosticOptions.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/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCCodeEmitter.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/system_error.h"
48 #include "llvm/Target/TargetAsmBackend.h"
49 #include "llvm/Target/TargetAsmInfo.h"
50 #include "llvm/Target/TargetAsmParser.h"
51 #include "llvm/Target/TargetData.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetLoweringObjectFile.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Target/TargetRegistry.h"
57 #include "llvm/Target/TargetSelect.h"
58 #include "llvm/Target/TargetSubtargetInfo.h"
59 using namespace clang;
60 using namespace clang::driver;
61 using namespace llvm;
62
63 namespace {
64
65 /// \brief Helper class for representing a single invocation of the assembler.
66 struct AssemblerInvocation {
67   /// @name Target Options
68   /// @{
69
70   std::string Triple;
71
72   /// @}
73   /// @name Language Options
74   /// @{
75
76   std::vector<std::string> IncludePaths;
77   unsigned NoInitialTextSection : 1;
78   unsigned SaveTemporaryLabels : 1;
79
80   /// @}
81   /// @name Frontend Options
82   /// @{
83
84   std::string InputFile;
85   std::vector<std::string> LLVMArgs;
86   std::string OutputPath;
87   enum FileType {
88     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
89     FT_Null, ///< No output, for timing purposes.
90     FT_Obj   ///< Object file output.
91   };
92   FileType OutputType;
93   unsigned ShowHelp : 1;
94   unsigned ShowVersion : 1;
95
96   /// @}
97   /// @name Transliterate Options
98   /// @{
99
100   unsigned OutputAsmVariant;
101   unsigned ShowEncoding : 1;
102   unsigned ShowInst : 1;
103
104   /// @}
105   /// @name Assembler Options
106   /// @{
107
108   unsigned RelaxAll : 1;
109   unsigned NoExecStack : 1;
110
111   /// @}
112
113 public:
114   AssemblerInvocation() {
115     Triple = "";
116     NoInitialTextSection = 0;
117     InputFile = "-";
118     OutputPath = "-";
119     OutputType = FT_Asm;
120     OutputAsmVariant = 0;
121     ShowInst = 0;
122     ShowEncoding = 0;
123     RelaxAll = 0;
124     NoExecStack = 0;
125   }
126
127   static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
128                              const char **ArgEnd, Diagnostic &Diags);
129 };
130
131 }
132
133 void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
134                                          const char **ArgBegin,
135                                          const char **ArgEnd,
136                                          Diagnostic &Diags) {
137   using namespace clang::driver::cc1asoptions;
138   // Parse the arguments.
139   OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
140   unsigned MissingArgIndex, MissingArgCount;
141   OwningPtr<InputArgList> Args(
142     OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
143
144   // Check for missing argument error.
145   if (MissingArgCount)
146     Diags.Report(diag::err_drv_missing_argument)
147       << Args->getArgString(MissingArgIndex) << MissingArgCount;
148
149   // Issue errors on unknown arguments.
150   for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
151          ie = Args->filtered_end(); it != ie; ++it)
152     Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
153
154   // Construct the invocation.
155
156   // Target Options
157   Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
158   if (Opts.Triple.empty()) // Use the host triple if unspecified.
159     Opts.Triple = sys::getHostTriple();
160
161   // Language Options
162   Opts.IncludePaths = Args->getAllArgValues(OPT_I);
163   Opts.NoInitialTextSection = Args->hasArg(OPT_n);
164   Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
165
166   // Frontend Options
167   if (Args->hasArg(OPT_INPUT)) {
168     bool First = true;
169     for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
170            ie = Args->filtered_end(); it != ie; ++it, First=false) {
171       const Arg *A = it;
172       if (First)
173         Opts.InputFile = A->getValue(*Args);
174       else
175         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
176     }
177   }
178   Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
179   if (Args->hasArg(OPT_fatal_warnings))
180     Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
181   Opts.OutputPath = Args->getLastArgValue(OPT_o);
182   if (Arg *A = Args->getLastArg(OPT_filetype)) {
183     StringRef Name = A->getValue(*Args);
184     unsigned OutputType = StringSwitch<unsigned>(Name)
185       .Case("asm", FT_Asm)
186       .Case("null", FT_Null)
187       .Case("obj", FT_Obj)
188       .Default(~0U);
189     if (OutputType == ~0U)
190       Diags.Report(diag::err_drv_invalid_value)
191         << A->getAsString(*Args) << Name;
192     else
193       Opts.OutputType = FileType(OutputType);
194   }
195   Opts.ShowHelp = Args->hasArg(OPT_help);
196   Opts.ShowVersion = Args->hasArg(OPT_version);
197
198   // Transliterate Options
199   Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
200                                                    0, Diags);
201   Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
202   Opts.ShowInst = Args->hasArg(OPT_show_inst);
203
204   // Assemble Options
205   Opts.RelaxAll = Args->hasArg(OPT_relax_all);
206   Opts.NoExecStack =  Args->hasArg(OPT_no_exec_stack);
207 }
208
209 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
210                                               Diagnostic &Diags,
211                                               bool Binary) {
212   if (Opts.OutputPath.empty())
213     Opts.OutputPath = "-";
214
215   // Make sure that the Out file gets unlinked from the disk if we get a
216   // SIGINT.
217   if (Opts.OutputPath != "-")
218     sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
219
220   std::string Error;
221   raw_fd_ostream *Out =
222     new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
223                        (Binary ? raw_fd_ostream::F_Binary : 0));
224   if (!Error.empty()) {
225     Diags.Report(diag::err_fe_unable_to_open_output)
226       << Opts.OutputPath << Error;
227     return 0;
228   }
229
230   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
231 }
232
233 static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
234   // Get the target specific parser.
235   std::string Error;
236   const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
237   if (!TheTarget) {
238     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
239     return false;
240   }
241
242   OwningPtr<MemoryBuffer> BufferPtr;
243   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
244     Error = ec.message();
245     Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
246     return false;
247   }
248   MemoryBuffer *Buffer = BufferPtr.take();
249
250   SourceMgr SrcMgr;
251
252   // Tell SrcMgr about this buffer, which is what the parser will pick up.
253   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
254
255   // Record the location of the include directories so that the lexer can find
256   // it later.
257   SrcMgr.setIncludeDirs(Opts.IncludePaths);
258
259   OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));
260   assert(MAI && "Unable to create target asm info!");
261
262   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
263   formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
264   if (!Out)
265     return false;
266
267   // FIXME: We shouldn't need to do this (and link in codegen).
268   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple,
269                                                              "", ""));
270   if (!TM) {
271     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
272     return false;
273   }
274
275   const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
276   MCContext Ctx(*MAI, tai);
277   if (Opts.SaveTemporaryLabels)
278     Ctx.setAllowTemporaryLabels(false);
279
280   OwningPtr<MCStreamer> Str;
281
282   const TargetLoweringObjectFile &TLOF =
283     TM->getTargetLowering()->getObjFileLowering();
284   const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
285
286   const MCSubtargetInfo &STI = TM->getSubtarget<MCSubtargetInfo>();
287
288   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
289   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
290     MCInstPrinter *IP =
291       TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
292     MCCodeEmitter *CE = 0;
293     TargetAsmBackend *TAB = 0;
294     if (Opts.ShowEncoding) {
295       CE = TheTarget->createCodeEmitter(*TM->getInstrInfo(), STI, Ctx);
296       TAB = TheTarget->createAsmBackend(Opts.Triple);
297     }
298     Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
299                                            /*useLoc*/ true,
300                                            /*useCFI*/ true, IP, CE, TAB,
301                                            Opts.ShowInst));
302   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
303     Str.reset(createNullStreamer(Ctx));
304   } else {
305     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
306            "Invalid file type!");
307     MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM->getInstrInfo(),
308                                                      STI, Ctx);
309     TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
310     Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
311                                               CE, Opts.RelaxAll,
312                                               Opts.NoExecStack));
313     Str.get()->InitSections();
314   }
315
316   OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
317                                                   *Str.get(), *MAI));
318   OwningPtr<TargetAsmParser>
319     TAP(TheTarget->createAsmParser(const_cast<MCSubtargetInfo&>(STI), *Parser));
320   if (!TAP) {
321     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
322     return false;
323   }
324
325   Parser->setTargetParser(*TAP.get());
326
327   bool Success = !Parser->Run(Opts.NoInitialTextSection);
328
329   // Close the output.
330   delete Out;
331
332   // Delete output on errors.
333   if (!Success && Opts.OutputPath != "-")
334     sys::Path(Opts.OutputPath).eraseFromDisk();
335
336   return Success;
337 }
338
339 static void LLVMErrorHandler(void *UserData, const std::string &Message) {
340   Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
341
342   Diags.Report(diag::err_fe_error_backend) << Message;
343
344   // We cannot recover from llvm errors.
345   exit(1);
346 }
347
348 int cc1as_main(const char **ArgBegin, const char **ArgEnd,
349                const char *Argv0, void *MainAddr) {
350   // Print a stack trace if we signal out.
351   sys::PrintStackTraceOnErrorSignal();
352   PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
353   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
354
355   // Initialize targets and assembly printers/parsers.
356   InitializeAllTargetInfos();
357   // FIXME: We shouldn't need to initialize the Target(Machine)s.
358   InitializeAllTargets();
359   InitializeAllMCAsmInfos();
360   InitializeAllMCInstrInfos();
361   InitializeAllMCSubtargetInfos();
362   InitializeAllAsmPrinters();
363   InitializeAllAsmParsers();
364
365   // Construct our diagnostic client.
366   TextDiagnosticPrinter *DiagClient
367     = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
368   DiagClient->setPrefix("clang -cc1as");
369   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
370   Diagnostic Diags(DiagID, DiagClient);
371
372   // Set an error handler, so that any LLVM backend diagnostics go through our
373   // error handler.
374   ScopedFatalErrorHandler FatalErrorHandler
375     (LLVMErrorHandler, static_cast<void*>(&Diags));
376
377   // Parse the arguments.
378   AssemblerInvocation Asm;
379   AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
380
381   // Honor -help.
382   if (Asm.ShowHelp) {
383     llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
384     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
385     return 0;
386   }
387
388   // Honor -version.
389   //
390   // FIXME: Use a better -version message?
391   if (Asm.ShowVersion) {
392     llvm::cl::PrintVersionMessage();
393     return 0;
394   }
395
396   // Honor -mllvm.
397   //
398   // FIXME: Remove this, one day.
399   if (!Asm.LLVMArgs.empty()) {
400     unsigned NumArgs = Asm.LLVMArgs.size();
401     const char **Args = new const char*[NumArgs + 2];
402     Args[0] = "clang (LLVM option parsing)";
403     for (unsigned i = 0; i != NumArgs; ++i)
404       Args[i + 1] = Asm.LLVMArgs[i].c_str();
405     Args[NumArgs + 1] = 0;
406     llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
407   }
408
409   // Execute the invocation, unless there were parsing errors.
410   bool Success = false;
411   if (!Diags.hasErrorOccurred())
412     Success = ExecuteAssembler(Asm, Diags);
413
414   // If any timers were active but haven't been destroyed yet, print their
415   // results now.
416   TimerGroup::printAll(errs());
417
418   return !Success;
419 }