8 #include "llvm/Analysis/TargetLibraryInfo.h"
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/CodeGen/TargetSubtargetInfo.h"
11 #include "llvm/IR/AutoUpgrade.h"
12 #include "llvm/IR/AssemblyAnnotationWriter.h"
13 #include "llvm/IR/IntrinsicInst.h"
14 #include "llvm/Support/CBindingWrapping.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/Host.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
19 #include "llvm/Transforms/IPO/AlwaysInliner.h"
20 #include "llvm/Transforms/IPO/FunctionImport.h"
21 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
22 #include "llvm/LTO/LTO.h"
24 #include "llvm-c/Transforms/PassManagerBuilder.h"
27 using namespace llvm::legacy;
29 extern cl::opt<bool> EnableARMEHABI;
31 typedef struct LLVMOpaquePass *LLVMPassRef;
32 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
34 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
35 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
36 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
37 LLVMPassManagerBuilderRef)
39 extern "C" void LLVMInitializePasses() {
40 PassRegistry &Registry = *PassRegistry::getPassRegistry();
41 initializeCore(Registry);
42 initializeCodeGen(Registry);
43 initializeScalarOpts(Registry);
44 initializeVectorization(Registry);
45 initializeIPO(Registry);
46 initializeAnalysis(Registry);
47 initializeTransformUtils(Registry);
48 initializeInstCombine(Registry);
49 initializeInstrumentation(Registry);
50 initializeTarget(Registry);
53 enum class LLVMRustPassKind {
59 static LLVMRustPassKind toRust(PassKind Kind) {
62 return LLVMRustPassKind::Function;
64 return LLVMRustPassKind::Module;
66 return LLVMRustPassKind::Other;
70 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
71 StringRef SR(PassName);
72 PassRegistry *PR = PassRegistry::getPassRegistry();
74 const PassInfo *PI = PR->getPassInfo(SR);
76 return wrap(PI->createPass());
81 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
83 Pass *Pass = unwrap(RustPass);
84 return toRust(Pass->getPassKind());
87 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
89 Pass *Pass = unwrap(RustPass);
90 PassManagerBase *PMB = unwrap(PMR);
95 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
96 LLVMPassManagerBuilderRef PMBR,
97 LLVMPassManagerRef PMR
99 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
103 void LLVMRustAddLastExtensionPasses(
104 LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
105 auto AddExtensionPasses = [Passes, NumPasses](
106 const PassManagerBuilder &Builder, PassManagerBase &PM) {
107 for (size_t I = 0; I < NumPasses; I++) {
108 PM.add(unwrap(Passes[I]));
111 // Add the passes to both of the pre-finalization extension points,
112 // so they are run for optimized and non-optimized builds.
113 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
115 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
119 #ifdef LLVM_COMPONENT_X86
120 #define SUBTARGET_X86 SUBTARGET(X86)
122 #define SUBTARGET_X86
125 #ifdef LLVM_COMPONENT_ARM
126 #define SUBTARGET_ARM SUBTARGET(ARM)
128 #define SUBTARGET_ARM
131 #ifdef LLVM_COMPONENT_AARCH64
132 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
134 #define SUBTARGET_AARCH64
137 #ifdef LLVM_COMPONENT_MIPS
138 #define SUBTARGET_MIPS SUBTARGET(Mips)
140 #define SUBTARGET_MIPS
143 #ifdef LLVM_COMPONENT_POWERPC
144 #define SUBTARGET_PPC SUBTARGET(PPC)
146 #define SUBTARGET_PPC
149 #ifdef LLVM_COMPONENT_SYSTEMZ
150 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
152 #define SUBTARGET_SYSTEMZ
155 #ifdef LLVM_COMPONENT_MSP430
156 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
158 #define SUBTARGET_MSP430
161 #ifdef LLVM_COMPONENT_RISCV
162 #define SUBTARGET_RISCV SUBTARGET(RISCV)
164 #define SUBTARGET_RISCV
167 #ifdef LLVM_COMPONENT_SPARC
168 #define SUBTARGET_SPARC SUBTARGET(Sparc)
170 #define SUBTARGET_SPARC
173 #ifdef LLVM_COMPONENT_HEXAGON
174 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
176 #define SUBTARGET_HEXAGON
179 #define GEN_SUBTARGETS \
191 #define SUBTARGET(x) \
193 extern const SubtargetFeatureKV x##FeatureKV[]; \
194 extern const SubtargetFeatureKV x##SubTypeKV[]; \
200 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
201 const char *Feature) {
202 TargetMachine *Target = unwrap(TM);
203 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
204 return MCInfo->checkFeatures(std::string("+") + Feature);
207 enum class LLVMRustCodeModel {
216 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
218 case LLVMRustCodeModel::Small:
219 return CodeModel::Small;
220 case LLVMRustCodeModel::Kernel:
221 return CodeModel::Kernel;
222 case LLVMRustCodeModel::Medium:
223 return CodeModel::Medium;
224 case LLVMRustCodeModel::Large:
225 return CodeModel::Large;
227 report_fatal_error("Bad CodeModel.");
231 enum class LLVMRustCodeGenOptLevel {
239 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
241 case LLVMRustCodeGenOptLevel::None:
242 return CodeGenOpt::None;
243 case LLVMRustCodeGenOptLevel::Less:
244 return CodeGenOpt::Less;
245 case LLVMRustCodeGenOptLevel::Default:
246 return CodeGenOpt::Default;
247 case LLVMRustCodeGenOptLevel::Aggressive:
248 return CodeGenOpt::Aggressive;
250 report_fatal_error("Bad CodeGenOptLevel.");
254 enum class LLVMRustRelocMode {
264 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
266 case LLVMRustRelocMode::Default:
268 case LLVMRustRelocMode::Static:
269 return Reloc::Static;
270 case LLVMRustRelocMode::PIC:
272 case LLVMRustRelocMode::DynamicNoPic:
273 return Reloc::DynamicNoPIC;
274 case LLVMRustRelocMode::ROPI:
276 case LLVMRustRelocMode::RWPI:
278 case LLVMRustRelocMode::ROPIRWPI:
279 return Reloc::ROPI_RWPI;
281 report_fatal_error("Bad RelocModel.");
285 /// getLongestEntryLength - Return the length of the longest entry in the table.
286 template<typename KV>
287 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
289 for (auto &I : Table)
290 MaxLen = std::max(MaxLen, std::strlen(I.Key));
294 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
295 const TargetMachine *Target = unwrap(TM);
296 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
297 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
298 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
299 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
300 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
302 printf("Available CPUs for this target:\n");
303 if (HostArch == TargetArch) {
304 const StringRef HostCPU = sys::getHostCPUName();
305 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
306 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
308 for (auto &CPU : CPUTable)
309 printf(" %-*s\n", MaxCPULen, CPU.Key);
313 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
314 const TargetMachine *Target = unwrap(TM);
315 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
316 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
317 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
319 printf("Available features for this target:\n");
320 for (auto &Feature : FeatTable)
321 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
324 printf("Use +feature to enable a feature, or -feature to disable it.\n"
325 "For example, rustc -C -target-cpu=mycpu -C "
326 "target-feature=+feature1,-feature2\n\n");
331 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
332 printf("Target CPU help is not supported by this LLVM version.\n\n");
335 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
336 printf("Target features help is not supported by this LLVM version.\n\n");
340 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
341 StringRef Name = sys::getHostCPUName();
346 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
347 const char *TripleStr, const char *CPU, const char *Feature,
348 LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
349 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
350 bool PositionIndependentExecutable, bool FunctionSections,
352 bool TrapUnreachable,
355 bool EmitStackSizeSection) {
357 auto OptLevel = fromRust(RustOptLevel);
358 auto RM = fromRust(RustReloc);
361 Triple Trip(Triple::normalize(TripleStr));
362 const llvm::Target *TheTarget =
363 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
364 if (TheTarget == nullptr) {
365 LLVMRustSetLastError(Error.c_str());
369 TargetOptions Options;
371 Options.FloatABIType = FloatABI::Default;
373 Options.FloatABIType = FloatABI::Soft;
375 Options.DataSections = DataSections;
376 Options.FunctionSections = FunctionSections;
377 Options.MCOptions.AsmVerbose = AsmComments;
378 Options.MCOptions.PreserveAsmComments = AsmComments;
380 if (TrapUnreachable) {
381 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
382 // This limits the extent of possible undefined behavior in some cases, as
383 // it prevents control flow from "falling through" into whatever code
384 // happens to be laid out next in memory.
385 Options.TrapUnreachable = true;
389 Options.ThreadModel = ThreadModel::Single;
392 Options.EmitStackSizeSection = EmitStackSizeSection;
394 Optional<CodeModel::Model> CM;
395 if (RustCM != LLVMRustCodeModel::None)
396 CM = fromRust(RustCM);
397 TargetMachine *TM = TheTarget->createTargetMachine(
398 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
402 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
406 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
407 // passes for a target to a pass manager. We export that functionality through
409 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
410 LLVMPassManagerRef PMR,
412 PassManagerBase *PM = unwrap(PMR);
414 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
417 extern "C" void LLVMRustConfigurePassManagerBuilder(
418 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
419 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
420 const char* PGOGenPath, const char* PGOUsePath) {
421 #if LLVM_VERSION_GE(7, 0)
422 unwrap(PMBR)->MergeFunctions = MergeFunctions;
424 unwrap(PMBR)->SLPVectorize = SLPVectorize;
425 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
426 unwrap(PMBR)->LoopVectorize = LoopVectorize;
427 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
431 unwrap(PMBR)->EnablePGOInstrGen = true;
432 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
436 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
440 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
441 // field of a PassManagerBuilder, we expose our own method of doing so.
442 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
444 bool DisableSimplifyLibCalls) {
445 Triple TargetTriple(unwrap(M)->getTargetTriple());
446 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
447 if (DisableSimplifyLibCalls)
448 TLI->disableAllFunctions();
449 unwrap(PMBR)->LibraryInfo = TLI;
452 // Unfortunately, the LLVM C API doesn't provide a way to create the
453 // TargetLibraryInfo pass, so we use this method to do so.
454 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
455 bool DisableSimplifyLibCalls) {
456 Triple TargetTriple(unwrap(M)->getTargetTriple());
457 TargetLibraryInfoImpl TLII(TargetTriple);
458 if (DisableSimplifyLibCalls)
459 TLII.disableAllFunctions();
460 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
463 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
464 // all the functions in a module, so we do that manually here. You'll find
465 // similar code in clang's BackendUtil.cpp file.
466 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
468 llvm::legacy::FunctionPassManager *P =
469 unwrap<llvm::legacy::FunctionPassManager>(PMR);
470 P->doInitialization();
472 // Upgrade all calls to old intrinsics first.
473 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
474 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
476 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
478 if (!I->isDeclaration())
484 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
485 // Initializing the command-line options more than once is not allowed. So,
486 // check if they've already been initialized. (This could happen if we're
487 // being called from rustpkg, for example). If the arguments change, then
488 // that's just kinda unfortunate.
489 static bool Initialized = false;
493 cl::ParseCommandLineOptions(Argc, Argv);
496 enum class LLVMRustFileType {
502 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
504 case LLVMRustFileType::AssemblyFile:
505 return TargetMachine::CGFT_AssemblyFile;
506 case LLVMRustFileType::ObjectFile:
507 return TargetMachine::CGFT_ObjectFile;
509 report_fatal_error("Bad FileType.");
513 extern "C" LLVMRustResult
514 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
515 LLVMModuleRef M, const char *Path,
516 LLVMRustFileType RustFileType) {
517 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
518 auto FileType = fromRust(RustFileType);
520 std::string ErrorInfo;
522 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
524 ErrorInfo = EC.message();
525 if (ErrorInfo != "") {
526 LLVMRustSetLastError(ErrorInfo.c_str());
527 return LLVMRustResult::Failure;
530 #if LLVM_VERSION_GE(7, 0)
531 buffer_ostream BOS(OS);
532 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
534 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
538 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
539 // stream (OS), so the only real safe place to delete this is here? Don't we
540 // wish this was written in Rust?
542 return LLVMRustResult::Success;
546 // Callback to demangle function name
548 // * name to be demangled
551 // * output buffer len
552 // Returns len of demangled string, or 0 if demangle failed.
553 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
558 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
560 std::vector<char> Buf;
563 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
565 // Return empty string if demangle failed
566 // or if name does not need to be demangled
567 StringRef CallDemangle(StringRef name) {
572 if (Buf.size() < name.size() * 2) {
573 // Semangled name usually shorter than mangled,
574 // but allocate twice as much memory just in case
575 Buf.resize(name.size() * 2);
578 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
584 auto Demangled = StringRef(Buf.data(), R);
585 if (Demangled == name) {
586 // Do not print anything if demangled name is equal to mangled.
593 void emitFunctionAnnot(const Function *F,
594 formatted_raw_ostream &OS) override {
595 StringRef Demangled = CallDemangle(F->getName());
596 if (Demangled.empty()) {
600 OS << "; " << Demangled << "\n";
603 void emitInstructionAnnot(const Instruction *I,
604 formatted_raw_ostream &OS) override {
607 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
609 Value = CI->getCalledValue();
610 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
612 Value = II->getCalledValue();
614 // Could demangle more operations, e. g.
615 // `store %place, @function`.
619 if (!Value->hasName()) {
623 StringRef Demangled = CallDemangle(Value->getName());
624 if (Demangled.empty()) {
628 OS << "; " << Name << " " << Demangled << "\n";
632 class RustPrintModulePass : public ModulePass {
637 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
638 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
639 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
641 bool runOnModule(Module &M) override {
642 RustAssemblyAnnotationWriter AW(Demangle);
644 M.print(*OS, &AW, false);
649 void getAnalysisUsage(AnalysisUsage &AU) const override {
650 AU.setPreservesAll();
653 static StringRef name() { return "RustPrintModulePass"; }
659 void initializeRustPrintModulePassPass(PassRegistry&);
662 char RustPrintModulePass::ID = 0;
663 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
664 "Print rust module to stderr", false, false)
666 extern "C" LLVMRustResult
667 LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
668 const char *Path, DemangleFn Demangle) {
669 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
670 std::string ErrorInfo;
673 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
675 ErrorInfo = EC.message();
676 if (ErrorInfo != "") {
677 LLVMRustSetLastError(ErrorInfo.c_str());
678 return LLVMRustResult::Failure;
681 formatted_raw_ostream FOS(OS);
683 PM->add(new RustPrintModulePass(FOS, Demangle));
687 return LLVMRustResult::Success;
690 extern "C" void LLVMRustPrintPasses() {
691 LLVMInitializePasses();
692 struct MyListener : PassRegistrationListener {
693 void passEnumerate(const PassInfo *Info) {
694 StringRef PassArg = Info->getPassArgument();
695 StringRef PassName = Info->getPassName();
696 if (!PassArg.empty()) {
697 // These unsigned->signed casts could theoretically overflow, but
698 // realistically never will (and even if, the result is implementation
699 // defined rather plain UB).
700 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
701 (int)PassName.size(), PassName.data());
706 PassRegistry *PR = PassRegistry::getPassRegistry();
707 PR->enumerateWith(&Listener);
710 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
712 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
715 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
717 llvm::legacy::PassManager passes;
719 auto PreserveFunctions = [=](const GlobalValue &GV) {
720 for (size_t I = 0; I < Len; I++) {
721 if (GV.getName() == Symbols[I]) {
728 passes.add(llvm::createInternalizePass(PreserveFunctions));
730 passes.run(*unwrap(M));
733 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
734 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
736 GV->setDoesNotThrow();
737 Function *F = dyn_cast<Function>(GV);
741 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
742 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
743 if (isa<InvokeInst>(I)) {
744 InvokeInst *CI = cast<InvokeInst>(I);
745 CI->setDoesNotThrow();
753 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
754 LLVMTargetMachineRef TMR) {
755 TargetMachine *Target = unwrap(TMR);
756 unwrap(Module)->setDataLayout(Target->createDataLayout());
759 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
760 unwrap(M)->setPIELevel(PIELevel::Level::Large);
763 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
764 // right now. This ThinLTO support is only enabled on "recent ish" versions of
765 // LLVM, and otherwise it's just blanket rejected from other compilers.
767 // Most of this implementation is straight copied from LLVM. At the time of
768 // this writing it wasn't *quite* suitable to reuse more code from upstream
769 // for our purposes, but we should strive to upstream this support once it's
770 // ready to go! I figure we may want a bit of testing locally first before
771 // sending this upstream to LLVM. I hear though they're quite eager to receive
772 // feedback like this!
774 // If you're reading this code and wondering "what in the world" or you're
775 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
776 // then fear not! (ok maybe fear a little). All code here is mostly based
777 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
779 // You'll find that the general layout here roughly corresponds to the `run`
780 // method in that file as well as `ProcessThinLTOModule`. Functions are
781 // specifically commented below as well, but if you're updating this code
782 // or otherwise trying to understand it, the LLVM source will be useful in
783 // interpreting the mysteries within.
785 // Otherwise I'll apologize in advance, it probably requires a relatively
786 // significant investment on your part to "truly understand" what's going on
787 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
788 // and various online resources about ThinLTO to make heads or tails of all
791 // This is a shared data structure which *must* be threadsafe to share
792 // read-only amongst threads. This also corresponds basically to the arguments
793 // of the `ProcessThinLTOModule` function in the LLVM source.
794 struct LLVMRustThinLTOData {
795 // The combined index that is the global analysis over all modules we're
796 // performing ThinLTO for. This is mostly managed by LLVM.
797 ModuleSummaryIndex Index;
799 // All modules we may look at, stored as in-memory serialized versions. This
800 // is later used when inlining to ensure we can extract any module to inline
802 StringMap<MemoryBufferRef> ModuleMap;
804 // A set that we manage of everything we *don't* want internalized. Note that
805 // this includes all transitive references right now as well, but it may not
807 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
809 // Not 100% sure what these are, but they impact what's internalized and
810 // what's inlined across modules, I believe.
811 StringMap<FunctionImporter::ImportMapTy> ImportLists;
812 StringMap<FunctionImporter::ExportSetTy> ExportLists;
813 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
815 #if LLVM_VERSION_GE(7, 0)
816 LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
820 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
821 struct LLVMRustThinLTOModule {
822 const char *identifier;
827 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
829 static const GlobalValueSummary *
830 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
831 auto StrongDefForLinker = llvm::find_if(
832 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
833 auto Linkage = Summary->linkage();
834 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
835 !GlobalValue::isWeakForLinker(Linkage);
837 if (StrongDefForLinker != GVSummaryList.end())
838 return StrongDefForLinker->get();
840 auto FirstDefForLinker = llvm::find_if(
841 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
842 auto Linkage = Summary->linkage();
843 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
845 if (FirstDefForLinker == GVSummaryList.end())
847 return FirstDefForLinker->get();
850 // The main entry point for creating the global ThinLTO analysis. The structure
851 // here is basically the same as before threads are spawned in the `run`
852 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
853 extern "C" LLVMRustThinLTOData*
854 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
856 const char **preserved_symbols,
858 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
860 // Load each module's summary and merge it into one combined index
861 for (int i = 0; i < num_modules; i++) {
862 auto module = &modules[i];
863 StringRef buffer(module->data, module->len);
864 MemoryBufferRef mem_buffer(buffer, module->identifier);
866 Ret->ModuleMap[module->identifier] = mem_buffer;
868 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
869 LLVMRustSetLastError(toString(std::move(Err)).c_str());
874 // Collect for each module the list of function it defines (GUID -> Summary)
875 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
877 // Convert the preserved symbols set from string to GUID, this is then needed
878 // for internalization.
879 for (int i = 0; i < num_symbols; i++) {
880 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
881 Ret->GUIDPreservedSymbols.insert(GUID);
884 // Collect the import/export lists for all modules from the call-graph in the
887 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
888 #if LLVM_VERSION_GE(7, 0)
889 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
890 return PrevailingType::Unknown;
892 #if LLVM_VERSION_GE(8, 0)
893 // We don't have a complete picture in our use of ThinLTO, just our immediate
894 // crate, so we need `ImportEnabled = false` to limit internalization.
895 // Otherwise, we sometimes lose `static` values -- see #60184.
896 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
897 deadIsPrevailing, /* ImportEnabled = */ false);
899 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
902 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
904 ComputeCrossModuleImport(
906 Ret->ModuleToDefinedGVSummaries,
911 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
912 // impacts the caching.
914 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
915 // being lifted from `lib/LTO/LTO.cpp` as well
916 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
917 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
918 for (auto &I : Ret->Index) {
919 if (I.second.SummaryList.size() > 1)
920 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
922 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
923 const auto &Prevailing = PrevailingCopy.find(GUID);
924 if (Prevailing == PrevailingCopy.end())
926 return Prevailing->second == S;
928 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
929 GlobalValue::GUID GUID,
930 GlobalValue::LinkageTypes NewLinkage) {
931 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
933 #if LLVM_VERSION_GE(9, 0)
934 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
935 Ret->GUIDPreservedSymbols);
936 #elif LLVM_VERSION_GE(8, 0)
937 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
939 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
942 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
943 // callback below. This callback below will dictate the linkage for all
944 // summaries in the index, and we basically just only want to ensure that dead
945 // symbols are internalized. Otherwise everything that's already external
946 // linkage will stay as external, and internal will stay as internal.
947 std::set<GlobalValue::GUID> ExportedGUIDs;
948 for (auto &List : Ret->Index) {
949 for (auto &GVS: List.second.SummaryList) {
950 if (GlobalValue::isLocalLinkage(GVS->linkage()))
952 auto GUID = GVS->getOriginalName();
953 if (GVS->flags().Live)
954 ExportedGUIDs.insert(GUID);
957 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
958 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
959 return (ExportList != Ret->ExportLists.end() &&
960 ExportList->second.count(GUID)) ||
961 ExportedGUIDs.count(GUID);
963 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
965 return Ret.release();
969 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
973 // Below are the various passes that happen *per module* when doing ThinLTO.
975 // In other words, these are the functions that are all run concurrently
976 // with one another, one per module. The passes here correspond to the analysis
977 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
978 // `ProcessThinLTOModule` function. Here they're split up into separate steps
979 // so rustc can save off the intermediate bytecode between each step.
982 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
983 Module &Mod = *unwrap(M);
984 if (renameModuleForThinLTO(Mod, Data->Index)) {
985 LLVMRustSetLastError("renameModuleForThinLTO failed");
992 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
993 Module &Mod = *unwrap(M);
994 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
995 #if LLVM_VERSION_GE(8, 0)
996 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
998 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1004 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1005 Module &Mod = *unwrap(M);
1006 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1007 thinLTOInternalizeModule(Mod, DefinedGlobals);
1012 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1013 Module &Mod = *unwrap(M);
1015 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1016 auto Loader = [&](StringRef Identifier) {
1017 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1018 auto &Context = Mod.getContext();
1019 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1024 // The rest of this closure is a workaround for
1025 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1026 // we accidentally import wasm custom sections into different modules,
1027 // duplicating them by in the final output artifact.
1029 // The issue is worked around here by manually removing the
1030 // `wasm.custom_sections` named metadata node from any imported module. This
1031 // we know isn't used by any optimization pass so there's no need for it to
1034 // Note that the metadata is currently lazily loaded, so we materialize it
1035 // here before looking up if there's metadata inside. The `FunctionImporter`
1036 // will immediately materialize metadata anyway after an import, so this
1037 // shouldn't be a perf hit.
1038 if (Error Err = (*MOrErr)->materializeMetadata()) {
1039 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1043 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1044 if (WasmCustomSections)
1045 WasmCustomSections->eraseFromParent();
1049 FunctionImporter Importer(Data->Index, Loader);
1050 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1052 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1058 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1059 const char*, // importing module name
1060 const char*); // imported module name
1062 // Calls `module_name_callback` for each module import done by ThinLTO.
1063 // The callback is provided with regular null-terminated C strings.
1065 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1066 LLVMRustModuleNameCallback module_name_callback,
1067 void* callback_payload) {
1068 for (const auto& importing_module : data->ImportLists) {
1069 const std::string importing_module_id = importing_module.getKey().str();
1070 const auto& imports = importing_module.getValue();
1071 for (const auto& imported_module : imports) {
1072 const std::string imported_module_id = imported_module.getKey().str();
1073 module_name_callback(callback_payload,
1074 importing_module_id.c_str(),
1075 imported_module_id.c_str());
1080 // This struct and various functions are sort of a hack right now, but the
1081 // problem is that we've got in-memory LLVM modules after we generate and
1082 // optimize all codegen-units for one compilation in rustc. To be compatible
1083 // with the LTO support above we need to serialize the modules plus their
1084 // ThinLTO summary into memory.
1086 // This structure is basically an owned version of a serialize module, with
1087 // a ThinLTO summary attached.
1088 struct LLVMRustThinLTOBuffer {
1092 extern "C" LLVMRustThinLTOBuffer*
1093 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1094 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1096 raw_string_ostream OS(Ret->data);
1098 legacy::PassManager PM;
1099 PM.add(createWriteThinLTOBitcodePass(OS));
1103 return Ret.release();
1107 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1111 extern "C" const void*
1112 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1113 return Buffer->data.data();
1117 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1118 return Buffer->data.length();
1121 // This is what we used to parse upstream bitcode for actual ThinLTO
1122 // processing. We'll call this once per module optimized through ThinLTO, and
1123 // it'll be called concurrently on many threads.
1124 extern "C" LLVMModuleRef
1125 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1128 const char *identifier) {
1129 StringRef Data(data, len);
1130 MemoryBufferRef Buffer(Data, identifier);
1131 unwrap(Context)->enableDebugTypeODRUniquing();
1132 Expected<std::unique_ptr<Module>> SrcOrError =
1133 parseBitcodeFile(Buffer, *unwrap(Context));
1135 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1138 return wrap(std::move(*SrcOrError).release());
1141 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1142 // the comment in `back/lto.rs` for why this exists.
1144 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1146 DICompileUnit **B) {
1147 Module *M = unwrap(Mod);
1148 DICompileUnit **Cur = A;
1149 DICompileUnit **Next = B;
1150 for (DICompileUnit *CU : M->debug_compile_units()) {
1159 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1160 // the comment in `back/lto.rs` for why this exists.
1162 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1163 Module *M = unwrap(Mod);
1165 // If the original source module didn't have a `DICompileUnit` then try to
1166 // merge all the existing compile units. If there aren't actually any though
1167 // then there's not much for us to do so return.
1168 if (Unit == nullptr) {
1169 for (DICompileUnit *CU : M->debug_compile_units()) {
1173 if (Unit == nullptr)
1177 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1178 // process it recursively. Note that we specifically iterate over instructions
1179 // to ensure we feed everything into it.
1180 DebugInfoFinder Finder;
1181 Finder.processModule(*M);
1182 for (Function &F : M->functions()) {
1183 for (auto &FI : F) {
1184 for (Instruction &BI : FI) {
1185 if (auto Loc = BI.getDebugLoc())
1186 Finder.processLocation(*M, Loc);
1187 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1188 Finder.processValue(*M, DVI);
1189 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1190 Finder.processDeclare(*M, DDI);
1195 // After we've found all our debuginfo, rewrite all subprograms to point to
1196 // the same `DICompileUnit`.
1197 for (auto &F : Finder.subprograms()) {
1198 F->replaceUnit(Unit);
1201 // Erase any other references to other `DICompileUnit` instances, the verifier
1202 // will later ensure that we don't actually have any other stale references to
1204 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1205 MD->clearOperands();
1206 MD->addOperand(Unit);