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