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.CompressDebugSections = Opts.CompressDebugSections;
477 MCOptions.AsSecureLogFile = Opts.AsSecureLogFile;
478
479 std::unique_ptr<MCAsmInfo> MAI(
480 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple: Opts.Triple, Options: MCOptions));
481 assert(MAI && "Unable to create target asm info!");
482
483 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
484 // may be created with a combination of default and explicit settings.
485
486
487 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
488 if (Opts.OutputPath.empty())
489 Opts.OutputPath = "-";
490 std::unique_ptr<raw_fd_ostream> FDOS =
491 getOutputStream(Path: Opts.OutputPath, Diags, Binary: IsBinary);
492 if (!FDOS)
493 return true;
494 std::unique_ptr<raw_fd_ostream> DwoOS;
495 if (!Opts.SplitDwarfOutput.empty())
496 DwoOS = getOutputStream(Path: Opts.SplitDwarfOutput, Diags, Binary: IsBinary);
497
498 // Build up the feature string from the target feature list.
499 std::string FS = llvm::join(R&: Opts.Features, Separator: ",");
500
501 std::unique_ptr<MCSubtargetInfo> STI(
502 TheTarget->createMCSubtargetInfo(TheTriple: Opts.Triple, CPU: Opts.CPU, Features: FS));
503 if (!STI) {
504 return Diags.Report(DiagID: diag::err_fe_unable_to_create_subtarget)
505 << Opts.CPU << FS.empty() << FS;
506 }
507
508 MCContext Ctx(Triple(Opts.Triple), MAI.get(), MRI.get(), STI.get(), &SrcMgr,
509 &MCOptions);
510
511 bool PIC = false;
512 if (Opts.RelocationModel == "static") {
513 PIC = false;
514 } else if (Opts.RelocationModel == "pic") {
515 PIC = true;
516 } else {
517 assert(Opts.RelocationModel == "dynamic-no-pic" &&
518 "Invalid PIC model!");
519 PIC = false;
520 }
521
522 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
523 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
524 std::unique_ptr<MCObjectFileInfo> MOFI(
525 TheTarget->createMCObjectFileInfo(Ctx, PIC));
526 Ctx.setObjectFileInfo(MOFI.get());
527
528 if (Opts.GenDwarfForAssembly)
529 Ctx.setGenDwarfForAssembly(true);
530 if (!Opts.DwarfDebugFlags.empty())
531 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
532 if (!Opts.DwarfDebugProducer.empty())
533 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
534 if (!Opts.DebugCompilationDir.empty())
535 Ctx.setCompilationDir(Opts.DebugCompilationDir);
536 else {
537 // If no compilation dir is set, try to use the current directory.
538 if (auto CWD = VFS->getCurrentWorkingDirectory())
539 Ctx.setCompilationDir(*CWD);
540 }
541 if (!Opts.DebugPrefixMap.empty())
542 for (const auto &KV : Opts.DebugPrefixMap)
543 Ctx.addDebugPrefixMapEntry(From: KV.first, To: KV.second);
544 if (!Opts.MainFileName.empty())
545 Ctx.setMainFileName(StringRef(Opts.MainFileName));
546 Ctx.setDwarfFormat(Opts.Dwarf64 ? dwarf::DWARF64 : dwarf::DWARF32);
547 Ctx.setDwarfVersion(Opts.DwarfVersion);
548 if (Opts.GenDwarfForAssembly)
549 Ctx.setGenDwarfRootFile(FileName: Opts.InputFile,
550 Buffer: SrcMgr.getMemoryBuffer(i: BufferIndex)->getBuffer());
551
552 std::unique_ptr<MCStreamer> Str;
553
554 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
555 assert(MCII && "Unable to create instruction info!");
556
557 raw_pwrite_stream *Out = FDOS.get();
558 std::unique_ptr<buffer_ostream> BOS;
559
560 MCOptions.MCNoWarn = Opts.NoWarn;
561 MCOptions.MCFatalWarnings = Opts.FatalWarnings;
562 MCOptions.MCNoTypeCheck = Opts.NoTypeCheck;
563 MCOptions.ShowMCInst = Opts.ShowInst;
564 MCOptions.AsmVerbose = true;
565 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
566 MCOptions.ABIName = Opts.TargetABI;
567
568 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
569 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
570 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
571 T: llvm::Triple(Opts.Triple), SyntaxVariant: Opts.OutputAsmVariant, MAI: *MAI, MII: *MCII, MRI: *MRI));
572
573 std::unique_ptr<MCCodeEmitter> CE;
574 if (Opts.ShowEncoding)
575 CE.reset(p: TheTarget->createMCCodeEmitter(II: *MCII, Ctx));
576 std::unique_ptr<MCAsmBackend> MAB(
577 TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions));
578
579 auto FOut = std::make_unique<formatted_raw_ostream>(args&: *Out);
580 Str.reset(p: TheTarget->createAsmStreamer(Ctx, OS: std::move(FOut), IP: std::move(IP),
581 CE: std::move(CE), TAB: std::move(MAB)));
582 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
583 Str.reset(p: createNullStreamer(Ctx));
584 } else {
585 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
586 "Invalid file type!");
587 if (!FDOS->supportsSeeking()) {
588 BOS = std::make_unique<buffer_ostream>(args&: *FDOS);
589 Out = BOS.get();
590 }
591
592 std::unique_ptr<MCCodeEmitter> CE(
593 TheTarget->createMCCodeEmitter(II: *MCII, Ctx));
594 std::unique_ptr<MCAsmBackend> MAB(
595 TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions));
596 assert(MAB && "Unable to create asm backend!");
597
598 std::unique_ptr<MCObjectWriter> OW =
599 DwoOS ? MAB->createDwoObjectWriter(OS&: *Out, DwoOS&: *DwoOS)
600 : MAB->createObjectWriter(OS&: *Out);
601
602 Triple T(Opts.Triple);
603 Str.reset(p: TheTarget->createMCObjectStreamer(
604 T, Ctx, TAB: std::move(MAB), OW: std::move(OW), Emitter: std::move(CE), STI: *STI));
605 if (T.isOSBinFormatMachO() && T.isOSDarwin()) {
606 Triple *TVT = Opts.DarwinTargetVariantTriple
607 ? &*Opts.DarwinTargetVariantTriple
608 : nullptr;
609 Str->emitVersionForTarget(Target: T, SDKVersion: VersionTuple(), DarwinTargetVariantTriple: TVT,
610 DarwinTargetVariantSDKVersion: Opts.DarwinTargetVariantSDKVersion);
611 }
612 }
613
614 // When -fembed-bitcode is passed to clang_as, a 1-byte marker
615 // is emitted in __LLVM,__asm section if the object file is MachO format.
616 if (Opts.EmbedBitcode && Ctx.getObjectFileType() == MCContext::IsMachO) {
617 MCSection *AsmLabel = Ctx.getMachOSection(
618 Segment: "__LLVM", Section: "__asm", TypeAndAttributes: MachO::S_REGULAR, Reserved2: 4, K: SectionKind::getReadOnly());
619 Str->switchSection(Section: AsmLabel);
620 Str->emitZeros(NumBytes: 1);
621 }
622
623 bool Failed = false;
624
625 std::unique_ptr<MCAsmParser> Parser(
626 createMCAsmParser(SrcMgr, Ctx, *Str, *MAI));
627
628 // FIXME: init MCTargetOptions from sanitizer flags here.
629 std::unique_ptr<MCTargetAsmParser> TAP(
630 TheTarget->createMCAsmParser(STI: *STI, Parser&: *Parser, MII: *MCII, Options: MCOptions));
631 if (!TAP)
632 Failed = Diags.Report(DiagID: diag::err_target_unknown_triple) << Opts.Triple.str();
633
634 // Set values for symbols, if any.
635 for (auto &S : Opts.SymbolDefs) {
636 auto Pair = StringRef(S).split(Separator: '=');
637 auto Sym = Pair.first;
638 auto Val = Pair.second;
639 int64_t Value;
640 // We have already error checked this in the driver.
641 Val.getAsInteger(Radix: 0, Result&: Value);
642 Ctx.setSymbolValue(Streamer&: Parser->getStreamer(), Sym, Val: Value);
643 }
644
645 if (!Failed) {
646 Parser->setTargetParser(*TAP);
647 Failed = Parser->Run(NoInitialTextSection: Opts.NoInitialTextSection);
648 }
649
650 return Failed;
651}
652
653static bool ExecuteAssembler(AssemblerInvocation &Opts,
654 DiagnosticsEngine &Diags,
655 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
656 bool Failed = ExecuteAssemblerImpl(Opts, Diags, VFS);
657
658 // Delete output file if there were errors.
659 if (Failed) {
660 if (Opts.OutputPath != "-")
661 sys::fs::remove(path: Opts.OutputPath);
662 if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
663 sys::fs::remove(path: Opts.SplitDwarfOutput);
664 }
665
666 return Failed;
667}
668
669static void LLVMErrorHandler(void *UserData, const char *Message,
670 bool GenCrashDiag) {
671 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
672
673 Diags.Report(DiagID: diag::err_fe_error_backend) << Message;
674
675 // We cannot recover from llvm errors.
676 sys::Process::Exit(RetCode: 1);
677}
678
679int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
680 // Initialize targets and assembly printers/parsers.
681 InitializeAllTargetInfos();
682 InitializeAllTargetMCs();
683 InitializeAllAsmParsers();
684
685 // Construct our diagnostic client.
686 DiagnosticOptions DiagOpts;
687 TextDiagnosticPrinter *DiagClient =
688 new TextDiagnosticPrinter(errs(), DiagOpts);
689 DiagClient->setPrefix("clang -cc1as");
690 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagClient);
691
692 auto VFS = [] {
693 auto BypassSandbox = sys::sandbox::scopedDisable();
694 return vfs::getRealFileSystem();
695 }();
696
697 // Set an error handler, so that any LLVM backend diagnostics go through our
698 // error handler.
699 ScopedFatalErrorHandler FatalErrorHandler
700 (LLVMErrorHandler, static_cast<void*>(&Diags));
701
702 // Parse the arguments.
703 AssemblerInvocation Asm;
704 if (!AssemblerInvocation::CreateFromArgs(Opts&: Asm, Argv, Diags))
705 return 1;
706
707 if (Asm.ShowHelp) {
708 getDriverOptTable().printHelp(
709 OS&: llvm::outs(), Usage: "clang -cc1as [options] file...",
710 Title: "Clang Integrated Assembler", /*ShowHidden=*/false,
711 /*ShowAllAliases=*/false, VisibilityMask: llvm::opt::Visibility(options::CC1AsOption));
712
713 return 0;
714 }
715
716 // Honor -version.
717 //
718 // FIXME: Use a better -version message?
719 if (Asm.ShowVersion) {
720 llvm::cl::PrintVersionMessage();
721 return 0;
722 }
723
724 // Honor -mllvm.
725 //
726 // FIXME: Remove this, one day.
727 if (!Asm.LLVMArgs.empty()) {
728 unsigned NumArgs = Asm.LLVMArgs.size();
729 auto Args = std::make_unique<const char*[]>(num: NumArgs + 2);
730 Args[0] = "clang (LLVM option parsing)";
731 for (unsigned i = 0; i != NumArgs; ++i)
732 Args[i + 1] = Asm.LLVMArgs[i].c_str();
733 Args[NumArgs + 1] = nullptr;
734 llvm::cl::ParseCommandLineOptions(argc: NumArgs + 1, argv: Args.get(), /*Overview=*/"",
735 /*Errs=*/nullptr, /*VFS=*/VFS.get());
736 }
737
738 // Execute the invocation, unless there were parsing errors.
739 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Opts&: Asm, Diags, VFS);
740
741 // If any timers were active but haven't been destroyed yet, print their
742 // results now.
743 TimerGroup::printAll(OS&: errs());
744 TimerGroup::clearAll();
745
746 return !!Failed;
747}
748