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