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