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_SPARC
175 #define SUBTARGET_SPARC SUBTARGET(Sparc)
177 #define SUBTARGET_SPARC
180 #ifdef LLVM_COMPONENT_HEXAGON
181 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
183 #define SUBTARGET_HEXAGON
186 #define GEN_SUBTARGETS \
197 #define SUBTARGET(x) \
199 extern const SubtargetFeatureKV x##FeatureKV[]; \
200 extern const SubtargetFeatureKV x##SubTypeKV[]; \
206 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
207 const char *Feature) {
209 TargetMachine *Target = unwrap(TM);
210 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
211 const FeatureBitset &Bits = MCInfo->getFeatureBits();
212 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
214 for (auto &FeatureEntry : FeatTable)
215 if (!strcmp(FeatureEntry.Key, Feature))
216 return (Bits & FeatureEntry.Value) == FeatureEntry.Value;
221 enum class LLVMRustCodeModel {
230 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
232 case LLVMRustCodeModel::Small:
233 return CodeModel::Small;
234 case LLVMRustCodeModel::Kernel:
235 return CodeModel::Kernel;
236 case LLVMRustCodeModel::Medium:
237 return CodeModel::Medium;
238 case LLVMRustCodeModel::Large:
239 return CodeModel::Large;
241 report_fatal_error("Bad CodeModel.");
245 enum class LLVMRustCodeGenOptLevel {
253 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
255 case LLVMRustCodeGenOptLevel::None:
256 return CodeGenOpt::None;
257 case LLVMRustCodeGenOptLevel::Less:
258 return CodeGenOpt::Less;
259 case LLVMRustCodeGenOptLevel::Default:
260 return CodeGenOpt::Default;
261 case LLVMRustCodeGenOptLevel::Aggressive:
262 return CodeGenOpt::Aggressive;
264 report_fatal_error("Bad CodeGenOptLevel.");
268 enum class LLVMRustRelocMode {
278 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
280 case LLVMRustRelocMode::Default:
282 case LLVMRustRelocMode::Static:
283 return Reloc::Static;
284 case LLVMRustRelocMode::PIC:
286 case LLVMRustRelocMode::DynamicNoPic:
287 return Reloc::DynamicNoPIC;
288 #if LLVM_VERSION_GE(4, 0)
289 case LLVMRustRelocMode::ROPI:
291 case LLVMRustRelocMode::RWPI:
293 case LLVMRustRelocMode::ROPIRWPI:
294 return Reloc::ROPI_RWPI;
300 report_fatal_error("Bad RelocModel.");
304 /// getLongestEntryLength - Return the length of the longest entry in the table.
306 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
308 for (auto &I : Table)
309 MaxLen = std::max(MaxLen, std::strlen(I.Key));
313 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
314 const TargetMachine *Target = unwrap(TM);
315 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
316 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
317 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
318 const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
319 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
321 printf("Available CPUs for this target:\n");
322 if (HostArch == TargetArch) {
323 const StringRef HostCPU = sys::getHostCPUName();
324 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
325 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
327 for (auto &CPU : CPUTable)
328 printf(" %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
332 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
333 const TargetMachine *Target = unwrap(TM);
334 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
335 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
336 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
338 printf("Available features for this target:\n");
339 for (auto &Feature : FeatTable)
340 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
343 printf("Use +feature to enable a feature, or -feature to disable it.\n"
344 "For example, rustc -C -target-cpu=mycpu -C "
345 "target-feature=+feature1,-feature2\n\n");
350 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
351 printf("Target CPU help is not supported by this LLVM version.\n\n");
354 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
355 printf("Target features help is not supported by this LLVM version.\n\n");
359 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
360 const char *TripleStr, const char *CPU, const char *Feature,
361 LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
362 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
363 bool PositionIndependentExecutable, bool FunctionSections,
365 bool TrapUnreachable,
368 auto OptLevel = fromRust(RustOptLevel);
369 auto RM = fromRust(RustReloc);
372 Triple Trip(Triple::normalize(TripleStr));
373 const llvm::Target *TheTarget =
374 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
375 if (TheTarget == nullptr) {
376 LLVMRustSetLastError(Error.c_str());
380 StringRef RealCPU = CPU;
381 if (RealCPU == "native") {
382 RealCPU = sys::getHostCPUName();
385 TargetOptions Options;
387 Options.FloatABIType = FloatABI::Default;
389 Options.FloatABIType = FloatABI::Soft;
391 Options.DataSections = DataSections;
392 Options.FunctionSections = FunctionSections;
394 if (TrapUnreachable) {
395 // Tell LLVM to translate `unreachable` into an explicit trap instruction.
396 // This limits the extent of possible undefined behavior in some cases, as
397 // it prevents control flow from "falling through" into whatever code
398 // happens to be laid out next in memory.
399 Options.TrapUnreachable = true;
403 Options.ThreadModel = ThreadModel::Single;
406 #if LLVM_VERSION_GE(6, 0)
407 Optional<CodeModel::Model> CM;
409 CodeModel::Model CM = CodeModel::Model::Default;
411 if (RustCM != LLVMRustCodeModel::None)
412 CM = fromRust(RustCM);
413 TargetMachine *TM = TheTarget->createTargetMachine(
414 Trip.getTriple(), RealCPU, Feature, Options, RM, CM, OptLevel);
418 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
422 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
423 // passes for a target to a pass manager. We export that functionality through
425 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
426 LLVMPassManagerRef PMR,
428 PassManagerBase *PM = unwrap(PMR);
430 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
433 extern "C" void LLVMRustConfigurePassManagerBuilder(
434 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
435 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize,
436 const char* PGOGenPath, const char* PGOUsePath) {
437 // Ignore mergefunc for now as enabling it causes crashes.
438 // unwrap(PMBR)->MergeFunctions = MergeFunctions;
439 unwrap(PMBR)->SLPVectorize = SLPVectorize;
440 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
441 unwrap(PMBR)->LoopVectorize = LoopVectorize;
446 unwrap(PMBR)->EnablePGOInstrGen = true;
447 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
451 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
454 assert(!PGOGenPath && !PGOUsePath && "Should've caught earlier");
458 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
459 // field of a PassManagerBuilder, we expose our own method of doing so.
460 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
462 bool DisableSimplifyLibCalls) {
463 Triple TargetTriple(unwrap(M)->getTargetTriple());
464 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
465 if (DisableSimplifyLibCalls)
466 TLI->disableAllFunctions();
467 unwrap(PMBR)->LibraryInfo = TLI;
470 // Unfortunately, the LLVM C API doesn't provide a way to create the
471 // TargetLibraryInfo pass, so we use this method to do so.
472 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
473 bool DisableSimplifyLibCalls) {
474 Triple TargetTriple(unwrap(M)->getTargetTriple());
475 TargetLibraryInfoImpl TLII(TargetTriple);
476 if (DisableSimplifyLibCalls)
477 TLII.disableAllFunctions();
478 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
481 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
482 // all the functions in a module, so we do that manually here. You'll find
483 // similar code in clang's BackendUtil.cpp file.
484 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
486 llvm::legacy::FunctionPassManager *P =
487 unwrap<llvm::legacy::FunctionPassManager>(PMR);
488 P->doInitialization();
490 // Upgrade all calls to old intrinsics first.
491 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
492 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
494 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
496 if (!I->isDeclaration())
502 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
503 // Initializing the command-line options more than once is not allowed. So,
504 // check if they've already been initialized. (This could happen if we're
505 // being called from rustpkg, for example). If the arguments change, then
506 // that's just kinda unfortunate.
507 static bool Initialized = false;
511 cl::ParseCommandLineOptions(Argc, Argv);
514 enum class LLVMRustFileType {
520 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
522 case LLVMRustFileType::AssemblyFile:
523 return TargetMachine::CGFT_AssemblyFile;
524 case LLVMRustFileType::ObjectFile:
525 return TargetMachine::CGFT_ObjectFile;
527 report_fatal_error("Bad FileType.");
531 extern "C" LLVMRustResult
532 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
533 LLVMModuleRef M, const char *Path,
534 LLVMRustFileType RustFileType) {
535 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
536 auto FileType = fromRust(RustFileType);
538 std::string ErrorInfo;
540 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
542 ErrorInfo = EC.message();
543 if (ErrorInfo != "") {
544 LLVMRustSetLastError(ErrorInfo.c_str());
545 return LLVMRustResult::Failure;
548 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
551 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
552 // stream (OS), so the only real safe place to delete this is here? Don't we
553 // wish this was written in Rust?
555 return LLVMRustResult::Success;
559 // Callback to demangle function name
561 // * name to be demangled
564 // * output buffer len
565 // Returns len of demangled string, or 0 if demangle failed.
566 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
571 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
573 std::vector<char> Buf;
576 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
578 // Return empty string if demangle failed
579 // or if name does not need to be demangled
580 StringRef CallDemangle(StringRef name) {
585 if (Buf.size() < name.size() * 2) {
586 // Semangled name usually shorter than mangled,
587 // but allocate twice as much memory just in case
588 Buf.resize(name.size() * 2);
591 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
597 auto Demangled = StringRef(Buf.data(), R);
598 if (Demangled == name) {
599 // Do not print anything if demangled name is equal to mangled.
606 void emitFunctionAnnot(const Function *F,
607 formatted_raw_ostream &OS) override {
608 StringRef Demangled = CallDemangle(F->getName());
609 if (Demangled.empty()) {
613 OS << "; " << Demangled << "\n";
616 void emitInstructionAnnot(const Instruction *I,
617 formatted_raw_ostream &OS) override {
620 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
622 Value = CI->getCalledValue();
623 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
625 Value = II->getCalledValue();
627 // Could demangle more operations, e. g.
628 // `store %place, @function`.
632 if (!Value->hasName()) {
636 StringRef Demangled = CallDemangle(Value->getName());
637 if (Demangled.empty()) {
641 OS << "; " << Name << " " << Demangled << "\n";
645 class RustPrintModulePass : public ModulePass {
650 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
651 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
652 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
654 bool runOnModule(Module &M) override {
655 RustAssemblyAnnotationWriter AW(Demangle);
657 M.print(*OS, &AW, false);
662 void getAnalysisUsage(AnalysisUsage &AU) const override {
663 AU.setPreservesAll();
666 static StringRef name() { return "RustPrintModulePass"; }
672 void initializeRustPrintModulePassPass(PassRegistry&);
675 char RustPrintModulePass::ID = 0;
676 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
677 "Print rust module to stderr", false, false)
679 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
680 const char *Path, DemangleFn Demangle) {
681 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
682 std::string ErrorInfo;
685 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
687 ErrorInfo = EC.message();
689 formatted_raw_ostream FOS(OS);
691 PM->add(new RustPrintModulePass(FOS, Demangle));
696 extern "C" void LLVMRustPrintPasses() {
697 LLVMInitializePasses();
698 struct MyListener : PassRegistrationListener {
699 void passEnumerate(const PassInfo *Info) {
700 #if LLVM_VERSION_GE(4, 0)
701 StringRef PassArg = Info->getPassArgument();
702 StringRef PassName = Info->getPassName();
703 if (!PassArg.empty()) {
704 // These unsigned->signed casts could theoretically overflow, but
705 // realistically never will (and even if, the result is implementation
706 // defined rather plain UB).
707 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
708 (int)PassName.size(), PassName.data());
711 if (Info->getPassArgument() && *Info->getPassArgument()) {
712 printf("%15s - %s\n", Info->getPassArgument(), Info->getPassName());
718 PassRegistry *PR = PassRegistry::getPassRegistry();
719 PR->enumerateWith(&Listener);
722 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
724 #if LLVM_VERSION_GE(4, 0)
725 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
727 unwrap(PMBR)->Inliner = createAlwaysInlinerPass(AddLifetimes);
731 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
733 llvm::legacy::PassManager passes;
735 auto PreserveFunctions = [=](const GlobalValue &GV) {
736 for (size_t I = 0; I < Len; I++) {
737 if (GV.getName() == Symbols[I]) {
744 passes.add(llvm::createInternalizePass(PreserveFunctions));
746 passes.run(*unwrap(M));
749 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
750 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
752 GV->setDoesNotThrow();
753 Function *F = dyn_cast<Function>(GV);
757 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
758 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
759 if (isa<InvokeInst>(I)) {
760 InvokeInst *CI = cast<InvokeInst>(I);
761 CI->setDoesNotThrow();
769 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
770 LLVMTargetMachineRef TMR) {
771 TargetMachine *Target = unwrap(TMR);
772 unwrap(Module)->setDataLayout(Target->createDataLayout());
775 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
776 unwrap(M)->setPIELevel(PIELevel::Level::Large);
780 LLVMRustThinLTOAvailable() {
781 #if LLVM_VERSION_GE(4, 0)
789 LLVMRustPGOAvailable() {
797 #if LLVM_VERSION_GE(4, 0)
799 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
800 // right now. This ThinLTO support is only enabled on "recent ish" versions of
801 // LLVM, and otherwise it's just blanket rejected from other compilers.
803 // Most of this implementation is straight copied from LLVM. At the time of
804 // this writing it wasn't *quite* suitable to reuse more code from upstream
805 // for our purposes, but we should strive to upstream this support once it's
806 // ready to go! I figure we may want a bit of testing locally first before
807 // sending this upstream to LLVM. I hear though they're quite eager to receive
808 // feedback like this!
810 // If you're reading this code and wondering "what in the world" or you're
811 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
812 // then fear not! (ok maybe fear a little). All code here is mostly based
813 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
815 // You'll find that the general layout here roughly corresponds to the `run`
816 // method in that file as well as `ProcessThinLTOModule`. Functions are
817 // specifically commented below as well, but if you're updating this code
818 // or otherwise trying to understand it, the LLVM source will be useful in
819 // interpreting the mysteries within.
821 // Otherwise I'll apologize in advance, it probably requires a relatively
822 // significant investment on your part to "truly understand" what's going on
823 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
824 // and various online resources about ThinLTO to make heads or tails of all
828 LLVMRustWriteThinBitcodeToFile(LLVMPassManagerRef PMR,
830 const char *BcFile) {
831 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
833 llvm::raw_fd_ostream bc(BcFile, EC, llvm::sys::fs::F_None);
835 LLVMRustSetLastError(EC.message().c_str());
838 PM->add(createWriteThinLTOBitcodePass(bc));
844 // This is a shared data structure which *must* be threadsafe to share
845 // read-only amongst threads. This also corresponds basically to the arguments
846 // of the `ProcessThinLTOModule` function in the LLVM source.
847 struct LLVMRustThinLTOData {
848 // The combined index that is the global analysis over all modules we're
849 // performing ThinLTO for. This is mostly managed by LLVM.
850 ModuleSummaryIndex Index;
852 // All modules we may look at, stored as in-memory serialized versions. This
853 // is later used when inlining to ensure we can extract any module to inline
855 StringMap<MemoryBufferRef> ModuleMap;
857 // A set that we manage of everything we *don't* want internalized. Note that
858 // this includes all transitive references right now as well, but it may not
860 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
862 // Not 100% sure what these are, but they impact what's internalized and
863 // what's inlined across modules, I believe.
864 StringMap<FunctionImporter::ImportMapTy> ImportLists;
865 StringMap<FunctionImporter::ExportSetTy> ExportLists;
866 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
868 #if LLVM_VERSION_GE(7, 0)
869 LLVMRustThinLTOData() : Index(/* isPerformingAnalysis = */ false) {}
873 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
874 struct LLVMRustThinLTOModule {
875 const char *identifier;
880 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
882 static const GlobalValueSummary *
883 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
884 auto StrongDefForLinker = llvm::find_if(
885 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
886 auto Linkage = Summary->linkage();
887 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
888 !GlobalValue::isWeakForLinker(Linkage);
890 if (StrongDefForLinker != GVSummaryList.end())
891 return StrongDefForLinker->get();
893 auto FirstDefForLinker = llvm::find_if(
894 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
895 auto Linkage = Summary->linkage();
896 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
898 if (FirstDefForLinker == GVSummaryList.end())
900 return FirstDefForLinker->get();
903 // The main entry point for creating the global ThinLTO analysis. The structure
904 // here is basically the same as before threads are spawned in the `run`
905 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
906 extern "C" LLVMRustThinLTOData*
907 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
909 const char **preserved_symbols,
911 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
913 // Load each module's summary and merge it into one combined index
914 for (int i = 0; i < num_modules; i++) {
915 auto module = &modules[i];
916 StringRef buffer(module->data, module->len);
917 MemoryBufferRef mem_buffer(buffer, module->identifier);
919 Ret->ModuleMap[module->identifier] = mem_buffer;
921 #if LLVM_VERSION_GE(5, 0)
922 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
923 LLVMRustSetLastError(toString(std::move(Err)).c_str());
927 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
928 object::ModuleSummaryIndexObjectFile::create(mem_buffer);
930 LLVMRustSetLastError(toString(ObjOrErr.takeError()).c_str());
933 auto Index = (*ObjOrErr)->takeIndex();
934 Ret->Index.mergeFrom(std::move(Index), i);
938 // Collect for each module the list of function it defines (GUID -> Summary)
939 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
941 // Convert the preserved symbols set from string to GUID, this is then needed
942 // for internalization.
943 for (int i = 0; i < num_symbols; i++) {
944 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
945 Ret->GUIDPreservedSymbols.insert(GUID);
948 // Collect the import/export lists for all modules from the call-graph in the
951 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
952 #if LLVM_VERSION_GE(5, 0)
953 #if LLVM_VERSION_GE(7, 0)
954 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
955 return PrevailingType::Unknown;
957 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
959 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
961 ComputeCrossModuleImport(
963 Ret->ModuleToDefinedGVSummaries,
968 auto DeadSymbols = computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
969 ComputeCrossModuleImport(
971 Ret->ModuleToDefinedGVSummaries,
978 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
979 // impacts the caching.
981 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
982 // being lifted from `lib/LTO/LTO.cpp` as well
983 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
984 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
985 for (auto &I : Ret->Index) {
986 #if LLVM_VERSION_GE(5, 0)
987 if (I.second.SummaryList.size() > 1)
988 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
990 if (I.second.size() > 1)
991 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
994 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
995 const auto &Prevailing = PrevailingCopy.find(GUID);
996 if (Prevailing == PrevailingCopy.end())
998 return Prevailing->second == S;
1000 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1001 GlobalValue::GUID GUID,
1002 GlobalValue::LinkageTypes NewLinkage) {
1003 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1005 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
1007 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
1008 // callback below. This callback below will dictate the linkage for all
1009 // summaries in the index, and we basically just only want to ensure that dead
1010 // symbols are internalized. Otherwise everything that's already external
1011 // linkage will stay as external, and internal will stay as internal.
1012 std::set<GlobalValue::GUID> ExportedGUIDs;
1013 for (auto &List : Ret->Index) {
1014 #if LLVM_VERSION_GE(5, 0)
1015 for (auto &GVS: List.second.SummaryList) {
1017 for (auto &GVS: List.second) {
1019 if (GlobalValue::isLocalLinkage(GVS->linkage()))
1021 auto GUID = GVS->getOriginalName();
1022 #if LLVM_VERSION_GE(5, 0)
1023 if (GVS->flags().Live)
1025 if (!DeadSymbols.count(GUID))
1027 ExportedGUIDs.insert(GUID);
1030 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1031 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
1032 return (ExportList != Ret->ExportLists.end() &&
1033 ExportList->second.count(GUID)) ||
1034 ExportedGUIDs.count(GUID);
1036 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
1038 return Ret.release();
1042 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1046 // Below are the various passes that happen *per module* when doing ThinLTO.
1048 // In other words, these are the functions that are all run concurrently
1049 // with one another, one per module. The passes here correspond to the analysis
1050 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
1051 // `ProcessThinLTOModule` function. Here they're split up into separate steps
1052 // so rustc can save off the intermediate bytecode between each step.
1055 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1056 Module &Mod = *unwrap(M);
1057 if (renameModuleForThinLTO(Mod, Data->Index)) {
1058 LLVMRustSetLastError("renameModuleForThinLTO failed");
1065 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1066 Module &Mod = *unwrap(M);
1067 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1068 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1073 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1074 Module &Mod = *unwrap(M);
1075 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1076 thinLTOInternalizeModule(Mod, DefinedGlobals);
1081 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1082 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 return getLazyBitcodeModule(Memory, Context, true, true);
1089 FunctionImporter Importer(Data->Index, Loader);
1090 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1092 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1098 // This struct and various functions are sort of a hack right now, but the
1099 // problem is that we've got in-memory LLVM modules after we generate and
1100 // optimize all codegen-units for one compilation in rustc. To be compatible
1101 // with the LTO support above we need to serialize the modules plus their
1102 // ThinLTO summary into memory.
1104 // This structure is basically an owned version of a serialize module, with
1105 // a ThinLTO summary attached.
1106 struct LLVMRustThinLTOBuffer {
1110 extern "C" LLVMRustThinLTOBuffer*
1111 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1112 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1114 raw_string_ostream OS(Ret->data);
1116 legacy::PassManager PM;
1117 PM.add(createWriteThinLTOBitcodePass(OS));
1121 return Ret.release();
1125 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1129 extern "C" const void*
1130 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1131 return Buffer->data.data();
1135 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1136 return Buffer->data.length();
1139 // This is what we used to parse upstream bitcode for actual ThinLTO
1140 // processing. We'll call this once per module optimized through ThinLTO, and
1141 // it'll be called concurrently on many threads.
1142 extern "C" LLVMModuleRef
1143 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1146 const char *identifier) {
1147 StringRef Data(data, len);
1148 MemoryBufferRef Buffer(Data, identifier);
1149 unwrap(Context)->enableDebugTypeODRUniquing();
1150 Expected<std::unique_ptr<Module>> SrcOrError =
1151 parseBitcodeFile(Buffer, *unwrap(Context));
1153 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1156 return wrap(std::move(*SrcOrError).release());
1159 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1160 // the comment in `back/lto.rs` for why this exists.
1162 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1164 DICompileUnit **B) {
1165 Module *M = unwrap(Mod);
1166 DICompileUnit **Cur = A;
1167 DICompileUnit **Next = B;
1168 for (DICompileUnit *CU : M->debug_compile_units()) {
1177 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1178 // the comment in `back/lto.rs` for why this exists.
1180 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1181 Module *M = unwrap(Mod);
1183 // If the original source module didn't have a `DICompileUnit` then try to
1184 // merge all the existing compile units. If there aren't actually any though
1185 // then there's not much for us to do so return.
1186 if (Unit == nullptr) {
1187 for (DICompileUnit *CU : M->debug_compile_units()) {
1191 if (Unit == nullptr)
1195 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1196 // process it recursively. Note that we specifically iterate over instructions
1197 // to ensure we feed everything into it.
1198 DebugInfoFinder Finder;
1199 Finder.processModule(*M);
1200 for (Function &F : M->functions()) {
1201 for (auto &FI : F) {
1202 for (Instruction &BI : FI) {
1203 if (auto Loc = BI.getDebugLoc())
1204 Finder.processLocation(*M, Loc);
1205 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1206 Finder.processValue(*M, DVI);
1207 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1208 Finder.processDeclare(*M, DDI);
1213 // After we've found all our debuginfo, rewrite all subprograms to point to
1214 // the same `DICompileUnit`.
1215 for (auto &F : Finder.subprograms()) {
1216 F->replaceUnit(Unit);
1219 // Erase any other references to other `DICompileUnit` instances, the verifier
1220 // will later ensure that we don't actually have any other stale references to
1222 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1223 MD->clearOperands();
1224 MD->addOperand(Unit);
1228 LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) {
1229 Module *M = unwrap(Mod);
1230 for (Function &F : M->functions()) {
1231 if (F.hasAvailableExternallyLinkage())
1239 LLVMRustWriteThinBitcodeToFile(LLVMPassManagerRef PMR,
1241 const char *BcFile) {
1242 report_fatal_error("ThinLTO not available");
1245 struct LLVMRustThinLTOData {
1248 struct LLVMRustThinLTOModule {
1251 extern "C" LLVMRustThinLTOData*
1252 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
1254 const char **preserved_symbols,
1256 report_fatal_error("ThinLTO not available");
1260 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1261 report_fatal_error("ThinLTO not available");
1265 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1266 report_fatal_error("ThinLTO not available");
1270 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1271 report_fatal_error("ThinLTO not available");
1275 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1276 report_fatal_error("ThinLTO not available");
1280 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1281 report_fatal_error("ThinLTO not available");
1284 struct LLVMRustThinLTOBuffer {
1287 extern "C" LLVMRustThinLTOBuffer*
1288 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1289 report_fatal_error("ThinLTO not available");
1293 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1294 report_fatal_error("ThinLTO not available");
1297 extern "C" const void*
1298 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1299 report_fatal_error("ThinLTO not available");
1303 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1304 report_fatal_error("ThinLTO not available");
1307 extern "C" LLVMModuleRef
1308 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1311 const char *identifier) {
1312 report_fatal_error("ThinLTO not available");
1316 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1318 DICompileUnit **B) {
1319 report_fatal_error("ThinLTO not available");
1323 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod) {
1324 report_fatal_error("ThinLTO not available");
1328 LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) {
1329 report_fatal_error("ThinLTO not available");
1332 #endif // LLVM_VERSION_GE(4, 0)