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