1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/Support/CBindingWrapping.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
29 #include "llvm/Transforms/IPO/AlwaysInliner.h"
30 #include "llvm/Transforms/IPO/FunctionImport.h"
31 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
32 #include "llvm/LTO/LTO.h"
34 #include "llvm-c/Transforms/PassManagerBuilder.h"
37 using namespace llvm::legacy;
39 extern cl::opt<bool> EnableARMEHABI;
41 typedef struct LLVMOpaquePass *LLVMPassRef;
42 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
44 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
45 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
46 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
47 LLVMPassManagerBuilderRef)
49 extern "C" void LLVMInitializePasses() {
50 PassRegistry &Registry = *PassRegistry::getPassRegistry();
51 initializeCore(Registry);
52 initializeCodeGen(Registry);
53 initializeScalarOpts(Registry);
54 initializeVectorization(Registry);
55 initializeIPO(Registry);
56 initializeAnalysis(Registry);
57 initializeTransformUtils(Registry);
58 initializeInstCombine(Registry);
59 initializeInstrumentation(Registry);
60 initializeTarget(Registry);
63 enum class LLVMRustPassKind {
69 static LLVMRustPassKind toRust(PassKind Kind) {
72 return LLVMRustPassKind::Function;
74 return LLVMRustPassKind::Module;
76 return LLVMRustPassKind::Other;
80 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
81 StringRef SR(PassName);
82 PassRegistry *PR = PassRegistry::getPassRegistry();
84 const PassInfo *PI = PR->getPassInfo(SR);
86 return wrap(PI->createPass());
91 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
93 Pass *Pass = unwrap(RustPass);
94 return toRust(Pass->getPassKind());
97 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
99 Pass *Pass = unwrap(RustPass);
100 PassManagerBase *PMB = unwrap(PMR);
105 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
106 LLVMPassManagerBuilderRef PMBR,
107 LLVMPassManagerRef PMR
109 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
112 #ifdef LLVM_COMPONENT_X86
113 #define SUBTARGET_X86 SUBTARGET(X86)
115 #define SUBTARGET_X86
118 #ifdef LLVM_COMPONENT_ARM
119 #define SUBTARGET_ARM SUBTARGET(ARM)
121 #define SUBTARGET_ARM
124 #ifdef LLVM_COMPONENT_AARCH64
125 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
127 #define SUBTARGET_AARCH64
130 #ifdef LLVM_COMPONENT_MIPS
131 #define SUBTARGET_MIPS SUBTARGET(Mips)
133 #define SUBTARGET_MIPS
136 #ifdef LLVM_COMPONENT_POWERPC
137 #define SUBTARGET_PPC SUBTARGET(PPC)
139 #define SUBTARGET_PPC
142 #ifdef LLVM_COMPONENT_SYSTEMZ
143 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
145 #define SUBTARGET_SYSTEMZ
148 #ifdef LLVM_COMPONENT_MSP430
149 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
151 #define SUBTARGET_MSP430
154 #ifdef LLVM_COMPONENT_RISCV
155 #define SUBTARGET_RISCV SUBTARGET(RISCV)
157 #define SUBTARGET_RISCV
160 #ifdef LLVM_COMPONENT_SPARC
161 #define SUBTARGET_SPARC SUBTARGET(Sparc)
163 #define SUBTARGET_SPARC
166 #ifdef LLVM_COMPONENT_HEXAGON
167 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
169 #define SUBTARGET_HEXAGON
172 #define GEN_SUBTARGETS \
184 #define SUBTARGET(x) \
186 extern const SubtargetFeatureKV x##FeatureKV[]; \
187 extern const SubtargetFeatureKV x##SubTypeKV[]; \
193 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
194 const char *Feature) {
195 TargetMachine *Target = unwrap(TM);
196 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
197 return MCInfo->checkFeatures(std::string("+") + Feature);
200 enum class LLVMRustCodeModel {
209 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
211 case LLVMRustCodeModel::Small:
212 return CodeModel::Small;
213 case LLVMRustCodeModel::Kernel:
214 return CodeModel::Kernel;
215 case LLVMRustCodeModel::Medium:
216 return CodeModel::Medium;
217 case LLVMRustCodeModel::Large:
218 return CodeModel::Large;
220 report_fatal_error("Bad CodeModel.");
224 enum class LLVMRustCodeGenOptLevel {
232 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
234 case LLVMRustCodeGenOptLevel::None:
235 return CodeGenOpt::None;
236 case LLVMRustCodeGenOptLevel::Less:
237 return CodeGenOpt::Less;
238 case LLVMRustCodeGenOptLevel::Default:
239 return CodeGenOpt::Default;
240 case LLVMRustCodeGenOptLevel::Aggressive:
241 return CodeGenOpt::Aggressive;
243 report_fatal_error("Bad CodeGenOptLevel.");
247 enum class LLVMRustRelocMode {
257 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
259 case LLVMRustRelocMode::Default:
261 case LLVMRustRelocMode::Static:
262 return Reloc::Static;
263 case LLVMRustRelocMode::PIC:
265 case LLVMRustRelocMode::DynamicNoPic:
266 return Reloc::DynamicNoPIC;
267 case LLVMRustRelocMode::ROPI:
269 case LLVMRustRelocMode::RWPI:
271 case LLVMRustRelocMode::ROPIRWPI:
272 return Reloc::ROPI_RWPI;
274 report_fatal_error("Bad RelocModel.");
278 /// getLongestEntryLength - Return the length of the longest entry in the table.
280 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
282 for (auto &I : Table)
283 MaxLen = std::max(MaxLen, std::strlen(I.Key));
287 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
288 const TargetMachine *Target = unwrap(TM);
289 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
290 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
291 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
292 const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
293 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
295 printf("Available CPUs for this target:\n");
296 if (HostArch == TargetArch) {
297 const StringRef HostCPU = sys::getHostCPUName();
298 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
299 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
301 for (auto &CPU : CPUTable)
302 printf(" %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
306 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
307 const TargetMachine *Target = unwrap(TM);
308 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
309 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
310 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
312 printf("Available features for this target:\n");
313 for (auto &Feature : FeatTable)
314 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
317 printf("Use +feature to enable a feature, or -feature to disable it.\n"
318 "For example, rustc -C -target-cpu=mycpu -C "
319 "target-feature=+feature1,-feature2\n\n");
324 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
325 printf("Target CPU help is not supported by this LLVM version.\n\n");
328 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
329 printf("Target features help is not supported by this LLVM version.\n\n");
333 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
334 StringRef Name = sys::getHostCPUName();
339 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
340 const char *TripleStr, const char *CPU, const char *Feature,
341 LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
342 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
343 bool PositionIndependentExecutable, bool FunctionSections,
345 bool TrapUnreachable,
348 bool EmitStackSizeSection) {
350 auto OptLevel = fromRust(RustOptLevel);
351 auto RM = fromRust(RustReloc);
354 Triple Trip(Triple::normalize(TripleStr));
355 const llvm::Target *TheTarget =
356 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
357 if (TheTarget == nullptr) {
358 LLVMRustSetLastError(Error.c_str());
362 TargetOptions Options;
364 Options.FloatABIType = FloatABI::Default;
366 Options.FloatABIType = FloatABI::Soft;
368 Options.DataSections = DataSections;
369 Options.FunctionSections = FunctionSections;
370 Options.MCOptions.AsmVerbose = AsmComments;
371 Options.MCOptions.PreserveAsmComments = AsmComments;
373 if (TrapUnreachable) {
374 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
375 // This limits the extent of possible undefined behavior in some cases, as
376 // it prevents control flow from "falling through" into whatever code
377 // happens to be laid out next in memory.
378 Options.TrapUnreachable = true;
382 Options.ThreadModel = ThreadModel::Single;
385 Options.EmitStackSizeSection = EmitStackSizeSection;
387 Optional<CodeModel::Model> CM;
388 if (RustCM != LLVMRustCodeModel::None)
389 CM = fromRust(RustCM);
390 TargetMachine *TM = TheTarget->createTargetMachine(
391 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
395 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
399 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
400 // passes for a target to a pass manager. We export that functionality through
402 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
403 LLVMPassManagerRef PMR,
405 PassManagerBase *PM = unwrap(PMR);
407 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
410 extern "C" void LLVMRustConfigurePassManagerBuilder(
411 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
412 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
413 const char* PGOGenPath, const char* PGOUsePath) {
414 #if LLVM_VERSION_GE(7, 0)
415 unwrap(PMBR)->MergeFunctions = MergeFunctions;
417 unwrap(PMBR)->SLPVectorize = SLPVectorize;
418 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
419 unwrap(PMBR)->LoopVectorize = LoopVectorize;
420 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
424 unwrap(PMBR)->EnablePGOInstrGen = true;
425 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
429 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
433 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
434 // field of a PassManagerBuilder, we expose our own method of doing so.
435 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
437 bool DisableSimplifyLibCalls) {
438 Triple TargetTriple(unwrap(M)->getTargetTriple());
439 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
440 if (DisableSimplifyLibCalls)
441 TLI->disableAllFunctions();
442 unwrap(PMBR)->LibraryInfo = TLI;
445 // Unfortunately, the LLVM C API doesn't provide a way to create the
446 // TargetLibraryInfo pass, so we use this method to do so.
447 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
448 bool DisableSimplifyLibCalls) {
449 Triple TargetTriple(unwrap(M)->getTargetTriple());
450 TargetLibraryInfoImpl TLII(TargetTriple);
451 if (DisableSimplifyLibCalls)
452 TLII.disableAllFunctions();
453 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
456 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
457 // all the functions in a module, so we do that manually here. You'll find
458 // similar code in clang's BackendUtil.cpp file.
459 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
461 llvm::legacy::FunctionPassManager *P =
462 unwrap<llvm::legacy::FunctionPassManager>(PMR);
463 P->doInitialization();
465 // Upgrade all calls to old intrinsics first.
466 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
467 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
469 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
471 if (!I->isDeclaration())
477 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
478 // Initializing the command-line options more than once is not allowed. So,
479 // check if they've already been initialized. (This could happen if we're
480 // being called from rustpkg, for example). If the arguments change, then
481 // that's just kinda unfortunate.
482 static bool Initialized = false;
486 cl::ParseCommandLineOptions(Argc, Argv);
489 enum class LLVMRustFileType {
495 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
497 case LLVMRustFileType::AssemblyFile:
498 return TargetMachine::CGFT_AssemblyFile;
499 case LLVMRustFileType::ObjectFile:
500 return TargetMachine::CGFT_ObjectFile;
502 report_fatal_error("Bad FileType.");
506 extern "C" LLVMRustResult
507 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
508 LLVMModuleRef M, const char *Path,
509 LLVMRustFileType RustFileType) {
510 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
511 auto FileType = fromRust(RustFileType);
513 std::string ErrorInfo;
515 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
517 ErrorInfo = EC.message();
518 if (ErrorInfo != "") {
519 LLVMRustSetLastError(ErrorInfo.c_str());
520 return LLVMRustResult::Failure;
523 #if LLVM_VERSION_GE(7, 0)
524 buffer_ostream BOS(OS);
525 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
527 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
531 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
532 // stream (OS), so the only real safe place to delete this is here? Don't we
533 // wish this was written in Rust?
535 return LLVMRustResult::Success;
539 // Callback to demangle function name
541 // * name to be demangled
544 // * output buffer len
545 // Returns len of demangled string, or 0 if demangle failed.
546 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
551 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
553 std::vector<char> Buf;
556 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
558 // Return empty string if demangle failed
559 // or if name does not need to be demangled
560 StringRef CallDemangle(StringRef name) {
565 if (Buf.size() < name.size() * 2) {
566 // Semangled name usually shorter than mangled,
567 // but allocate twice as much memory just in case
568 Buf.resize(name.size() * 2);
571 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
577 auto Demangled = StringRef(Buf.data(), R);
578 if (Demangled == name) {
579 // Do not print anything if demangled name is equal to mangled.
586 void emitFunctionAnnot(const Function *F,
587 formatted_raw_ostream &OS) override {
588 StringRef Demangled = CallDemangle(F->getName());
589 if (Demangled.empty()) {
593 OS << "; " << Demangled << "\n";
596 void emitInstructionAnnot(const Instruction *I,
597 formatted_raw_ostream &OS) override {
600 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
602 Value = CI->getCalledValue();
603 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
605 Value = II->getCalledValue();
607 // Could demangle more operations, e. g.
608 // `store %place, @function`.
612 if (!Value->hasName()) {
616 StringRef Demangled = CallDemangle(Value->getName());
617 if (Demangled.empty()) {
621 OS << "; " << Name << " " << Demangled << "\n";
625 class RustPrintModulePass : public ModulePass {
630 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
631 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
632 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
634 bool runOnModule(Module &M) override {
635 RustAssemblyAnnotationWriter AW(Demangle);
637 M.print(*OS, &AW, false);
642 void getAnalysisUsage(AnalysisUsage &AU) const override {
643 AU.setPreservesAll();
646 static StringRef name() { return "RustPrintModulePass"; }
652 void initializeRustPrintModulePassPass(PassRegistry&);
655 char RustPrintModulePass::ID = 0;
656 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
657 "Print rust module to stderr", false, false)
659 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
660 const char *Path, DemangleFn Demangle) {
661 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
662 std::string ErrorInfo;
665 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
667 ErrorInfo = EC.message();
669 formatted_raw_ostream FOS(OS);
671 PM->add(new RustPrintModulePass(FOS, Demangle));
676 extern "C" void LLVMRustPrintPasses() {
677 LLVMInitializePasses();
678 struct MyListener : PassRegistrationListener {
679 void passEnumerate(const PassInfo *Info) {
680 StringRef PassArg = Info->getPassArgument();
681 StringRef PassName = Info->getPassName();
682 if (!PassArg.empty()) {
683 // These unsigned->signed casts could theoretically overflow, but
684 // realistically never will (and even if, the result is implementation
685 // defined rather plain UB).
686 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
687 (int)PassName.size(), PassName.data());
692 PassRegistry *PR = PassRegistry::getPassRegistry();
693 PR->enumerateWith(&Listener);
696 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
698 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
701 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
703 llvm::legacy::PassManager passes;
705 auto PreserveFunctions = [=](const GlobalValue &GV) {
706 for (size_t I = 0; I < Len; I++) {
707 if (GV.getName() == Symbols[I]) {
714 passes.add(llvm::createInternalizePass(PreserveFunctions));
716 passes.run(*unwrap(M));
719 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
720 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
722 GV->setDoesNotThrow();
723 Function *F = dyn_cast<Function>(GV);
727 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
728 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
729 if (isa<InvokeInst>(I)) {
730 InvokeInst *CI = cast<InvokeInst>(I);
731 CI->setDoesNotThrow();
739 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
740 LLVMTargetMachineRef TMR) {
741 TargetMachine *Target = unwrap(TMR);
742 unwrap(Module)->setDataLayout(Target->createDataLayout());
745 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
746 unwrap(M)->setPIELevel(PIELevel::Level::Large);
749 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
750 // right now. This ThinLTO support is only enabled on "recent ish" versions of
751 // LLVM, and otherwise it's just blanket rejected from other compilers.
753 // Most of this implementation is straight copied from LLVM. At the time of
754 // this writing it wasn't *quite* suitable to reuse more code from upstream
755 // for our purposes, but we should strive to upstream this support once it's
756 // ready to go! I figure we may want a bit of testing locally first before
757 // sending this upstream to LLVM. I hear though they're quite eager to receive
758 // feedback like this!
760 // If you're reading this code and wondering "what in the world" or you're
761 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
762 // then fear not! (ok maybe fear a little). All code here is mostly based
763 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
765 // You'll find that the general layout here roughly corresponds to the `run`
766 // method in that file as well as `ProcessThinLTOModule`. Functions are
767 // specifically commented below as well, but if you're updating this code
768 // or otherwise trying to understand it, the LLVM source will be useful in
769 // interpreting the mysteries within.
771 // Otherwise I'll apologize in advance, it probably requires a relatively
772 // significant investment on your part to "truly understand" what's going on
773 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
774 // and various online resources about ThinLTO to make heads or tails of all
777 // This is a shared data structure which *must* be threadsafe to share
778 // read-only amongst threads. This also corresponds basically to the arguments
779 // of the `ProcessThinLTOModule` function in the LLVM source.
780 struct LLVMRustThinLTOData {
781 // The combined index that is the global analysis over all modules we're
782 // performing ThinLTO for. This is mostly managed by LLVM.
783 ModuleSummaryIndex Index;
785 // All modules we may look at, stored as in-memory serialized versions. This
786 // is later used when inlining to ensure we can extract any module to inline
788 StringMap<MemoryBufferRef> ModuleMap;
790 // A set that we manage of everything we *don't* want internalized. Note that
791 // this includes all transitive references right now as well, but it may not
793 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
795 // Not 100% sure what these are, but they impact what's internalized and
796 // what's inlined across modules, I believe.
797 StringMap<FunctionImporter::ImportMapTy> ImportLists;
798 StringMap<FunctionImporter::ExportSetTy> ExportLists;
799 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
801 #if LLVM_VERSION_GE(7, 0)
802 LLVMRustThinLTOData() : Index(/* isPerformingAnalysis = */ false) {}
806 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
807 struct LLVMRustThinLTOModule {
808 const char *identifier;
813 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
815 static const GlobalValueSummary *
816 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
817 auto StrongDefForLinker = llvm::find_if(
818 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
819 auto Linkage = Summary->linkage();
820 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
821 !GlobalValue::isWeakForLinker(Linkage);
823 if (StrongDefForLinker != GVSummaryList.end())
824 return StrongDefForLinker->get();
826 auto FirstDefForLinker = llvm::find_if(
827 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
828 auto Linkage = Summary->linkage();
829 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
831 if (FirstDefForLinker == GVSummaryList.end())
833 return FirstDefForLinker->get();
836 // The main entry point for creating the global ThinLTO analysis. The structure
837 // here is basically the same as before threads are spawned in the `run`
838 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
839 extern "C" LLVMRustThinLTOData*
840 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
842 const char **preserved_symbols,
844 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
846 // Load each module's summary and merge it into one combined index
847 for (int i = 0; i < num_modules; i++) {
848 auto module = &modules[i];
849 StringRef buffer(module->data, module->len);
850 MemoryBufferRef mem_buffer(buffer, module->identifier);
852 Ret->ModuleMap[module->identifier] = mem_buffer;
854 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
855 LLVMRustSetLastError(toString(std::move(Err)).c_str());
860 // Collect for each module the list of function it defines (GUID -> Summary)
861 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
863 // Convert the preserved symbols set from string to GUID, this is then needed
864 // for internalization.
865 for (int i = 0; i < num_symbols; i++) {
866 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
867 Ret->GUIDPreservedSymbols.insert(GUID);
870 // Collect the import/export lists for all modules from the call-graph in the
873 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
874 #if LLVM_VERSION_GE(7, 0)
875 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
876 return PrevailingType::Unknown;
878 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
880 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
882 ComputeCrossModuleImport(
884 Ret->ModuleToDefinedGVSummaries,
889 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
890 // impacts the caching.
892 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
893 // being lifted from `lib/LTO/LTO.cpp` as well
894 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
895 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
896 for (auto &I : Ret->Index) {
897 if (I.second.SummaryList.size() > 1)
898 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
900 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
901 const auto &Prevailing = PrevailingCopy.find(GUID);
902 if (Prevailing == PrevailingCopy.end())
904 return Prevailing->second == S;
906 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
907 GlobalValue::GUID GUID,
908 GlobalValue::LinkageTypes NewLinkage) {
909 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
911 #if LLVM_VERSION_GE(8, 0)
912 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
914 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
917 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
918 // callback below. This callback below will dictate the linkage for all
919 // summaries in the index, and we basically just only want to ensure that dead
920 // symbols are internalized. Otherwise everything that's already external
921 // linkage will stay as external, and internal will stay as internal.
922 std::set<GlobalValue::GUID> ExportedGUIDs;
923 for (auto &List : Ret->Index) {
924 for (auto &GVS: List.second.SummaryList) {
925 if (GlobalValue::isLocalLinkage(GVS->linkage()))
927 auto GUID = GVS->getOriginalName();
928 if (GVS->flags().Live)
929 ExportedGUIDs.insert(GUID);
932 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
933 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
934 return (ExportList != Ret->ExportLists.end() &&
935 ExportList->second.count(GUID)) ||
936 ExportedGUIDs.count(GUID);
938 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
940 return Ret.release();
944 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
948 // Below are the various passes that happen *per module* when doing ThinLTO.
950 // In other words, these are the functions that are all run concurrently
951 // with one another, one per module. The passes here correspond to the analysis
952 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
953 // `ProcessThinLTOModule` function. Here they're split up into separate steps
954 // so rustc can save off the intermediate bytecode between each step.
957 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
958 Module &Mod = *unwrap(M);
959 if (renameModuleForThinLTO(Mod, Data->Index)) {
960 LLVMRustSetLastError("renameModuleForThinLTO failed");
967 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
968 Module &Mod = *unwrap(M);
969 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
970 #if LLVM_VERSION_GE(8, 0)
971 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
973 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
979 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
980 Module &Mod = *unwrap(M);
981 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
982 thinLTOInternalizeModule(Mod, DefinedGlobals);
987 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
988 Module &Mod = *unwrap(M);
990 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
991 auto Loader = [&](StringRef Identifier) {
992 const auto &Memory = Data->ModuleMap.lookup(Identifier);
993 auto &Context = Mod.getContext();
994 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
999 // The rest of this closure is a workaround for
1000 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1001 // we accidentally import wasm custom sections into different modules,
1002 // duplicating them by in the final output artifact.
1004 // The issue is worked around here by manually removing the
1005 // `wasm.custom_sections` named metadata node from any imported module. This
1006 // we know isn't used by any optimization pass so there's no need for it to
1009 // Note that the metadata is currently lazily loaded, so we materialize it
1010 // here before looking up if there's metadata inside. The `FunctionImporter`
1011 // will immediately materialize metadata anyway after an import, so this
1012 // shouldn't be a perf hit.
1013 if (Error Err = (*MOrErr)->materializeMetadata()) {
1014 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1018 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1019 if (WasmCustomSections)
1020 WasmCustomSections->eraseFromParent();
1024 FunctionImporter Importer(Data->Index, Loader);
1025 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1027 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1033 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1034 const char*, // importing module name
1035 const char*); // imported module name
1037 // Calls `module_name_callback` for each module import done by ThinLTO.
1038 // The callback is provided with regular null-terminated C strings.
1040 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1041 LLVMRustModuleNameCallback module_name_callback,
1042 void* callback_payload) {
1043 for (const auto& importing_module : data->ImportLists) {
1044 const std::string importing_module_id = importing_module.getKey().str();
1045 const auto& imports = importing_module.getValue();
1046 for (const auto& imported_module : imports) {
1047 const std::string imported_module_id = imported_module.getKey().str();
1048 module_name_callback(callback_payload,
1049 importing_module_id.c_str(),
1050 imported_module_id.c_str());
1055 // This struct and various functions are sort of a hack right now, but the
1056 // problem is that we've got in-memory LLVM modules after we generate and
1057 // optimize all codegen-units for one compilation in rustc. To be compatible
1058 // with the LTO support above we need to serialize the modules plus their
1059 // ThinLTO summary into memory.
1061 // This structure is basically an owned version of a serialize module, with
1062 // a ThinLTO summary attached.
1063 struct LLVMRustThinLTOBuffer {
1067 extern "C" LLVMRustThinLTOBuffer*
1068 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1069 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1071 raw_string_ostream OS(Ret->data);
1073 legacy::PassManager PM;
1074 PM.add(createWriteThinLTOBitcodePass(OS));
1078 return Ret.release();
1082 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1086 extern "C" const void*
1087 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1088 return Buffer->data.data();
1092 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1093 return Buffer->data.length();
1096 // This is what we used to parse upstream bitcode for actual ThinLTO
1097 // processing. We'll call this once per module optimized through ThinLTO, and
1098 // it'll be called concurrently on many threads.
1099 extern "C" LLVMModuleRef
1100 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1103 const char *identifier) {
1104 StringRef Data(data, len);
1105 MemoryBufferRef Buffer(Data, identifier);
1106 unwrap(Context)->enableDebugTypeODRUniquing();
1107 Expected<std::unique_ptr<Module>> SrcOrError =
1108 parseBitcodeFile(Buffer, *unwrap(Context));
1110 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1113 return wrap(std::move(*SrcOrError).release());
1116 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1117 // the comment in `back/lto.rs` for why this exists.
1119 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1121 DICompileUnit **B) {
1122 Module *M = unwrap(Mod);
1123 DICompileUnit **Cur = A;
1124 DICompileUnit **Next = B;
1125 for (DICompileUnit *CU : M->debug_compile_units()) {
1134 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1135 // the comment in `back/lto.rs` for why this exists.
1137 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1138 Module *M = unwrap(Mod);
1140 // If the original source module didn't have a `DICompileUnit` then try to
1141 // merge all the existing compile units. If there aren't actually any though
1142 // then there's not much for us to do so return.
1143 if (Unit == nullptr) {
1144 for (DICompileUnit *CU : M->debug_compile_units()) {
1148 if (Unit == nullptr)
1152 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1153 // process it recursively. Note that we specifically iterate over instructions
1154 // to ensure we feed everything into it.
1155 DebugInfoFinder Finder;
1156 Finder.processModule(*M);
1157 for (Function &F : M->functions()) {
1158 for (auto &FI : F) {
1159 for (Instruction &BI : FI) {
1160 if (auto Loc = BI.getDebugLoc())
1161 Finder.processLocation(*M, Loc);
1162 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1163 Finder.processValue(*M, DVI);
1164 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1165 Finder.processDeclare(*M, DDI);
1170 // After we've found all our debuginfo, rewrite all subprograms to point to
1171 // the same `DICompileUnit`.
1172 for (auto &F : Finder.subprograms()) {
1173 F->replaceUnit(Unit);
1176 // Erase any other references to other `DICompileUnit` instances, the verifier
1177 // will later ensure that we don't actually have any other stale references to
1179 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1180 MD->clearOperands();
1181 MD->addOperand(Unit);