blob: 0222f00dc6b881e1552a0117aa42643a7b1436d2 [file] [log] [blame]
Daniel Dunbar41b5b172010-05-20 17:49:16 +00001//===-- 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"
Duncan Sands2dc14532010-08-30 09:42:39 +000027#include "llvm/ADT/Triple.h"
Daniel Dunbar7374f1b2010-07-17 02:26:21 +000028#include "llvm/MC/MCParser/MCAsmParser.h"
29#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000030#include "llvm/MC/MCCodeEmitter.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCStreamer.h"
Daniel Dunbarc673af72010-05-20 18:15:20 +000033#include "llvm/Support/CommandLine.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000034#include "llvm/Support/FormattedStream.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ManagedStatic.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/PrettyStackTrace.h"
39#include "llvm/Support/SourceMgr.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000042#include "llvm/Support/Host.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000045#include "llvm/Support/system_error.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000046#include "llvm/Target/TargetAsmBackend.h"
Rafael Espindola7872d482010-12-10 07:40:14 +000047#include "llvm/Target/TargetAsmInfo.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000048#include "llvm/Target/TargetAsmParser.h"
49#include "llvm/Target/TargetData.h"
Rafael Espindola7872d482010-12-10 07:40:14 +000050#include "llvm/Target/TargetLowering.h"
51#include "llvm/Target/TargetLoweringObjectFile.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000052#include "llvm/Target/TargetMachine.h"
53#include "llvm/Target/TargetRegistry.h"
54#include "llvm/Target/TargetSelect.h"
55using namespace clang;
56using namespace clang::driver;
57using namespace llvm;
58
59namespace {
60
61/// \brief Helper class for representing a single invocation of the assembler.
62struct AssemblerInvocation {
63 /// @name Target Options
64 /// @{
65
66 std::string Triple;
67
68 /// @}
69 /// @name Language Options
70 /// @{
71
72 std::vector<std::string> IncludePaths;
73 unsigned NoInitialTextSection : 1;
Daniel Dunbar402adc32011-03-28 22:49:24 +000074 unsigned SaveTemporaryLabels : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000075
76 /// @}
77 /// @name Frontend Options
78 /// @{
79
80 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000081 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000082 std::string OutputPath;
83 enum FileType {
84 FT_Asm, ///< Assembly (.s) output, transliterate mode.
85 FT_Null, ///< No output, for timing purposes.
86 FT_Obj ///< Object file output.
87 };
88 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000089 unsigned ShowHelp : 1;
90 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000091
92 /// @}
93 /// @name Transliterate Options
94 /// @{
95
96 unsigned OutputAsmVariant;
97 unsigned ShowEncoding : 1;
98 unsigned ShowInst : 1;
99
100 /// @}
101 /// @name Assembler Options
102 /// @{
103
104 unsigned RelaxAll : 1;
Rafael Espindola3176cca2011-01-23 17:58:26 +0000105 unsigned NoExecStack : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000106
107 /// @}
108
109public:
110 AssemblerInvocation() {
111 Triple = "";
112 NoInitialTextSection = 0;
113 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000114 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000115 OutputType = FT_Asm;
116 OutputAsmVariant = 0;
117 ShowInst = 0;
118 ShowEncoding = 0;
119 RelaxAll = 0;
Rafael Espindola3176cca2011-01-23 17:58:26 +0000120 NoExecStack = 0;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000121 }
122
123 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
124 const char **ArgEnd, Diagnostic &Diags);
125};
126
127}
128
129void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
130 const char **ArgBegin,
131 const char **ArgEnd,
132 Diagnostic &Diags) {
133 using namespace clang::driver::cc1asoptions;
134 // Parse the arguments.
135 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
136 unsigned MissingArgIndex, MissingArgCount;
137 OwningPtr<InputArgList> Args(
138 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
139
140 // Check for missing argument error.
141 if (MissingArgCount)
142 Diags.Report(diag::err_drv_missing_argument)
143 << Args->getArgString(MissingArgIndex) << MissingArgCount;
144
145 // Issue errors on unknown arguments.
146 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
147 ie = Args->filtered_end(); it != ie; ++it)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000148 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000149
150 // Construct the invocation.
151
152 // Target Options
Duncan Sands2dc14532010-08-30 09:42:39 +0000153 Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000154 if (Opts.Triple.empty()) // Use the host triple if unspecified.
155 Opts.Triple = sys::getHostTriple();
156
157 // Language Options
158 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
159 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
Daniel Dunbar402adc32011-03-28 22:49:24 +0000160 Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000161
162 // Frontend Options
163 if (Args->hasArg(OPT_INPUT)) {
164 bool First = true;
165 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
166 ie = Args->filtered_end(); it != ie; ++it, First=false) {
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000167 const Arg *A = it;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000168 if (First)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000169 Opts.InputFile = A->getValue(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000170 else
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000171 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000172 }
173 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000174 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000175 Opts.OutputPath = Args->getLastArgValue(OPT_o);
176 if (Arg *A = Args->getLastArg(OPT_filetype)) {
177 StringRef Name = A->getValue(*Args);
178 unsigned OutputType = StringSwitch<unsigned>(Name)
179 .Case("asm", FT_Asm)
180 .Case("null", FT_Null)
181 .Case("obj", FT_Obj)
182 .Default(~0U);
183 if (OutputType == ~0U)
184 Diags.Report(diag::err_drv_invalid_value)
185 << A->getAsString(*Args) << Name;
186 else
187 Opts.OutputType = FileType(OutputType);
188 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000189 Opts.ShowHelp = Args->hasArg(OPT_help);
190 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000191
192 // Transliterate Options
193 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
194 0, Diags);
195 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
196 Opts.ShowInst = Args->hasArg(OPT_show_inst);
197
198 // Assemble Options
199 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
Rafael Espindola3176cca2011-01-23 17:58:26 +0000200 Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000201}
202
203static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
204 Diagnostic &Diags,
205 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000206 if (Opts.OutputPath.empty())
207 Opts.OutputPath = "-";
208
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000209 // Make sure that the Out file gets unlinked from the disk if we get a
210 // SIGINT.
211 if (Opts.OutputPath != "-")
212 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
213
214 std::string Error;
215 raw_fd_ostream *Out =
216 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
217 (Binary ? raw_fd_ostream::F_Binary : 0));
218 if (!Error.empty()) {
219 Diags.Report(diag::err_fe_unable_to_open_output)
220 << Opts.OutputPath << Error;
221 return 0;
222 }
223
224 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
225}
226
227static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
228 // Get the target specific parser.
229 std::string Error;
230 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
231 if (!TheTarget) {
232 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
233 return false;
234 }
235
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000236 OwningPtr<MemoryBuffer> BufferPtr;
237 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000238 Error = ec.message();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000239 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
240 return false;
241 }
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000242 MemoryBuffer *Buffer = BufferPtr.take();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000243
244 SourceMgr SrcMgr;
245
246 // Tell SrcMgr about this buffer, which is what the parser will pick up.
247 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
248
249 // Record the location of the include directories so that the lexer can find
250 // it later.
251 SrcMgr.setIncludeDirs(Opts.IncludePaths);
252
253 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
254 assert(MAI && "Unable to create target asm info!");
255
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000256 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
257 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
258 if (!Out)
259 return false;
260
261 // FIXME: We shouldn't need to do this (and link in codegen).
262 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
263 if (!TM) {
264 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
265 return false;
266 }
267
Rafael Espindola7872d482010-12-10 07:40:14 +0000268 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
269 MCContext Ctx(*MAI, tai);
Daniel Dunbar402adc32011-03-28 22:49:24 +0000270 if (Opts.SaveTemporaryLabels)
271 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola7872d482010-12-10 07:40:14 +0000272
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000273 OwningPtr<MCStreamer> Str;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000274
Rafael Espindola7872d482010-12-10 07:40:14 +0000275 const TargetLoweringObjectFile &TLOF =
276 TM->getTargetLowering()->getObjFileLowering();
277 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
278
Rafael Espindola3176cca2011-01-23 17:58:26 +0000279 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000280 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
281 MCInstPrinter *IP =
Bill Wendlingad3dfbe2011-03-21 05:02:03 +0000282 TheTarget->createMCInstPrinter(*TM, Opts.OutputAsmVariant, *MAI);
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000283 MCCodeEmitter *CE = 0;
Daniel Dunbar66cdf262010-12-16 03:06:05 +0000284 TargetAsmBackend *TAB = 0;
285 if (Opts.ShowEncoding) {
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000286 CE = TheTarget->createCodeEmitter(*TM, Ctx);
Daniel Dunbar66cdf262010-12-16 03:06:05 +0000287 TAB = TheTarget->createAsmBackend(Opts.Triple);
288 }
Rafael Espindola7872d482010-12-10 07:40:14 +0000289 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
Daniel Dunbar66cdf262010-12-16 03:06:05 +0000290 /*useLoc*/ true, IP, CE, TAB,
Rafael Espindola7872d482010-12-10 07:40:14 +0000291 Opts.ShowInst));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000292 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
293 Str.reset(createNullStreamer(Ctx));
294 } else {
295 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
296 "Invalid file type!");
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000297 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
298 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
299 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
Rafael Espindola3176cca2011-01-23 17:58:26 +0000300 CE, Opts.RelaxAll,
301 Opts.NoExecStack));
Rafael Espindola4f036fa2010-10-13 14:53:57 +0000302 Str.get()->InitSections();
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000303 }
304
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000305 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
306 *Str.get(), *MAI));
Daniel Dunbare9122a32010-07-19 00:33:53 +0000307 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000308 if (!TAP) {
309 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
310 return false;
311 }
312
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000313 Parser->setTargetParser(*TAP.get());
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000314
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000315 bool Success = !Parser->Run(Opts.NoInitialTextSection);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000316
317 // Close the output.
318 delete Out;
319
320 // Delete output on errors.
321 if (!Success && Opts.OutputPath != "-")
322 sys::Path(Opts.OutputPath).eraseFromDisk();
323
324 return Success;
325}
326
327static void LLVMErrorHandler(void *UserData, const std::string &Message) {
328 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
329
330 Diags.Report(diag::err_fe_error_backend) << Message;
331
332 // We cannot recover from llvm errors.
333 exit(1);
334}
335
336int cc1as_main(const char **ArgBegin, const char **ArgEnd,
337 const char *Argv0, void *MainAddr) {
338 // Print a stack trace if we signal out.
339 sys::PrintStackTraceOnErrorSignal();
340 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
341 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
342
343 // Initialize targets and assembly printers/parsers.
344 InitializeAllTargetInfos();
345 // FIXME: We shouldn't need to initialize the Target(Machine)s.
346 InitializeAllTargets();
347 InitializeAllAsmPrinters();
348 InitializeAllAsmParsers();
349
350 // Construct our diagnostic client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000351 TextDiagnosticPrinter *DiagClient
352 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
353 DiagClient->setPrefix("clang -cc1as");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000354 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
355 Diagnostic Diags(DiagID, DiagClient);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000356
357 // Set an error handler, so that any LLVM backend diagnostics go through our
358 // error handler.
Dan Gohman726578c2010-08-18 21:23:17 +0000359 ScopedFatalErrorHandler FatalErrorHandler
360 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000361
362 // Parse the arguments.
363 AssemblerInvocation Asm;
364 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
365
Daniel Dunbarc673af72010-05-20 18:15:20 +0000366 // Honor -help.
367 if (Asm.ShowHelp) {
368 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
369 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
370 return 0;
371 }
372
373 // Honor -version.
374 //
375 // FIXME: Use a better -version message?
376 if (Asm.ShowVersion) {
377 llvm::cl::PrintVersionMessage();
378 return 0;
379 }
380
381 // Honor -mllvm.
382 //
383 // FIXME: Remove this, one day.
384 if (!Asm.LLVMArgs.empty()) {
385 unsigned NumArgs = Asm.LLVMArgs.size();
386 const char **Args = new const char*[NumArgs + 2];
387 Args[0] = "clang (LLVM option parsing)";
388 for (unsigned i = 0; i != NumArgs; ++i)
389 Args[i + 1] = Asm.LLVMArgs[i].c_str();
390 Args[NumArgs + 1] = 0;
391 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
392 }
393
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000394 // Execute the invocation, unless there were parsing errors.
395 bool Success = false;
Argyrios Kyrtzidise8f0ba72010-11-19 00:19:18 +0000396 if (!Diags.hasErrorOccurred())
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000397 Success = ExecuteAssembler(Asm, Diags);
398
399 // If any timers were active but haven't been destroyed yet, print their
400 // results now.
401 TimerGroup::printAll(errs());
402
403 return !Success;
404}