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/IR/AutoUpgrade.h"
21 #include "llvm/IR/AssemblyAnnotationWriter.h"
22 #include "llvm/Support/CBindingWrapping.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Host.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
28 #if LLVM_VERSION_GE(6, 0)
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
35 #if LLVM_VERSION_GE(4, 0)
36 #include "llvm/Transforms/IPO/AlwaysInliner.h"
37 #include "llvm/Transforms/IPO/FunctionImport.h"
38 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
39 #include "llvm/LTO/LTO.h"
40 #if LLVM_VERSION_LE(4, 0)
41 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
45 #include "llvm-c/Transforms/PassManagerBuilder.h"
47 #if LLVM_VERSION_GE(4, 0)
52 using namespace llvm::legacy;
54 extern cl::opt<bool> EnableARMEHABI;
56 typedef struct LLVMOpaquePass *LLVMPassRef;
57 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
59 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
60 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
61 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
62 LLVMPassManagerBuilderRef)
64 extern "C" void LLVMInitializePasses() {
65 PassRegistry &Registry = *PassRegistry::getPassRegistry();
66 initializeCore(Registry);
67 initializeCodeGen(Registry);
68 initializeScalarOpts(Registry);
69 initializeVectorization(Registry);
70 initializeIPO(Registry);
71 initializeAnalysis(Registry);
72 initializeTransformUtils(Registry);
73 initializeInstCombine(Registry);
74 initializeInstrumentation(Registry);
75 initializeTarget(Registry);
78 enum class LLVMRustPassKind {
84 static LLVMRustPassKind toRust(PassKind Kind) {
87 return LLVMRustPassKind::Function;
89 return LLVMRustPassKind::Module;
91 return LLVMRustPassKind::Other;
95 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
96 StringRef SR(PassName);
97 PassRegistry *PR = PassRegistry::getPassRegistry();
99 const PassInfo *PI = PR->getPassInfo(SR);
101 return wrap(PI->createPass());
106 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
108 Pass *Pass = unwrap(RustPass);
109 return toRust(Pass->getPassKind());
112 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
114 Pass *Pass = unwrap(RustPass);
115 PassManagerBase *PMB = unwrap(PMR);
120 bool LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
121 LLVMPassManagerBuilderRef PMBR,
122 LLVMPassManagerRef PMR
124 #if LLVM_VERSION_GE(4, 0)
125 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
132 #ifdef LLVM_COMPONENT_X86
133 #define SUBTARGET_X86 SUBTARGET(X86)
135 #define SUBTARGET_X86
138 #ifdef LLVM_COMPONENT_ARM
139 #define SUBTARGET_ARM SUBTARGET(ARM)
141 #define SUBTARGET_ARM
144 #ifdef LLVM_COMPONENT_AARCH64
145 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
147 #define SUBTARGET_AARCH64
150 #ifdef LLVM_COMPONENT_MIPS
151 #define SUBTARGET_MIPS SUBTARGET(Mips)
153 #define SUBTARGET_MIPS
156 #ifdef LLVM_COMPONENT_POWERPC
157 #define SUBTARGET_PPC SUBTARGET(PPC)
159 #define SUBTARGET_PPC
162 #ifdef LLVM_COMPONENT_SYSTEMZ
163 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
165 #define SUBTARGET_SYSTEMZ
168 #ifdef LLVM_COMPONENT_MSP430
169 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
171 #define SUBTARGET_MSP430
174 #ifdef LLVM_COMPONENT_RISCV
175 #define SUBTARGET_RISCV SUBTARGET(RISCV)
177 #define SUBTARGET_RISCV
180 #ifdef LLVM_COMPONENT_SPARC
181 #define SUBTARGET_SPARC SUBTARGET(Sparc)
183 #define SUBTARGET_SPARC
186 #ifdef LLVM_COMPONENT_HEXAGON
187 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
189 #define SUBTARGET_HEXAGON
192 #define GEN_SUBTARGETS \
204 #define SUBTARGET(x) \
206 extern const SubtargetFeatureKV x##FeatureKV[]; \
207 extern const SubtargetFeatureKV x##SubTypeKV[]; \
213 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
214 const char *Feature) {
215 #if LLVM_VERSION_GE(6, 0)
216 TargetMachine *Target = unwrap(TM);
217 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
218 return MCInfo->checkFeatures(std::string("+") + Feature);
224 enum class LLVMRustCodeModel {
233 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
235 case LLVMRustCodeModel::Small:
236 return CodeModel::Small;
237 case LLVMRustCodeModel::Kernel:
238 return CodeModel::Kernel;
239 case LLVMRustCodeModel::Medium:
240 return CodeModel::Medium;
241 case LLVMRustCodeModel::Large:
242 return CodeModel::Large;
244 report_fatal_error("Bad CodeModel.");
248 enum class LLVMRustCodeGenOptLevel {
256 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
258 case LLVMRustCodeGenOptLevel::None:
259 return CodeGenOpt::None;
260 case LLVMRustCodeGenOptLevel::Less:
261 return CodeGenOpt::Less;
262 case LLVMRustCodeGenOptLevel::Default:
263 return CodeGenOpt::Default;
264 case LLVMRustCodeGenOptLevel::Aggressive:
265 return CodeGenOpt::Aggressive;
267 report_fatal_error("Bad CodeGenOptLevel.");
271 enum class LLVMRustRelocMode {
281 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
283 case LLVMRustRelocMode::Default:
285 case LLVMRustRelocMode::Static:
286 return Reloc::Static;
287 case LLVMRustRelocMode::PIC:
289 case LLVMRustRelocMode::DynamicNoPic:
290 return Reloc::DynamicNoPIC;
291 #if LLVM_VERSION_GE(4, 0)
292 case LLVMRustRelocMode::ROPI:
294 case LLVMRustRelocMode::RWPI:
296 case LLVMRustRelocMode::ROPIRWPI:
297 return Reloc::ROPI_RWPI;
303 report_fatal_error("Bad RelocModel.");
307 /// getLongestEntryLength - Return the length of the longest entry in the table.
309 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
311 for (auto &I : Table)
312 MaxLen = std::max(MaxLen, std::strlen(I.Key));
316 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
317 const TargetMachine *Target = unwrap(TM);
318 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
319 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
320 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
321 const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
322 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
324 printf("Available CPUs for this target:\n");
325 if (HostArch == TargetArch) {
326 const StringRef HostCPU = sys::getHostCPUName();
327 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
328 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
330 for (auto &CPU : CPUTable)
331 printf(" %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
335 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
336 const TargetMachine *Target = unwrap(TM);
337 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
338 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
339 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
341 printf("Available features for this target:\n");
342 for (auto &Feature : FeatTable)
343 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
346 printf("Use +feature to enable a feature, or -feature to disable it.\n"
347 "For example, rustc -C -target-cpu=mycpu -C "
348 "target-feature=+feature1,-feature2\n\n");
353 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
354 printf("Target CPU help is not supported by this LLVM version.\n\n");
357 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
358 printf("Target features help is not supported by this LLVM version.\n\n");
362 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
363 StringRef Name = sys::getHostCPUName();
368 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
369 const char *TripleStr, const char *CPU, const char *Feature,
370 LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
371 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
372 bool PositionIndependentExecutable, bool FunctionSections,
374 bool TrapUnreachable,
378 auto OptLevel = fromRust(RustOptLevel);
379 auto RM = fromRust(RustReloc);
382 Triple Trip(Triple::normalize(TripleStr));
383 const llvm::Target *TheTarget =
384 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
385 if (TheTarget == nullptr) {
386 LLVMRustSetLastError(Error.c_str());
390 TargetOptions Options;
392 Options.FloatABIType = FloatABI::Default;
394 Options.FloatABIType = FloatABI::Soft;
396 Options.DataSections = DataSections;
397 Options.FunctionSections = FunctionSections;
398 Options.MCOptions.AsmVerbose = AsmComments;
399 Options.MCOptions.PreserveAsmComments = AsmComments;
401 if (TrapUnreachable) {
402 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
403 // This limits the extent of possible undefined behavior in some cases, as
404 // it prevents control flow from "falling through" into whatever code
405 // happens to be laid out next in memory.
406 Options.TrapUnreachable = true;
410 Options.ThreadModel = ThreadModel::Single;
413 #if LLVM_VERSION_GE(6, 0)
414 Optional<CodeModel::Model> CM;
416 CodeModel::Model CM = CodeModel::Model::Default;
418 if (RustCM != LLVMRustCodeModel::None)
419 CM = fromRust(RustCM);
420 TargetMachine *TM = TheTarget->createTargetMachine(
421 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
425 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
429 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
430 // passes for a target to a pass manager. We export that functionality through
432 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
433 LLVMPassManagerRef PMR,
435 PassManagerBase *PM = unwrap(PMR);
437 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
440 extern "C" void LLVMRustConfigurePassManagerBuilder(
441 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
442 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
443 const char* PGOGenPath, const char* PGOUsePath) {
445 unwrap(PMBR)->MergeFunctions = MergeFunctions;
447 unwrap(PMBR)->SLPVectorize = SLPVectorize;
448 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
449 unwrap(PMBR)->LoopVectorize = LoopVectorize;
450 #if LLVM_VERSION_GE(4, 0)
451 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
457 unwrap(PMBR)->EnablePGOInstrGen = true;
458 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
462 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
465 assert(!PGOGenPath && !PGOUsePath && "Should've caught earlier");
469 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
470 // field of a PassManagerBuilder, we expose our own method of doing so.
471 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
473 bool DisableSimplifyLibCalls) {
474 Triple TargetTriple(unwrap(M)->getTargetTriple());
475 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
476 if (DisableSimplifyLibCalls)
477 TLI->disableAllFunctions();
478 unwrap(PMBR)->LibraryInfo = TLI;
481 // Unfortunately, the LLVM C API doesn't provide a way to create the
482 // TargetLibraryInfo pass, so we use this method to do so.
483 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
484 bool DisableSimplifyLibCalls) {
485 Triple TargetTriple(unwrap(M)->getTargetTriple());
486 TargetLibraryInfoImpl TLII(TargetTriple);
487 if (DisableSimplifyLibCalls)
488 TLII.disableAllFunctions();
489 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
492 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
493 // all the functions in a module, so we do that manually here. You'll find
494 // similar code in clang's BackendUtil.cpp file.
495 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
497 llvm::legacy::FunctionPassManager *P =
498 unwrap<llvm::legacy::FunctionPassManager>(PMR);
499 P->doInitialization();
501 // Upgrade all calls to old intrinsics first.
502 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
503 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
505 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
507 if (!I->isDeclaration())
513 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
514 // Initializing the command-line options more than once is not allowed. So,
515 // check if they've already been initialized. (This could happen if we're
516 // being called from rustpkg, for example). If the arguments change, then
517 // that's just kinda unfortunate.
518 static bool Initialized = false;
522 cl::ParseCommandLineOptions(Argc, Argv);
525 enum class LLVMRustFileType {
531 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
533 case LLVMRustFileType::AssemblyFile:
534 return TargetMachine::CGFT_AssemblyFile;
535 case LLVMRustFileType::ObjectFile:
536 return TargetMachine::CGFT_ObjectFile;
538 report_fatal_error("Bad FileType.");
542 extern "C" LLVMRustResult
543 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
544 LLVMModuleRef M, const char *Path,
545 LLVMRustFileType RustFileType) {
546 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
547 auto FileType = fromRust(RustFileType);
549 std::string ErrorInfo;
551 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
553 ErrorInfo = EC.message();
554 if (ErrorInfo != "") {
555 LLVMRustSetLastError(ErrorInfo.c_str());
556 return LLVMRustResult::Failure;
559 #if LLVM_VERSION_GE(7, 0)
560 buffer_ostream BOS(OS);
561 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
563 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
567 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
568 // stream (OS), so the only real safe place to delete this is here? Don't we
569 // wish this was written in Rust?
571 return LLVMRustResult::Success;
575 // Callback to demangle function name
577 // * name to be demangled
580 // * output buffer len
581 // Returns len of demangled string, or 0 if demangle failed.
582 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
587 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
589 std::vector<char> Buf;
592 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
594 // Return empty string if demangle failed
595 // or if name does not need to be demangled
596 StringRef CallDemangle(StringRef name) {
601 if (Buf.size() < name.size() * 2) {
602 // Semangled name usually shorter than mangled,
603 // but allocate twice as much memory just in case
604 Buf.resize(name.size() * 2);
607 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
613 auto Demangled = StringRef(Buf.data(), R);
614 if (Demangled == name) {
615 // Do not print anything if demangled name is equal to mangled.
622 void emitFunctionAnnot(const Function *F,
623 formatted_raw_ostream &OS) override {
624 StringRef Demangled = CallDemangle(F->getName());
625 if (Demangled.empty()) {
629 OS << "; " << Demangled << "\n";
632 void emitInstructionAnnot(const Instruction *I,
633 formatted_raw_ostream &OS) override {
636 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
638 Value = CI->getCalledValue();
639 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
641 Value = II->getCalledValue();
643 // Could demangle more operations, e. g.
644 // `store %place, @function`.
648 if (!Value->hasName()) {
652 StringRef Demangled = CallDemangle(Value->getName());
653 if (Demangled.empty()) {
657 OS << "; " << Name << " " << Demangled << "\n";
661 class RustPrintModulePass : public ModulePass {
666 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
667 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
668 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
670 bool runOnModule(Module &M) override {
671 RustAssemblyAnnotationWriter AW(Demangle);
673 M.print(*OS, &AW, false);
678 void getAnalysisUsage(AnalysisUsage &AU) const override {
679 AU.setPreservesAll();
682 static StringRef name() { return "RustPrintModulePass"; }
688 void initializeRustPrintModulePassPass(PassRegistry&);
691 char RustPrintModulePass::ID = 0;
692 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
693 "Print rust module to stderr", false, false)
695 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
696 const char *Path, DemangleFn Demangle) {
697 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
698 std::string ErrorInfo;
701 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
703 ErrorInfo = EC.message();
705 formatted_raw_ostream FOS(OS);
707 PM->add(new RustPrintModulePass(FOS, Demangle));
712 extern "C" void LLVMRustPrintPasses() {
713 LLVMInitializePasses();
714 struct MyListener : PassRegistrationListener {
715 void passEnumerate(const PassInfo *Info) {
716 #if LLVM_VERSION_GE(4, 0)
717 StringRef PassArg = Info->getPassArgument();
718 StringRef PassName = Info->getPassName();
719 if (!PassArg.empty()) {
720 // These unsigned->signed casts could theoretically overflow, but
721 // realistically never will (and even if, the result is implementation
722 // defined rather plain UB).
723 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
724 (int)PassName.size(), PassName.data());
727 if (Info->getPassArgument() && *Info->getPassArgument()) {
728 printf("%15s - %s\n", Info->getPassArgument(), Info->getPassName());
734 PassRegistry *PR = PassRegistry::getPassRegistry();
735 PR->enumerateWith(&Listener);
738 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
740 #if LLVM_VERSION_GE(4, 0)
741 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
743 unwrap(PMBR)->Inliner = createAlwaysInlinerPass(AddLifetimes);
747 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
749 llvm::legacy::PassManager passes;
751 auto PreserveFunctions = [=](const GlobalValue &GV) {
752 for (size_t I = 0; I < Len; I++) {
753 if (GV.getName() == Symbols[I]) {
760 passes.add(llvm::createInternalizePass(PreserveFunctions));
762 passes.run(*unwrap(M));
765 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
766 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
768 GV->setDoesNotThrow();
769 Function *F = dyn_cast<Function>(GV);
773 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
774 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
775 if (isa<InvokeInst>(I)) {
776 InvokeInst *CI = cast<InvokeInst>(I);
777 CI->setDoesNotThrow();
785 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
786 LLVMTargetMachineRef TMR) {
787 TargetMachine *Target = unwrap(TMR);
788 unwrap(Module)->setDataLayout(Target->createDataLayout());
791 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
792 unwrap(M)->setPIELevel(PIELevel::Level::Large);
796 LLVMRustThinLTOAvailable() {
797 #if LLVM_VERSION_GE(4, 0)
805 LLVMRustPGOAvailable() {
813 #if LLVM_VERSION_GE(4, 0)
815 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
816 // right now. This ThinLTO support is only enabled on "recent ish" versions of
817 // LLVM, and otherwise it's just blanket rejected from other compilers.
819 // Most of this implementation is straight copied from LLVM. At the time of
820 // this writing it wasn't *quite* suitable to reuse more code from upstream
821 // for our purposes, but we should strive to upstream this support once it's
822 // ready to go! I figure we may want a bit of testing locally first before
823 // sending this upstream to LLVM. I hear though they're quite eager to receive
824 // feedback like this!
826 // If you're reading this code and wondering "what in the world" or you're
827 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
828 // then fear not! (ok maybe fear a little). All code here is mostly based
829 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
831 // You'll find that the general layout here roughly corresponds to the `run`
832 // method in that file as well as `ProcessThinLTOModule`. Functions are
833 // specifically commented below as well, but if you're updating this code
834 // or otherwise trying to understand it, the LLVM source will be useful in
835 // interpreting the mysteries within.
837 // Otherwise I'll apologize in advance, it probably requires a relatively
838 // significant investment on your part to "truly understand" what's going on
839 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
840 // and various online resources about ThinLTO to make heads or tails of all
843 // This is a shared data structure which *must* be threadsafe to share
844 // read-only amongst threads. This also corresponds basically to the arguments
845 // of the `ProcessThinLTOModule` function in the LLVM source.
846 struct LLVMRustThinLTOData {
847 // The combined index that is the global analysis over all modules we're
848 // performing ThinLTO for. This is mostly managed by LLVM.
849 ModuleSummaryIndex Index;
851 // All modules we may look at, stored as in-memory serialized versions. This
852 // is later used when inlining to ensure we can extract any module to inline
854 StringMap<MemoryBufferRef> ModuleMap;
856 // A set that we manage of everything we *don't* want internalized. Note that
857 // this includes all transitive references right now as well, but it may not
859 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
861 // Not 100% sure what these are, but they impact what's internalized and
862 // what's inlined across modules, I believe.
863 StringMap<FunctionImporter::ImportMapTy> ImportLists;
864 StringMap<FunctionImporter::ExportSetTy> ExportLists;
865 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
867 #if LLVM_VERSION_GE(7, 0)
868 LLVMRustThinLTOData() : Index(/* isPerformingAnalysis = */ false) {}
872 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
873 struct LLVMRustThinLTOModule {
874 const char *identifier;
879 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
881 static const GlobalValueSummary *
882 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
883 auto StrongDefForLinker = llvm::find_if(
884 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
885 auto Linkage = Summary->linkage();
886 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
887 !GlobalValue::isWeakForLinker(Linkage);
889 if (StrongDefForLinker != GVSummaryList.end())
890 return StrongDefForLinker->get();
892 auto FirstDefForLinker = llvm::find_if(
893 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
894 auto Linkage = Summary->linkage();
895 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
897 if (FirstDefForLinker == GVSummaryList.end())
899 return FirstDefForLinker->get();
902 // The main entry point for creating the global ThinLTO analysis. The structure
903 // here is basically the same as before threads are spawned in the `run`
904 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
905 extern "C" LLVMRustThinLTOData*
906 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
908 const char **preserved_symbols,
910 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
912 // Load each module's summary and merge it into one combined index
913 for (int i = 0; i < num_modules; i++) {
914 auto module = &modules[i];
915 StringRef buffer(module->data, module->len);
916 MemoryBufferRef mem_buffer(buffer, module->identifier);
918 Ret->ModuleMap[module->identifier] = mem_buffer;
920 #if LLVM_VERSION_GE(5, 0)
921 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
922 LLVMRustSetLastError(toString(std::move(Err)).c_str());
926 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
927 object::ModuleSummaryIndexObjectFile::create(mem_buffer);
929 LLVMRustSetLastError(toString(ObjOrErr.takeError()).c_str());
932 auto Index = (*ObjOrErr)->takeIndex();
933 Ret->Index.mergeFrom(std::move(Index), i);
937 // Collect for each module the list of function it defines (GUID -> Summary)
938 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
940 // Convert the preserved symbols set from string to GUID, this is then needed
941 // for internalization.
942 for (int i = 0; i < num_symbols; i++) {
943 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
944 Ret->GUIDPreservedSymbols.insert(GUID);
947 // Collect the import/export lists for all modules from the call-graph in the
950 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
951 #if LLVM_VERSION_GE(5, 0)
952 #if LLVM_VERSION_GE(7, 0)
953 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
954 return PrevailingType::Unknown;
956 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
958 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
960 ComputeCrossModuleImport(
962 Ret->ModuleToDefinedGVSummaries,
967 auto DeadSymbols = computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
968 ComputeCrossModuleImport(
970 Ret->ModuleToDefinedGVSummaries,
977 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
978 // impacts the caching.
980 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
981 // being lifted from `lib/LTO/LTO.cpp` as well
982 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
983 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
984 for (auto &I : Ret->Index) {
985 #if LLVM_VERSION_GE(5, 0)
986 if (I.second.SummaryList.size() > 1)
987 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
989 if (I.second.size() > 1)
990 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
993 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
994 const auto &Prevailing = PrevailingCopy.find(GUID);
995 if (Prevailing == PrevailingCopy.end())
997 return Prevailing->second == S;
999 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1000 GlobalValue::GUID GUID,
1001 GlobalValue::LinkageTypes NewLinkage) {
1002 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1004 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
1006 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
1007 // callback below. This callback below will dictate the linkage for all
1008 // summaries in the index, and we basically just only want to ensure that dead
1009 // symbols are internalized. Otherwise everything that's already external
1010 // linkage will stay as external, and internal will stay as internal.
1011 std::set<GlobalValue::GUID> ExportedGUIDs;
1012 for (auto &List : Ret->Index) {
1013 #if LLVM_VERSION_GE(5, 0)
1014 for (auto &GVS: List.second.SummaryList) {
1016 for (auto &GVS: List.second) {
1018 if (GlobalValue::isLocalLinkage(GVS->linkage()))
1020 auto GUID = GVS->getOriginalName();
1021 #if LLVM_VERSION_GE(5, 0)
1022 if (GVS->flags().Live)
1024 if (!DeadSymbols.count(GUID))
1026 ExportedGUIDs.insert(GUID);
1029 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1030 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
1031 return (ExportList != Ret->ExportLists.end() &&
1032 ExportList->second.count(GUID)) ||
1033 ExportedGUIDs.count(GUID);
1035 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
1037 return Ret.release();
1041 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1045 // Below are the various passes that happen *per module* when doing ThinLTO.
1047 // In other words, these are the functions that are all run concurrently
1048 // with one another, one per module. The passes here correspond to the analysis
1049 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
1050 // `ProcessThinLTOModule` function. Here they're split up into separate steps
1051 // so rustc can save off the intermediate bytecode between each step.
1054 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1055 Module &Mod = *unwrap(M);
1056 if (renameModuleForThinLTO(Mod, Data->Index)) {
1057 LLVMRustSetLastError("renameModuleForThinLTO failed");
1064 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1065 Module &Mod = *unwrap(M);
1066 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1067 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1072 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1073 Module &Mod = *unwrap(M);
1074 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1075 thinLTOInternalizeModule(Mod, DefinedGlobals);
1080 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1081 Module &Mod = *unwrap(M);
1083 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1084 auto Loader = [&](StringRef Identifier) {
1085 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1086 auto &Context = Mod.getContext();
1087 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1092 // The rest of this closure is a workaround for
1093 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1094 // we accidentally import wasm custom sections into different modules,
1095 // duplicating them by in the final output artifact.
1097 // The issue is worked around here by manually removing the
1098 // `wasm.custom_sections` named metadata node from any imported module. This
1099 // we know isn't used by any optimization pass so there's no need for it to
1102 // Note that the metadata is currently lazily loaded, so we materialize it
1103 // here before looking up if there's metadata inside. The `FunctionImporter`
1104 // will immediately materialize metadata anyway after an import, so this
1105 // shouldn't be a perf hit.
1106 if (Error Err = (*MOrErr)->materializeMetadata()) {
1107 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1111 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1112 if (WasmCustomSections)
1113 WasmCustomSections->eraseFromParent();
1117 FunctionImporter Importer(Data->Index, Loader);
1118 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1120 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1126 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1127 const char*, // importing module name
1128 const char*); // imported module name
1130 // Calls `module_name_callback` for each module import done by ThinLTO.
1131 // The callback is provided with regular null-terminated C strings.
1133 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1134 LLVMRustModuleNameCallback module_name_callback,
1135 void* callback_payload) {
1136 for (const auto& importing_module : data->ImportLists) {
1137 const std::string importing_module_id = importing_module.getKey().str();
1138 const auto& imports = importing_module.getValue();
1139 for (const auto& imported_module : imports) {
1140 const std::string imported_module_id = imported_module.getKey().str();
1141 module_name_callback(callback_payload,
1142 importing_module_id.c_str(),
1143 imported_module_id.c_str());
1148 // This struct and various functions are sort of a hack right now, but the
1149 // problem is that we've got in-memory LLVM modules after we generate and
1150 // optimize all codegen-units for one compilation in rustc. To be compatible
1151 // with the LTO support above we need to serialize the modules plus their
1152 // ThinLTO summary into memory.
1154 // This structure is basically an owned version of a serialize module, with
1155 // a ThinLTO summary attached.
1156 struct LLVMRustThinLTOBuffer {
1160 extern "C" LLVMRustThinLTOBuffer*
1161 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1162 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1164 raw_string_ostream OS(Ret->data);
1166 legacy::PassManager PM;
1167 PM.add(createWriteThinLTOBitcodePass(OS));
1171 return Ret.release();
1175 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1179 extern "C" const void*
1180 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1181 return Buffer->data.data();
1185 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1186 return Buffer->data.length();
1189 // This is what we used to parse upstream bitcode for actual ThinLTO
1190 // processing. We'll call this once per module optimized through ThinLTO, and
1191 // it'll be called concurrently on many threads.
1192 extern "C" LLVMModuleRef
1193 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1196 const char *identifier) {
1197 StringRef Data(data, len);
1198 MemoryBufferRef Buffer(Data, identifier);
1199 unwrap(Context)->enableDebugTypeODRUniquing();
1200 Expected<std::unique_ptr<Module>> SrcOrError =
1201 parseBitcodeFile(Buffer, *unwrap(Context));
1203 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1206 return wrap(std::move(*SrcOrError).release());
1209 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1210 // the comment in `back/lto.rs` for why this exists.
1212 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1214 DICompileUnit **B) {
1215 Module *M = unwrap(Mod);
1216 DICompileUnit **Cur = A;
1217 DICompileUnit **Next = B;
1218 for (DICompileUnit *CU : M->debug_compile_units()) {
1227 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1228 // the comment in `back/lto.rs` for why this exists.
1230 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1231 Module *M = unwrap(Mod);
1233 // If the original source module didn't have a `DICompileUnit` then try to
1234 // merge all the existing compile units. If there aren't actually any though
1235 // then there's not much for us to do so return.
1236 if (Unit == nullptr) {
1237 for (DICompileUnit *CU : M->debug_compile_units()) {
1241 if (Unit == nullptr)
1245 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1246 // process it recursively. Note that we specifically iterate over instructions
1247 // to ensure we feed everything into it.
1248 DebugInfoFinder Finder;
1249 Finder.processModule(*M);
1250 for (Function &F : M->functions()) {
1251 for (auto &FI : F) {
1252 for (Instruction &BI : FI) {
1253 if (auto Loc = BI.getDebugLoc())
1254 Finder.processLocation(*M, Loc);
1255 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1256 Finder.processValue(*M, DVI);
1257 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1258 Finder.processDeclare(*M, DDI);
1263 // After we've found all our debuginfo, rewrite all subprograms to point to
1264 // the same `DICompileUnit`.
1265 for (auto &F : Finder.subprograms()) {
1266 F->replaceUnit(Unit);
1269 // Erase any other references to other `DICompileUnit` instances, the verifier
1270 // will later ensure that we don't actually have any other stale references to
1272 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1273 MD->clearOperands();
1274 MD->addOperand(Unit);
1279 struct LLVMRustThinLTOData {
1282 struct LLVMRustThinLTOModule {
1285 extern "C" LLVMRustThinLTOData*
1286 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
1288 const char **preserved_symbols,
1290 report_fatal_error("ThinLTO not available");
1294 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1295 report_fatal_error("ThinLTO not available");
1299 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1300 report_fatal_error("ThinLTO not available");
1304 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1305 report_fatal_error("ThinLTO not available");
1309 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1310 report_fatal_error("ThinLTO not available");
1313 extern "C" LLVMRustThinLTOModuleImports
1314 LLVMRustGetLLVMRustThinLTOModuleImports(const LLVMRustThinLTOData *Data) {
1315 report_fatal_error("ThinLTO not available");
1319 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1320 report_fatal_error("ThinLTO not available");
1323 struct LLVMRustThinLTOBuffer {
1326 extern "C" LLVMRustThinLTOBuffer*
1327 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1328 report_fatal_error("ThinLTO not available");
1332 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1333 report_fatal_error("ThinLTO not available");
1336 extern "C" const void*
1337 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1338 report_fatal_error("ThinLTO not available");
1342 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1343 report_fatal_error("ThinLTO not available");
1346 extern "C" LLVMModuleRef
1347 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1350 const char *identifier) {
1351 report_fatal_error("ThinLTO not available");
1355 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1357 DICompileUnit **B) {
1358 report_fatal_error("ThinLTO not available");
1362 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod) {
1363 report_fatal_error("ThinLTO not available");
1366 #endif // LLVM_VERSION_GE(4, 0)