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/Target/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/ObjCARC.h"
55 #include "llvm/Transforms/Scalar.h"
56 #include "llvm/Transforms/Scalar/GVN.h"
57 #include "llvm/Transforms/Utils/SymbolRewriter.h"
59 using namespace clang;
64 // Default filename used for profile generation.
65 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
67 class EmitAssemblyHelper {
68 DiagnosticsEngine &Diags;
69 const HeaderSearchOptions &HSOpts;
70 const CodeGenOptions &CodeGenOpts;
71 const clang::TargetOptions &TargetOpts;
72 const LangOptions &LangOpts;
75 Timer CodeGenerationTime;
77 std::unique_ptr<raw_pwrite_stream> OS;
79 TargetIRAnalysis getTargetIRAnalysis() const {
81 return TM->getTargetIRAnalysis();
83 return TargetIRAnalysis();
86 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
88 /// Generates the TargetMachine.
89 /// Leaves TM unchanged if it is unable to create the target machine.
90 /// Some of our clang tests specify triples which are not built
91 /// into clang. This is okay because these tests check the generated
92 /// IR, and they require DataLayout which depends on the triple.
93 /// In this case, we allow this method to fail and not report an error.
94 /// When MustCreateTM is used, we print an error if we are unable to load
95 /// the requested target.
96 void CreateTargetMachine(bool MustCreateTM);
98 /// Add passes necessary to emit assembly or LLVM IR.
100 /// \return True on success.
101 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
102 raw_pwrite_stream &OS);
105 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
106 const HeaderSearchOptions &HeaderSearchOpts,
107 const CodeGenOptions &CGOpts,
108 const clang::TargetOptions &TOpts,
109 const LangOptions &LOpts, Module *M)
110 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
111 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
112 CodeGenerationTime("codegen", "Code Generation Time") {}
114 ~EmitAssemblyHelper() {
115 if (CodeGenOpts.DisableFree)
116 BuryPointer(std::move(TM));
119 std::unique_ptr<TargetMachine> TM;
121 void EmitAssembly(BackendAction Action,
122 std::unique_ptr<raw_pwrite_stream> OS);
124 void EmitAssemblyWithNewPassManager(BackendAction Action,
125 std::unique_ptr<raw_pwrite_stream> OS);
128 // We need this wrapper to access LangOpts and CGOpts from extension functions
129 // that we add to the PassManagerBuilder.
130 class PassManagerBuilderWrapper : public PassManagerBuilder {
132 PassManagerBuilderWrapper(const Triple &TargetTriple,
133 const CodeGenOptions &CGOpts,
134 const LangOptions &LangOpts)
135 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
136 LangOpts(LangOpts) {}
137 const Triple &getTargetTriple() const { return TargetTriple; }
138 const CodeGenOptions &getCGOpts() const { return CGOpts; }
139 const LangOptions &getLangOpts() const { return LangOpts; }
142 const Triple &TargetTriple;
143 const CodeGenOptions &CGOpts;
144 const LangOptions &LangOpts;
148 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
149 if (Builder.OptLevel > 0)
150 PM.add(createObjCARCAPElimPass());
153 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
154 if (Builder.OptLevel > 0)
155 PM.add(createObjCARCExpandPass());
158 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
159 if (Builder.OptLevel > 0)
160 PM.add(createObjCARCOptPass());
163 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
164 legacy::PassManagerBase &PM) {
165 PM.add(createAddDiscriminatorsPass());
168 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
169 legacy::PassManagerBase &PM) {
170 PM.add(createBoundsCheckingPass());
173 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
174 legacy::PassManagerBase &PM) {
175 const PassManagerBuilderWrapper &BuilderWrapper =
176 static_cast<const PassManagerBuilderWrapper&>(Builder);
177 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
178 SanitizerCoverageOptions Opts;
180 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
181 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
182 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
183 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
184 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
185 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
186 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
187 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
188 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
189 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
190 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
191 PM.add(createSanitizerCoverageModulePass(Opts));
194 // Check if ASan should use GC-friendly instrumentation for globals.
195 // First of all, there is no point if -fdata-sections is off (expect for MachO,
196 // where this is not a factor). Also, on ELF this feature requires an assembler
197 // extension that only works with -integrated-as at the moment.
198 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
199 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
201 switch (T.getObjectFormat()) {
206 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
212 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
213 legacy::PassManagerBase &PM) {
214 const PassManagerBuilderWrapper &BuilderWrapper =
215 static_cast<const PassManagerBuilderWrapper&>(Builder);
216 const Triple &T = BuilderWrapper.getTargetTriple();
217 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
218 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
219 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
220 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
221 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
223 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
227 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
228 legacy::PassManagerBase &PM) {
229 PM.add(createAddressSanitizerFunctionPass(
230 /*CompileKernel*/ true,
231 /*Recover*/ true, /*UseAfterScope*/ false));
232 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
236 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
237 legacy::PassManagerBase &PM) {
238 const PassManagerBuilderWrapper &BuilderWrapper =
239 static_cast<const PassManagerBuilderWrapper&>(Builder);
240 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
241 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
242 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
243 PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
245 // MemorySanitizer inserts complex instrumentation that mostly follows
246 // the logic of the original code, but operates on "shadow" values.
247 // It can benefit from re-running some general purpose optimization passes.
248 if (Builder.OptLevel > 0) {
249 PM.add(createEarlyCSEPass());
250 PM.add(createReassociatePass());
251 PM.add(createLICMPass());
252 PM.add(createGVNPass());
253 PM.add(createInstructionCombiningPass());
254 PM.add(createDeadStoreEliminationPass());
258 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
259 legacy::PassManagerBase &PM) {
260 PM.add(createThreadSanitizerPass());
263 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
264 legacy::PassManagerBase &PM) {
265 const PassManagerBuilderWrapper &BuilderWrapper =
266 static_cast<const PassManagerBuilderWrapper&>(Builder);
267 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
268 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
271 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
272 legacy::PassManagerBase &PM) {
273 const PassManagerBuilderWrapper &BuilderWrapper =
274 static_cast<const PassManagerBuilderWrapper&>(Builder);
275 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
276 EfficiencySanitizerOptions Opts;
277 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
278 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
279 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
280 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
281 PM.add(createEfficiencySanitizerPass(Opts));
284 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
285 const CodeGenOptions &CodeGenOpts) {
286 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
287 if (!CodeGenOpts.SimplifyLibCalls)
288 TLII->disableAllFunctions();
290 // Disable individual libc/libm calls in TargetLibraryInfo.
292 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
293 if (TLII->getLibFunc(FuncName, F))
294 TLII->setUnavailable(F);
297 switch (CodeGenOpts.getVecLib()) {
298 case CodeGenOptions::Accelerate:
299 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
301 case CodeGenOptions::SVML:
302 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
310 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
311 legacy::PassManager *MPM) {
312 llvm::SymbolRewriter::RewriteDescriptorList DL;
314 llvm::SymbolRewriter::RewriteMapParser MapParser;
315 for (const auto &MapFile : Opts.RewriteMapFiles)
316 MapParser.parse(MapFile, &DL);
318 MPM->add(createRewriteSymbolsPass(DL));
321 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
322 switch (CodeGenOpts.OptimizationLevel) {
324 llvm_unreachable("Invalid optimization level!");
326 return CodeGenOpt::None;
328 return CodeGenOpt::Less;
330 return CodeGenOpt::Default; // O2/Os/Oz
332 return CodeGenOpt::Aggressive;
336 static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
338 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
339 .Case("small", llvm::CodeModel::Small)
340 .Case("kernel", llvm::CodeModel::Kernel)
341 .Case("medium", llvm::CodeModel::Medium)
342 .Case("large", llvm::CodeModel::Large)
343 .Case("default", llvm::CodeModel::Default)
345 assert(CodeModel != ~0u && "invalid code model!");
346 return static_cast<llvm::CodeModel::Model>(CodeModel);
349 static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
350 // Keep this synced with the equivalent code in
351 // lib/Frontend/CompilerInvocation.cpp
352 llvm::Optional<llvm::Reloc::Model> RM;
353 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
354 .Case("static", llvm::Reloc::Static)
355 .Case("pic", llvm::Reloc::PIC_)
356 .Case("ropi", llvm::Reloc::ROPI)
357 .Case("rwpi", llvm::Reloc::RWPI)
358 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
359 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
360 assert(RM.hasValue() && "invalid PIC model!");
364 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
365 if (Action == Backend_EmitObj)
366 return TargetMachine::CGFT_ObjectFile;
367 else if (Action == Backend_EmitMCNull)
368 return TargetMachine::CGFT_Null;
370 assert(Action == Backend_EmitAssembly && "Invalid action!");
371 return TargetMachine::CGFT_AssemblyFile;
375 static void initTargetOptions(llvm::TargetOptions &Options,
376 const CodeGenOptions &CodeGenOpts,
377 const clang::TargetOptions &TargetOpts,
378 const LangOptions &LangOpts,
379 const HeaderSearchOptions &HSOpts) {
380 Options.ThreadModel =
381 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
382 .Case("posix", llvm::ThreadModel::POSIX)
383 .Case("single", llvm::ThreadModel::Single);
385 // Set float ABI type.
386 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
387 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
388 "Invalid Floating Point ABI!");
389 Options.FloatABIType =
390 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
391 .Case("soft", llvm::FloatABI::Soft)
392 .Case("softfp", llvm::FloatABI::Soft)
393 .Case("hard", llvm::FloatABI::Hard)
394 .Default(llvm::FloatABI::Default);
396 // Set FP fusion mode.
397 switch (LangOpts.getDefaultFPContractMode()) {
398 case LangOptions::FPC_Off:
399 // Preserve any contraction performed by the front-end. (Strict performs
400 // splitting of the muladd instrinsic in the backend.)
401 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403 case LangOptions::FPC_On:
404 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
406 case LangOptions::FPC_Fast:
407 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
411 Options.UseInitArray = CodeGenOpts.UseInitArray;
412 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
413 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
414 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
417 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
418 .Case("4", llvm::EABI::EABI4)
419 .Case("5", llvm::EABI::EABI5)
420 .Case("gnu", llvm::EABI::GNU)
421 .Default(llvm::EABI::Default);
423 if (LangOpts.SjLjExceptions)
424 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
426 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
427 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
428 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
429 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
430 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
431 Options.FunctionSections = CodeGenOpts.FunctionSections;
432 Options.DataSections = CodeGenOpts.DataSections;
433 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
434 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
435 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
437 if (CodeGenOpts.EnableSplitDwarf)
438 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
439 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
440 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
441 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
442 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
443 Options.MCOptions.MCIncrementalLinkerCompatible =
444 CodeGenOpts.IncrementalLinkerCompatible;
445 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
446 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
447 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
448 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
449 Options.MCOptions.ABIName = TargetOpts.ABI;
450 for (const auto &Entry : HSOpts.UserEntries)
451 if (!Entry.IsFramework &&
452 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
453 Entry.Group == frontend::IncludeDirGroup::Angled ||
454 Entry.Group == frontend::IncludeDirGroup::System))
455 Options.MCOptions.IASSearchPaths.push_back(
456 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
459 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
460 legacy::FunctionPassManager &FPM) {
461 // Handle disabling of all LLVM passes, where we want to preserve the
462 // internal module before any optimization.
463 if (CodeGenOpts.DisableLLVMPasses)
466 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
467 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
468 // are inserted before PMBuilder ones - they'd get the default-constructed
469 // TLI with an unknown target otherwise.
470 Triple TargetTriple(TheModule->getTargetTriple());
471 std::unique_ptr<TargetLibraryInfoImpl> TLII(
472 createTLII(TargetTriple, CodeGenOpts));
474 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
476 // At O0 and O1 we only run the always inliner which is more efficient. At
477 // higher optimization levels we run the normal inliner.
478 if (CodeGenOpts.OptimizationLevel <= 1) {
479 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
480 !CodeGenOpts.DisableLifetimeMarkers);
481 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
483 // We do not want to inline hot callsites for SamplePGO module-summary build
484 // because profile annotation will happen again in ThinLTO backend, and we
485 // want the IR of the hot path to match the profile.
486 PMBuilder.Inliner = createFunctionInliningPass(
487 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
488 (!CodeGenOpts.SampleProfileFile.empty() &&
489 CodeGenOpts.EmitSummaryIndex));
492 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
493 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
494 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
495 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
496 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
498 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
499 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
500 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
501 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
502 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
504 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
507 TM->adjustPassManager(PMBuilder);
509 if (CodeGenOpts.DebugInfoForProfiling ||
510 !CodeGenOpts.SampleProfileFile.empty())
511 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
512 addAddDiscriminatorsPass);
514 // In ObjC ARC mode, add the main ARC optimization passes.
515 if (LangOpts.ObjCAutoRefCount) {
516 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
517 addObjCARCExpandPass);
518 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
519 addObjCARCAPElimPass);
520 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
524 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
525 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
526 addBoundsCheckingPass);
527 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
528 addBoundsCheckingPass);
531 if (CodeGenOpts.SanitizeCoverageType ||
532 CodeGenOpts.SanitizeCoverageIndirectCalls ||
533 CodeGenOpts.SanitizeCoverageTraceCmp) {
534 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
535 addSanitizerCoveragePass);
536 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
537 addSanitizerCoveragePass);
540 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
541 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
542 addAddressSanitizerPasses);
543 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
544 addAddressSanitizerPasses);
547 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
548 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
549 addKernelAddressSanitizerPasses);
550 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
551 addKernelAddressSanitizerPasses);
554 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
555 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
556 addMemorySanitizerPass);
557 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
558 addMemorySanitizerPass);
561 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
562 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
563 addThreadSanitizerPass);
564 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
565 addThreadSanitizerPass);
568 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
569 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
570 addDataFlowSanitizerPass);
571 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
572 addDataFlowSanitizerPass);
575 if (LangOpts.CoroutinesTS)
576 addCoroutinePassesToExtensionPoints(PMBuilder);
578 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
579 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
580 addEfficiencySanitizerPass);
581 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
582 addEfficiencySanitizerPass);
585 // Set up the per-function pass manager.
586 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
587 if (CodeGenOpts.VerifyModule)
588 FPM.add(createVerifierPass());
590 // Set up the per-module pass manager.
591 if (!CodeGenOpts.RewriteMapFiles.empty())
592 addSymbolRewriterPass(CodeGenOpts, &MPM);
594 if (!CodeGenOpts.DisableGCov &&
595 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
596 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
597 // LLVM's -default-gcov-version flag is set to something invalid.
599 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
600 Options.EmitData = CodeGenOpts.EmitGcovArcs;
601 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
602 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
603 Options.NoRedZone = CodeGenOpts.DisableRedZone;
604 Options.FunctionNamesInData =
605 !CodeGenOpts.CoverageNoFunctionNamesInData;
606 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
607 MPM.add(createGCOVProfilerPass(Options));
608 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
609 MPM.add(createStripSymbolsPass(true));
612 if (CodeGenOpts.hasProfileClangInstr()) {
613 InstrProfOptions Options;
614 Options.NoRedZone = CodeGenOpts.DisableRedZone;
615 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
616 MPM.add(createInstrProfilingLegacyPass(Options));
618 if (CodeGenOpts.hasProfileIRInstr()) {
619 PMBuilder.EnablePGOInstrGen = true;
620 if (!CodeGenOpts.InstrProfileOutput.empty())
621 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
623 PMBuilder.PGOInstrGen = DefaultProfileGenName;
625 if (CodeGenOpts.hasProfileIRUse())
626 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
628 if (!CodeGenOpts.SampleProfileFile.empty())
629 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
631 PMBuilder.populateFunctionPassManager(FPM);
632 PMBuilder.populateModulePassManager(MPM);
635 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
636 SmallVector<const char *, 16> BackendArgs;
637 BackendArgs.push_back("clang"); // Fake program name.
638 if (!CodeGenOpts.DebugPass.empty()) {
639 BackendArgs.push_back("-debug-pass");
640 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
642 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
643 BackendArgs.push_back("-limit-float-precision");
644 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
646 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
647 BackendArgs.push_back(BackendOption.c_str());
648 BackendArgs.push_back(nullptr);
649 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
653 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
654 // Create the TargetMachine for generating code.
656 std::string Triple = TheModule->getTargetTriple();
657 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
660 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
664 llvm::CodeModel::Model CM = getCodeModel(CodeGenOpts);
665 std::string FeaturesStr =
666 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
667 llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
668 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
670 llvm::TargetOptions Options;
671 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
672 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
673 Options, RM, CM, OptLevel));
676 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
677 BackendAction Action,
678 raw_pwrite_stream &OS) {
680 llvm::Triple TargetTriple(TheModule->getTargetTriple());
681 std::unique_ptr<TargetLibraryInfoImpl> TLII(
682 createTLII(TargetTriple, CodeGenOpts));
683 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
685 // Normal mode, emit a .s or .o file by running the code generator. Note,
686 // this also adds codegenerator level optimization passes.
687 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
689 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
690 // "codegen" passes so that it isn't run multiple times when there is
691 // inlining happening.
692 if (CodeGenOpts.OptimizationLevel > 0)
693 CodeGenPasses.add(createObjCARCContractPass());
695 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
696 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
697 Diags.Report(diag::err_fe_unable_to_interface_with_target);
704 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
705 std::unique_ptr<raw_pwrite_stream> OS) {
706 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
708 setCommandLineOpts(CodeGenOpts);
710 bool UsesCodeGen = (Action != Backend_EmitNothing &&
711 Action != Backend_EmitBC &&
712 Action != Backend_EmitLL);
713 CreateTargetMachine(UsesCodeGen);
715 if (UsesCodeGen && !TM)
718 TheModule->setDataLayout(TM->createDataLayout());
720 legacy::PassManager PerModulePasses;
722 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
724 legacy::FunctionPassManager PerFunctionPasses(TheModule);
725 PerFunctionPasses.add(
726 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
728 CreatePasses(PerModulePasses, PerFunctionPasses);
730 legacy::PassManager CodeGenPasses;
732 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
734 std::unique_ptr<raw_fd_ostream> ThinLinkOS;
737 case Backend_EmitNothing:
741 if (CodeGenOpts.EmitSummaryIndex) {
742 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
744 ThinLinkOS.reset(new llvm::raw_fd_ostream(
745 CodeGenOpts.ThinLinkBitcodeFile, EC,
746 llvm::sys::fs::F_None));
748 Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
754 createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
758 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
763 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
767 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
771 // Before executing passes, print the final values of the LLVM options.
772 cl::PrintOptionValues();
774 // Run passes. For now we do all passes at once, but eventually we
775 // would like to have the option of streaming code generation.
778 PrettyStackTraceString CrashInfo("Per-function optimization");
780 PerFunctionPasses.doInitialization();
781 for (Function &F : *TheModule)
782 if (!F.isDeclaration())
783 PerFunctionPasses.run(F);
784 PerFunctionPasses.doFinalization();
788 PrettyStackTraceString CrashInfo("Per-module optimization passes");
789 PerModulePasses.run(*TheModule);
793 PrettyStackTraceString CrashInfo("Code generation");
794 CodeGenPasses.run(*TheModule);
798 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
799 switch (Opts.OptimizationLevel) {
801 llvm_unreachable("Invalid optimization level!");
804 return PassBuilder::O1;
807 switch (Opts.OptimizeSize) {
809 llvm_unreachable("Invalide optimization level for size!");
812 return PassBuilder::O2;
815 return PassBuilder::Os;
818 return PassBuilder::Oz;
822 return PassBuilder::O3;
826 /// A clean version of `EmitAssembly` that uses the new pass manager.
828 /// Not all features are currently supported in this system, but where
829 /// necessary it falls back to the legacy pass manager to at least provide
830 /// basic functionality.
832 /// This API is planned to have its functionality finished and then to replace
833 /// `EmitAssembly` at some point in the future when the default switches.
834 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
835 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
836 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
837 setCommandLineOpts(CodeGenOpts);
839 // The new pass manager always makes a target machine available to passes
840 // during construction.
841 CreateTargetMachine(/*MustCreateTM*/ true);
843 // This will already be diagnosed, just bail.
845 TheModule->setDataLayout(TM->createDataLayout());
849 // -fprofile-generate.
850 PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
851 if (PGOOpt.RunProfileGen)
852 PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
853 DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
856 if (CodeGenOpts.hasProfileIRUse())
857 PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
859 // Only pass a PGO options struct if -fprofile-generate or
860 // -fprofile-use were passed on the cmdline.
861 PassBuilder PB(TM.get(),
862 (PGOOpt.RunProfileGen ||
863 !PGOOpt.ProfileUseFile.empty()) ?
864 Optional<PGOOptions>(PGOOpt) : None);
866 LoopAnalysisManager LAM;
867 FunctionAnalysisManager FAM;
868 CGSCCAnalysisManager CGAM;
869 ModuleAnalysisManager MAM;
871 // Register the AA manager first so that our version is the one used.
872 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
874 // Register all the basic analyses with the managers.
875 PB.registerModuleAnalyses(MAM);
876 PB.registerCGSCCAnalyses(CGAM);
877 PB.registerFunctionAnalyses(FAM);
878 PB.registerLoopAnalyses(LAM);
879 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
881 ModulePassManager MPM;
883 if (!CodeGenOpts.DisableLLVMPasses) {
884 if (CodeGenOpts.OptimizationLevel == 0) {
885 // Build a minimal pipeline based on the semantics required by Clang,
886 // which is just that always inlining occurs.
887 MPM.addPass(AlwaysInlinerPass());
889 // Otherwise, use the default pass pipeline. We also have to map our
890 // optimization levels into one of the distinct levels used to configure
892 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
894 MPM = PB.buildPerModuleDefaultPipeline(Level);
898 // FIXME: We still use the legacy pass manager to do code generation. We
899 // create that pass manager here and use it as needed below.
900 legacy::PassManager CodeGenPasses;
901 bool NeedCodeGen = false;
902 Optional<raw_fd_ostream> ThinLinkOS;
904 // Append any output we need to the pass manager.
906 case Backend_EmitNothing:
910 if (CodeGenOpts.EmitSummaryIndex) {
911 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
913 ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
914 llvm::sys::fs::F_None);
916 Diags.Report(diag::err_fe_unable_to_open_output)
917 << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
922 ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
924 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
925 CodeGenOpts.EmitSummaryIndex,
926 CodeGenOpts.EmitSummaryIndex));
931 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
934 case Backend_EmitAssembly:
935 case Backend_EmitMCNull:
936 case Backend_EmitObj:
939 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
940 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
941 // FIXME: Should we handle this error differently?
946 // Before executing passes, print the final values of the LLVM options.
947 cl::PrintOptionValues();
949 // Now that we have all of the passes ready, run them.
951 PrettyStackTraceString CrashInfo("Optimizer");
952 MPM.run(*TheModule, MAM);
955 // Now if needed, run the legacy PM for codegen.
957 PrettyStackTraceString CrashInfo("Code generation");
958 CodeGenPasses.run(*TheModule);
962 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
963 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
965 return BMsOrErr.takeError();
967 // The bitcode file may contain multiple modules, we want the one with a
969 for (BitcodeModule &BM : *BMsOrErr) {
970 Expected<bool> HasSummary = BM.hasSummary();
971 if (HasSummary && *HasSummary)
975 return make_error<StringError>("Could not find module summary",
976 inconvertibleErrorCode());
979 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
980 const HeaderSearchOptions &HeaderOpts,
981 const CodeGenOptions &CGOpts,
982 const clang::TargetOptions &TOpts,
983 const LangOptions &LOpts,
984 std::unique_ptr<raw_pwrite_stream> OS,
985 std::string SampleProfile,
986 BackendAction Action) {
987 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
988 ModuleToDefinedGVSummaries;
989 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
991 setCommandLineOpts(CGOpts);
993 // We can simply import the values mentioned in the combined index, since
994 // we should only invoke this using the individual indexes written out
995 // via a WriteIndexesThinBackend.
996 FunctionImporter::ImportMapTy ImportList;
997 for (auto &GlobalList : *CombinedIndex) {
998 // Ignore entries for undefined references.
999 if (GlobalList.second.SummaryList.empty())
1002 auto GUID = GlobalList.first;
1003 assert(GlobalList.second.SummaryList.size() == 1 &&
1004 "Expected individual combined index to have one summary per GUID");
1005 auto &Summary = GlobalList.second.SummaryList[0];
1006 // Skip the summaries for the importing module. These are included to
1007 // e.g. record required linkage changes.
1008 if (Summary->modulePath() == M->getModuleIdentifier())
1010 // Doesn't matter what value we plug in to the map, just needs an entry
1011 // to provoke importing by thinBackend.
1012 ImportList[Summary->modulePath()][GUID] = 1;
1015 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1016 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1018 for (auto &I : ImportList) {
1019 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1020 llvm::MemoryBuffer::getFile(I.first());
1022 errs() << "Error loading imported file '" << I.first()
1023 << "': " << MBOrErr.getError().message() << "\n";
1027 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1029 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1030 errs() << "Error loading imported file '" << I.first()
1031 << "': " << EIB.message() << '\n';
1035 ModuleMap.insert({I.first(), *BMOrErr});
1037 OwnedImports.push_back(std::move(*MBOrErr));
1039 auto AddStream = [&](size_t Task) {
1040 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1043 Conf.CPU = TOpts.CPU;
1044 Conf.CodeModel = getCodeModel(CGOpts);
1045 Conf.MAttrs = TOpts.Features;
1046 Conf.RelocModel = getRelocModel(CGOpts);
1047 Conf.CGOptLevel = getCGOptLevel(CGOpts);
1048 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1049 Conf.SampleProfile = std::move(SampleProfile);
1050 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1052 case Backend_EmitNothing:
1053 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1057 case Backend_EmitLL:
1058 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1059 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1063 case Backend_EmitBC:
1064 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1065 WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1070 Conf.CGFileType = getCodeGenFileType(Action);
1073 if (Error E = thinBackend(
1074 Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1075 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1076 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1077 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1082 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1083 const HeaderSearchOptions &HeaderOpts,
1084 const CodeGenOptions &CGOpts,
1085 const clang::TargetOptions &TOpts,
1086 const LangOptions &LOpts,
1087 const llvm::DataLayout &TDesc, Module *M,
1088 BackendAction Action,
1089 std::unique_ptr<raw_pwrite_stream> OS) {
1090 if (!CGOpts.ThinLTOIndexFile.empty()) {
1091 // If we are performing a ThinLTO importing compile, load the function index
1092 // into memory and pass it into runThinLTOBackend, which will run the
1093 // function importer and invoke LTO passes.
1094 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1095 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1096 /*IgnoreEmptyThinLTOIndexFile*/true);
1098 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1099 "Error loading index file '" +
1100 CGOpts.ThinLTOIndexFile + "': ");
1103 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1104 // A null CombinedIndex means we should skip ThinLTO compilation
1105 // (LLVM will optionally ignore empty index files, returning null instead
1107 bool DoThinLTOBackend = CombinedIndex != nullptr;
1108 if (DoThinLTOBackend) {
1109 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1110 LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1115 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1117 if (CGOpts.ExperimentalNewPassManager)
1118 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1120 AsmHelper.EmitAssembly(Action, std::move(OS));
1122 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1125 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1126 if (DLDesc != TDesc.getStringRepresentation()) {
1127 unsigned DiagID = Diags.getCustomDiagID(
1128 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1129 "expected target description '%1'");
1130 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1135 static const char* getSectionNameForBitcode(const Triple &T) {
1136 switch (T.getObjectFormat()) {
1138 return "__LLVM,__bitcode";
1142 case Triple::UnknownObjectFormat:
1145 llvm_unreachable("Unimplemented ObjectFormatType");
1148 static const char* getSectionNameForCommandline(const Triple &T) {
1149 switch (T.getObjectFormat()) {
1151 return "__LLVM,__cmdline";
1155 case Triple::UnknownObjectFormat:
1158 llvm_unreachable("Unimplemented ObjectFormatType");
1161 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1162 // __LLVM,__bitcode section.
1163 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1164 llvm::MemoryBufferRef Buf) {
1165 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1168 // Save llvm.compiler.used and remote it.
1169 SmallVector<Constant*, 2> UsedArray;
1170 SmallSet<GlobalValue*, 4> UsedGlobals;
1171 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1172 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1173 for (auto *GV : UsedGlobals) {
1174 if (GV->getName() != "llvm.embedded.module" &&
1175 GV->getName() != "llvm.cmdline")
1176 UsedArray.push_back(
1177 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1180 Used->eraseFromParent();
1182 // Embed the bitcode for the llvm module.
1184 ArrayRef<uint8_t> ModuleData;
1185 Triple T(M->getTargetTriple());
1186 // Create a constant that contains the bitcode.
1187 // In case of embedding a marker, ignore the input Buf and use the empty
1188 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1189 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1190 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1191 (const unsigned char *)Buf.getBufferEnd())) {
1192 // If the input is LLVM Assembly, bitcode is produced by serializing
1193 // the module. Use-lists order need to be perserved in this case.
1194 llvm::raw_string_ostream OS(Data);
1195 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1197 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1199 // If the input is LLVM bitcode, write the input byte stream directly.
1200 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1201 Buf.getBufferSize());
1203 llvm::Constant *ModuleConstant =
1204 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1205 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1206 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1208 GV->setSection(getSectionNameForBitcode(T));
1209 UsedArray.push_back(
1210 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1211 if (llvm::GlobalVariable *Old =
1212 M->getGlobalVariable("llvm.embedded.module", true)) {
1213 assert(Old->hasOneUse() &&
1214 "llvm.embedded.module can only be used once in llvm.compiler.used");
1216 Old->eraseFromParent();
1218 GV->setName("llvm.embedded.module");
1221 // Skip if only bitcode needs to be embedded.
1222 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1223 // Embed command-line options.
1224 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1225 CGOpts.CmdArgs.size());
1226 llvm::Constant *CmdConstant =
1227 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1228 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1229 llvm::GlobalValue::PrivateLinkage,
1231 GV->setSection(getSectionNameForCommandline(T));
1232 UsedArray.push_back(
1233 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1234 if (llvm::GlobalVariable *Old =
1235 M->getGlobalVariable("llvm.cmdline", true)) {
1236 assert(Old->hasOneUse() &&
1237 "llvm.cmdline can only be used once in llvm.compiler.used");
1239 Old->eraseFromParent();
1241 GV->setName("llvm.cmdline");
1245 if (UsedArray.empty())
1248 // Recreate llvm.compiler.used.
1249 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1250 auto *NewUsed = new GlobalVariable(
1251 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1252 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1253 NewUsed->setSection("llvm.metadata");