blob: b8f2b687883dcc260af24898aeab770c1c4bd665 [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"
Daniel Dunbar7374f1b2010-07-17 02:26:21 +000027#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000029#include "llvm/MC/MCCodeEmitter.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCStreamer.h"
Daniel Dunbarc673af72010-05-20 18:15:20 +000032#include "llvm/Support/CommandLine.h"
Daniel Dunbar41b5b172010-05-20 17:49:16 +000033#include "llvm/Support/FormattedStream.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/ManagedStatic.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/PrettyStackTrace.h"
38#include "llvm/Support/SourceMgr.h"
39#include "llvm/Support/Timer.h"
40#include "llvm/Support/raw_ostream.h"
41#include "llvm/System/Host.h"
42#include "llvm/System/Path.h"
43#include "llvm/System/Signals.h"
44#include "llvm/Target/TargetAsmBackend.h"
45#include "llvm/Target/TargetAsmParser.h"
46#include "llvm/Target/TargetData.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Target/TargetRegistry.h"
49#include "llvm/Target/TargetSelect.h"
50using namespace clang;
51using namespace clang::driver;
52using namespace llvm;
53
54namespace {
55
56/// \brief Helper class for representing a single invocation of the assembler.
57struct AssemblerInvocation {
58 /// @name Target Options
59 /// @{
60
61 std::string Triple;
62
63 /// @}
64 /// @name Language Options
65 /// @{
66
67 std::vector<std::string> IncludePaths;
68 unsigned NoInitialTextSection : 1;
69
70 /// @}
71 /// @name Frontend Options
72 /// @{
73
74 std::string InputFile;
Daniel Dunbarc673af72010-05-20 18:15:20 +000075 std::vector<std::string> LLVMArgs;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000076 std::string OutputPath;
77 enum FileType {
78 FT_Asm, ///< Assembly (.s) output, transliterate mode.
79 FT_Null, ///< No output, for timing purposes.
80 FT_Obj ///< Object file output.
81 };
82 FileType OutputType;
Daniel Dunbarc673af72010-05-20 18:15:20 +000083 unsigned ShowHelp : 1;
84 unsigned ShowVersion : 1;
Daniel Dunbar41b5b172010-05-20 17:49:16 +000085
86 /// @}
87 /// @name Transliterate Options
88 /// @{
89
90 unsigned OutputAsmVariant;
91 unsigned ShowEncoding : 1;
92 unsigned ShowInst : 1;
93
94 /// @}
95 /// @name Assembler Options
96 /// @{
97
98 unsigned RelaxAll : 1;
99
100 /// @}
101
102public:
103 AssemblerInvocation() {
104 Triple = "";
105 NoInitialTextSection = 0;
106 InputFile = "-";
Daniel Dunbarc673af72010-05-20 18:15:20 +0000107 OutputPath = "-";
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000108 OutputType = FT_Asm;
109 OutputAsmVariant = 0;
110 ShowInst = 0;
111 ShowEncoding = 0;
112 RelaxAll = 0;
113 }
114
115 static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
116 const char **ArgEnd, Diagnostic &Diags);
117};
118
119}
120
121void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
122 const char **ArgBegin,
123 const char **ArgEnd,
124 Diagnostic &Diags) {
125 using namespace clang::driver::cc1asoptions;
126 // Parse the arguments.
127 OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
128 unsigned MissingArgIndex, MissingArgCount;
129 OwningPtr<InputArgList> Args(
130 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
131
132 // Check for missing argument error.
133 if (MissingArgCount)
134 Diags.Report(diag::err_drv_missing_argument)
135 << Args->getArgString(MissingArgIndex) << MissingArgCount;
136
137 // Issue errors on unknown arguments.
138 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
139 ie = Args->filtered_end(); it != ie; ++it)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000140 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000141
142 // Construct the invocation.
143
144 // Target Options
145 Opts.Triple = Args->getLastArgValue(OPT_triple);
146 if (Opts.Triple.empty()) // Use the host triple if unspecified.
147 Opts.Triple = sys::getHostTriple();
148
149 // Language Options
150 Opts.IncludePaths = Args->getAllArgValues(OPT_I);
151 Opts.NoInitialTextSection = Args->hasArg(OPT_n);
152
153 // Frontend Options
154 if (Args->hasArg(OPT_INPUT)) {
155 bool First = true;
156 for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
157 ie = Args->filtered_end(); it != ie; ++it, First=false) {
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000158 const Arg *A = it;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000159 if (First)
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000160 Opts.InputFile = A->getValue(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000161 else
Daniel Dunbar7e4953e2010-06-11 22:00:13 +0000162 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000163 }
164 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000165 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000166 Opts.OutputPath = Args->getLastArgValue(OPT_o);
167 if (Arg *A = Args->getLastArg(OPT_filetype)) {
168 StringRef Name = A->getValue(*Args);
169 unsigned OutputType = StringSwitch<unsigned>(Name)
170 .Case("asm", FT_Asm)
171 .Case("null", FT_Null)
172 .Case("obj", FT_Obj)
173 .Default(~0U);
174 if (OutputType == ~0U)
175 Diags.Report(diag::err_drv_invalid_value)
176 << A->getAsString(*Args) << Name;
177 else
178 Opts.OutputType = FileType(OutputType);
179 }
Daniel Dunbarc673af72010-05-20 18:15:20 +0000180 Opts.ShowHelp = Args->hasArg(OPT_help);
181 Opts.ShowVersion = Args->hasArg(OPT_version);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000182
183 // Transliterate Options
184 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
185 0, Diags);
186 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
187 Opts.ShowInst = Args->hasArg(OPT_show_inst);
188
189 // Assemble Options
190 Opts.RelaxAll = Args->hasArg(OPT_relax_all);
191}
192
193static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
194 Diagnostic &Diags,
195 bool Binary) {
Daniel Dunbarc673af72010-05-20 18:15:20 +0000196 if (Opts.OutputPath.empty())
197 Opts.OutputPath = "-";
198
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000199 // Make sure that the Out file gets unlinked from the disk if we get a
200 // SIGINT.
201 if (Opts.OutputPath != "-")
202 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
203
204 std::string Error;
205 raw_fd_ostream *Out =
206 new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
207 (Binary ? raw_fd_ostream::F_Binary : 0));
208 if (!Error.empty()) {
209 Diags.Report(diag::err_fe_unable_to_open_output)
210 << Opts.OutputPath << Error;
211 return 0;
212 }
213
214 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
215}
216
217static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
218 // Get the target specific parser.
219 std::string Error;
220 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
221 if (!TheTarget) {
222 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
223 return false;
224 }
225
226 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, &Error);
227 if (Buffer == 0) {
228 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
229 return false;
230 }
231
232 SourceMgr SrcMgr;
233
234 // Tell SrcMgr about this buffer, which is what the parser will pick up.
235 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
236
237 // Record the location of the include directories so that the lexer can find
238 // it later.
239 SrcMgr.setIncludeDirs(Opts.IncludePaths);
240
241 OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
242 assert(MAI && "Unable to create target asm info!");
243
244 MCContext Ctx(*MAI);
245 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
246 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
247 if (!Out)
248 return false;
249
250 // FIXME: We shouldn't need to do this (and link in codegen).
251 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
252 if (!TM) {
253 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
254 return false;
255 }
256
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000257 OwningPtr<MCStreamer> Str;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000258
259 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
260 MCInstPrinter *IP =
261 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000262 MCCodeEmitter *CE = 0;
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000263 if (Opts.ShowEncoding)
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000264 CE = TheTarget->createCodeEmitter(*TM, Ctx);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000265 Str.reset(createAsmStreamer(Ctx, *Out,TM->getTargetData()->isLittleEndian(),
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000266 /*asmverbose*/true, IP, CE, Opts.ShowInst));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000267 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
268 Str.reset(createNullStreamer(Ctx));
269 } else {
270 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
271 "Invalid file type!");
Benjamin Kramer7ac3d5a2010-07-29 17:48:03 +0000272 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
273 TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
274 Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
275 CE, Opts.RelaxAll));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000276 }
277
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000278 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
279 *Str.get(), *MAI));
Daniel Dunbare9122a32010-07-19 00:33:53 +0000280 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000281 if (!TAP) {
282 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
283 return false;
284 }
285
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000286 Parser->setTargetParser(*TAP.get());
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000287
Daniel Dunbar7374f1b2010-07-17 02:26:21 +0000288 bool Success = !Parser->Run(Opts.NoInitialTextSection);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000289
290 // Close the output.
291 delete Out;
292
293 // Delete output on errors.
294 if (!Success && Opts.OutputPath != "-")
295 sys::Path(Opts.OutputPath).eraseFromDisk();
296
297 return Success;
298}
299
300static void LLVMErrorHandler(void *UserData, const std::string &Message) {
301 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
302
303 Diags.Report(diag::err_fe_error_backend) << Message;
304
305 // We cannot recover from llvm errors.
306 exit(1);
307}
308
309int cc1as_main(const char **ArgBegin, const char **ArgEnd,
310 const char *Argv0, void *MainAddr) {
311 // Print a stack trace if we signal out.
312 sys::PrintStackTraceOnErrorSignal();
313 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
314 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
315
316 // Initialize targets and assembly printers/parsers.
317 InitializeAllTargetInfos();
318 // FIXME: We shouldn't need to initialize the Target(Machine)s.
319 InitializeAllTargets();
320 InitializeAllAsmPrinters();
321 InitializeAllAsmParsers();
322
323 // Construct our diagnostic client.
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000324 TextDiagnosticPrinter *DiagClient
325 = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
326 DiagClient->setPrefix("clang -cc1as");
327 Diagnostic Diags(DiagClient);
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000328
329 // Set an error handler, so that any LLVM backend diagnostics go through our
330 // error handler.
Dan Gohman726578c2010-08-18 21:23:17 +0000331 ScopedFatalErrorHandler FatalErrorHandler
332 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000333
334 // Parse the arguments.
335 AssemblerInvocation Asm;
336 AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
337
Daniel Dunbarc673af72010-05-20 18:15:20 +0000338 // Honor -help.
339 if (Asm.ShowHelp) {
340 llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
341 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
342 return 0;
343 }
344
345 // Honor -version.
346 //
347 // FIXME: Use a better -version message?
348 if (Asm.ShowVersion) {
349 llvm::cl::PrintVersionMessage();
350 return 0;
351 }
352
353 // Honor -mllvm.
354 //
355 // FIXME: Remove this, one day.
356 if (!Asm.LLVMArgs.empty()) {
357 unsigned NumArgs = Asm.LLVMArgs.size();
358 const char **Args = new const char*[NumArgs + 2];
359 Args[0] = "clang (LLVM option parsing)";
360 for (unsigned i = 0; i != NumArgs; ++i)
361 Args[i + 1] = Asm.LLVMArgs[i].c_str();
362 Args[NumArgs + 1] = 0;
363 llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
364 }
365
Daniel Dunbar41b5b172010-05-20 17:49:16 +0000366 // Execute the invocation, unless there were parsing errors.
367 bool Success = false;
368 if (!Diags.getNumErrors())
369 Success = ExecuteAssembler(Asm, Diags);
370
371 // If any timers were active but haven't been destroyed yet, print their
372 // results now.
373 TimerGroup::printAll(errs());
374
375 return !Success;
376}