1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSummaryIndex.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/LTO/LTOBackend.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/Passes/PassBuilder.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/Transforms/Coroutines.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/IPO/AlwaysInliner.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
53 #include "llvm/Transforms/Instrumentation.h"
54 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include "llvm/Transforms/Scalar.h"
57 #include "llvm/Transforms/Scalar/GVN.h"
58 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
59 #include "llvm/Transforms/Utils/SymbolRewriter.h"
61 using namespace clang;
66 // Default filename used for profile generation.
67 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
69 class EmitAssemblyHelper {
70 DiagnosticsEngine &Diags;
71 const HeaderSearchOptions &HSOpts;
72 const CodeGenOptions &CodeGenOpts;
73 const clang::TargetOptions &TargetOpts;
74 const LangOptions &LangOpts;
77 Timer CodeGenerationTime;
79 std::unique_ptr<raw_pwrite_stream> OS;
81 TargetIRAnalysis getTargetIRAnalysis() const {
83 return TM->getTargetIRAnalysis();
85 return TargetIRAnalysis();
88 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
90 /// Generates the TargetMachine.
91 /// Leaves TM unchanged if it is unable to create the target machine.
92 /// Some of our clang tests specify triples which are not built
93 /// into clang. This is okay because these tests check the generated
94 /// IR, and they require DataLayout which depends on the triple.
95 /// In this case, we allow this method to fail and not report an error.
96 /// When MustCreateTM is used, we print an error if we are unable to load
97 /// the requested target.
98 void CreateTargetMachine(bool MustCreateTM);
100 /// Add passes necessary to emit assembly or LLVM IR.
102 /// \return True on success.
103 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
104 raw_pwrite_stream &OS);
107 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
108 const HeaderSearchOptions &HeaderSearchOpts,
109 const CodeGenOptions &CGOpts,
110 const clang::TargetOptions &TOpts,
111 const LangOptions &LOpts, Module *M)
112 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
113 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
114 CodeGenerationTime("codegen", "Code Generation Time") {}
116 ~EmitAssemblyHelper() {
117 if (CodeGenOpts.DisableFree)
118 BuryPointer(std::move(TM));
121 std::unique_ptr<TargetMachine> TM;
123 void EmitAssembly(BackendAction Action,
124 std::unique_ptr<raw_pwrite_stream> OS);
126 void EmitAssemblyWithNewPassManager(BackendAction Action,
127 std::unique_ptr<raw_pwrite_stream> OS);
130 // We need this wrapper to access LangOpts and CGOpts from extension functions
131 // that we add to the PassManagerBuilder.
132 class PassManagerBuilderWrapper : public PassManagerBuilder {
134 PassManagerBuilderWrapper(const Triple &TargetTriple,
135 const CodeGenOptions &CGOpts,
136 const LangOptions &LangOpts)
137 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
138 LangOpts(LangOpts) {}
139 const Triple &getTargetTriple() const { return TargetTriple; }
140 const CodeGenOptions &getCGOpts() const { return CGOpts; }
141 const LangOptions &getLangOpts() const { return LangOpts; }
144 const Triple &TargetTriple;
145 const CodeGenOptions &CGOpts;
146 const LangOptions &LangOpts;
150 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
151 if (Builder.OptLevel > 0)
152 PM.add(createObjCARCAPElimPass());
155 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
156 if (Builder.OptLevel > 0)
157 PM.add(createObjCARCExpandPass());
160 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
161 if (Builder.OptLevel > 0)
162 PM.add(createObjCARCOptPass());
165 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
166 legacy::PassManagerBase &PM) {
167 PM.add(createAddDiscriminatorsPass());
170 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
171 legacy::PassManagerBase &PM) {
172 PM.add(createBoundsCheckingLegacyPass());
175 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
176 legacy::PassManagerBase &PM) {
177 const PassManagerBuilderWrapper &BuilderWrapper =
178 static_cast<const PassManagerBuilderWrapper&>(Builder);
179 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
180 SanitizerCoverageOptions Opts;
182 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
183 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
184 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
185 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
186 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
187 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
188 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
189 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
190 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
191 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
192 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
193 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
194 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
195 PM.add(createSanitizerCoverageModulePass(Opts));
198 // Check if ASan should use GC-friendly instrumentation for globals.
199 // First of all, there is no point if -fdata-sections is off (expect for MachO,
200 // where this is not a factor). Also, on ELF this feature requires an assembler
201 // extension that only works with -integrated-as at the moment.
202 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
203 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
205 switch (T.getObjectFormat()) {
210 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
216 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
217 legacy::PassManagerBase &PM) {
218 const PassManagerBuilderWrapper &BuilderWrapper =
219 static_cast<const PassManagerBuilderWrapper&>(Builder);
220 const Triple &T = BuilderWrapper.getTargetTriple();
221 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
222 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
223 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
224 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
225 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
227 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
231 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
232 legacy::PassManagerBase &PM) {
233 PM.add(createAddressSanitizerFunctionPass(
234 /*CompileKernel*/ true,
235 /*Recover*/ true, /*UseAfterScope*/ false));
236 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
240 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
241 legacy::PassManagerBase &PM) {
242 const PassManagerBuilderWrapper &BuilderWrapper =
243 static_cast<const PassManagerBuilderWrapper &>(Builder);
244 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
245 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
246 PM.add(createHWAddressSanitizerPass(Recover));
249 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
250 legacy::PassManagerBase &PM) {
251 const PassManagerBuilderWrapper &BuilderWrapper =
252 static_cast<const PassManagerBuilderWrapper&>(Builder);
253 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
254 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
255 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
256 PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
258 // MemorySanitizer inserts complex instrumentation that mostly follows
259 // the logic of the original code, but operates on "shadow" values.
260 // It can benefit from re-running some general purpose optimization passes.
261 if (Builder.OptLevel > 0) {
262 PM.add(createEarlyCSEPass());
263 PM.add(createReassociatePass());
264 PM.add(createLICMPass());
265 PM.add(createGVNPass());
266 PM.add(createInstructionCombiningPass());
267 PM.add(createDeadStoreEliminationPass());
271 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
272 legacy::PassManagerBase &PM) {
273 PM.add(createThreadSanitizerPass());
276 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
277 legacy::PassManagerBase &PM) {
278 const PassManagerBuilderWrapper &BuilderWrapper =
279 static_cast<const PassManagerBuilderWrapper&>(Builder);
280 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
281 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
284 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
285 legacy::PassManagerBase &PM) {
286 const PassManagerBuilderWrapper &BuilderWrapper =
287 static_cast<const PassManagerBuilderWrapper&>(Builder);
288 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
289 EfficiencySanitizerOptions Opts;
290 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
291 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
292 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
293 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
294 PM.add(createEfficiencySanitizerPass(Opts));
297 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
298 const CodeGenOptions &CodeGenOpts) {
299 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
300 if (!CodeGenOpts.SimplifyLibCalls)
301 TLII->disableAllFunctions();
303 // Disable individual libc/libm calls in TargetLibraryInfo.
305 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
306 if (TLII->getLibFunc(FuncName, F))
307 TLII->setUnavailable(F);
310 switch (CodeGenOpts.getVecLib()) {
311 case CodeGenOptions::Accelerate:
312 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
314 case CodeGenOptions::SVML:
315 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
323 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
324 legacy::PassManager *MPM) {
325 llvm::SymbolRewriter::RewriteDescriptorList DL;
327 llvm::SymbolRewriter::RewriteMapParser MapParser;
328 for (const auto &MapFile : Opts.RewriteMapFiles)
329 MapParser.parse(MapFile, &DL);
331 MPM->add(createRewriteSymbolsPass(DL));
334 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
335 switch (CodeGenOpts.OptimizationLevel) {
337 llvm_unreachable("Invalid optimization level!");
339 return CodeGenOpt::None;
341 return CodeGenOpt::Less;
343 return CodeGenOpt::Default; // O2/Os/Oz
345 return CodeGenOpt::Aggressive;
349 static Optional<llvm::CodeModel::Model>
350 getCodeModel(const CodeGenOptions &CodeGenOpts) {
351 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
352 .Case("small", llvm::CodeModel::Small)
353 .Case("kernel", llvm::CodeModel::Kernel)
354 .Case("medium", llvm::CodeModel::Medium)
355 .Case("large", llvm::CodeModel::Large)
356 .Case("default", ~1u)
358 assert(CodeModel != ~0u && "invalid code model!");
359 if (CodeModel == ~1u)
361 return static_cast<llvm::CodeModel::Model>(CodeModel);
364 static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
365 // Keep this synced with the equivalent code in
366 // lib/Frontend/CompilerInvocation.cpp
367 llvm::Optional<llvm::Reloc::Model> RM;
368 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
369 .Case("static", llvm::Reloc::Static)
370 .Case("pic", llvm::Reloc::PIC_)
371 .Case("ropi", llvm::Reloc::ROPI)
372 .Case("rwpi", llvm::Reloc::RWPI)
373 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
374 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
375 assert(RM.hasValue() && "invalid PIC model!");
379 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
380 if (Action == Backend_EmitObj)
381 return TargetMachine::CGFT_ObjectFile;
382 else if (Action == Backend_EmitMCNull)
383 return TargetMachine::CGFT_Null;
385 assert(Action == Backend_EmitAssembly && "Invalid action!");
386 return TargetMachine::CGFT_AssemblyFile;
390 static void initTargetOptions(llvm::TargetOptions &Options,
391 const CodeGenOptions &CodeGenOpts,
392 const clang::TargetOptions &TargetOpts,
393 const LangOptions &LangOpts,
394 const HeaderSearchOptions &HSOpts) {
395 Options.ThreadModel =
396 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
397 .Case("posix", llvm::ThreadModel::POSIX)
398 .Case("single", llvm::ThreadModel::Single);
400 // Set float ABI type.
401 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
402 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
403 "Invalid Floating Point ABI!");
404 Options.FloatABIType =
405 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
406 .Case("soft", llvm::FloatABI::Soft)
407 .Case("softfp", llvm::FloatABI::Soft)
408 .Case("hard", llvm::FloatABI::Hard)
409 .Default(llvm::FloatABI::Default);
411 // Set FP fusion mode.
412 switch (LangOpts.getDefaultFPContractMode()) {
413 case LangOptions::FPC_Off:
414 // Preserve any contraction performed by the front-end. (Strict performs
415 // splitting of the muladd instrinsic in the backend.)
416 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
418 case LangOptions::FPC_On:
419 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
421 case LangOptions::FPC_Fast:
422 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
426 Options.UseInitArray = CodeGenOpts.UseInitArray;
427 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
428 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
429 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
432 Options.EABIVersion = TargetOpts.EABIVersion;
434 if (LangOpts.SjLjExceptions)
435 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
436 if (LangOpts.SEHExceptions)
437 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
438 if (LangOpts.DWARFExceptions)
439 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
441 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
442 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
443 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
444 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
445 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
446 Options.FunctionSections = CodeGenOpts.FunctionSections;
447 Options.DataSections = CodeGenOpts.DataSections;
448 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
449 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
450 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
452 if (CodeGenOpts.EnableSplitDwarf)
453 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
454 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
455 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
456 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
457 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
458 Options.MCOptions.MCIncrementalLinkerCompatible =
459 CodeGenOpts.IncrementalLinkerCompatible;
460 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
461 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
462 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
463 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
464 Options.MCOptions.ABIName = TargetOpts.ABI;
465 for (const auto &Entry : HSOpts.UserEntries)
466 if (!Entry.IsFramework &&
467 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
468 Entry.Group == frontend::IncludeDirGroup::Angled ||
469 Entry.Group == frontend::IncludeDirGroup::System))
470 Options.MCOptions.IASSearchPaths.push_back(
471 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
474 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
475 legacy::FunctionPassManager &FPM) {
476 // Handle disabling of all LLVM passes, where we want to preserve the
477 // internal module before any optimization.
478 if (CodeGenOpts.DisableLLVMPasses)
481 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
482 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
483 // are inserted before PMBuilder ones - they'd get the default-constructed
484 // TLI with an unknown target otherwise.
485 Triple TargetTriple(TheModule->getTargetTriple());
486 std::unique_ptr<TargetLibraryInfoImpl> TLII(
487 createTLII(TargetTriple, CodeGenOpts));
489 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
491 // At O0 and O1 we only run the always inliner which is more efficient. At
492 // higher optimization levels we run the normal inliner.
493 if (CodeGenOpts.OptimizationLevel <= 1) {
494 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
495 !CodeGenOpts.DisableLifetimeMarkers);
496 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
498 // We do not want to inline hot callsites for SamplePGO module-summary build
499 // because profile annotation will happen again in ThinLTO backend, and we
500 // want the IR of the hot path to match the profile.
501 PMBuilder.Inliner = createFunctionInliningPass(
502 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
503 (!CodeGenOpts.SampleProfileFile.empty() &&
504 CodeGenOpts.EmitSummaryIndex));
507 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
508 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
509 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
510 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
512 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
513 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
514 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
515 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
516 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
518 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
521 TM->adjustPassManager(PMBuilder);
523 if (CodeGenOpts.DebugInfoForProfiling ||
524 !CodeGenOpts.SampleProfileFile.empty())
525 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
526 addAddDiscriminatorsPass);
528 // In ObjC ARC mode, add the main ARC optimization passes.
529 if (LangOpts.ObjCAutoRefCount) {
530 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
531 addObjCARCExpandPass);
532 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
533 addObjCARCAPElimPass);
534 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
538 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
539 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
540 addBoundsCheckingPass);
541 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
542 addBoundsCheckingPass);
545 if (CodeGenOpts.SanitizeCoverageType ||
546 CodeGenOpts.SanitizeCoverageIndirectCalls ||
547 CodeGenOpts.SanitizeCoverageTraceCmp) {
548 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
549 addSanitizerCoveragePass);
550 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
551 addSanitizerCoveragePass);
554 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
555 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
556 addAddressSanitizerPasses);
557 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
558 addAddressSanitizerPasses);
561 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
562 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
563 addKernelAddressSanitizerPasses);
564 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
565 addKernelAddressSanitizerPasses);
568 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
569 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
570 addHWAddressSanitizerPasses);
571 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
572 addHWAddressSanitizerPasses);
575 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
576 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
577 addMemorySanitizerPass);
578 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
579 addMemorySanitizerPass);
582 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
583 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
584 addThreadSanitizerPass);
585 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
586 addThreadSanitizerPass);
589 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
590 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
591 addDataFlowSanitizerPass);
592 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
593 addDataFlowSanitizerPass);
596 if (LangOpts.CoroutinesTS)
597 addCoroutinePassesToExtensionPoints(PMBuilder);
599 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
600 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
601 addEfficiencySanitizerPass);
602 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
603 addEfficiencySanitizerPass);
606 // Set up the per-function pass manager.
607 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
608 if (CodeGenOpts.VerifyModule)
609 FPM.add(createVerifierPass());
611 // Set up the per-module pass manager.
612 if (!CodeGenOpts.RewriteMapFiles.empty())
613 addSymbolRewriterPass(CodeGenOpts, &MPM);
615 if (!CodeGenOpts.DisableGCov &&
616 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
617 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
618 // LLVM's -default-gcov-version flag is set to something invalid.
620 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
621 Options.EmitData = CodeGenOpts.EmitGcovArcs;
622 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
623 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
624 Options.NoRedZone = CodeGenOpts.DisableRedZone;
625 Options.FunctionNamesInData =
626 !CodeGenOpts.CoverageNoFunctionNamesInData;
627 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
628 MPM.add(createGCOVProfilerPass(Options));
629 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
630 MPM.add(createStripSymbolsPass(true));
633 if (CodeGenOpts.hasProfileClangInstr()) {
634 InstrProfOptions Options;
635 Options.NoRedZone = CodeGenOpts.DisableRedZone;
636 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
637 MPM.add(createInstrProfilingLegacyPass(Options));
639 if (CodeGenOpts.hasProfileIRInstr()) {
640 PMBuilder.EnablePGOInstrGen = true;
641 if (!CodeGenOpts.InstrProfileOutput.empty())
642 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
644 PMBuilder.PGOInstrGen = DefaultProfileGenName;
646 if (CodeGenOpts.hasProfileIRUse())
647 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
649 if (!CodeGenOpts.SampleProfileFile.empty())
650 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
652 PMBuilder.populateFunctionPassManager(FPM);
653 PMBuilder.populateModulePassManager(MPM);
656 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
657 SmallVector<const char *, 16> BackendArgs;
658 BackendArgs.push_back("clang"); // Fake program name.
659 if (!CodeGenOpts.DebugPass.empty()) {
660 BackendArgs.push_back("-debug-pass");
661 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
663 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
664 BackendArgs.push_back("-limit-float-precision");
665 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
667 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
668 BackendArgs.push_back(BackendOption.c_str());
669 BackendArgs.push_back(nullptr);
670 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
674 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
675 // Create the TargetMachine for generating code.
677 std::string Triple = TheModule->getTargetTriple();
678 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
681 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
685 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
686 std::string FeaturesStr =
687 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
688 llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
689 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
691 llvm::TargetOptions Options;
692 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
693 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
694 Options, RM, CM, OptLevel));
697 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
698 BackendAction Action,
699 raw_pwrite_stream &OS) {
701 llvm::Triple TargetTriple(TheModule->getTargetTriple());
702 std::unique_ptr<TargetLibraryInfoImpl> TLII(
703 createTLII(TargetTriple, CodeGenOpts));
704 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
706 // Normal mode, emit a .s or .o file by running the code generator. Note,
707 // this also adds codegenerator level optimization passes.
708 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
710 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
711 // "codegen" passes so that it isn't run multiple times when there is
712 // inlining happening.
713 if (CodeGenOpts.OptimizationLevel > 0)
714 CodeGenPasses.add(createObjCARCContractPass());
716 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
717 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
718 Diags.Report(diag::err_fe_unable_to_interface_with_target);
725 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
726 std::unique_ptr<raw_pwrite_stream> OS) {
727 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
729 setCommandLineOpts(CodeGenOpts);
731 bool UsesCodeGen = (Action != Backend_EmitNothing &&
732 Action != Backend_EmitBC &&
733 Action != Backend_EmitLL);
734 CreateTargetMachine(UsesCodeGen);
736 if (UsesCodeGen && !TM)
739 TheModule->setDataLayout(TM->createDataLayout());
741 legacy::PassManager PerModulePasses;
743 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
745 legacy::FunctionPassManager PerFunctionPasses(TheModule);
746 PerFunctionPasses.add(
747 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
749 CreatePasses(PerModulePasses, PerFunctionPasses);
751 legacy::PassManager CodeGenPasses;
753 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
755 std::unique_ptr<raw_fd_ostream> ThinLinkOS;
758 case Backend_EmitNothing:
762 if (CodeGenOpts.EmitSummaryIndex) {
763 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
765 ThinLinkOS.reset(new llvm::raw_fd_ostream(
766 CodeGenOpts.ThinLinkBitcodeFile, EC,
767 llvm::sys::fs::F_None));
769 Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
775 createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
779 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
784 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
788 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
792 // Before executing passes, print the final values of the LLVM options.
793 cl::PrintOptionValues();
795 // Run passes. For now we do all passes at once, but eventually we
796 // would like to have the option of streaming code generation.
799 PrettyStackTraceString CrashInfo("Per-function optimization");
801 PerFunctionPasses.doInitialization();
802 for (Function &F : *TheModule)
803 if (!F.isDeclaration())
804 PerFunctionPasses.run(F);
805 PerFunctionPasses.doFinalization();
809 PrettyStackTraceString CrashInfo("Per-module optimization passes");
810 PerModulePasses.run(*TheModule);
814 PrettyStackTraceString CrashInfo("Code generation");
815 CodeGenPasses.run(*TheModule);
819 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
820 switch (Opts.OptimizationLevel) {
822 llvm_unreachable("Invalid optimization level!");
825 return PassBuilder::O1;
828 switch (Opts.OptimizeSize) {
830 llvm_unreachable("Invalide optimization level for size!");
833 return PassBuilder::O2;
836 return PassBuilder::Os;
839 return PassBuilder::Oz;
843 return PassBuilder::O3;
847 /// A clean version of `EmitAssembly` that uses the new pass manager.
849 /// Not all features are currently supported in this system, but where
850 /// necessary it falls back to the legacy pass manager to at least provide
851 /// basic functionality.
853 /// This API is planned to have its functionality finished and then to replace
854 /// `EmitAssembly` at some point in the future when the default switches.
855 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
856 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
857 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
858 setCommandLineOpts(CodeGenOpts);
860 // The new pass manager always makes a target machine available to passes
861 // during construction.
862 CreateTargetMachine(/*MustCreateTM*/ true);
864 // This will already be diagnosed, just bail.
866 TheModule->setDataLayout(TM->createDataLayout());
868 Optional<PGOOptions> PGOOpt;
870 if (CodeGenOpts.hasProfileIRInstr())
871 // -fprofile-generate.
872 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
873 ? DefaultProfileGenName
874 : CodeGenOpts.InstrProfileOutput,
875 "", "", true, CodeGenOpts.DebugInfoForProfiling);
876 else if (CodeGenOpts.hasProfileIRUse())
878 PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
879 CodeGenOpts.DebugInfoForProfiling);
880 else if (!CodeGenOpts.SampleProfileFile.empty())
881 // -fprofile-sample-use
882 PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
883 CodeGenOpts.DebugInfoForProfiling);
884 else if (CodeGenOpts.DebugInfoForProfiling)
885 // -fdebug-info-for-profiling
886 PGOOpt = PGOOptions("", "", "", false, true);
888 PassBuilder PB(TM.get(), PGOOpt);
890 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
891 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
892 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
893 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
895 // Register the AA manager first so that our version is the one used.
896 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
898 // Register the target library analysis directly and give it a customized
900 Triple TargetTriple(TheModule->getTargetTriple());
901 std::unique_ptr<TargetLibraryInfoImpl> TLII(
902 createTLII(TargetTriple, CodeGenOpts));
903 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
904 MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
906 // Register all the basic analyses with the managers.
907 PB.registerModuleAnalyses(MAM);
908 PB.registerCGSCCAnalyses(CGAM);
909 PB.registerFunctionAnalyses(FAM);
910 PB.registerLoopAnalyses(LAM);
911 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
913 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
915 if (!CodeGenOpts.DisableLLVMPasses) {
916 bool IsThinLTO = CodeGenOpts.EmitSummaryIndex;
917 bool IsLTO = CodeGenOpts.PrepareForLTO;
919 if (CodeGenOpts.OptimizationLevel == 0) {
920 // Build a minimal pipeline based on the semantics required by Clang,
921 // which is just that always inlining occurs.
922 MPM.addPass(AlwaysInlinerPass());
924 // At -O0 we directly run necessary sanitizer passes.
925 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
926 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
928 // Lastly, add a semantically necessary pass for ThinLTO.
930 MPM.addPass(NameAnonGlobalPass());
932 // Map our optimization levels into one of the distinct levels used to
933 // configure the pipeline.
934 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
936 // Register callbacks to schedule sanitizer passes at the appropriate part of
938 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
939 PB.registerScalarOptimizerLateEPCallback(
940 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
941 FPM.addPass(BoundsCheckingPass());
945 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
946 Level, CodeGenOpts.DebugPassManager);
947 MPM.addPass(NameAnonGlobalPass());
949 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
950 CodeGenOpts.DebugPassManager);
952 MPM = PB.buildPerModuleDefaultPipeline(Level,
953 CodeGenOpts.DebugPassManager);
958 // FIXME: We still use the legacy pass manager to do code generation. We
959 // create that pass manager here and use it as needed below.
960 legacy::PassManager CodeGenPasses;
961 bool NeedCodeGen = false;
962 Optional<raw_fd_ostream> ThinLinkOS;
964 // Append any output we need to the pass manager.
966 case Backend_EmitNothing:
970 if (CodeGenOpts.EmitSummaryIndex) {
971 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
973 ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
974 llvm::sys::fs::F_None);
976 Diags.Report(diag::err_fe_unable_to_open_output)
977 << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
982 ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
984 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
985 CodeGenOpts.EmitSummaryIndex,
986 CodeGenOpts.EmitSummaryIndex));
991 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
994 case Backend_EmitAssembly:
995 case Backend_EmitMCNull:
996 case Backend_EmitObj:
999 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1000 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
1001 // FIXME: Should we handle this error differently?
1006 // Before executing passes, print the final values of the LLVM options.
1007 cl::PrintOptionValues();
1009 // Now that we have all of the passes ready, run them.
1011 PrettyStackTraceString CrashInfo("Optimizer");
1012 MPM.run(*TheModule, MAM);
1015 // Now if needed, run the legacy PM for codegen.
1017 PrettyStackTraceString CrashInfo("Code generation");
1018 CodeGenPasses.run(*TheModule);
1022 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1023 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1025 return BMsOrErr.takeError();
1027 // The bitcode file may contain multiple modules, we want the one that is
1028 // marked as being the ThinLTO module.
1029 for (BitcodeModule &BM : *BMsOrErr) {
1030 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1031 if (LTOInfo && LTOInfo->IsThinLTO)
1035 return make_error<StringError>("Could not find module summary",
1036 inconvertibleErrorCode());
1039 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1040 const HeaderSearchOptions &HeaderOpts,
1041 const CodeGenOptions &CGOpts,
1042 const clang::TargetOptions &TOpts,
1043 const LangOptions &LOpts,
1044 std::unique_ptr<raw_pwrite_stream> OS,
1045 std::string SampleProfile,
1046 BackendAction Action) {
1047 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1048 ModuleToDefinedGVSummaries;
1049 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1051 setCommandLineOpts(CGOpts);
1053 // We can simply import the values mentioned in the combined index, since
1054 // we should only invoke this using the individual indexes written out
1055 // via a WriteIndexesThinBackend.
1056 FunctionImporter::ImportMapTy ImportList;
1057 for (auto &GlobalList : *CombinedIndex) {
1058 // Ignore entries for undefined references.
1059 if (GlobalList.second.SummaryList.empty())
1062 auto GUID = GlobalList.first;
1063 assert(GlobalList.second.SummaryList.size() == 1 &&
1064 "Expected individual combined index to have one summary per GUID");
1065 auto &Summary = GlobalList.second.SummaryList[0];
1066 // Skip the summaries for the importing module. These are included to
1067 // e.g. record required linkage changes.
1068 if (Summary->modulePath() == M->getModuleIdentifier())
1070 // Doesn't matter what value we plug in to the map, just needs an entry
1071 // to provoke importing by thinBackend.
1072 ImportList[Summary->modulePath()][GUID] = 1;
1075 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1076 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1078 for (auto &I : ImportList) {
1079 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1080 llvm::MemoryBuffer::getFile(I.first());
1082 errs() << "Error loading imported file '" << I.first()
1083 << "': " << MBOrErr.getError().message() << "\n";
1087 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1089 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1090 errs() << "Error loading imported file '" << I.first()
1091 << "': " << EIB.message() << '\n';
1095 ModuleMap.insert({I.first(), *BMOrErr});
1097 OwnedImports.push_back(std::move(*MBOrErr));
1099 auto AddStream = [&](size_t Task) {
1100 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1103 Conf.CPU = TOpts.CPU;
1104 Conf.CodeModel = getCodeModel(CGOpts);
1105 Conf.MAttrs = TOpts.Features;
1106 Conf.RelocModel = getRelocModel(CGOpts);
1107 Conf.CGOptLevel = getCGOptLevel(CGOpts);
1108 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1109 Conf.SampleProfile = std::move(SampleProfile);
1110 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1111 Conf.DebugPassManager = CGOpts.DebugPassManager;
1113 case Backend_EmitNothing:
1114 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1118 case Backend_EmitLL:
1119 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1120 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1124 case Backend_EmitBC:
1125 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1126 WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1131 Conf.CGFileType = getCodeGenFileType(Action);
1134 if (Error E = thinBackend(
1135 Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1136 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1137 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1138 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1143 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1144 const HeaderSearchOptions &HeaderOpts,
1145 const CodeGenOptions &CGOpts,
1146 const clang::TargetOptions &TOpts,
1147 const LangOptions &LOpts,
1148 const llvm::DataLayout &TDesc, Module *M,
1149 BackendAction Action,
1150 std::unique_ptr<raw_pwrite_stream> OS) {
1151 if (!CGOpts.ThinLTOIndexFile.empty()) {
1152 // If we are performing a ThinLTO importing compile, load the function index
1153 // into memory and pass it into runThinLTOBackend, which will run the
1154 // function importer and invoke LTO passes.
1155 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1156 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1157 /*IgnoreEmptyThinLTOIndexFile*/true);
1159 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1160 "Error loading index file '" +
1161 CGOpts.ThinLTOIndexFile + "': ");
1164 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1165 // A null CombinedIndex means we should skip ThinLTO compilation
1166 // (LLVM will optionally ignore empty index files, returning null instead
1168 bool DoThinLTOBackend = CombinedIndex != nullptr;
1169 if (DoThinLTOBackend) {
1170 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1171 LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1176 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1178 if (CGOpts.ExperimentalNewPassManager)
1179 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1181 AsmHelper.EmitAssembly(Action, std::move(OS));
1183 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1186 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1187 if (DLDesc != TDesc.getStringRepresentation()) {
1188 unsigned DiagID = Diags.getCustomDiagID(
1189 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1190 "expected target description '%1'");
1191 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1196 static const char* getSectionNameForBitcode(const Triple &T) {
1197 switch (T.getObjectFormat()) {
1199 return "__LLVM,__bitcode";
1203 case Triple::UnknownObjectFormat:
1206 llvm_unreachable("Unimplemented ObjectFormatType");
1209 static const char* getSectionNameForCommandline(const Triple &T) {
1210 switch (T.getObjectFormat()) {
1212 return "__LLVM,__cmdline";
1216 case Triple::UnknownObjectFormat:
1219 llvm_unreachable("Unimplemented ObjectFormatType");
1222 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1223 // __LLVM,__bitcode section.
1224 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1225 llvm::MemoryBufferRef Buf) {
1226 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1229 // Save llvm.compiler.used and remote it.
1230 SmallVector<Constant*, 2> UsedArray;
1231 SmallSet<GlobalValue*, 4> UsedGlobals;
1232 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1233 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1234 for (auto *GV : UsedGlobals) {
1235 if (GV->getName() != "llvm.embedded.module" &&
1236 GV->getName() != "llvm.cmdline")
1237 UsedArray.push_back(
1238 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1241 Used->eraseFromParent();
1243 // Embed the bitcode for the llvm module.
1245 ArrayRef<uint8_t> ModuleData;
1246 Triple T(M->getTargetTriple());
1247 // Create a constant that contains the bitcode.
1248 // In case of embedding a marker, ignore the input Buf and use the empty
1249 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1250 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1251 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1252 (const unsigned char *)Buf.getBufferEnd())) {
1253 // If the input is LLVM Assembly, bitcode is produced by serializing
1254 // the module. Use-lists order need to be perserved in this case.
1255 llvm::raw_string_ostream OS(Data);
1256 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1258 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1260 // If the input is LLVM bitcode, write the input byte stream directly.
1261 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1262 Buf.getBufferSize());
1264 llvm::Constant *ModuleConstant =
1265 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1266 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1267 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1269 GV->setSection(getSectionNameForBitcode(T));
1270 UsedArray.push_back(
1271 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1272 if (llvm::GlobalVariable *Old =
1273 M->getGlobalVariable("llvm.embedded.module", true)) {
1274 assert(Old->hasOneUse() &&
1275 "llvm.embedded.module can only be used once in llvm.compiler.used");
1277 Old->eraseFromParent();
1279 GV->setName("llvm.embedded.module");
1282 // Skip if only bitcode needs to be embedded.
1283 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1284 // Embed command-line options.
1285 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1286 CGOpts.CmdArgs.size());
1287 llvm::Constant *CmdConstant =
1288 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1289 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1290 llvm::GlobalValue::PrivateLinkage,
1292 GV->setSection(getSectionNameForCommandline(T));
1293 UsedArray.push_back(
1294 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1295 if (llvm::GlobalVariable *Old =
1296 M->getGlobalVariable("llvm.cmdline", true)) {
1297 assert(Old->hasOneUse() &&
1298 "llvm.cmdline can only be used once in llvm.compiler.used");
1300 Old->eraseFromParent();
1302 GV->setName("llvm.cmdline");
1306 if (UsedArray.empty())
1309 // Recreate llvm.compiler.used.
1310 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1311 auto *NewUsed = new GlobalVariable(
1312 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1313 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1314 NewUsed->setSection("llvm.metadata");