1 | //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This is the entry point to the clang -cc1as functionality, which implements |
10 | // the direct interface to the LLVM MC based assembler. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "clang/Basic/Diagnostic.h" |
15 | #include "clang/Basic/DiagnosticOptions.h" |
16 | #include "clang/Driver/DriverDiagnostic.h" |
17 | #include "clang/Driver/Options.h" |
18 | #include "clang/Frontend/FrontendDiagnostic.h" |
19 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
20 | #include "clang/Frontend/Utils.h" |
21 | #include "llvm/ADT/STLExtras.h" |
22 | #include "llvm/ADT/StringExtras.h" |
23 | #include "llvm/ADT/StringSwitch.h" |
24 | #include "llvm/IR/DataLayout.h" |
25 | #include "llvm/MC/MCAsmBackend.h" |
26 | #include "llvm/MC/MCAsmInfo.h" |
27 | #include "llvm/MC/MCCodeEmitter.h" |
28 | #include "llvm/MC/MCContext.h" |
29 | #include "llvm/MC/MCInstPrinter.h" |
30 | #include "llvm/MC/MCInstrInfo.h" |
31 | #include "llvm/MC/MCObjectFileInfo.h" |
32 | #include "llvm/MC/MCObjectWriter.h" |
33 | #include "llvm/MC/MCParser/MCAsmParser.h" |
34 | #include "llvm/MC/MCParser/MCTargetAsmParser.h" |
35 | #include "llvm/MC/MCRegisterInfo.h" |
36 | #include "llvm/MC/MCSectionMachO.h" |
37 | #include "llvm/MC/MCStreamer.h" |
38 | #include "llvm/MC/MCSubtargetInfo.h" |
39 | #include "llvm/MC/MCTargetOptions.h" |
40 | #include "llvm/MC/TargetRegistry.h" |
41 | #include "llvm/Option/Arg.h" |
42 | #include "llvm/Option/ArgList.h" |
43 | #include "llvm/Option/OptTable.h" |
44 | #include "llvm/Support/CommandLine.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include "llvm/Support/FileSystem.h" |
47 | #include "llvm/Support/FormattedStream.h" |
48 | #include "llvm/Support/MemoryBuffer.h" |
49 | #include "llvm/Support/Path.h" |
50 | #include "llvm/Support/Process.h" |
51 | #include "llvm/Support/Signals.h" |
52 | #include "llvm/Support/SourceMgr.h" |
53 | #include "llvm/Support/TargetSelect.h" |
54 | #include "llvm/Support/Timer.h" |
55 | #include "llvm/Support/raw_ostream.h" |
56 | #include "llvm/TargetParser/Host.h" |
57 | #include "llvm/TargetParser/Triple.h" |
58 | #include <memory> |
59 | #include <optional> |
60 | #include <system_error> |
61 | using namespace clang; |
62 | using namespace clang::driver; |
63 | using namespace clang::driver::options; |
64 | using namespace llvm; |
65 | using namespace llvm::opt; |
66 | |
67 | namespace { |
68 | |
69 | /// Helper class for representing a single invocation of the assembler. |
70 | struct AssemblerInvocation { |
71 | /// @name Target Options |
72 | /// @{ |
73 | |
74 | /// The name of the target triple to assemble for. |
75 | std::string Triple; |
76 | |
77 | /// If given, the name of the target CPU to determine which instructions |
78 | /// are legal. |
79 | std::string CPU; |
80 | |
81 | /// The list of target specific features to enable or disable -- this should |
82 | /// be a list of strings starting with '+' or '-'. |
83 | std::vector<std::string> Features; |
84 | |
85 | /// The list of symbol definitions. |
86 | std::vector<std::string> SymbolDefs; |
87 | |
88 | /// @} |
89 | /// @name Language Options |
90 | /// @{ |
91 | |
92 | std::vector<std::string> IncludePaths; |
93 | LLVM_PREFERRED_TYPE(bool) |
94 | unsigned NoInitialTextSection : 1; |
95 | LLVM_PREFERRED_TYPE(bool) |
96 | unsigned SaveTemporaryLabels : 1; |
97 | LLVM_PREFERRED_TYPE(bool) |
98 | unsigned GenDwarfForAssembly : 1; |
99 | LLVM_PREFERRED_TYPE(bool) |
100 | unsigned Dwarf64 : 1; |
101 | unsigned DwarfVersion; |
102 | std::string DwarfDebugFlags; |
103 | std::string DwarfDebugProducer; |
104 | std::string DebugCompilationDir; |
105 | llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap; |
106 | llvm::DebugCompressionType CompressDebugSections = |
107 | llvm::DebugCompressionType::None; |
108 | std::string MainFileName; |
109 | std::string SplitDwarfOutput; |
110 | |
111 | /// @} |
112 | /// @name Frontend Options |
113 | /// @{ |
114 | |
115 | std::string InputFile; |
116 | std::vector<std::string> LLVMArgs; |
117 | std::string OutputPath; |
118 | enum FileType { |
119 | FT_Asm, ///< Assembly (.s) output, transliterate mode. |
120 | FT_Null, ///< No output, for timing purposes. |
121 | FT_Obj ///< Object file output. |
122 | }; |
123 | FileType OutputType; |
124 | LLVM_PREFERRED_TYPE(bool) |
125 | unsigned ShowHelp : 1; |
126 | LLVM_PREFERRED_TYPE(bool) |
127 | unsigned ShowVersion : 1; |
128 | |
129 | /// @} |
130 | /// @name Transliterate Options |
131 | /// @{ |
132 | |
133 | unsigned OutputAsmVariant; |
134 | LLVM_PREFERRED_TYPE(bool) |
135 | unsigned ShowEncoding : 1; |
136 | LLVM_PREFERRED_TYPE(bool) |
137 | unsigned ShowInst : 1; |
138 | |
139 | /// @} |
140 | /// @name Assembler Options |
141 | /// @{ |
142 | |
143 | LLVM_PREFERRED_TYPE(bool) |
144 | unsigned RelaxAll : 1; |
145 | LLVM_PREFERRED_TYPE(bool) |
146 | unsigned NoExecStack : 1; |
147 | LLVM_PREFERRED_TYPE(bool) |
148 | unsigned FatalWarnings : 1; |
149 | LLVM_PREFERRED_TYPE(bool) |
150 | unsigned NoWarn : 1; |
151 | LLVM_PREFERRED_TYPE(bool) |
152 | unsigned NoTypeCheck : 1; |
153 | LLVM_PREFERRED_TYPE(bool) |
154 | unsigned IncrementalLinkerCompatible : 1; |
155 | LLVM_PREFERRED_TYPE(bool) |
156 | unsigned EmbedBitcode : 1; |
157 | |
158 | /// Whether to emit DWARF unwind info. |
159 | EmitDwarfUnwindType EmitDwarfUnwind; |
160 | |
161 | // Whether to emit compact-unwind for non-canonical entries. |
162 | // Note: maybe overriden by other constraints. |
163 | LLVM_PREFERRED_TYPE(bool) |
164 | unsigned EmitCompactUnwindNonCanonical : 1; |
165 | |
166 | LLVM_PREFERRED_TYPE(bool) |
167 | unsigned Crel : 1; |
168 | LLVM_PREFERRED_TYPE(bool) |
169 | unsigned ImplicitMapsyms : 1; |
170 | |
171 | LLVM_PREFERRED_TYPE(bool) |
172 | unsigned X86RelaxRelocations : 1; |
173 | LLVM_PREFERRED_TYPE(bool) |
174 | unsigned X86Sse2Avx : 1; |
175 | |
176 | /// The name of the relocation model to use. |
177 | std::string RelocationModel; |
178 | |
179 | /// The ABI targeted by the backend. Specified using -target-abi. Empty |
180 | /// otherwise. |
181 | std::string TargetABI; |
182 | |
183 | /// Darwin target variant triple, the variant of the deployment target |
184 | /// for which the code is being compiled. |
185 | std::optional<llvm::Triple> DarwinTargetVariantTriple; |
186 | |
187 | /// The version of the darwin target variant SDK which was used during the |
188 | /// compilation |
189 | llvm::VersionTuple DarwinTargetVariantSDKVersion; |
190 | |
191 | /// The name of a file to use with \c .secure_log_unique directives. |
192 | std::string AsSecureLogFile; |
193 | /// @} |
194 | |
195 | public: |
196 | AssemblerInvocation() { |
197 | Triple = "" ; |
198 | NoInitialTextSection = 0; |
199 | InputFile = "-" ; |
200 | OutputPath = "-" ; |
201 | OutputType = FT_Asm; |
202 | OutputAsmVariant = 0; |
203 | ShowInst = 0; |
204 | ShowEncoding = 0; |
205 | RelaxAll = 0; |
206 | NoExecStack = 0; |
207 | FatalWarnings = 0; |
208 | NoWarn = 0; |
209 | NoTypeCheck = 0; |
210 | IncrementalLinkerCompatible = 0; |
211 | Dwarf64 = 0; |
212 | DwarfVersion = 0; |
213 | EmbedBitcode = 0; |
214 | EmitDwarfUnwind = EmitDwarfUnwindType::Default; |
215 | EmitCompactUnwindNonCanonical = false; |
216 | Crel = false; |
217 | ImplicitMapsyms = 0; |
218 | X86RelaxRelocations = 0; |
219 | X86Sse2Avx = 0; |
220 | } |
221 | |
222 | static bool CreateFromArgs(AssemblerInvocation &Res, |
223 | ArrayRef<const char *> Argv, |
224 | DiagnosticsEngine &Diags); |
225 | }; |
226 | |
227 | } |
228 | |
229 | bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts, |
230 | ArrayRef<const char *> Argv, |
231 | DiagnosticsEngine &Diags) { |
232 | bool Success = true; |
233 | |
234 | // Parse the arguments. |
235 | const OptTable &OptTbl = getDriverOptTable(); |
236 | |
237 | llvm::opt::Visibility VisibilityMask(options::CC1AsOption); |
238 | unsigned MissingArgIndex, MissingArgCount; |
239 | InputArgList Args = |
240 | OptTbl.ParseArgs(Args: Argv, MissingArgIndex, MissingArgCount, VisibilityMask); |
241 | |
242 | // Check for missing argument error. |
243 | if (MissingArgCount) { |
244 | Diags.Report(diag::err_drv_missing_argument) |
245 | << Args.getArgString(Index: MissingArgIndex) << MissingArgCount; |
246 | Success = false; |
247 | } |
248 | |
249 | // Issue errors on unknown arguments. |
250 | for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { |
251 | auto ArgString = A->getAsString(Args); |
252 | std::string Nearest; |
253 | if (OptTbl.findNearest(ArgString, Nearest, VisibilityMask) > 1) |
254 | Diags.Report(diag::err_drv_unknown_argument) << ArgString; |
255 | else |
256 | Diags.Report(diag::err_drv_unknown_argument_with_suggestion) |
257 | << ArgString << Nearest; |
258 | Success = false; |
259 | } |
260 | |
261 | // Construct the invocation. |
262 | |
263 | // Target Options |
264 | Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(Id: OPT_triple)); |
265 | if (Arg *A = Args.getLastArg(options::OPT_darwin_target_variant_triple)) |
266 | Opts.DarwinTargetVariantTriple = llvm::Triple(A->getValue()); |
267 | if (Arg *A = Args.getLastArg(OPT_darwin_target_variant_sdk_version_EQ)) { |
268 | VersionTuple Version; |
269 | if (Version.tryParse(string: A->getValue())) |
270 | Diags.Report(diag::err_drv_invalid_value) |
271 | << A->getAsString(Args) << A->getValue(); |
272 | else |
273 | Opts.DarwinTargetVariantSDKVersion = Version; |
274 | } |
275 | |
276 | Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu)); |
277 | Opts.Features = Args.getAllArgValues(Id: OPT_target_feature); |
278 | |
279 | // Use the default target triple if unspecified. |
280 | if (Opts.Triple.empty()) |
281 | Opts.Triple = llvm::sys::getDefaultTargetTriple(); |
282 | |
283 | // Language Options |
284 | Opts.IncludePaths = Args.getAllArgValues(Id: OPT_I); |
285 | Opts.NoInitialTextSection = Args.hasArg(OPT_n); |
286 | Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels); |
287 | // Any DebugInfoKind implies GenDwarfForAssembly. |
288 | Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ); |
289 | |
290 | if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) { |
291 | Opts.CompressDebugSections = |
292 | llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue()) |
293 | .Case(S: "none" , Value: llvm::DebugCompressionType::None) |
294 | .Case(S: "zlib" , Value: llvm::DebugCompressionType::Zlib) |
295 | .Case(S: "zstd" , Value: llvm::DebugCompressionType::Zstd) |
296 | .Default(Value: llvm::DebugCompressionType::None); |
297 | } |
298 | |
299 | if (auto *DwarfFormatArg = Args.getLastArg(OPT_gdwarf64, OPT_gdwarf32)) |
300 | Opts.Dwarf64 = DwarfFormatArg->getOption().matches(OPT_gdwarf64); |
301 | Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags); |
302 | Opts.DwarfDebugFlags = |
303 | std::string(Args.getLastArgValue(OPT_dwarf_debug_flags)); |
304 | Opts.DwarfDebugProducer = |
305 | std::string(Args.getLastArgValue(OPT_dwarf_debug_producer)); |
306 | if (const Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ, |
307 | options::OPT_fdebug_compilation_dir_EQ)) |
308 | Opts.DebugCompilationDir = A->getValue(); |
309 | Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name)); |
310 | |
311 | for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { |
312 | auto Split = StringRef(Arg).split('='); |
313 | Opts.DebugPrefixMap.emplace_back(Split.first, Split.second); |
314 | } |
315 | |
316 | // Frontend Options |
317 | if (Args.hasArg(OPT_INPUT)) { |
318 | bool First = true; |
319 | for (const Arg *A : Args.filtered(OPT_INPUT)) { |
320 | if (First) { |
321 | Opts.InputFile = A->getValue(); |
322 | First = false; |
323 | } else { |
324 | Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args); |
325 | Success = false; |
326 | } |
327 | } |
328 | } |
329 | Opts.LLVMArgs = Args.getAllArgValues(Id: OPT_mllvm); |
330 | Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o)); |
331 | Opts.SplitDwarfOutput = |
332 | std::string(Args.getLastArgValue(OPT_split_dwarf_output)); |
333 | if (Arg *A = Args.getLastArg(OPT_filetype)) { |
334 | StringRef Name = A->getValue(); |
335 | unsigned OutputType = StringSwitch<unsigned>(Name) |
336 | .Case(S: "asm" , Value: FT_Asm) |
337 | .Case(S: "null" , Value: FT_Null) |
338 | .Case(S: "obj" , Value: FT_Obj) |
339 | .Default(Value: ~0U); |
340 | if (OutputType == ~0U) { |
341 | Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; |
342 | Success = false; |
343 | } else |
344 | Opts.OutputType = FileType(OutputType); |
345 | } |
346 | Opts.ShowHelp = Args.hasArg(OPT_help); |
347 | Opts.ShowVersion = Args.hasArg(OPT_version); |
348 | |
349 | // Transliterate Options |
350 | Opts.OutputAsmVariant = |
351 | getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags); |
352 | Opts.ShowEncoding = Args.hasArg(OPT_show_encoding); |
353 | Opts.ShowInst = Args.hasArg(OPT_show_inst); |
354 | |
355 | // Assemble Options |
356 | Opts.RelaxAll = Args.hasArg(OPT_mrelax_all); |
357 | Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); |
358 | Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); |
359 | Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn); |
360 | Opts.NoTypeCheck = Args.hasArg(OPT_mno_type_check); |
361 | Opts.RelocationModel = |
362 | std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic" )); |
363 | Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi)); |
364 | Opts.IncrementalLinkerCompatible = |
365 | Args.hasArg(OPT_mincremental_linker_compatible); |
366 | Opts.SymbolDefs = Args.getAllArgValues(Id: OPT_defsym); |
367 | |
368 | // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag. |
369 | // EmbedBitcode behaves the same for all embed options for assembly files. |
370 | if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) { |
371 | Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue()) |
372 | .Case(S: "all" , Value: 1) |
373 | .Case(S: "bitcode" , Value: 1) |
374 | .Case(S: "marker" , Value: 1) |
375 | .Default(Value: 0); |
376 | } |
377 | |
378 | if (auto *A = Args.getLastArg(OPT_femit_dwarf_unwind_EQ)) { |
379 | Opts.EmitDwarfUnwind = |
380 | llvm::StringSwitch<EmitDwarfUnwindType>(A->getValue()) |
381 | .Case(S: "always" , Value: EmitDwarfUnwindType::Always) |
382 | .Case(S: "no-compact-unwind" , Value: EmitDwarfUnwindType::NoCompactUnwind) |
383 | .Case(S: "default" , Value: EmitDwarfUnwindType::Default); |
384 | } |
385 | |
386 | Opts.EmitCompactUnwindNonCanonical = |
387 | Args.hasArg(OPT_femit_compact_unwind_non_canonical); |
388 | Opts.Crel = Args.hasArg(OPT_crel); |
389 | Opts.ImplicitMapsyms = Args.hasArg(OPT_mmapsyms_implicit); |
390 | Opts.X86RelaxRelocations = !Args.hasArg(OPT_mrelax_relocations_no); |
391 | Opts.X86Sse2Avx = Args.hasArg(OPT_msse2avx); |
392 | |
393 | Opts.AsSecureLogFile = Args.getLastArgValue(OPT_as_secure_log_file); |
394 | |
395 | return Success; |
396 | } |
397 | |
398 | static std::unique_ptr<raw_fd_ostream> |
399 | getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) { |
400 | // Make sure that the Out file gets unlinked from the disk if we get a |
401 | // SIGINT. |
402 | if (Path != "-" ) |
403 | sys::RemoveFileOnSignal(Filename: Path); |
404 | |
405 | std::error_code EC; |
406 | auto Out = std::make_unique<raw_fd_ostream>( |
407 | args&: Path, args&: EC, args: (Binary ? sys::fs::OF_None : sys::fs::OF_TextWithCRLF)); |
408 | if (EC) { |
409 | Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); |
410 | return nullptr; |
411 | } |
412 | |
413 | return Out; |
414 | } |
415 | |
416 | static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts, |
417 | DiagnosticsEngine &Diags) { |
418 | // Get the target specific parser. |
419 | std::string Error; |
420 | const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr: Opts.Triple, Error); |
421 | if (!TheTarget) |
422 | return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; |
423 | |
424 | ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = |
425 | MemoryBuffer::getFileOrSTDIN(Filename: Opts.InputFile, /*IsText=*/true); |
426 | |
427 | if (std::error_code EC = Buffer.getError()) { |
428 | return Diags.Report(diag::err_fe_error_reading) |
429 | << Opts.InputFile << EC.message(); |
430 | } |
431 | |
432 | SourceMgr SrcMgr; |
433 | |
434 | // Tell SrcMgr about this buffer, which is what the parser will pick up. |
435 | unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(F: std::move(*Buffer), IncludeLoc: SMLoc()); |
436 | |
437 | // Record the location of the include directories so that the lexer can find |
438 | // it later. |
439 | SrcMgr.setIncludeDirs(Opts.IncludePaths); |
440 | |
441 | std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: Opts.Triple)); |
442 | assert(MRI && "Unable to create target register info!" ); |
443 | |
444 | MCTargetOptions MCOptions; |
445 | MCOptions.MCRelaxAll = Opts.RelaxAll; |
446 | MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind; |
447 | MCOptions.EmitCompactUnwindNonCanonical = Opts.EmitCompactUnwindNonCanonical; |
448 | MCOptions.MCSaveTempLabels = Opts.SaveTemporaryLabels; |
449 | MCOptions.Crel = Opts.Crel; |
450 | MCOptions.ImplicitMapSyms = Opts.ImplicitMapsyms; |
451 | MCOptions.X86RelaxRelocations = Opts.X86RelaxRelocations; |
452 | MCOptions.X86Sse2Avx = Opts.X86Sse2Avx; |
453 | MCOptions.CompressDebugSections = Opts.CompressDebugSections; |
454 | MCOptions.AsSecureLogFile = Opts.AsSecureLogFile; |
455 | |
456 | std::unique_ptr<MCAsmInfo> MAI( |
457 | TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple: Opts.Triple, Options: MCOptions)); |
458 | assert(MAI && "Unable to create target asm info!" ); |
459 | |
460 | // Ensure MCAsmInfo initialization occurs before any use, otherwise sections |
461 | // may be created with a combination of default and explicit settings. |
462 | |
463 | |
464 | bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; |
465 | if (Opts.OutputPath.empty()) |
466 | Opts.OutputPath = "-" ; |
467 | std::unique_ptr<raw_fd_ostream> FDOS = |
468 | getOutputStream(Path: Opts.OutputPath, Diags, Binary: IsBinary); |
469 | if (!FDOS) |
470 | return true; |
471 | std::unique_ptr<raw_fd_ostream> DwoOS; |
472 | if (!Opts.SplitDwarfOutput.empty()) |
473 | DwoOS = getOutputStream(Path: Opts.SplitDwarfOutput, Diags, Binary: IsBinary); |
474 | |
475 | // Build up the feature string from the target feature list. |
476 | std::string FS = llvm::join(R&: Opts.Features, Separator: "," ); |
477 | |
478 | std::unique_ptr<MCSubtargetInfo> STI( |
479 | TheTarget->createMCSubtargetInfo(TheTriple: Opts.Triple, CPU: Opts.CPU, Features: FS)); |
480 | assert(STI && "Unable to create subtarget info!" ); |
481 | |
482 | MCContext Ctx(Triple(Opts.Triple), MAI.get(), MRI.get(), STI.get(), &SrcMgr, |
483 | &MCOptions); |
484 | |
485 | bool PIC = false; |
486 | if (Opts.RelocationModel == "static" ) { |
487 | PIC = false; |
488 | } else if (Opts.RelocationModel == "pic" ) { |
489 | PIC = true; |
490 | } else { |
491 | assert(Opts.RelocationModel == "dynamic-no-pic" && |
492 | "Invalid PIC model!" ); |
493 | PIC = false; |
494 | } |
495 | |
496 | // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and |
497 | // MCObjectFileInfo needs a MCContext reference in order to initialize itself. |
498 | std::unique_ptr<MCObjectFileInfo> MOFI( |
499 | TheTarget->createMCObjectFileInfo(Ctx, PIC)); |
500 | Ctx.setObjectFileInfo(MOFI.get()); |
501 | |
502 | if (Opts.GenDwarfForAssembly) |
503 | Ctx.setGenDwarfForAssembly(true); |
504 | if (!Opts.DwarfDebugFlags.empty()) |
505 | Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags)); |
506 | if (!Opts.DwarfDebugProducer.empty()) |
507 | Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer)); |
508 | if (!Opts.DebugCompilationDir.empty()) |
509 | Ctx.setCompilationDir(Opts.DebugCompilationDir); |
510 | else { |
511 | // If no compilation dir is set, try to use the current directory. |
512 | SmallString<128> CWD; |
513 | if (!sys::fs::current_path(result&: CWD)) |
514 | Ctx.setCompilationDir(CWD); |
515 | } |
516 | if (!Opts.DebugPrefixMap.empty()) |
517 | for (const auto &KV : Opts.DebugPrefixMap) |
518 | Ctx.addDebugPrefixMapEntry(From: KV.first, To: KV.second); |
519 | if (!Opts.MainFileName.empty()) |
520 | Ctx.setMainFileName(StringRef(Opts.MainFileName)); |
521 | Ctx.setDwarfFormat(Opts.Dwarf64 ? dwarf::DWARF64 : dwarf::DWARF32); |
522 | Ctx.setDwarfVersion(Opts.DwarfVersion); |
523 | if (Opts.GenDwarfForAssembly) |
524 | Ctx.setGenDwarfRootFile(FileName: Opts.InputFile, |
525 | Buffer: SrcMgr.getMemoryBuffer(i: BufferIndex)->getBuffer()); |
526 | |
527 | std::unique_ptr<MCStreamer> Str; |
528 | |
529 | std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); |
530 | assert(MCII && "Unable to create instruction info!" ); |
531 | |
532 | raw_pwrite_stream *Out = FDOS.get(); |
533 | std::unique_ptr<buffer_ostream> BOS; |
534 | |
535 | MCOptions.MCNoWarn = Opts.NoWarn; |
536 | MCOptions.MCFatalWarnings = Opts.FatalWarnings; |
537 | MCOptions.MCNoTypeCheck = Opts.NoTypeCheck; |
538 | MCOptions.ShowMCInst = Opts.ShowInst; |
539 | MCOptions.AsmVerbose = true; |
540 | MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory; |
541 | MCOptions.ABIName = Opts.TargetABI; |
542 | |
543 | // FIXME: There is a bit of code duplication with addPassesToEmitFile. |
544 | if (Opts.OutputType == AssemblerInvocation::FT_Asm) { |
545 | std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( |
546 | T: llvm::Triple(Opts.Triple), SyntaxVariant: Opts.OutputAsmVariant, MAI: *MAI, MII: *MCII, MRI: *MRI)); |
547 | |
548 | std::unique_ptr<MCCodeEmitter> CE; |
549 | if (Opts.ShowEncoding) |
550 | CE.reset(p: TheTarget->createMCCodeEmitter(II: *MCII, Ctx)); |
551 | std::unique_ptr<MCAsmBackend> MAB( |
552 | TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions)); |
553 | |
554 | auto FOut = std::make_unique<formatted_raw_ostream>(args&: *Out); |
555 | Str.reset(p: TheTarget->createAsmStreamer(Ctx, OS: std::move(FOut), IP: std::move(IP), |
556 | CE: std::move(CE), TAB: std::move(MAB))); |
557 | } else if (Opts.OutputType == AssemblerInvocation::FT_Null) { |
558 | Str.reset(p: createNullStreamer(Ctx)); |
559 | } else { |
560 | assert(Opts.OutputType == AssemblerInvocation::FT_Obj && |
561 | "Invalid file type!" ); |
562 | if (!FDOS->supportsSeeking()) { |
563 | BOS = std::make_unique<buffer_ostream>(args&: *FDOS); |
564 | Out = BOS.get(); |
565 | } |
566 | |
567 | std::unique_ptr<MCCodeEmitter> CE( |
568 | TheTarget->createMCCodeEmitter(II: *MCII, Ctx)); |
569 | std::unique_ptr<MCAsmBackend> MAB( |
570 | TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions)); |
571 | assert(MAB && "Unable to create asm backend!" ); |
572 | |
573 | std::unique_ptr<MCObjectWriter> OW = |
574 | DwoOS ? MAB->createDwoObjectWriter(OS&: *Out, DwoOS&: *DwoOS) |
575 | : MAB->createObjectWriter(OS&: *Out); |
576 | |
577 | Triple T(Opts.Triple); |
578 | Str.reset(p: TheTarget->createMCObjectStreamer( |
579 | T, Ctx, TAB: std::move(MAB), OW: std::move(OW), Emitter: std::move(CE), STI: *STI)); |
580 | Str->initSections(NoExecStack: Opts.NoExecStack, STI: *STI); |
581 | if (T.isOSBinFormatMachO() && T.isOSDarwin()) { |
582 | Triple *TVT = Opts.DarwinTargetVariantTriple |
583 | ? &*Opts.DarwinTargetVariantTriple |
584 | : nullptr; |
585 | Str->emitVersionForTarget(Target: T, SDKVersion: VersionTuple(), DarwinTargetVariantTriple: TVT, |
586 | DarwinTargetVariantSDKVersion: Opts.DarwinTargetVariantSDKVersion); |
587 | } |
588 | } |
589 | |
590 | // When -fembed-bitcode is passed to clang_as, a 1-byte marker |
591 | // is emitted in __LLVM,__asm section if the object file is MachO format. |
592 | if (Opts.EmbedBitcode && Ctx.getObjectFileType() == MCContext::IsMachO) { |
593 | MCSection *AsmLabel = Ctx.getMachOSection( |
594 | Segment: "__LLVM" , Section: "__asm" , TypeAndAttributes: MachO::S_REGULAR, Reserved2: 4, K: SectionKind::getReadOnly()); |
595 | Str->switchSection(Section: AsmLabel); |
596 | Str->emitZeros(NumBytes: 1); |
597 | } |
598 | |
599 | bool Failed = false; |
600 | |
601 | std::unique_ptr<MCAsmParser> Parser( |
602 | createMCAsmParser(SrcMgr, Ctx, *Str, *MAI)); |
603 | |
604 | // FIXME: init MCTargetOptions from sanitizer flags here. |
605 | std::unique_ptr<MCTargetAsmParser> TAP( |
606 | TheTarget->createMCAsmParser(STI: *STI, Parser&: *Parser, MII: *MCII, Options: MCOptions)); |
607 | if (!TAP) |
608 | Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; |
609 | |
610 | // Set values for symbols, if any. |
611 | for (auto &S : Opts.SymbolDefs) { |
612 | auto Pair = StringRef(S).split(Separator: '='); |
613 | auto Sym = Pair.first; |
614 | auto Val = Pair.second; |
615 | int64_t Value; |
616 | // We have already error checked this in the driver. |
617 | Val.getAsInteger(Radix: 0, Result&: Value); |
618 | Ctx.setSymbolValue(Streamer&: Parser->getStreamer(), Sym, Val: Value); |
619 | } |
620 | |
621 | if (!Failed) { |
622 | Parser->setTargetParser(*TAP); |
623 | Failed = Parser->Run(NoInitialTextSection: Opts.NoInitialTextSection); |
624 | } |
625 | |
626 | return Failed; |
627 | } |
628 | |
629 | static bool ExecuteAssembler(AssemblerInvocation &Opts, |
630 | DiagnosticsEngine &Diags) { |
631 | bool Failed = ExecuteAssemblerImpl(Opts, Diags); |
632 | |
633 | // Delete output file if there were errors. |
634 | if (Failed) { |
635 | if (Opts.OutputPath != "-" ) |
636 | sys::fs::remove(path: Opts.OutputPath); |
637 | if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-" ) |
638 | sys::fs::remove(path: Opts.SplitDwarfOutput); |
639 | } |
640 | |
641 | return Failed; |
642 | } |
643 | |
644 | static void LLVMErrorHandler(void *UserData, const char *Message, |
645 | bool GenCrashDiag) { |
646 | DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); |
647 | |
648 | Diags.Report(diag::err_fe_error_backend) << Message; |
649 | |
650 | // We cannot recover from llvm errors. |
651 | sys::Process::Exit(RetCode: 1); |
652 | } |
653 | |
654 | int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { |
655 | // Initialize targets and assembly printers/parsers. |
656 | InitializeAllTargetInfos(); |
657 | InitializeAllTargetMCs(); |
658 | InitializeAllAsmParsers(); |
659 | |
660 | // Construct our diagnostic client. |
661 | DiagnosticOptions DiagOpts; |
662 | TextDiagnosticPrinter *DiagClient = |
663 | new TextDiagnosticPrinter(errs(), DiagOpts); |
664 | DiagClient->setPrefix("clang -cc1as" ); |
665 | IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); |
666 | DiagnosticsEngine Diags(DiagID, DiagOpts, DiagClient); |
667 | |
668 | // Set an error handler, so that any LLVM backend diagnostics go through our |
669 | // error handler. |
670 | ScopedFatalErrorHandler FatalErrorHandler |
671 | (LLVMErrorHandler, static_cast<void*>(&Diags)); |
672 | |
673 | // Parse the arguments. |
674 | AssemblerInvocation Asm; |
675 | if (!AssemblerInvocation::CreateFromArgs(Opts&: Asm, Argv, Diags)) |
676 | return 1; |
677 | |
678 | if (Asm.ShowHelp) { |
679 | getDriverOptTable().printHelp( |
680 | OS&: llvm::outs(), Usage: "clang -cc1as [options] file..." , |
681 | Title: "Clang Integrated Assembler" , /*ShowHidden=*/false, |
682 | /*ShowAllAliases=*/false, |
683 | VisibilityMask: llvm::opt::Visibility(driver::options::CC1AsOption)); |
684 | |
685 | return 0; |
686 | } |
687 | |
688 | // Honor -version. |
689 | // |
690 | // FIXME: Use a better -version message? |
691 | if (Asm.ShowVersion) { |
692 | llvm::cl::PrintVersionMessage(); |
693 | return 0; |
694 | } |
695 | |
696 | // Honor -mllvm. |
697 | // |
698 | // FIXME: Remove this, one day. |
699 | if (!Asm.LLVMArgs.empty()) { |
700 | unsigned NumArgs = Asm.LLVMArgs.size(); |
701 | auto Args = std::make_unique<const char*[]>(num: NumArgs + 2); |
702 | Args[0] = "clang (LLVM option parsing)" ; |
703 | for (unsigned i = 0; i != NumArgs; ++i) |
704 | Args[i + 1] = Asm.LLVMArgs[i].c_str(); |
705 | Args[NumArgs + 1] = nullptr; |
706 | llvm::cl::ParseCommandLineOptions(argc: NumArgs + 1, argv: Args.get()); |
707 | } |
708 | |
709 | // Execute the invocation, unless there were parsing errors. |
710 | bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Opts&: Asm, Diags); |
711 | |
712 | // If any timers were active but haven't been destroyed yet, print their |
713 | // results now. |
714 | TimerGroup::printAll(OS&: errs()); |
715 | TimerGroup::clearAll(); |
716 | |
717 | return !!Failed; |
718 | } |
719 | |