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