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/Instrumentation.h"
53 #include "llvm/Transforms/ObjCARC.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Transforms/Scalar/GVN.h"
56 #include "llvm/Transforms/Utils/SymbolRewriter.h"
58 using namespace clang;
63 // Default filename used for profile generation.
64 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
66 class EmitAssemblyHelper {
67 DiagnosticsEngine &Diags;
68 const HeaderSearchOptions &HSOpts;
69 const CodeGenOptions &CodeGenOpts;
70 const clang::TargetOptions &TargetOpts;
71 const LangOptions &LangOpts;
74 Timer CodeGenerationTime;
76 std::unique_ptr<raw_pwrite_stream> OS;
78 TargetIRAnalysis getTargetIRAnalysis() const {
80 return TM->getTargetIRAnalysis();
82 return TargetIRAnalysis();
85 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
87 /// Generates the TargetMachine.
88 /// Leaves TM unchanged if it is unable to create the target machine.
89 /// Some of our clang tests specify triples which are not built
90 /// into clang. This is okay because these tests check the generated
91 /// IR, and they require DataLayout which depends on the triple.
92 /// In this case, we allow this method to fail and not report an error.
93 /// When MustCreateTM is used, we print an error if we are unable to load
94 /// the requested target.
95 void CreateTargetMachine(bool MustCreateTM);
97 /// Add passes necessary to emit assembly or LLVM IR.
99 /// \return True on success.
100 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
101 raw_pwrite_stream &OS);
104 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
105 const HeaderSearchOptions &HeaderSearchOpts,
106 const CodeGenOptions &CGOpts,
107 const clang::TargetOptions &TOpts,
108 const LangOptions &LOpts, Module *M)
109 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
110 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
111 CodeGenerationTime("codegen", "Code Generation Time") {}
113 ~EmitAssemblyHelper() {
114 if (CodeGenOpts.DisableFree)
115 BuryPointer(std::move(TM));
118 std::unique_ptr<TargetMachine> TM;
120 void EmitAssembly(BackendAction Action,
121 std::unique_ptr<raw_pwrite_stream> OS);
123 void EmitAssemblyWithNewPassManager(BackendAction Action,
124 std::unique_ptr<raw_pwrite_stream> OS);
127 // We need this wrapper to access LangOpts and CGOpts from extension functions
128 // that we add to the PassManagerBuilder.
129 class PassManagerBuilderWrapper : public PassManagerBuilder {
131 PassManagerBuilderWrapper(const Triple &TargetTriple,
132 const CodeGenOptions &CGOpts,
133 const LangOptions &LangOpts)
134 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
135 LangOpts(LangOpts) {}
136 const Triple &getTargetTriple() const { return TargetTriple; }
137 const CodeGenOptions &getCGOpts() const { return CGOpts; }
138 const LangOptions &getLangOpts() const { return LangOpts; }
141 const Triple &TargetTriple;
142 const CodeGenOptions &CGOpts;
143 const LangOptions &LangOpts;
147 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 if (Builder.OptLevel > 0)
149 PM.add(createObjCARCAPElimPass());
152 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153 if (Builder.OptLevel > 0)
154 PM.add(createObjCARCExpandPass());
157 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
158 if (Builder.OptLevel > 0)
159 PM.add(createObjCARCOptPass());
162 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
163 legacy::PassManagerBase &PM) {
164 PM.add(createAddDiscriminatorsPass());
167 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
168 legacy::PassManagerBase &PM) {
169 PM.add(createBoundsCheckingPass());
172 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
173 legacy::PassManagerBase &PM) {
174 const PassManagerBuilderWrapper &BuilderWrapper =
175 static_cast<const PassManagerBuilderWrapper&>(Builder);
176 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
177 SanitizerCoverageOptions Opts;
179 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
180 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
181 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
182 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
183 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
184 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
185 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
186 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
187 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
188 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
189 PM.add(createSanitizerCoverageModulePass(Opts));
192 // Check if ASan should use GC-friendly instrumentation for globals.
193 // First of all, there is no point if -fdata-sections is off (expect for MachO,
194 // where this is not a factor). Also, on ELF this feature requires an assembler
195 // extension that only works with -integrated-as at the moment.
196 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
197 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
199 switch (T.getObjectFormat()) {
204 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
210 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
211 legacy::PassManagerBase &PM) {
212 const PassManagerBuilderWrapper &BuilderWrapper =
213 static_cast<const PassManagerBuilderWrapper&>(Builder);
214 const Triple &T = BuilderWrapper.getTargetTriple();
215 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
216 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
217 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
218 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
219 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
221 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
225 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
226 legacy::PassManagerBase &PM) {
227 PM.add(createAddressSanitizerFunctionPass(
228 /*CompileKernel*/ true,
229 /*Recover*/ true, /*UseAfterScope*/ false));
230 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
234 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
235 legacy::PassManagerBase &PM) {
236 const PassManagerBuilderWrapper &BuilderWrapper =
237 static_cast<const PassManagerBuilderWrapper&>(Builder);
238 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
239 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
240 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
241 PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
243 // MemorySanitizer inserts complex instrumentation that mostly follows
244 // the logic of the original code, but operates on "shadow" values.
245 // It can benefit from re-running some general purpose optimization passes.
246 if (Builder.OptLevel > 0) {
247 PM.add(createEarlyCSEPass());
248 PM.add(createReassociatePass());
249 PM.add(createLICMPass());
250 PM.add(createGVNPass());
251 PM.add(createInstructionCombiningPass());
252 PM.add(createDeadStoreEliminationPass());
256 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
257 legacy::PassManagerBase &PM) {
258 PM.add(createThreadSanitizerPass());
261 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
262 legacy::PassManagerBase &PM) {
263 const PassManagerBuilderWrapper &BuilderWrapper =
264 static_cast<const PassManagerBuilderWrapper&>(Builder);
265 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
266 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
269 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
270 legacy::PassManagerBase &PM) {
271 const PassManagerBuilderWrapper &BuilderWrapper =
272 static_cast<const PassManagerBuilderWrapper&>(Builder);
273 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
274 EfficiencySanitizerOptions Opts;
275 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
276 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
277 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
278 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
279 PM.add(createEfficiencySanitizerPass(Opts));
282 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
283 const CodeGenOptions &CodeGenOpts) {
284 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
285 if (!CodeGenOpts.SimplifyLibCalls)
286 TLII->disableAllFunctions();
288 // Disable individual libc/libm calls in TargetLibraryInfo.
290 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
291 if (TLII->getLibFunc(FuncName, F))
292 TLII->setUnavailable(F);
295 switch (CodeGenOpts.getVecLib()) {
296 case CodeGenOptions::Accelerate:
297 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
299 case CodeGenOptions::SVML:
300 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
308 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
309 legacy::PassManager *MPM) {
310 llvm::SymbolRewriter::RewriteDescriptorList DL;
312 llvm::SymbolRewriter::RewriteMapParser MapParser;
313 for (const auto &MapFile : Opts.RewriteMapFiles)
314 MapParser.parse(MapFile, &DL);
316 MPM->add(createRewriteSymbolsPass(DL));
319 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
320 switch (CodeGenOpts.OptimizationLevel) {
322 llvm_unreachable("Invalid optimization level!");
324 return CodeGenOpt::None;
326 return CodeGenOpt::Less;
328 return CodeGenOpt::Default; // O2/Os/Oz
330 return CodeGenOpt::Aggressive;
334 static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
336 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
337 .Case("small", llvm::CodeModel::Small)
338 .Case("kernel", llvm::CodeModel::Kernel)
339 .Case("medium", llvm::CodeModel::Medium)
340 .Case("large", llvm::CodeModel::Large)
341 .Case("default", llvm::CodeModel::Default)
343 assert(CodeModel != ~0u && "invalid code model!");
344 return static_cast<llvm::CodeModel::Model>(CodeModel);
347 static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
348 // Keep this synced with the equivalent code in
349 // lib/Frontend/CompilerInvocation.cpp
350 llvm::Optional<llvm::Reloc::Model> RM;
351 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
352 .Case("static", llvm::Reloc::Static)
353 .Case("pic", llvm::Reloc::PIC_)
354 .Case("ropi", llvm::Reloc::ROPI)
355 .Case("rwpi", llvm::Reloc::RWPI)
356 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
357 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
358 assert(RM.hasValue() && "invalid PIC model!");
362 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
363 if (Action == Backend_EmitObj)
364 return TargetMachine::CGFT_ObjectFile;
365 else if (Action == Backend_EmitMCNull)
366 return TargetMachine::CGFT_Null;
368 assert(Action == Backend_EmitAssembly && "Invalid action!");
369 return TargetMachine::CGFT_AssemblyFile;
373 static void initTargetOptions(llvm::TargetOptions &Options,
374 const CodeGenOptions &CodeGenOpts,
375 const clang::TargetOptions &TargetOpts,
376 const LangOptions &LangOpts,
377 const HeaderSearchOptions &HSOpts) {
378 Options.ThreadModel =
379 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
380 .Case("posix", llvm::ThreadModel::POSIX)
381 .Case("single", llvm::ThreadModel::Single);
383 // Set float ABI type.
384 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
385 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
386 "Invalid Floating Point ABI!");
387 Options.FloatABIType =
388 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
389 .Case("soft", llvm::FloatABI::Soft)
390 .Case("softfp", llvm::FloatABI::Soft)
391 .Case("hard", llvm::FloatABI::Hard)
392 .Default(llvm::FloatABI::Default);
394 // Set FP fusion mode.
395 switch (LangOpts.getDefaultFPContractMode()) {
396 case LangOptions::FPC_Off:
397 // Preserve any contraction performed by the front-end. (Strict performs
398 // splitting of the muladd instrinsic in the backend.)
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
401 case LangOptions::FPC_On:
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
404 case LangOptions::FPC_Fast:
405 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
409 Options.UseInitArray = CodeGenOpts.UseInitArray;
410 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
411 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
412 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
415 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
416 .Case("4", llvm::EABI::EABI4)
417 .Case("5", llvm::EABI::EABI5)
418 .Case("gnu", llvm::EABI::GNU)
419 .Default(llvm::EABI::Default);
421 if (LangOpts.SjLjExceptions)
422 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
424 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
425 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
426 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
427 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
428 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
429 Options.FunctionSections = CodeGenOpts.FunctionSections;
430 Options.DataSections = CodeGenOpts.DataSections;
431 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
432 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
433 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
435 if (CodeGenOpts.EnableSplitDwarf)
436 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
437 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
438 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
439 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
440 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
441 Options.MCOptions.MCIncrementalLinkerCompatible =
442 CodeGenOpts.IncrementalLinkerCompatible;
443 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
444 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
445 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
446 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
447 Options.MCOptions.ABIName = TargetOpts.ABI;
448 for (const auto &Entry : HSOpts.UserEntries)
449 if (!Entry.IsFramework &&
450 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
451 Entry.Group == frontend::IncludeDirGroup::Angled ||
452 Entry.Group == frontend::IncludeDirGroup::System))
453 Options.MCOptions.IASSearchPaths.push_back(
454 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
457 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
458 legacy::FunctionPassManager &FPM) {
459 // Handle disabling of all LLVM passes, where we want to preserve the
460 // internal module before any optimization.
461 if (CodeGenOpts.DisableLLVMPasses)
464 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
465 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
466 // are inserted before PMBuilder ones - they'd get the default-constructed
467 // TLI with an unknown target otherwise.
468 Triple TargetTriple(TheModule->getTargetTriple());
469 std::unique_ptr<TargetLibraryInfoImpl> TLII(
470 createTLII(TargetTriple, CodeGenOpts));
472 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
474 // At O0 and O1 we only run the always inliner which is more efficient. At
475 // higher optimization levels we run the normal inliner.
476 if (CodeGenOpts.OptimizationLevel <= 1) {
477 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
478 !CodeGenOpts.DisableLifetimeMarkers);
479 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
481 // We do not want to inline hot callsites for SamplePGO module-summary build
482 // because profile annotation will happen again in ThinLTO backend, and we
483 // want the IR of the hot path to match the profile.
484 PMBuilder.Inliner = createFunctionInliningPass(
485 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
486 (!CodeGenOpts.SampleProfileFile.empty() &&
487 CodeGenOpts.EmitSummaryIndex));
490 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
491 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
492 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
493 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
494 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
496 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
497 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
498 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
499 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
500 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
502 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
505 TM->adjustPassManager(PMBuilder);
507 if (CodeGenOpts.DebugInfoForProfiling ||
508 !CodeGenOpts.SampleProfileFile.empty())
509 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
510 addAddDiscriminatorsPass);
512 // In ObjC ARC mode, add the main ARC optimization passes.
513 if (LangOpts.ObjCAutoRefCount) {
514 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
515 addObjCARCExpandPass);
516 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
517 addObjCARCAPElimPass);
518 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
522 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
523 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
524 addBoundsCheckingPass);
525 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
526 addBoundsCheckingPass);
529 if (CodeGenOpts.SanitizeCoverageType ||
530 CodeGenOpts.SanitizeCoverageIndirectCalls ||
531 CodeGenOpts.SanitizeCoverageTraceCmp) {
532 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
533 addSanitizerCoveragePass);
534 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
535 addSanitizerCoveragePass);
538 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
539 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
540 addAddressSanitizerPasses);
541 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
542 addAddressSanitizerPasses);
545 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
546 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
547 addKernelAddressSanitizerPasses);
548 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
549 addKernelAddressSanitizerPasses);
552 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
553 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
554 addMemorySanitizerPass);
555 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
556 addMemorySanitizerPass);
559 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
560 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
561 addThreadSanitizerPass);
562 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
563 addThreadSanitizerPass);
566 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
567 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
568 addDataFlowSanitizerPass);
569 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
570 addDataFlowSanitizerPass);
573 if (LangOpts.CoroutinesTS)
574 addCoroutinePassesToExtensionPoints(PMBuilder);
576 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
577 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
578 addEfficiencySanitizerPass);
579 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
580 addEfficiencySanitizerPass);
583 // Set up the per-function pass manager.
584 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
585 if (CodeGenOpts.VerifyModule)
586 FPM.add(createVerifierPass());
588 // Set up the per-module pass manager.
589 if (!CodeGenOpts.RewriteMapFiles.empty())
590 addSymbolRewriterPass(CodeGenOpts, &MPM);
592 if (!CodeGenOpts.DisableGCov &&
593 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
594 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
595 // LLVM's -default-gcov-version flag is set to something invalid.
597 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
598 Options.EmitData = CodeGenOpts.EmitGcovArcs;
599 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
600 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
601 Options.NoRedZone = CodeGenOpts.DisableRedZone;
602 Options.FunctionNamesInData =
603 !CodeGenOpts.CoverageNoFunctionNamesInData;
604 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
605 MPM.add(createGCOVProfilerPass(Options));
606 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
607 MPM.add(createStripSymbolsPass(true));
610 if (CodeGenOpts.hasProfileClangInstr()) {
611 InstrProfOptions Options;
612 Options.NoRedZone = CodeGenOpts.DisableRedZone;
613 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
614 MPM.add(createInstrProfilingLegacyPass(Options));
616 if (CodeGenOpts.hasProfileIRInstr()) {
617 PMBuilder.EnablePGOInstrGen = true;
618 if (!CodeGenOpts.InstrProfileOutput.empty())
619 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
621 PMBuilder.PGOInstrGen = DefaultProfileGenName;
623 if (CodeGenOpts.hasProfileIRUse())
624 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
626 if (!CodeGenOpts.SampleProfileFile.empty())
627 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
629 PMBuilder.populateFunctionPassManager(FPM);
630 PMBuilder.populateModulePassManager(MPM);
633 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
634 SmallVector<const char *, 16> BackendArgs;
635 BackendArgs.push_back("clang"); // Fake program name.
636 if (!CodeGenOpts.DebugPass.empty()) {
637 BackendArgs.push_back("-debug-pass");
638 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
640 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
641 BackendArgs.push_back("-limit-float-precision");
642 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
644 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
645 BackendArgs.push_back(BackendOption.c_str());
646 BackendArgs.push_back(nullptr);
647 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
651 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
652 // Create the TargetMachine for generating code.
654 std::string Triple = TheModule->getTargetTriple();
655 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
658 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
662 llvm::CodeModel::Model CM = getCodeModel(CodeGenOpts);
663 std::string FeaturesStr =
664 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
665 llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
666 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
668 llvm::TargetOptions Options;
669 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
670 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
671 Options, RM, CM, OptLevel));
674 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
675 BackendAction Action,
676 raw_pwrite_stream &OS) {
678 llvm::Triple TargetTriple(TheModule->getTargetTriple());
679 std::unique_ptr<TargetLibraryInfoImpl> TLII(
680 createTLII(TargetTriple, CodeGenOpts));
681 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
683 // Normal mode, emit a .s or .o file by running the code generator. Note,
684 // this also adds codegenerator level optimization passes.
685 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
687 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
688 // "codegen" passes so that it isn't run multiple times when there is
689 // inlining happening.
690 if (CodeGenOpts.OptimizationLevel > 0)
691 CodeGenPasses.add(createObjCARCContractPass());
693 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
694 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
695 Diags.Report(diag::err_fe_unable_to_interface_with_target);
702 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
703 std::unique_ptr<raw_pwrite_stream> OS) {
704 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
706 setCommandLineOpts(CodeGenOpts);
708 bool UsesCodeGen = (Action != Backend_EmitNothing &&
709 Action != Backend_EmitBC &&
710 Action != Backend_EmitLL);
711 CreateTargetMachine(UsesCodeGen);
713 if (UsesCodeGen && !TM)
716 TheModule->setDataLayout(TM->createDataLayout());
718 legacy::PassManager PerModulePasses;
720 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
722 legacy::FunctionPassManager PerFunctionPasses(TheModule);
723 PerFunctionPasses.add(
724 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
726 CreatePasses(PerModulePasses, PerFunctionPasses);
728 legacy::PassManager CodeGenPasses;
730 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
732 std::unique_ptr<raw_fd_ostream> ThinLinkOS;
735 case Backend_EmitNothing:
739 if (CodeGenOpts.EmitSummaryIndex) {
740 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
742 ThinLinkOS.reset(new llvm::raw_fd_ostream(
743 CodeGenOpts.ThinLinkBitcodeFile, EC,
744 llvm::sys::fs::F_None));
746 Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
752 createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
756 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
761 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
765 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
769 // Before executing passes, print the final values of the LLVM options.
770 cl::PrintOptionValues();
772 // Run passes. For now we do all passes at once, but eventually we
773 // would like to have the option of streaming code generation.
776 PrettyStackTraceString CrashInfo("Per-function optimization");
778 PerFunctionPasses.doInitialization();
779 for (Function &F : *TheModule)
780 if (!F.isDeclaration())
781 PerFunctionPasses.run(F);
782 PerFunctionPasses.doFinalization();
786 PrettyStackTraceString CrashInfo("Per-module optimization passes");
787 PerModulePasses.run(*TheModule);
791 PrettyStackTraceString CrashInfo("Code generation");
792 CodeGenPasses.run(*TheModule);
796 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
797 switch (Opts.OptimizationLevel) {
799 llvm_unreachable("Invalid optimization level!");
802 return PassBuilder::O1;
805 switch (Opts.OptimizeSize) {
807 llvm_unreachable("Invalide optimization level for size!");
810 return PassBuilder::O2;
813 return PassBuilder::Os;
816 return PassBuilder::Oz;
820 return PassBuilder::O3;
824 /// A clean version of `EmitAssembly` that uses the new pass manager.
826 /// Not all features are currently supported in this system, but where
827 /// necessary it falls back to the legacy pass manager to at least provide
828 /// basic functionality.
830 /// This API is planned to have its functionality finished and then to replace
831 /// `EmitAssembly` at some point in the future when the default switches.
832 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
833 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
834 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
835 setCommandLineOpts(CodeGenOpts);
837 // The new pass manager always makes a target machine available to passes
838 // during construction.
839 CreateTargetMachine(/*MustCreateTM*/ true);
841 // This will already be diagnosed, just bail.
843 TheModule->setDataLayout(TM->createDataLayout());
847 // -fprofile-generate.
848 PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
849 if (PGOOpt.RunProfileGen)
850 PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
851 DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
854 if (CodeGenOpts.hasProfileIRUse())
855 PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
857 // Only pass a PGO options struct if -fprofile-generate or
858 // -fprofile-use were passed on the cmdline.
859 PassBuilder PB(TM.get(),
860 (PGOOpt.RunProfileGen ||
861 !PGOOpt.ProfileUseFile.empty()) ?
862 Optional<PGOOptions>(PGOOpt) : None);
864 LoopAnalysisManager LAM;
865 FunctionAnalysisManager FAM;
866 CGSCCAnalysisManager CGAM;
867 ModuleAnalysisManager MAM;
869 // Register the AA manager first so that our version is the one used.
870 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
872 // Register all the basic analyses with the managers.
873 PB.registerModuleAnalyses(MAM);
874 PB.registerCGSCCAnalyses(CGAM);
875 PB.registerFunctionAnalyses(FAM);
876 PB.registerLoopAnalyses(LAM);
877 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
879 ModulePassManager MPM;
881 if (!CodeGenOpts.DisableLLVMPasses) {
882 if (CodeGenOpts.OptimizationLevel == 0) {
883 // Build a minimal pipeline based on the semantics required by Clang,
884 // which is just that always inlining occurs.
885 MPM.addPass(AlwaysInlinerPass());
887 // Otherwise, use the default pass pipeline. We also have to map our
888 // optimization levels into one of the distinct levels used to configure
890 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
892 MPM = PB.buildPerModuleDefaultPipeline(Level);
896 // FIXME: We still use the legacy pass manager to do code generation. We
897 // create that pass manager here and use it as needed below.
898 legacy::PassManager CodeGenPasses;
899 bool NeedCodeGen = false;
901 // Append any output we need to the pass manager.
903 case Backend_EmitNothing:
907 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
908 CodeGenOpts.EmitSummaryIndex,
909 CodeGenOpts.EmitSummaryIndex));
913 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
916 case Backend_EmitAssembly:
917 case Backend_EmitMCNull:
918 case Backend_EmitObj:
921 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
922 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
923 // FIXME: Should we handle this error differently?
928 // Before executing passes, print the final values of the LLVM options.
929 cl::PrintOptionValues();
931 // Now that we have all of the passes ready, run them.
933 PrettyStackTraceString CrashInfo("Optimizer");
934 MPM.run(*TheModule, MAM);
937 // Now if needed, run the legacy PM for codegen.
939 PrettyStackTraceString CrashInfo("Code generation");
940 CodeGenPasses.run(*TheModule);
944 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
945 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
947 return BMsOrErr.takeError();
949 // The bitcode file may contain multiple modules, we want the one with a
951 for (BitcodeModule &BM : *BMsOrErr) {
952 Expected<bool> HasSummary = BM.hasSummary();
953 if (HasSummary && *HasSummary)
957 return make_error<StringError>("Could not find module summary",
958 inconvertibleErrorCode());
961 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
962 const HeaderSearchOptions &HeaderOpts,
963 const CodeGenOptions &CGOpts,
964 const clang::TargetOptions &TOpts,
965 const LangOptions &LOpts,
966 std::unique_ptr<raw_pwrite_stream> OS,
967 std::string SampleProfile,
968 BackendAction Action) {
969 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
970 ModuleToDefinedGVSummaries;
971 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
973 setCommandLineOpts(CGOpts);
975 // We can simply import the values mentioned in the combined index, since
976 // we should only invoke this using the individual indexes written out
977 // via a WriteIndexesThinBackend.
978 FunctionImporter::ImportMapTy ImportList;
979 for (auto &GlobalList : *CombinedIndex) {
980 // Ignore entries for undefined references.
981 if (GlobalList.second.SummaryList.empty())
984 auto GUID = GlobalList.first;
985 assert(GlobalList.second.SummaryList.size() == 1 &&
986 "Expected individual combined index to have one summary per GUID");
987 auto &Summary = GlobalList.second.SummaryList[0];
988 // Skip the summaries for the importing module. These are included to
989 // e.g. record required linkage changes.
990 if (Summary->modulePath() == M->getModuleIdentifier())
992 // Doesn't matter what value we plug in to the map, just needs an entry
993 // to provoke importing by thinBackend.
994 ImportList[Summary->modulePath()][GUID] = 1;
997 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
998 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1000 for (auto &I : ImportList) {
1001 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1002 llvm::MemoryBuffer::getFile(I.first());
1004 errs() << "Error loading imported file '" << I.first()
1005 << "': " << MBOrErr.getError().message() << "\n";
1009 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1011 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1012 errs() << "Error loading imported file '" << I.first()
1013 << "': " << EIB.message() << '\n';
1017 ModuleMap.insert({I.first(), *BMOrErr});
1019 OwnedImports.push_back(std::move(*MBOrErr));
1021 auto AddStream = [&](size_t Task) {
1022 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1025 Conf.CPU = TOpts.CPU;
1026 Conf.CodeModel = getCodeModel(CGOpts);
1027 Conf.MAttrs = TOpts.Features;
1028 Conf.RelocModel = getRelocModel(CGOpts);
1029 Conf.CGOptLevel = getCGOptLevel(CGOpts);
1030 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1031 Conf.SampleProfile = std::move(SampleProfile);
1033 case Backend_EmitNothing:
1034 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1038 case Backend_EmitLL:
1039 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1040 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1044 case Backend_EmitBC:
1045 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1046 WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1051 Conf.CGFileType = getCodeGenFileType(Action);
1054 if (Error E = thinBackend(
1055 Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1056 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1057 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1058 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1063 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1064 const HeaderSearchOptions &HeaderOpts,
1065 const CodeGenOptions &CGOpts,
1066 const clang::TargetOptions &TOpts,
1067 const LangOptions &LOpts,
1068 const llvm::DataLayout &TDesc, Module *M,
1069 BackendAction Action,
1070 std::unique_ptr<raw_pwrite_stream> OS) {
1071 if (!CGOpts.ThinLTOIndexFile.empty()) {
1072 // If we are performing a ThinLTO importing compile, load the function index
1073 // into memory and pass it into runThinLTOBackend, which will run the
1074 // function importer and invoke LTO passes.
1075 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1076 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
1078 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1079 "Error loading index file '" +
1080 CGOpts.ThinLTOIndexFile + "': ");
1083 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1084 // A null CombinedIndex means we should skip ThinLTO compilation
1085 // (LLVM will optionally ignore empty index files, returning null instead
1087 bool DoThinLTOBackend = CombinedIndex != nullptr;
1088 if (DoThinLTOBackend) {
1089 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1090 LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1095 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1097 if (CGOpts.ExperimentalNewPassManager)
1098 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1100 AsmHelper.EmitAssembly(Action, std::move(OS));
1102 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1105 std::string DLDesc = M->getDataLayout().getStringRepresentation();
1106 if (DLDesc != TDesc.getStringRepresentation()) {
1107 unsigned DiagID = Diags.getCustomDiagID(
1108 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1109 "expected target description '%1'");
1110 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1115 static const char* getSectionNameForBitcode(const Triple &T) {
1116 switch (T.getObjectFormat()) {
1118 return "__LLVM,__bitcode";
1122 case Triple::UnknownObjectFormat:
1125 llvm_unreachable("Unimplemented ObjectFormatType");
1128 static const char* getSectionNameForCommandline(const Triple &T) {
1129 switch (T.getObjectFormat()) {
1131 return "__LLVM,__cmdline";
1135 case Triple::UnknownObjectFormat:
1138 llvm_unreachable("Unimplemented ObjectFormatType");
1141 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1142 // __LLVM,__bitcode section.
1143 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1144 llvm::MemoryBufferRef Buf) {
1145 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1148 // Save llvm.compiler.used and remote it.
1149 SmallVector<Constant*, 2> UsedArray;
1150 SmallSet<GlobalValue*, 4> UsedGlobals;
1151 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1152 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1153 for (auto *GV : UsedGlobals) {
1154 if (GV->getName() != "llvm.embedded.module" &&
1155 GV->getName() != "llvm.cmdline")
1156 UsedArray.push_back(
1157 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1160 Used->eraseFromParent();
1162 // Embed the bitcode for the llvm module.
1164 ArrayRef<uint8_t> ModuleData;
1165 Triple T(M->getTargetTriple());
1166 // Create a constant that contains the bitcode.
1167 // In case of embedding a marker, ignore the input Buf and use the empty
1168 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1169 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1170 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1171 (const unsigned char *)Buf.getBufferEnd())) {
1172 // If the input is LLVM Assembly, bitcode is produced by serializing
1173 // the module. Use-lists order need to be perserved in this case.
1174 llvm::raw_string_ostream OS(Data);
1175 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1177 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1179 // If the input is LLVM bitcode, write the input byte stream directly.
1180 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1181 Buf.getBufferSize());
1183 llvm::Constant *ModuleConstant =
1184 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1185 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1186 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1188 GV->setSection(getSectionNameForBitcode(T));
1189 UsedArray.push_back(
1190 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1191 if (llvm::GlobalVariable *Old =
1192 M->getGlobalVariable("llvm.embedded.module", true)) {
1193 assert(Old->hasOneUse() &&
1194 "llvm.embedded.module can only be used once in llvm.compiler.used");
1196 Old->eraseFromParent();
1198 GV->setName("llvm.embedded.module");
1201 // Skip if only bitcode needs to be embedded.
1202 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1203 // Embed command-line options.
1204 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1205 CGOpts.CmdArgs.size());
1206 llvm::Constant *CmdConstant =
1207 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1208 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1209 llvm::GlobalValue::PrivateLinkage,
1211 GV->setSection(getSectionNameForCommandline(T));
1212 UsedArray.push_back(
1213 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1214 if (llvm::GlobalVariable *Old =
1215 M->getGlobalVariable("llvm.cmdline", true)) {
1216 assert(Old->hasOneUse() &&
1217 "llvm.cmdline can only be used once in llvm.compiler.used");
1219 Old->eraseFromParent();
1221 GV->setName("llvm.cmdline");
1225 if (UsedArray.empty())
1228 // Recreate llvm.compiler.used.
1229 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1230 auto *NewUsed = new GlobalVariable(
1231 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1232 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1233 NewUsed->setSection("llvm.metadata");