Debian Codegraph @

clang/lib/CodeGen/BackendUtil.cpp

raw
1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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 #include "clang/CodeGen/BackendUtil.h"
10 #include "BackendConsumer.h"
11 #include "LinkInModulesPass.h"
12 #include "clang/Basic/CodeGenOptions.h"
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/DiagnosticFrontend.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/TargetOptions.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/HeaderSearchOptions.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Analysis/GlobalsModRef.h"
22 #include "llvm/Analysis/RuntimeLibcallInfo.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeReader.h"
26 #include "llvm/Bitcode/BitcodeWriter.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/CodeGen/TargetSubtargetInfo.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/Frontend/Driver/CodeGenOptions.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/LLVMRemarkStreamer.h"
34 #include "llvm/IR/LegacyPassManager.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ModuleSummaryIndex.h"
37 #include "llvm/IR/PassManager.h"
38 #include "llvm/IR/Verifier.h"
39 #include "llvm/IRPrinter/IRPrintingPasses.h"
40 #include "llvm/LTO/LTOBackend.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Object/OffloadBinary.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Passes/StandardInstrumentations.h"
45 #include "llvm/Plugins/PassPlugin.h"
46 #include "llvm/ProfileData/InstrProfCorrelator.h"
47 #include "llvm/Support/BuryPointer.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/IOSandbox.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/PrettyStackTrace.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/TimeProfiler.h"
55 #include "llvm/Support/Timer.h"
56 #include "llvm/Support/ToolOutputFile.h"
57 #include "llvm/Support/VirtualFileSystem.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetMachine.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include "llvm/TargetParser/SubtargetFeature.h"
62 #include "llvm/TargetParser/Triple.h"
63 #include "llvm/Transforms/HipStdPar/HipStdPar.h"
64 #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
65 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
66 #include "llvm/Transforms/IPO/LowerTypeTests.h"
67 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
68 #include "llvm/Transforms/InstCombine/InstCombine.h"
69 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
71 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
72 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
73 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
74 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
75 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
76 #include "llvm/Transforms/Instrumentation/KCFI.h"
77 #include "llvm/Transforms/Instrumentation/LowerAllowCheckPass.h"
78 #include "llvm/Transforms/Instrumentation/MemProfInstrumentation.h"
79 #include "llvm/Transforms/Instrumentation/MemProfUse.h"
80 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
81 #include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
82 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
83 #include "llvm/Transforms/Instrumentation/RealtimeSanitizer.h"
84 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
85 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
86 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
87 #include "llvm/Transforms/Instrumentation/TypeSanitizer.h"
88 #include "llvm/Transforms/ObjCARC.h"
89 #include "llvm/Transforms/Scalar/EarlyCSE.h"
90 #include "llvm/Transforms/Scalar/GVN.h"
91 #include "llvm/Transforms/Scalar/JumpThreading.h"
92 #include "llvm/Transforms/Utils/Debugify.h"
93 #include "llvm/Transforms/Utils/ModuleUtils.h"
94 #include <limits>
95 #include <memory>
96 #include <optional>
97 using namespace clang;
98 using namespace llvm;
99
100 #define HANDLE_EXTENSION(Ext) \
101 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
102 #include "llvm/Support/Extension.def"
103
104 namespace llvm {
105 // Experiment to move sanitizers earlier.
106 static cl::opt<bool> ClSanitizeOnOptimizerEarlyEP(
107 "sanitizer-early-opt-ep", cl::Optional,
108 cl::desc("Insert sanitizers on OptimizerEarlyEP."));
109
110 // Experiment to mark cold functions as optsize/minsize/optnone.
111 // TODO: remove once this is exposed as a proper driver flag.
112 static cl::opt<PGOOptions::ColdFuncOpt> ClPGOColdFuncAttr(
113 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
114 cl::desc(
115 "Function attribute to apply to cold functions as determined by PGO"),
116 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
117 "Default (no attribute)"),
118 clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
119 "Mark cold functions with optsize."),
120 clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
121 "Mark cold functions with minsize."),
122 clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
123 "Mark cold functions with optnone.")));
124
125 LLVM_ABI extern cl::opt<InstrProfCorrelator::ProfCorrelatorKind>
126 ProfileCorrelate;
127 } // namespace llvm
128 namespace clang {
129 extern llvm::cl::opt<bool> ClSanitizeGuardChecks;
130 }
131
132 // Path and name of file used for profile generation
133 static std::string getProfileGenName(const CodeGenOptions &CodeGenOpts) {
134 std::string FileName = CodeGenOpts.InstrProfileOutput.empty()
135 ? llvm::driver::getDefaultProfileGenName()
136 : CodeGenOpts.InstrProfileOutput;
137 if (CodeGenOpts.ContinuousProfileSync)
138 FileName = "%c" + FileName;
139 return FileName;
140 }
141
142 namespace {
143
144 class EmitAssemblyHelper {
145 CompilerInstance &CI;
146 DiagnosticsEngine &Diags;
147 const CodeGenOptions &CodeGenOpts;
148 const clang::TargetOptions &TargetOpts;
149 const LangOptions &LangOpts;
150 llvm::Module *TheModule;
151 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
152
153 std::unique_ptr<raw_pwrite_stream> OS;
154
155 Triple TargetTriple;
156
157 TargetIRAnalysis getTargetIRAnalysis() const {
158 if (TM)
159 return TM->getTargetIRAnalysis();
160
161 return TargetIRAnalysis();
162 }
163
164 /// Generates the TargetMachine.
165 /// Leaves TM unchanged if it is unable to create the target machine.
166 /// Some of our clang tests specify triples which are not built
167 /// into clang. This is okay because these tests check the generated
168 /// IR, and they require DataLayout which depends on the triple.
169 /// In this case, we allow this method to fail and not report an error.
170 /// When MustCreateTM is used, we print an error if we are unable to load
171 /// the requested target.
172 void CreateTargetMachine(bool MustCreateTM);
173
174 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
175 std::error_code EC;
176 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
177 llvm::sys::fs::OF_None);
178 if (EC) {
179 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
180 F.reset();
181 }
182 return F;
183 }
184
185 void RunOptimizationPipeline(
186 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
187 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC);
188 void RunCodegenPipeline(BackendAction Action,
189 std::unique_ptr<raw_pwrite_stream> &OS,
190 std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
191
192 /// Check whether we should emit a module summary for regular LTO.
193 /// The module summary should be emitted by default for regular LTO
194 /// except for ld64 targets.
195 ///
196 /// \return True if the module summary should be emitted.
197 bool shouldEmitRegularLTOSummary() const {
198 return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
199 TargetTriple.getVendor() != llvm::Triple::Apple;
200 }
201
202 /// Check whether we should emit a flag for UnifiedLTO.
203 /// The UnifiedLTO module flag should be set when UnifiedLTO is enabled for
204 /// ThinLTO or Full LTO with module summaries.
205 bool shouldEmitUnifiedLTOModueFlag() const {
206 return CodeGenOpts.UnifiedLTO &&
207 (CodeGenOpts.PrepareForThinLTO || shouldEmitRegularLTOSummary());
208 }
209
210 public:
211 EmitAssemblyHelper(CompilerInstance &CI, CodeGenOptions &CGOpts,
212 llvm::Module *M,
213 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
214 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CGOpts),
215 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
216 TheModule(M), VFS(std::move(VFS)),
217 TargetTriple(TheModule->getTargetTriple()) {}
218
219 ~EmitAssemblyHelper() {
220 if (CodeGenOpts.DisableFree)
221 BuryPointer(std::move(TM));
222 }
223
224 std::unique_ptr<TargetMachine> TM;
225
226 // Emit output using the new pass manager for the optimization pipeline.
227 void emitAssembly(BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS,
228 BackendConsumer *BC);
229 };
230 } // namespace
231
232 static SanitizerCoverageOptions
233 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
234 SanitizerCoverageOptions Opts;
235 Opts.CoverageType =
236 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
237 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
238 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
239 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
240 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
241 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
242 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
243 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
244 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
245 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
246 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
247 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
248 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
249 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
250 Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
251 Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
252 Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
253 Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
254 return Opts;
255 }
256
257 static SanitizerBinaryMetadataOptions
258 getSanitizerBinaryMetadataOptions(const CodeGenOptions &CGOpts) {
259 SanitizerBinaryMetadataOptions Opts;
260 Opts.Covered = CGOpts.SanitizeBinaryMetadataCovered;
261 Opts.Atomics = CGOpts.SanitizeBinaryMetadataAtomics;
262 Opts.UAR = CGOpts.SanitizeBinaryMetadataUAR;
263 return Opts;
264 }
265
266 // Check if ASan should use GC-friendly instrumentation for globals.
267 // First of all, there is no point if -fdata-sections is off (expect for MachO,
268 // where this is not a factor). Also, on ELF this feature requires an assembler
269 // extension that only works with -integrated-as at the moment.
270 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
271 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
272 return false;
273 switch (T.getObjectFormat()) {
274 case Triple::MachO:
275 case Triple::COFF:
276 return true;
277 case Triple::ELF:
278 return !CGOpts.DisableIntegratedAS;
279 case Triple::GOFF:
280 llvm::report_fatal_error("ASan not implemented for GOFF");
281 case Triple::XCOFF:
282 llvm::report_fatal_error("ASan not implemented for XCOFF.");
283 case Triple::Wasm:
284 case Triple::DXContainer:
285 case Triple::SPIRV:
286 case Triple::UnknownObjectFormat:
287 break;
288 }
289 return false;
290 }
291
292 static std::optional<llvm::CodeModel::Model>
293 getCodeModel(const CodeGenOptions &CodeGenOpts) {
294 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
295 .Case("tiny", llvm::CodeModel::Tiny)
296 .Case("small", llvm::CodeModel::Small)
297 .Case("kernel", llvm::CodeModel::Kernel)
298 .Case("medium", llvm::CodeModel::Medium)
299 .Case("large", llvm::CodeModel::Large)
300 .Cases({"default", ""}, ~1u)
301 .Default(~0u);
302 assert(CodeModel != ~0u && "invalid code model!");
303 if (CodeModel == ~1u)
304 return std::nullopt;
305 return static_cast<llvm::CodeModel::Model>(CodeModel);
306 }
307
308 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
309 if (Action == Backend_EmitObj)
310 return CodeGenFileType::ObjectFile;
311 else if (Action == Backend_EmitMCNull)
312 return CodeGenFileType::Null;
313 else {
314 assert(Action == Backend_EmitAssembly && "Invalid action!");
315 return CodeGenFileType::AssemblyFile;
316 }
317 }
318
319 static bool actionRequiresCodeGen(BackendAction Action) {
320 return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
321 Action != Backend_EmitLL;
322 }
323
324 static std::string flattenClangCommandLine(ArrayRef<std::string> Args,
325 StringRef MainFilename,
326 ArrayRef<StringRef> InputFiles) {
327 if (Args.empty())
328 return std::string{};
329
330 std::string FlatCmdLine;
331 raw_string_ostream OS(FlatCmdLine);
332 bool PrintedOneArg = false;
333 if (!StringRef(Args[0]).contains("-cc1")) {
334 llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
335 PrintedOneArg = true;
336 }
337 for (unsigned i = 0; i < Args.size(); i++) {
338 StringRef Arg = Args[i];
339 if (Arg.empty())
340 continue;
341 if (Arg == "-main-file-name" || Arg == "-o") {
342 i++; // Skip this argument and next one.
343 continue;
344 }
345 if (Arg.starts_with("-object-file-name"))
346 continue;
347 // Strip the source positional, matching either MainFilename (the
348 // -main-file-name basename) or one of the resolved frontend input paths
349 // (which is what the cc1 positional looks like for an absolute driver
350 // input). Avoid a generic basename match: it would also strip values of
351 // args like `-include <path>` whose trailing component happens to equal
352 // the source basename.
353 if (Arg == MainFilename || llvm::is_contained(InputFiles, Arg))
354 continue;
355 // Skip fmessage-length for reproducibility.
356 if (Arg.starts_with("-fmessage-length"))
357 continue;
358 if (PrintedOneArg)
359 OS << " ";
360 llvm::sys::printArg(OS, Arg, /*Quote=*/true);
361 PrintedOneArg = true;
362 }
363 return FlatCmdLine;
364 }
365
366 static bool initTargetOptions(const CompilerInstance &CI,
367 DiagnosticsEngine &Diags,
368 llvm::TargetOptions &Options) {
369 const auto &CodeGenOpts = CI.getCodeGenOpts();
370 const auto &TargetOpts = CI.getTargetOpts();
371 const auto &LangOpts = CI.getLangOpts();
372 const auto &HSOpts = CI.getHeaderSearchOpts();
373 switch (LangOpts.getThreadModel()) {
374 case LangOptions::ThreadModelKind::POSIX:
375 Options.ThreadModel = llvm::ThreadModel::POSIX;
376 break;
377 case LangOptions::ThreadModelKind::Single:
378 Options.ThreadModel = llvm::ThreadModel::Single;
379 break;
380 }
381
382 // Set float ABI type.
383 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
384 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
385 "Invalid Floating Point ABI!");
386 Options.FloatABIType =
387 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
388 .Case("soft", llvm::FloatABI::Soft)
389 .Case("softfp", llvm::FloatABI::Soft)
390 .Case("hard", llvm::FloatABI::Hard)
391 .Default(llvm::FloatABI::Default);
392
393 // Set FP fusion mode.
394 switch (LangOpts.getDefaultFPContractMode()) {
395 case LangOptions::FPM_Off:
396 // Preserve any contraction performed by the front-end. (Strict performs
397 // splitting of the muladd intrinsic in the backend.)
398 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
399 break;
400 case LangOptions::FPM_On:
401 case LangOptions::FPM_FastHonorPragmas:
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 break;
404 case LangOptions::FPM_Fast:
405 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
406 break;
407 }
408
409 Options.BinutilsVersion =
410 llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
411 Options.UseInitArray = CodeGenOpts.UseInitArray;
412 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
413
414 // Set EABI version.
415 Options.EABIVersion = TargetOpts.EABIVersion;
416
417 if (CodeGenOpts.hasSjLjExceptions())
418 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
419 if (CodeGenOpts.hasSEHExceptions())
420 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
421 if (CodeGenOpts.hasDWARFExceptions())
422 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
423 if (CodeGenOpts.hasWasmExceptions())
424 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
425
426 Options.NoInfsFPMath = LangOpts.NoHonorInfs;
427 Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
428 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
429
430 Options.BBAddrMap = CodeGenOpts.BBAddrMap;
431 Options.BBSections =
432 llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
433 .Case("all", llvm::BasicBlockSection::All)
434 .StartsWith("list=", llvm::BasicBlockSection::List)
435 .Case("none", llvm::BasicBlockSection::None)
436 .Default(llvm::BasicBlockSection::None);
437
438 if (Options.BBSections == llvm::BasicBlockSection::List) {
439 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
440 CI.getVirtualFileSystem().getBufferForFile(
441 CodeGenOpts.BBSections.substr(5));
442 if (!MBOrErr) {
443 Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
444 << MBOrErr.getError().message();
445 return false;
446 }
447 Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
448 }
449
450 Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
451 Options.EnableStaticDataPartitioning =
452 CodeGenOpts.PartitionStaticDataSections;
453 Options.FunctionSections = CodeGenOpts.FunctionSections;
454 Options.DataSections = CodeGenOpts.DataSections;
455 Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
456 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
457 Options.UniqueBasicBlockSectionNames =
458 CodeGenOpts.UniqueBasicBlockSectionNames;
459 Options.SeparateNamedSections = CodeGenOpts.SeparateNamedSections;
460 Options.TLSSize = CodeGenOpts.TLSSize;
461 Options.EnableTLSDESC = CodeGenOpts.EnableTLSDESC;
462 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
463 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
464 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
465 Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
466 Options.EmitAddrsig = CodeGenOpts.Addrsig;
467 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
468 Options.EmitCallGraphSection = CodeGenOpts.CallGraphSection;
469 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
470 Options.EnableAIXExtendedAltivecABI = LangOpts.EnableAIXExtendedAltivecABI;
471 Options.XRayFunctionIndex = CodeGenOpts.XRayFunctionIndex;
472 Options.LoopAlignment = CodeGenOpts.LoopAlignment;
473 Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
474 Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
475 Options.Hotpatch = CodeGenOpts.HotPatch;
476 Options.JMCInstrument = CodeGenOpts.JMCInstrument;
477 Options.XCOFFReadOnlyPointers = CodeGenOpts.XCOFFReadOnlyPointers;
478 Options.VecLib =
479 convertDriverVectorLibraryToVectorLibrary(CodeGenOpts.getVecLib());
480
481 switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
482 case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
483 Options.SwiftAsyncFramePointer =
484 SwiftAsyncFramePointerMode::DeploymentBased;
485 break;
486
487 case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
488 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
489 break;
490
491 case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
492 Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
493 break;
494 }
495
496 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
497 Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
498 Options.MCOptions.EmitCompactUnwindNonCanonical =
499 CodeGenOpts.EmitCompactUnwindNonCanonical;
500 Options.MCOptions.EmitSFrameUnwind = CodeGenOpts.EmitSFrameUnwind;
501 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
502 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
503 Options.MCOptions.MCUseDwarfDirectory =
504 CodeGenOpts.NoDwarfDirectoryAsm
505 ? llvm::MCTargetOptions::DisableDwarfDirectory
506 : llvm::MCTargetOptions::EnableDwarfDirectory;
507 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
508 Options.MCOptions.MCIncrementalLinkerCompatible =
509 CodeGenOpts.IncrementalLinkerCompatible;
510 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
511 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
512 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
513 Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
514 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
515 Options.MCOptions.Crel = CodeGenOpts.Crel;
516 Options.MCOptions.ImplicitMapSyms = CodeGenOpts.ImplicitMapSyms;
517 Options.MCOptions.X86RelaxRelocations = CodeGenOpts.X86RelaxRelocations;
518 Options.MCOptions.CompressDebugSections =
519 CodeGenOpts.getCompressDebugSections();
520 if (CodeGenOpts.OutputAsmVariant != 3) // 3 (default): not specified
521 Options.MCOptions.OutputAsmVariant = CodeGenOpts.OutputAsmVariant;
522 Options.MCOptions.ABIName = TargetOpts.ABI;
523 for (const auto &Entry : HSOpts.UserEntries)
524 if (!Entry.IsFramework &&
525 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
526 Entry.Group == frontend::IncludeDirGroup::Angled ||
527 Entry.Group == frontend::IncludeDirGroup::System))
528 Options.MCOptions.IASSearchPaths.push_back(
529 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
530 Options.MCOptions.Argv0 = CodeGenOpts.Argv0 ? CodeGenOpts.Argv0 : "";
531 // Pass the resolved frontend inputs so flattenClangCommandLine can strip
532 // the cc1 source positional even when the driver received an absolute path
533 // (which won't match CodeGenOpts.MainFileName, that's just the basename).
534 SmallVector<StringRef, 1> InputFiles;
535 for (const auto &Input : CI.getFrontendOpts().Inputs)
536 if (Input.isFile())
537 InputFiles.push_back(Input.getFile());
538 Options.MCOptions.CommandlineArgs = flattenClangCommandLine(
539 CodeGenOpts.CommandLineArgs, CodeGenOpts.MainFileName, InputFiles);
540 Options.MCOptions.AsSecureLogFile = CodeGenOpts.AsSecureLogFile;
541 Options.MCOptions.PPCUseFullRegisterNames =
542 CodeGenOpts.PPCUseFullRegisterNames;
543 Options.MisExpect = CodeGenOpts.MisExpect;
544
545 return true;
546 }
547
548 static std::optional<GCOVOptions>
549 getGCOVOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) {
550 if (CodeGenOpts.CoverageNotesFile.empty() &&
551 CodeGenOpts.CoverageDataFile.empty())
552 return std::nullopt;
553 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
554 // LLVM's -default-gcov-version flag is set to something invalid.
555 GCOVOptions Options;
556 Options.EmitNotes = !CodeGenOpts.CoverageNotesFile.empty();
557 Options.EmitData = !CodeGenOpts.CoverageDataFile.empty();
558 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
559 Options.NoRedZone = CodeGenOpts.DisableRedZone;
560 Options.Filter = CodeGenOpts.ProfileFilterFiles;
561 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
562 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
563 return Options;
564 }
565
566 static std::optional<InstrProfOptions>
567 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
568 const LangOptions &LangOpts) {
569 if (!CodeGenOpts.hasProfileClangInstr())
570 return std::nullopt;
571 InstrProfOptions Options;
572 Options.NoRedZone = CodeGenOpts.DisableRedZone;
573 Options.InstrProfileOutput = CodeGenOpts.ContinuousProfileSync
574 ? ("%c" + CodeGenOpts.InstrProfileOutput)
575 : CodeGenOpts.InstrProfileOutput;
576 Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
577 return Options;
578 }
579
580 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts,
581 vfs::FileSystem &VFS) {
582 SmallVector<const char *, 16> BackendArgs;
583 BackendArgs.push_back("clang"); // Fake program name.
584 if (!CodeGenOpts.DebugPass.empty()) {
585 BackendArgs.push_back("-debug-pass");
586 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
587 }
588 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
589 BackendArgs.push_back("-limit-float-precision");
590 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
591 }
592
593 // Check for the default "clang" invocation that won't set any cl::opt values.
594 // Skip trying to parse the command line invocation to avoid the issues
595 // described below.
596 if (BackendArgs.size() == 1)
597 return;
598 BackendArgs.push_back(nullptr);
599 // FIXME: The command line parser below is not thread-safe and shares a global
600 // state, so this call might crash or overwrite the options of another Clang
601 // instance in the same process.
602 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data(),
603 /*Overview=*/"", /*Errs=*/nullptr,
604 /*VFS=*/&VFS);
605 }
606
607 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
608 // Create the TargetMachine for generating code.
609 std::string Error;
610 const llvm::Triple &Triple = TheModule->getTargetTriple();
611 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
612 if (!TheTarget) {
613 if (MustCreateTM)
614 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
615 return;
616 }
617
618 std::optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
619 std::string FeaturesStr =
620 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
621 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
622 std::optional<CodeGenOptLevel> OptLevelOrNone =
623 CodeGenOpt::getLevel(CodeGenOpts.OptimizationLevel);
624 assert(OptLevelOrNone && "Invalid optimization level!");
625 CodeGenOptLevel OptLevel = *OptLevelOrNone;
626
627 llvm::TargetOptions Options;
628 if (!initTargetOptions(CI, Diags, Options))
629 return;
630 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
631 Options, RM, CM, OptLevel));
632 if (TM)
633 TM->setLargeDataThreshold(CodeGenOpts.LargeDataThreshold);
634 }
635
636 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
637 switch (Opts.OptimizationLevel) {
638 default:
639 llvm_unreachable("Invalid optimization level!");
640
641 case 0:
642 return OptimizationLevel::O0;
643
644 case 1:
645 return OptimizationLevel::O1;
646
647 case 2:
648 switch (Opts.OptimizeSize) {
649 default:
650 llvm_unreachable("Invalid optimization level for size!");
651
652 case 0:
653 return OptimizationLevel::O2;
654
655 case 1:
656 return OptimizationLevel::Os;
657
658 case 2:
659 return OptimizationLevel::Oz;
660 }
661
662 case 3:
663 return OptimizationLevel::O3;
664 }
665 }
666
667 static void addKCFIPass(const Triple &TargetTriple, const LangOptions &LangOpts,
668 PassBuilder &PB) {
669 // If the back-end supports KCFI operand bundle lowering, skip KCFIPass.
670 if (TargetTriple.getArch() == llvm::Triple::x86_64 ||
671 TargetTriple.isAArch64(64) || TargetTriple.isRISCV() ||
672 TargetTriple.isARM() || TargetTriple.isThumb())
673 return;
674
675 // Ensure we lower KCFI operand bundles with -O0.
676 PB.registerOptimizerLastEPCallback(
677 [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) {
678 if (Level == OptimizationLevel::O0 &&
679 LangOpts.Sanitize.has(SanitizerKind::KCFI))
680 MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
681 });
682
683 // When optimizations are requested, run KCIFPass after InstCombine to
684 // avoid unnecessary checks.
685 PB.registerPeepholeEPCallback(
686 [&](FunctionPassManager &FPM, OptimizationLevel Level) {
687 if (Level != OptimizationLevel::O0 &&
688 LangOpts.Sanitize.has(SanitizerKind::KCFI))
689 FPM.addPass(KCFIPass());
690 });
691 }
692
693 static void addSanitizers(const Triple &TargetTriple,
694 const CodeGenOptions &CodeGenOpts,
695 const LangOptions &LangOpts, PassBuilder &PB) {
696 auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel Level,
697 ThinOrFullLTOPhase) {
698 if (CodeGenOpts.hasSanitizeCoverage()) {
699 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
700 MPM.addPass(
701 SanitizerCoveragePass(SancovOpts, PB.getVirtualFileSystemPtr(),
702 CodeGenOpts.SanitizeCoverageAllowlistFiles,
703 CodeGenOpts.SanitizeCoverageIgnorelistFiles));
704 }
705
706 if (CodeGenOpts.hasSanitizeBinaryMetadata()) {
707 MPM.addPass(SanitizerBinaryMetadataPass(
708 getSanitizerBinaryMetadataOptions(CodeGenOpts),
709 PB.getVirtualFileSystemPtr(),
710 CodeGenOpts.SanitizeMetadataIgnorelistFiles));
711 }
712
713 auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
714 if (LangOpts.Sanitize.has(Mask)) {
715 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
716 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
717
718 MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
719 CodeGenOpts.SanitizeMemoryParamRetval);
720 MPM.addPass(MemorySanitizerPass(options));
721 if (Level != OptimizationLevel::O0) {
722 // MemorySanitizer inserts complex instrumentation that mostly follows
723 // the logic of the original code, but operates on "shadow" values. It
724 // can benefit from re-running some general purpose optimization
725 // passes.
726 MPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
727 FunctionPassManager FPM;
728 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
729 FPM.addPass(InstCombinePass());
730 FPM.addPass(JumpThreadingPass());
731 FPM.addPass(GVNPass());
732 FPM.addPass(InstCombinePass());
733 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
734 }
735 }
736 };
737 MSanPass(SanitizerKind::Memory, false);
738 MSanPass(SanitizerKind::KernelMemory, true);
739
740 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
741 MPM.addPass(ModuleThreadSanitizerPass());
742 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
743 }
744
745 if (LangOpts.Sanitize.has(SanitizerKind::Type))
746 MPM.addPass(TypeSanitizerPass());
747
748 if (LangOpts.Sanitize.has(SanitizerKind::NumericalStability))
749 MPM.addPass(NumericalStabilitySanitizerPass());
750
751 if (LangOpts.Sanitize.has(SanitizerKind::Realtime))
752 MPM.addPass(RealtimeSanitizerPass());
753
754 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
755 if (LangOpts.Sanitize.has(Mask)) {
756 bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
757 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
758 llvm::AsanDtorKind DestructorKind =
759 CodeGenOpts.getSanitizeAddressDtor();
760 AddressSanitizerOptions Opts;
761 Opts.CompileKernel = CompileKernel;
762 Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
763 Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
764 Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
765 MPM.addPass(AddressSanitizerPass(Opts, UseGlobalGC, UseOdrIndicator,
766 DestructorKind));
767 }
768 };
769 ASanPass(SanitizerKind::Address, false);
770 ASanPass(SanitizerKind::KernelAddress, true);
771
772 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
773 if (LangOpts.Sanitize.has(Mask)) {
774 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
775 MPM.addPass(HWAddressSanitizerPass(
776 {CompileKernel, Recover,
777 /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
778 }
779 };
780 HWASanPass(SanitizerKind::HWAddress, false);
781 HWASanPass(SanitizerKind::KernelHWAddress, true);
782
783 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
784 MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles,
785 PB.getVirtualFileSystemPtr()));
786 }
787 };
788 if (ClSanitizeOnOptimizerEarlyEP) {
789 PB.registerOptimizerEarlyEPCallback(
790 [SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
791 ThinOrFullLTOPhase Phase) {
792 ModulePassManager NewMPM;
793 SanitizersCallback(NewMPM, Level, Phase);
794 if (!NewMPM.isEmpty()) {
795 // Sanitizers can abandon<GlobalsAA>.
796 NewMPM.addPass(RequireAnalysisPass<GlobalsAA, llvm::Module>());
797 MPM.addPass(std::move(NewMPM));
798 }
799 });
800 } else {
801 // LastEP does not need GlobalsAA.
802 PB.registerOptimizerLastEPCallback(SanitizersCallback);
803 }
804 }
805
806 void addLowerAllowCheckPass(const CodeGenOptions &CodeGenOpts,
807 const LangOptions &LangOpts, PassBuilder &PB) {
808 // SanitizeSkipHotCutoffs: doubles with range [0, 1]
809 // Opts.cutoffs: unsigned ints with range [0, 1000000]
810 auto ScaledCutoffs = CodeGenOpts.SanitizeSkipHotCutoffs.getAllScaled(1000000);
811 uint64_t AllowRuntimeCheckSkipHotCutoff =
812 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.value_or(0.0) * 1000000;
813 // Only register the pass if one of the relevant sanitizers is enabled.
814 // This avoids pipeline overhead for builds that do not use these sanitizers.
815 bool LowerAllowSanitize = LangOpts.Sanitize.hasOneOf(
816 SanitizerKind::Address | SanitizerKind::KernelAddress |
817 SanitizerKind::Thread | SanitizerKind::Memory |
818 SanitizerKind::KernelMemory | SanitizerKind::HWAddress |
819 SanitizerKind::KernelHWAddress);
820
821 // TODO: remove IsRequested()
822 if (LowerAllowCheckPass::IsRequested() || ScaledCutoffs.has_value() ||
823 CodeGenOpts.AllowRuntimeCheckSkipHotCutoff.has_value() ||
824 LowerAllowSanitize) {
825 // We want to call it after inline, which is about OptimizerEarlyEPCallback.
826 PB.registerOptimizerEarlyEPCallback(
827 [ScaledCutoffs, AllowRuntimeCheckSkipHotCutoff](
828 ModulePassManager &MPM, OptimizationLevel Level,
829 ThinOrFullLTOPhase Phase) {
830 LowerAllowCheckPass::Options Opts;
831 // TODO: after removing IsRequested(), make this unconditional
832 if (ScaledCutoffs.has_value())
833 Opts.cutoffs = ScaledCutoffs.value();
834 Opts.runtime_check = AllowRuntimeCheckSkipHotCutoff;
835 MPM.addPass(
836 createModuleToFunctionPassAdaptor(LowerAllowCheckPass(Opts)));
837 });
838 }
839 }
840
841 void EmitAssemblyHelper::RunOptimizationPipeline(
842 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
843 std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS, BackendConsumer *BC) {
844 std::optional<PGOOptions> PGOOpt;
845
846 if (CodeGenOpts.hasProfileIRInstr())
847 // -fprofile-generate.
848 PGOOpt = PGOOptions(getProfileGenName(CodeGenOpts), "", "",
849 CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRInstr,
850 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
851 CodeGenOpts.DebugInfoForProfiling,
852 /*PseudoProbeForProfiling=*/false,
853 CodeGenOpts.AtomicProfileUpdate);
854 else if (CodeGenOpts.hasProfileIRUse()) {
855 // -fprofile-use.
856 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
857 : PGOOptions::NoCSAction;
858 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
859 CodeGenOpts.ProfileRemappingFile,
860 CodeGenOpts.MemoryProfileUsePath, PGOOptions::IRUse,
861 CSAction, ClPGOColdFuncAttr,
862 CodeGenOpts.DebugInfoForProfiling);
863 } else if (!CodeGenOpts.SampleProfileFile.empty())
864 // -fprofile-sample-use
865 PGOOpt = PGOOptions(
866 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
867 CodeGenOpts.MemoryProfileUsePath, PGOOptions::SampleUse,
868 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
869 CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
870 else if (!CodeGenOpts.MemoryProfileUsePath.empty())
871 // -fmemory-profile-use (without any of the above options)
872 PGOOpt = PGOOptions("", "", "", CodeGenOpts.MemoryProfileUsePath,
873 PGOOptions::NoAction, PGOOptions::NoCSAction,
874 ClPGOColdFuncAttr, CodeGenOpts.DebugInfoForProfiling);
875 else if (CodeGenOpts.PseudoProbeForProfiling)
876 // -fpseudo-probe-for-profiling
877 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
878 PGOOptions::NoCSAction, ClPGOColdFuncAttr,
879 CodeGenOpts.DebugInfoForProfiling, true);
880 else if (CodeGenOpts.DebugInfoForProfiling)
881 // -fdebug-info-for-profiling
882 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
883 PGOOptions::NoCSAction, ClPGOColdFuncAttr, true);
884
885 // Check to see if we want to generate a CS profile.
886 if (CodeGenOpts.hasProfileCSIRInstr()) {
887 assert(!CodeGenOpts.hasProfileCSIRUse() &&
888 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
889 "the same time");
890 if (PGOOpt) {
891 assert(PGOOpt->Action != PGOOptions::IRInstr &&
892 PGOOpt->Action != PGOOptions::SampleUse &&
893 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
894 " pass");
895 PGOOpt->CSProfileGenFile = getProfileGenName(CodeGenOpts);
896 PGOOpt->CSAction = PGOOptions::CSIRInstr;
897 } else
898 PGOOpt = PGOOptions("", getProfileGenName(CodeGenOpts), "",
899 /*MemoryProfile=*/"", PGOOptions::NoAction,
900 PGOOptions::CSIRInstr, ClPGOColdFuncAttr,
901 CodeGenOpts.DebugInfoForProfiling);
902 }
903 if (TM)
904 TM->setPGOOption(PGOOpt);
905
906 PipelineTuningOptions PTO;
907 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
908 PTO.LoopInterchange = CodeGenOpts.InterchangeLoops;
909 PTO.LoopFusion = CodeGenOpts.FuseLoops;
910 // For historical reasons, loop interleaving is set to mirror setting for loop
911 // unrolling.
912 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
913 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
914 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
915 PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
916 // Only enable CGProfilePass when using integrated assembler, since
917 // non-integrated assemblers don't recognize .cgprofile section.
918 PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
919 PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
920 PTO.DevirtualizeSpeculatively = CodeGenOpts.DevirtualizeSpeculatively;
921
922 LoopAnalysisManager LAM;
923 FunctionAnalysisManager FAM;
924 CGSCCAnalysisManager CGAM;
925 ModuleAnalysisManager MAM;
926
927 bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
928 PassInstrumentationCallbacks PIC;
929 PrintPassOptions PrintPassOpts;
930 PrintPassOpts.Indent = DebugPassStructure;
931 PrintPassOpts.SkipAnalyses = DebugPassStructure;
932 StandardInstrumentations SI(
933 TheModule->getContext(),
934 (CodeGenOpts.DebugPassManager || DebugPassStructure),
935 CodeGenOpts.VerifyEach, PrintPassOpts);
936 SI.registerCallbacks(PIC, &MAM);
937 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC, CI.getVirtualFileSystemPtr());
938
939 // Handle the assignment tracking feature options.
940 switch (CodeGenOpts.getAssignmentTrackingMode()) {
941 case CodeGenOptions::AssignmentTrackingOpts::Forced:
942 PB.registerPipelineStartEPCallback(
943 [&](ModulePassManager &MPM, OptimizationLevel Level) {
944 MPM.addPass(AssignmentTrackingPass());
945 });
946 break;
947 case CodeGenOptions::AssignmentTrackingOpts::Enabled:
948 // Disable assignment tracking in LTO builds for now as the performance
949 // cost is too high. Disable for LLDB tuning due to llvm.org/PR43126.
950 if (!CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.PrepareForLTO &&
951 CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::LLDB) {
952 PB.registerPipelineStartEPCallback(
953 [&](ModulePassManager &MPM, OptimizationLevel Level) {
954 // Only use assignment tracking if optimisations are enabled.
955 if (Level != OptimizationLevel::O0)
956 MPM.addPass(AssignmentTrackingPass());
957 });
958 }
959 break;
960 case CodeGenOptions::AssignmentTrackingOpts::Disabled:
961 break;
962 }
963
964 // Enable verify-debuginfo-preserve-each for new PM.
965 DebugifyEachInstrumentation Debugify;
966 DebugInfoPerPass DebugInfoBeforePass;
967 if (CodeGenOpts.EnableDIPreservationVerify) {
968 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
969 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
970
971 if (!CodeGenOpts.DIBugsReportFilePath.empty())
972 Debugify.setOrigDIVerifyBugsReportFilePath(
973 CodeGenOpts.DIBugsReportFilePath);
974 Debugify.registerCallbacks(PIC, MAM);
975
976 #if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE
977 // If we're using debug location coverage tracking, mark all the
978 // instructions coming out of the frontend without a DebugLoc as being
979 // compiler-generated, to prevent both those instructions and new
980 // instructions that inherit their location from being treated as
981 // incorrectly empty locations.
982 for (Function &F : *TheModule) {
983 if (!F.getSubprogram())
984 continue;
985 for (BasicBlock &BB : F)
986 for (Instruction &I : BB)
987 if (!I.getDebugLoc())
988 I.setDebugLoc(DebugLoc::getCompilerGenerated());
989 }
990 #endif
991 }
992 // Register plugin callbacks with PB.
993 for (const std::unique_ptr<PassPlugin> &Plugin : CI.getPassPlugins())
994 Plugin->registerPassBuilderCallbacks(PB);
995 for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
996 PassCallback(PB);
997 #define HANDLE_EXTENSION(Ext) \
998 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
999 #include "llvm/Support/Extension.def"
1000
1001 // Register the target library analysis directly and give it a customized
1002 // preset TLI.
1003 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1004 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1005 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1006
1007 // Register all the basic analyses with the managers.
1008 PB.registerModuleAnalyses(MAM);
1009 PB.registerCGSCCAnalyses(CGAM);
1010 PB.registerFunctionAnalyses(FAM);
1011 PB.registerLoopAnalyses(LAM);
1012 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1013
1014 ModulePassManager MPM;
1015 // Add a verifier pass, before any other passes, to catch CodeGen issues.
1016 if (CodeGenOpts.VerifyModule)
1017 MPM.addPass(VerifierPass());
1018
1019 if (!CodeGenOpts.DisableLLVMPasses) {
1020 // Map our optimization levels into one of the distinct levels used to
1021 // configure the pipeline.
1022 OptimizationLevel Level = mapToLevel(CodeGenOpts);
1023
1024 const bool PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
1025 const bool PrepareForLTO = CodeGenOpts.PrepareForLTO;
1026
1027 if (LangOpts.ObjCAutoRefCount) {
1028 PB.registerPipelineStartEPCallback(
1029 [](ModulePassManager &MPM, OptimizationLevel Level) {
1030 if (Level != OptimizationLevel::O0)
1031 MPM.addPass(
1032 createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1033 });
1034 PB.registerScalarOptimizerLateEPCallback(
1035 [](FunctionPassManager &FPM, OptimizationLevel Level) {
1036 if (Level != OptimizationLevel::O0)
1037 FPM.addPass(ObjCARCOptPass());
1038 });
1039 }
1040
1041 // If we reached here with a non-empty index file name, then the index
1042 // file was empty and we are not performing ThinLTO backend compilation
1043 // (used in testing in a distributed build environment).
1044 bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1045 // If so drop any the type test assume sequences inserted for whole program
1046 // vtables so that codegen doesn't complain.
1047 if (IsThinLTOPostLink)
1048 PB.registerPipelineStartEPCallback(
1049 [](ModulePassManager &MPM, OptimizationLevel Level) {
1050 MPM.addPass(LowerTypeTestsPass(
1051 /*ExportSummary=*/nullptr,
1052 /*ImportSummary=*/nullptr,
1053 /*DropTypeTests=*/lowertypetests::DropTestKind::Assume));
1054 });
1055
1056 // Register callbacks to schedule sanitizer passes at the appropriate part
1057 // of the pipeline.
1058 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1059 PB.registerScalarOptimizerLateEPCallback([this](FunctionPassManager &FPM,
1060 OptimizationLevel Level) {
1061 BoundsCheckingPass::Options Options;
1062 if (CodeGenOpts.SanitizeSkipHotCutoffs[SanitizerKind::SO_LocalBounds] ||
1063 ClSanitizeGuardChecks) {
1064 static_assert(SanitizerKind::SO_LocalBounds <=
1065 std::numeric_limits<
1066 decltype(Options.GuardKind)::value_type>::max(),
1067 "Update type of llvm.allow.ubsan.check to represent "
1068 "SanitizerKind::SO_LocalBounds.");
1069 Options.GuardKind = SanitizerKind::SO_LocalBounds;
1070 }
1071 Options.Merge =
1072 CodeGenOpts.SanitizeMergeHandlers.has(SanitizerKind::LocalBounds);
1073 if (!CodeGenOpts.SanitizeTrap.has(SanitizerKind::LocalBounds)) {
1074 Options.Rt = {
1075 /*MinRuntime=*/static_cast<bool>(
1076 CodeGenOpts.SanitizeMinimalRuntime),
1077 /*MayReturn=*/
1078 CodeGenOpts.SanitizeRecover.has(SanitizerKind::LocalBounds),
1079 /*HandlerPreserveAllRegs=*/
1080 static_cast<bool>(CodeGenOpts.SanitizeHandlerPreserveAllRegs),
1081 };
1082 }
1083 FPM.addPass(BoundsCheckingPass(Options));
1084 });
1085
1086 if (!IsThinLTOPostLink) {
1087 // Most sanitizers only run during PreLink stage.
1088 addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1089 addKCFIPass(TargetTriple, LangOpts, PB);
1090 addLowerAllowCheckPass(CodeGenOpts, LangOpts, PB);
1091
1092 PB.registerPipelineStartEPCallback(
1093 [&](ModulePassManager &MPM, OptimizationLevel Level) {
1094 if (Level == OptimizationLevel::O0 &&
1095 LangOpts.Sanitize.has(SanitizerKind::AllocToken)) {
1096 // With the default O0 pipeline, LibFunc attrs are not inferred,
1097 // so we insert it here because we need it for accurate memory
1098 // allocation function detection with -fsanitize=alloc-token.
1099 // Note: This could also be added to the default O0 pipeline, but
1100 // has a non-trivial effect on generated IR size (attributes).
1101 MPM.addPass(InferFunctionAttrsPass());
1102 }
1103 });
1104 }
1105
1106 if (std::optional<GCOVOptions> Options =
1107 getGCOVOptions(CodeGenOpts, LangOpts))
1108 PB.registerPipelineStartEPCallback(
1109 [this, Options](ModulePassManager &MPM, OptimizationLevel Level) {
1110 MPM.addPass(
1111 GCOVProfilerPass(*Options, CI.getVirtualFileSystemPtr()));
1112 });
1113 if (std::optional<InstrProfOptions> Options =
1114 getInstrProfOptions(CodeGenOpts, LangOpts))
1115 PB.registerPipelineStartEPCallback(
1116 [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1117 MPM.addPass(InstrProfilingLoweringPass(*Options, false));
1118 });
1119
1120 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
1121 // the PGOOptions, and set this up there.
1122 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1123 PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
1124 OptimizationLevel Level,
1125 ThinOrFullLTOPhase) {
1126 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1127 MPM.addPass(ModuleMemProfilerPass());
1128 });
1129 }
1130
1131 if (CodeGenOpts.FatLTO) {
1132 MPM.addPass(PB.buildFatLTODefaultPipeline(
1133 Level, PrepareForThinLTO,
1134 PrepareForThinLTO || shouldEmitRegularLTOSummary()));
1135 } else if (PrepareForThinLTO) {
1136 MPM.addPass(PB.buildThinLTOPreLinkDefaultPipeline(Level));
1137 } else if (PrepareForLTO) {
1138 MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(Level));
1139 } else {
1140 MPM.addPass(PB.buildPerModuleDefaultPipeline(Level));
1141 }
1142 }
1143
1144 // Link against bitcodes supplied via the -mlink-builtin-bitcode option
1145 if (CodeGenOpts.LinkBitcodePostopt)
1146 MPM.addPass(LinkInModulesPass(BC));
1147
1148 if (LangOpts.HIPStdPar && !LangOpts.CUDAIsDevice &&
1149 LangOpts.HIPStdParInterposeAlloc)
1150 MPM.addPass(HipStdParAllocationInterpositionPass());
1151
1152 // Add a verifier pass if requested. We don't have to do this if the action
1153 // requires code generation because there will already be a verifier pass in
1154 // the code-generation pipeline.
1155 // Since we already added a verifier pass above, this
1156 // might even not run the analysis, if previous passes caused no changes.
1157 if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1158 MPM.addPass(VerifierPass());
1159
1160 if (Action == Backend_EmitBC || Action == Backend_EmitLL ||
1161 CodeGenOpts.FatLTO) {
1162 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1163 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1164 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1165 CodeGenOpts.EnableSplitLTOUnit);
1166 if (Action == Backend_EmitBC) {
1167 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1168 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1169 if (!ThinLinkOS)
1170 return;
1171 }
1172 MPM.addPass(ThinLTOBitcodeWriterPass(
1173 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1174 } else if (Action == Backend_EmitLL) {
1175 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1176 /*EmitLTOSummary=*/true));
1177 }
1178 } else {
1179 // Emit a module summary by default for Regular LTO except for ld64
1180 // targets
1181 bool EmitLTOSummary = shouldEmitRegularLTOSummary();
1182 if (EmitLTOSummary) {
1183 if (!TheModule->getModuleFlag("ThinLTO") && !CodeGenOpts.UnifiedLTO)
1184 TheModule->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
1185 if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1186 TheModule->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
1187 uint32_t(1));
1188 }
1189 if (Action == Backend_EmitBC) {
1190 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1191 EmitLTOSummary));
1192 } else if (Action == Backend_EmitLL) {
1193 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
1194 EmitLTOSummary));
1195 }
1196 }
1197
1198 if (shouldEmitUnifiedLTOModueFlag() &&
1199 !TheModule->getModuleFlag("UnifiedLTO"))
1200 TheModule->addModuleFlag(llvm::Module::Error, "UnifiedLTO", uint32_t(1));
1201 }
1202
1203 // FIXME: This should eventually be replaced by a first-class driver option.
1204 // This should be done for both clang and flang simultaneously.
1205 // Print a textual, '-passes=' compatible, representation of pipeline if
1206 // requested.
1207 if (PrintPipelinePasses) {
1208 MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
1209 auto PassName = PIC.getPassNameForClassName(ClassName);
1210 return PassName.empty() ? ClassName : PassName;
1211 });
1212 outs() << "\n";
1213 return;
1214 }
1215
1216 // Now that we have all of the passes ready, run them.
1217 {
1218 PrettyStackTraceString CrashInfo("Optimizer");
1219 llvm::TimeTraceScope TimeScope("Optimizer");
1220 Timer timer;
1221 if (CI.getCodeGenOpts().TimePasses) {
1222 timer.init("optimizer", "Optimizer", CI.getTimerGroup());
1223 CI.getFrontendTimer().yieldTo(timer);
1224 }
1225 MPM.run(*TheModule, MAM);
1226 if (CI.getCodeGenOpts().TimePasses)
1227 timer.yieldTo(CI.getFrontendTimer());
1228 }
1229 }
1230
1231 void EmitAssemblyHelper::RunCodegenPipeline(
1232 BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1233 std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1234 if (!actionRequiresCodeGen(Action))
1235 return;
1236
1237 // Normal mode, emit a .s or .o file by running the code generator. Note,
1238 // this also adds codegenerator level optimization passes.
1239 CodeGenFileType CGFT = getCodeGenFileType(Action);
1240
1241 // Invoke pre-codegen callback from plugin, which might want to take over the
1242 // entire code generation itself.
1243 for (const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.getPassPlugins()) {
1244 if (Plugin->invokePreCodeGenCallback(*TheModule, *TM, CGFT, *OS))
1245 return;
1246 }
1247
1248 // We still use the legacy PM to run the codegen pipeline since the new PM
1249 // does not work with the codegen pipeline.
1250 // FIXME: make the new PM work with the codegen pipeline.
1251 legacy::PassManager CodeGenPasses;
1252
1253 CodeGenPasses.add(
1254 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1255 // Add LibraryInfo.
1256 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1257 llvm::driver::createTLII(TargetTriple, CodeGenOpts.getVecLib()));
1258 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
1259
1260 const llvm::TargetOptions &Options = TM->Options;
1261 CodeGenPasses.add(new RuntimeLibraryInfoWrapper(
1262 TargetTriple, Options.ExceptionModel, Options.FloatABIType,
1263 Options.EABIVersion, Options.MCOptions.ABIName, Options.VecLib));
1264
1265 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1266 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1267 if (!DwoOS)
1268 return;
1269 }
1270
1271 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1272 DwoOS ? &DwoOS->os() : nullptr, CGFT,
1273 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
1274 Diags.Report(diag::err_fe_unable_to_interface_with_target);
1275 return;
1276 }
1277
1278 // If -print-pipeline-passes is requested, don't run the legacy pass manager.
1279 // FIXME: when codegen is switched to use the new pass manager, it should also
1280 // emit pass names here.
1281 if (PrintPipelinePasses) {
1282 return;
1283 }
1284
1285 {
1286 PrettyStackTraceString CrashInfo("Code generation");
1287 llvm::TimeTraceScope TimeScope("CodeGenPasses");
1288 Timer timer;
1289 if (CI.getCodeGenOpts().TimePasses) {
1290 timer.init("codegen", "Machine code generation", CI.getTimerGroup());
1291 CI.getFrontendTimer().yieldTo(timer);
1292 }
1293 CodeGenPasses.run(*TheModule);
1294 if (CI.getCodeGenOpts().TimePasses)
1295 timer.yieldTo(CI.getFrontendTimer());
1296 }
1297 }
1298
1299 void EmitAssemblyHelper::emitAssembly(BackendAction Action,
1300 std::unique_ptr<raw_pwrite_stream> OS,
1301 BackendConsumer *BC) {
1302 setCommandLineOpts(CodeGenOpts, CI.getVirtualFileSystem());
1303
1304 bool RequiresCodeGen = actionRequiresCodeGen(Action);
1305 CreateTargetMachine(RequiresCodeGen);
1306
1307 if (RequiresCodeGen && !TM)
1308 return;
1309 if (TM)
1310 TheModule->setDataLayout(TM->createDataLayout());
1311
1312 // Before executing passes, print the final values of the LLVM options.
1313 cl::PrintOptionValues();
1314
1315 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1316 RunOptimizationPipeline(Action, OS, ThinLinkOS, BC);
1317 RunCodegenPipeline(Action, OS, DwoOS);
1318
1319 if (ThinLinkOS)
1320 ThinLinkOS->keep();
1321 if (DwoOS)
1322 DwoOS->keep();
1323 }
1324
1325 static void
1326 runThinLTOBackend(CompilerInstance &CI, ModuleSummaryIndex *CombinedIndex,
1327 llvm::Module *M, std::unique_ptr<raw_pwrite_stream> OS,
1328 std::string SampleProfile, std::string ProfileRemapping,
1329 BackendAction Action) {
1330 DiagnosticsEngine &Diags = CI.getDiagnostics();
1331 const auto &CGOpts = CI.getCodeGenOpts();
1332 const auto &TOpts = CI.getTargetOpts();
1333 DenseMap<StringRef, DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1334 ModuleToDefinedGVSummaries;
1335 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1336
1337 setCommandLineOpts(CGOpts, CI.getVirtualFileSystem());
1338
1339 // We can simply import the values mentioned in the combined index, since
1340 // we should only invoke this using the individual indexes written out
1341 // via a WriteIndexesThinBackend.
1342 FunctionImporter::ImportIDTable ImportIDs;
1343 FunctionImporter::ImportMapTy ImportList(ImportIDs);
1344 if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1345 return;
1346
1347 auto AddStream = [&](size_t Task, const Twine &ModuleName) {
1348 return std::make_unique<CachedFileStream>(std::move(OS),
1349 CGOpts.ObjectFilenameForDebug);
1350 };
1351 lto::Config Conf;
1352 if (CGOpts.SaveTempsFilePrefix != "") {
1353 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1354 /* UseInputModulePath */ false)) {
1355 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1356 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1357 << '\n';
1358 });
1359 }
1360 }
1361 Conf.CPU = TOpts.CPU;
1362 Conf.CodeModel = getCodeModel(CGOpts);
1363 Conf.MAttrs = TOpts.Features;
1364 Conf.RelocModel = CGOpts.RelocationModel;
1365 std::optional<CodeGenOptLevel> OptLevelOrNone =
1366 CodeGenOpt::getLevel(CGOpts.OptimizationLevel);
1367 assert(OptLevelOrNone && "Invalid optimization level!");
1368 Conf.CGOptLevel = *OptLevelOrNone;
1369 Conf.OptLevel = CGOpts.OptimizationLevel;
1370 initTargetOptions(CI, Diags, Conf.Options);
1371 Conf.SampleProfile = std::move(SampleProfile);
1372 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1373 Conf.PTO.LoopInterchange = CGOpts.InterchangeLoops;
1374 Conf.PTO.LoopFusion = CGOpts.FuseLoops;
1375 // For historical reasons, loop interleaving is set to mirror setting for loop
1376 // unrolling.
1377 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1378 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1379 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1380 // Only enable CGProfilePass when using integrated assembler, since
1381 // non-integrated assemblers don't recognize .cgprofile section.
1382 Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1383
1384 // Context sensitive profile.
1385 if (CGOpts.hasProfileCSIRInstr()) {
1386 Conf.RunCSIRInstr = true;
1387 Conf.CSIRProfile = getProfileGenName(CGOpts);
1388 } else if (CGOpts.hasProfileCSIRUse()) {
1389 Conf.RunCSIRInstr = false;
1390 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1391 }
1392
1393 Conf.ProfileRemapping = std::move(ProfileRemapping);
1394 Conf.DebugPassManager = CGOpts.DebugPassManager;
1395 Conf.VerifyEach = CGOpts.VerifyEach;
1396 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1397 Conf.RemarksFilename = CGOpts.OptRecordFile;
1398 Conf.RemarksPasses = CGOpts.OptRecordPasses;
1399 Conf.RemarksFormat = CGOpts.OptRecordFormat;
1400 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1401 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1402 switch (Action) {
1403 case Backend_EmitNothing:
1404 Conf.PreCodeGenModuleHook = [](size_t Task, const llvm::Module &Mod) {
1405 return false;
1406 };
1407 break;
1408 case Backend_EmitLL:
1409 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1410 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1411 return false;
1412 };
1413 break;
1414 case Backend_EmitBC:
1415 Conf.PreCodeGenModuleHook = [&](size_t Task, const llvm::Module &Mod) {
1416 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1417 return false;
1418 };
1419 break;
1420 default:
1421 Conf.CGFileType = getCodeGenFileType(Action);
1422 break;
1423 }
1424
1425 // FIXME: Both ExecuteAction and thinBackend set up optimization remarks for
1426 // the same context.
1427 finalizeLLVMOptimizationRemarks(M->getContext());
1428 if (Error E =
1429 thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1430 ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1431 /*ModuleMap=*/nullptr, Conf.CodeGenOnly,
1432 /*IRAddStream=*/nullptr, CGOpts.CmdArgs)) {
1433 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1434 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1435 });
1436 }
1437 }
1438
1439 void clang::emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts,
1440 StringRef TDesc, llvm::Module *M,
1441 BackendAction Action,
1442 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
1443 std::unique_ptr<raw_pwrite_stream> OS,
1444 BackendConsumer *BC) {
1445 llvm::TimeTraceScope TimeScope("Backend");
1446 DiagnosticsEngine &Diags = CI.getDiagnostics();
1447
1448 std::unique_ptr<llvm::Module> EmptyModule;
1449 if (!CGOpts.ThinLTOIndexFile.empty()) {
1450 // FIXME(sandboxing): Figure out how to support distributed indexing.
1451 auto BypassSandbox = sys::sandbox::scopedDisable();
1452 // If we are performing a ThinLTO importing compile, load the function index
1453 // into memory and pass it into runThinLTOBackend, which will run the
1454 // function importer and invoke LTO passes.
1455 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1456 if (Error E = llvm::getModuleSummaryIndexForFile(
1457 CGOpts.ThinLTOIndexFile,
1458 /*IgnoreEmptyThinLTOIndexFile*/ true)
1459 .moveInto(CombinedIndex)) {
1460 logAllUnhandledErrors(std::move(E), errs(),
1461 "Error loading index file '" +
1462 CGOpts.ThinLTOIndexFile + "': ");
1463 return;
1464 }
1465
1466 // A null CombinedIndex means we should skip ThinLTO compilation
1467 // (LLVM will optionally ignore empty index files, returning null instead
1468 // of an error).
1469 if (CombinedIndex) {
1470 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1471 runThinLTOBackend(CI, CombinedIndex.get(), M, std::move(OS),
1472 CGOpts.SampleProfileFile, CGOpts.ProfileRemappingFile,
1473 Action);
1474 return;
1475 }
1476 // Distributed indexing detected that nothing from the module is needed
1477 // for the final linking. So we can skip the compilation. We sill need to
1478 // output an empty object file to make sure that a linker does not fail
1479 // trying to read it. Also for some features, like CFI, we must skip
1480 // the compilation as CombinedIndex does not contain all required
1481 // information.
1482 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1483 EmptyModule->setTargetTriple(M->getTargetTriple());
1484 M = EmptyModule.get();
1485 }
1486 }
1487
1488 EmitAssemblyHelper AsmHelper(CI, CGOpts, M, VFS);
1489 AsmHelper.emitAssembly(Action, std::move(OS), BC);
1490
1491 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1492 // DataLayout.
1493 if (AsmHelper.TM) {
1494 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1495 if (DLDesc != TDesc) {
1496 Diags.Report(diag::err_data_layout_mismatch) << DLDesc << TDesc;
1497 }
1498 }
1499 }
1500
1501 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1502 // __LLVM,__bitcode section.
1503 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1504 llvm::MemoryBufferRef Buf) {
1505 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1506 return;
1507 llvm::embedBitcodeInModule(
1508 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1509 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1510 CGOpts.CmdArgs);
1511 }
1512
1513 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1514 llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags) {
1515 if (CGOpts.OffloadObjects.empty())
1516 return;
1517
1518 for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1519 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1520 VFS.getBufferForFile(OffloadObject);
1521 if (ObjectOrErr.getError()) {
1522 Diags.Report(diag::err_failed_to_open_for_embedding) << OffloadObject;
1523 return;
1524 }
1525
1526 llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1527 Align(object::OffloadBinary::getAlignment()));
1528 }
1529 }