]> git.lizzy.rs Git - rust.git/blob - src/rustllvm/PassWrapper.cpp
Auto merge of #56863 - arielb1:supertrait-self-4, r=nikomatsakis
[rust.git] / src / rustllvm / PassWrapper.cpp
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.
4 //
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.
10
11 #include <stdio.h>
12
13 #include <vector>
14 #include <set>
15
16 #include "rustllvm.h"
17
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/Support/CBindingWrapping.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
29 #include "llvm/Transforms/IPO/AlwaysInliner.h"
30 #include "llvm/Transforms/IPO/FunctionImport.h"
31 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
32 #include "llvm/LTO/LTO.h"
33
34 #include "llvm-c/Transforms/PassManagerBuilder.h"
35
36 using namespace llvm;
37 using namespace llvm::legacy;
38
39 extern cl::opt<bool> EnableARMEHABI;
40
41 typedef struct LLVMOpaquePass *LLVMPassRef;
42 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
43
44 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
45 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
46 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
47                                    LLVMPassManagerBuilderRef)
48
49 extern "C" void LLVMInitializePasses() {
50   PassRegistry &Registry = *PassRegistry::getPassRegistry();
51   initializeCore(Registry);
52   initializeCodeGen(Registry);
53   initializeScalarOpts(Registry);
54   initializeVectorization(Registry);
55   initializeIPO(Registry);
56   initializeAnalysis(Registry);
57   initializeTransformUtils(Registry);
58   initializeInstCombine(Registry);
59   initializeInstrumentation(Registry);
60   initializeTarget(Registry);
61 }
62
63 enum class LLVMRustPassKind {
64   Other,
65   Function,
66   Module,
67 };
68
69 static LLVMRustPassKind toRust(PassKind Kind) {
70   switch (Kind) {
71   case PT_Function:
72     return LLVMRustPassKind::Function;
73   case PT_Module:
74     return LLVMRustPassKind::Module;
75   default:
76     return LLVMRustPassKind::Other;
77   }
78 }
79
80 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
81   StringRef SR(PassName);
82   PassRegistry *PR = PassRegistry::getPassRegistry();
83
84   const PassInfo *PI = PR->getPassInfo(SR);
85   if (PI) {
86     return wrap(PI->createPass());
87   }
88   return nullptr;
89 }
90
91 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
92   assert(RustPass);
93   Pass *Pass = unwrap(RustPass);
94   return toRust(Pass->getPassKind());
95 }
96
97 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
98   assert(RustPass);
99   Pass *Pass = unwrap(RustPass);
100   PassManagerBase *PMB = unwrap(PMR);
101   PMB->add(Pass);
102 }
103
104 extern "C"
105 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
106   LLVMPassManagerBuilderRef PMBR,
107   LLVMPassManagerRef PMR
108 ) {
109   unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
110 }
111
112 #ifdef LLVM_COMPONENT_X86
113 #define SUBTARGET_X86 SUBTARGET(X86)
114 #else
115 #define SUBTARGET_X86
116 #endif
117
118 #ifdef LLVM_COMPONENT_ARM
119 #define SUBTARGET_ARM SUBTARGET(ARM)
120 #else
121 #define SUBTARGET_ARM
122 #endif
123
124 #ifdef LLVM_COMPONENT_AARCH64
125 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
126 #else
127 #define SUBTARGET_AARCH64
128 #endif
129
130 #ifdef LLVM_COMPONENT_MIPS
131 #define SUBTARGET_MIPS SUBTARGET(Mips)
132 #else
133 #define SUBTARGET_MIPS
134 #endif
135
136 #ifdef LLVM_COMPONENT_POWERPC
137 #define SUBTARGET_PPC SUBTARGET(PPC)
138 #else
139 #define SUBTARGET_PPC
140 #endif
141
142 #ifdef LLVM_COMPONENT_SYSTEMZ
143 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
144 #else
145 #define SUBTARGET_SYSTEMZ
146 #endif
147
148 #ifdef LLVM_COMPONENT_MSP430
149 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
150 #else
151 #define SUBTARGET_MSP430
152 #endif
153
154 #ifdef LLVM_COMPONENT_RISCV
155 #define SUBTARGET_RISCV SUBTARGET(RISCV)
156 #else
157 #define SUBTARGET_RISCV
158 #endif
159
160 #ifdef LLVM_COMPONENT_SPARC
161 #define SUBTARGET_SPARC SUBTARGET(Sparc)
162 #else
163 #define SUBTARGET_SPARC
164 #endif
165
166 #ifdef LLVM_COMPONENT_HEXAGON
167 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
168 #else
169 #define SUBTARGET_HEXAGON
170 #endif
171
172 #define GEN_SUBTARGETS                                                         \
173   SUBTARGET_X86                                                                \
174   SUBTARGET_ARM                                                                \
175   SUBTARGET_AARCH64                                                            \
176   SUBTARGET_MIPS                                                               \
177   SUBTARGET_PPC                                                                \
178   SUBTARGET_SYSTEMZ                                                            \
179   SUBTARGET_MSP430                                                             \
180   SUBTARGET_SPARC                                                              \
181   SUBTARGET_HEXAGON                                                            \
182   SUBTARGET_RISCV                                                              \
183
184 #define SUBTARGET(x)                                                           \
185   namespace llvm {                                                             \
186   extern const SubtargetFeatureKV x##FeatureKV[];                              \
187   extern const SubtargetFeatureKV x##SubTypeKV[];                              \
188   }
189
190 GEN_SUBTARGETS
191 #undef SUBTARGET
192
193 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
194                                    const char *Feature) {
195   TargetMachine *Target = unwrap(TM);
196   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
197   return MCInfo->checkFeatures(std::string("+") + Feature);
198 }
199
200 enum class LLVMRustCodeModel {
201   Other,
202   Small,
203   Kernel,
204   Medium,
205   Large,
206   None,
207 };
208
209 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
210   switch (Model) {
211   case LLVMRustCodeModel::Small:
212     return CodeModel::Small;
213   case LLVMRustCodeModel::Kernel:
214     return CodeModel::Kernel;
215   case LLVMRustCodeModel::Medium:
216     return CodeModel::Medium;
217   case LLVMRustCodeModel::Large:
218     return CodeModel::Large;
219   default:
220     report_fatal_error("Bad CodeModel.");
221   }
222 }
223
224 enum class LLVMRustCodeGenOptLevel {
225   Other,
226   None,
227   Less,
228   Default,
229   Aggressive,
230 };
231
232 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
233   switch (Level) {
234   case LLVMRustCodeGenOptLevel::None:
235     return CodeGenOpt::None;
236   case LLVMRustCodeGenOptLevel::Less:
237     return CodeGenOpt::Less;
238   case LLVMRustCodeGenOptLevel::Default:
239     return CodeGenOpt::Default;
240   case LLVMRustCodeGenOptLevel::Aggressive:
241     return CodeGenOpt::Aggressive;
242   default:
243     report_fatal_error("Bad CodeGenOptLevel.");
244   }
245 }
246
247 enum class LLVMRustRelocMode {
248   Default,
249   Static,
250   PIC,
251   DynamicNoPic,
252   ROPI,
253   RWPI,
254   ROPIRWPI,
255 };
256
257 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
258   switch (RustReloc) {
259   case LLVMRustRelocMode::Default:
260     return None;
261   case LLVMRustRelocMode::Static:
262     return Reloc::Static;
263   case LLVMRustRelocMode::PIC:
264     return Reloc::PIC_;
265   case LLVMRustRelocMode::DynamicNoPic:
266     return Reloc::DynamicNoPIC;
267   case LLVMRustRelocMode::ROPI:
268     return Reloc::ROPI;
269   case LLVMRustRelocMode::RWPI:
270     return Reloc::RWPI;
271   case LLVMRustRelocMode::ROPIRWPI:
272     return Reloc::ROPI_RWPI;
273   }
274   report_fatal_error("Bad RelocModel.");
275 }
276
277 #ifdef LLVM_RUSTLLVM
278 /// getLongestEntryLength - Return the length of the longest entry in the table.
279 ///
280 static size_t getLongestEntryLength(ArrayRef<SubtargetFeatureKV> Table) {
281   size_t MaxLen = 0;
282   for (auto &I : Table)
283     MaxLen = std::max(MaxLen, std::strlen(I.Key));
284   return MaxLen;
285 }
286
287 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
288   const TargetMachine *Target = unwrap(TM);
289   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
290   const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
291   const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
292   const ArrayRef<SubtargetFeatureKV> CPUTable = MCInfo->getCPUTable();
293   unsigned MaxCPULen = getLongestEntryLength(CPUTable);
294
295   printf("Available CPUs for this target:\n");
296   if (HostArch == TargetArch) {
297     const StringRef HostCPU = sys::getHostCPUName();
298     printf("    %-*s - Select the CPU of the current host (currently %.*s).\n",
299       MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
300   }
301   for (auto &CPU : CPUTable)
302     printf("    %-*s - %s.\n", MaxCPULen, CPU.Key, CPU.Desc);
303   printf("\n");
304 }
305
306 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
307   const TargetMachine *Target = unwrap(TM);
308   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
309   const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
310   unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
311
312   printf("Available features for this target:\n");
313   for (auto &Feature : FeatTable)
314     printf("    %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
315   printf("\n");
316
317   printf("Use +feature to enable a feature, or -feature to disable it.\n"
318          "For example, rustc -C -target-cpu=mycpu -C "
319          "target-feature=+feature1,-feature2\n\n");
320 }
321
322 #else
323
324 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
325   printf("Target CPU help is not supported by this LLVM version.\n\n");
326 }
327
328 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
329   printf("Target features help is not supported by this LLVM version.\n\n");
330 }
331 #endif
332
333 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
334   StringRef Name = sys::getHostCPUName();
335   *len = Name.size();
336   return Name.data();
337 }
338
339 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
340     const char *TripleStr, const char *CPU, const char *Feature,
341     LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
342     LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
343     bool PositionIndependentExecutable, bool FunctionSections,
344     bool DataSections,
345     bool TrapUnreachable,
346     bool Singlethread,
347     bool AsmComments,
348     bool EmitStackSizeSection) {
349
350   auto OptLevel = fromRust(RustOptLevel);
351   auto RM = fromRust(RustReloc);
352
353   std::string Error;
354   Triple Trip(Triple::normalize(TripleStr));
355   const llvm::Target *TheTarget =
356       TargetRegistry::lookupTarget(Trip.getTriple(), Error);
357   if (TheTarget == nullptr) {
358     LLVMRustSetLastError(Error.c_str());
359     return nullptr;
360   }
361
362   TargetOptions Options;
363
364   Options.FloatABIType = FloatABI::Default;
365   if (UseSoftFloat) {
366     Options.FloatABIType = FloatABI::Soft;
367   }
368   Options.DataSections = DataSections;
369   Options.FunctionSections = FunctionSections;
370   Options.MCOptions.AsmVerbose = AsmComments;
371   Options.MCOptions.PreserveAsmComments = AsmComments;
372
373   if (TrapUnreachable) {
374     // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
375     // This limits the extent of possible undefined behavior in some cases, as
376     // it prevents control flow from "falling through" into whatever code
377     // happens to be laid out next in memory.
378     Options.TrapUnreachable = true;
379   }
380
381   if (Singlethread) {
382     Options.ThreadModel = ThreadModel::Single;
383   }
384
385   Options.EmitStackSizeSection = EmitStackSizeSection;
386
387   Optional<CodeModel::Model> CM;
388   if (RustCM != LLVMRustCodeModel::None)
389     CM = fromRust(RustCM);
390   TargetMachine *TM = TheTarget->createTargetMachine(
391       Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
392   return wrap(TM);
393 }
394
395 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
396   delete unwrap(TM);
397 }
398
399 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
400 // passes for a target to a pass manager. We export that functionality through
401 // this function.
402 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
403                                           LLVMPassManagerRef PMR,
404                                           LLVMModuleRef M) {
405   PassManagerBase *PM = unwrap(PMR);
406   PM->add(
407       createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
408 }
409
410 extern "C" void LLVMRustConfigurePassManagerBuilder(
411     LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
412     bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
413     const char* PGOGenPath, const char* PGOUsePath) {
414 #if LLVM_VERSION_GE(7, 0)
415   unwrap(PMBR)->MergeFunctions = MergeFunctions;
416 #endif
417   unwrap(PMBR)->SLPVectorize = SLPVectorize;
418   unwrap(PMBR)->OptLevel = fromRust(OptLevel);
419   unwrap(PMBR)->LoopVectorize = LoopVectorize;
420   unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
421
422   if (PGOGenPath) {
423     assert(!PGOUsePath);
424     unwrap(PMBR)->EnablePGOInstrGen = true;
425     unwrap(PMBR)->PGOInstrGen = PGOGenPath;
426   }
427   if (PGOUsePath) {
428     assert(!PGOGenPath);
429     unwrap(PMBR)->PGOInstrUse = PGOUsePath;
430   }
431 }
432
433 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
434 // field of a PassManagerBuilder, we expose our own method of doing so.
435 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
436                                               LLVMModuleRef M,
437                                               bool DisableSimplifyLibCalls) {
438   Triple TargetTriple(unwrap(M)->getTargetTriple());
439   TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
440   if (DisableSimplifyLibCalls)
441     TLI->disableAllFunctions();
442   unwrap(PMBR)->LibraryInfo = TLI;
443 }
444
445 // Unfortunately, the LLVM C API doesn't provide a way to create the
446 // TargetLibraryInfo pass, so we use this method to do so.
447 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
448                                        bool DisableSimplifyLibCalls) {
449   Triple TargetTriple(unwrap(M)->getTargetTriple());
450   TargetLibraryInfoImpl TLII(TargetTriple);
451   if (DisableSimplifyLibCalls)
452     TLII.disableAllFunctions();
453   unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
454 }
455
456 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
457 // all the functions in a module, so we do that manually here. You'll find
458 // similar code in clang's BackendUtil.cpp file.
459 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
460                                                LLVMModuleRef M) {
461   llvm::legacy::FunctionPassManager *P =
462       unwrap<llvm::legacy::FunctionPassManager>(PMR);
463   P->doInitialization();
464
465   // Upgrade all calls to old intrinsics first.
466   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
467     UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
468
469   for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
470        ++I)
471     if (!I->isDeclaration())
472       P->run(*I);
473
474   P->doFinalization();
475 }
476
477 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
478   // Initializing the command-line options more than once is not allowed. So,
479   // check if they've already been initialized.  (This could happen if we're
480   // being called from rustpkg, for example). If the arguments change, then
481   // that's just kinda unfortunate.
482   static bool Initialized = false;
483   if (Initialized)
484     return;
485   Initialized = true;
486   cl::ParseCommandLineOptions(Argc, Argv);
487 }
488
489 enum class LLVMRustFileType {
490   Other,
491   AssemblyFile,
492   ObjectFile,
493 };
494
495 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
496   switch (Type) {
497   case LLVMRustFileType::AssemblyFile:
498     return TargetMachine::CGFT_AssemblyFile;
499   case LLVMRustFileType::ObjectFile:
500     return TargetMachine::CGFT_ObjectFile;
501   default:
502     report_fatal_error("Bad FileType.");
503   }
504 }
505
506 extern "C" LLVMRustResult
507 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
508                         LLVMModuleRef M, const char *Path,
509                         LLVMRustFileType RustFileType) {
510   llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
511   auto FileType = fromRust(RustFileType);
512
513   std::string ErrorInfo;
514   std::error_code EC;
515   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
516   if (EC)
517     ErrorInfo = EC.message();
518   if (ErrorInfo != "") {
519     LLVMRustSetLastError(ErrorInfo.c_str());
520     return LLVMRustResult::Failure;
521   }
522
523 #if LLVM_VERSION_GE(7, 0)
524   buffer_ostream BOS(OS);
525   unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
526 #else
527   unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
528 #endif
529   PM->run(*unwrap(M));
530
531   // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
532   // stream (OS), so the only real safe place to delete this is here? Don't we
533   // wish this was written in Rust?
534   delete PM;
535   return LLVMRustResult::Success;
536 }
537
538
539 // Callback to demangle function name
540 // Parameters:
541 // * name to be demangled
542 // * name len
543 // * output buffer
544 // * output buffer len
545 // Returns len of demangled string, or 0 if demangle failed.
546 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
547
548
549 namespace {
550
551 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
552   DemangleFn Demangle;
553   std::vector<char> Buf;
554
555 public:
556   RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
557
558   // Return empty string if demangle failed
559   // or if name does not need to be demangled
560   StringRef CallDemangle(StringRef name) {
561     if (!Demangle) {
562       return StringRef();
563     }
564
565     if (Buf.size() < name.size() * 2) {
566       // Semangled name usually shorter than mangled,
567       // but allocate twice as much memory just in case
568       Buf.resize(name.size() * 2);
569     }
570
571     auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
572     if (!R) {
573       // Demangle failed.
574       return StringRef();
575     }
576
577     auto Demangled = StringRef(Buf.data(), R);
578     if (Demangled == name) {
579       // Do not print anything if demangled name is equal to mangled.
580       return StringRef();
581     }
582
583     return Demangled;
584   }
585
586   void emitFunctionAnnot(const Function *F,
587                          formatted_raw_ostream &OS) override {
588     StringRef Demangled = CallDemangle(F->getName());
589     if (Demangled.empty()) {
590         return;
591     }
592
593     OS << "; " << Demangled << "\n";
594   }
595
596   void emitInstructionAnnot(const Instruction *I,
597                             formatted_raw_ostream &OS) override {
598     const char *Name;
599     const Value *Value;
600     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
601       Name = "call";
602       Value = CI->getCalledValue();
603     } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
604       Name = "invoke";
605       Value = II->getCalledValue();
606     } else {
607       // Could demangle more operations, e. g.
608       // `store %place, @function`.
609       return;
610     }
611
612     if (!Value->hasName()) {
613       return;
614     }
615
616     StringRef Demangled = CallDemangle(Value->getName());
617     if (Demangled.empty()) {
618       return;
619     }
620
621     OS << "; " << Name << " " << Demangled << "\n";
622   }
623 };
624
625 class RustPrintModulePass : public ModulePass {
626   raw_ostream* OS;
627   DemangleFn Demangle;
628 public:
629   static char ID;
630   RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
631   RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
632       : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
633
634   bool runOnModule(Module &M) override {
635     RustAssemblyAnnotationWriter AW(Demangle);
636
637     M.print(*OS, &AW, false);
638
639     return false;
640   }
641
642   void getAnalysisUsage(AnalysisUsage &AU) const override {
643     AU.setPreservesAll();
644   }
645
646   static StringRef name() { return "RustPrintModulePass"; }
647 };
648
649 } // namespace
650
651 namespace llvm {
652   void initializeRustPrintModulePassPass(PassRegistry&);
653 }
654
655 char RustPrintModulePass::ID = 0;
656 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
657                 "Print rust module to stderr", false, false)
658
659 extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
660                                     const char *Path, DemangleFn Demangle) {
661   llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
662   std::string ErrorInfo;
663
664   std::error_code EC;
665   raw_fd_ostream OS(Path, EC, sys::fs::F_None);
666   if (EC)
667     ErrorInfo = EC.message();
668
669   formatted_raw_ostream FOS(OS);
670
671   PM->add(new RustPrintModulePass(FOS, Demangle));
672
673   PM->run(*unwrap(M));
674 }
675
676 extern "C" void LLVMRustPrintPasses() {
677   LLVMInitializePasses();
678   struct MyListener : PassRegistrationListener {
679     void passEnumerate(const PassInfo *Info) {
680       StringRef PassArg = Info->getPassArgument();
681       StringRef PassName = Info->getPassName();
682       if (!PassArg.empty()) {
683         // These unsigned->signed casts could theoretically overflow, but
684         // realistically never will (and even if, the result is implementation
685         // defined rather plain UB).
686         printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
687                (int)PassName.size(), PassName.data());
688       }
689     }
690   } Listener;
691
692   PassRegistry *PR = PassRegistry::getPassRegistry();
693   PR->enumerateWith(&Listener);
694 }
695
696 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
697                                             bool AddLifetimes) {
698   unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
699 }
700
701 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
702                                            size_t Len) {
703   llvm::legacy::PassManager passes;
704
705   auto PreserveFunctions = [=](const GlobalValue &GV) {
706     for (size_t I = 0; I < Len; I++) {
707       if (GV.getName() == Symbols[I]) {
708         return true;
709       }
710     }
711     return false;
712   };
713
714   passes.add(llvm::createInternalizePass(PreserveFunctions));
715
716   passes.run(*unwrap(M));
717 }
718
719 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
720   for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
721        ++GV) {
722     GV->setDoesNotThrow();
723     Function *F = dyn_cast<Function>(GV);
724     if (F == nullptr)
725       continue;
726
727     for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
728       for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
729         if (isa<InvokeInst>(I)) {
730           InvokeInst *CI = cast<InvokeInst>(I);
731           CI->setDoesNotThrow();
732         }
733       }
734     }
735   }
736 }
737
738 extern "C" void
739 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
740                                        LLVMTargetMachineRef TMR) {
741   TargetMachine *Target = unwrap(TMR);
742   unwrap(Module)->setDataLayout(Target->createDataLayout());
743 }
744
745 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
746   unwrap(M)->setPIELevel(PIELevel::Level::Large);
747 }
748
749 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
750 // right now. This ThinLTO support is only enabled on "recent ish" versions of
751 // LLVM, and otherwise it's just blanket rejected from other compilers.
752 //
753 // Most of this implementation is straight copied from LLVM. At the time of
754 // this writing it wasn't *quite* suitable to reuse more code from upstream
755 // for our purposes, but we should strive to upstream this support once it's
756 // ready to go! I figure we may want a bit of testing locally first before
757 // sending this upstream to LLVM. I hear though they're quite eager to receive
758 // feedback like this!
759 //
760 // If you're reading this code and wondering "what in the world" or you're
761 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
762 // then fear not! (ok maybe fear a little). All code here is mostly based
763 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
764 //
765 // You'll find that the general layout here roughly corresponds to the `run`
766 // method in that file as well as `ProcessThinLTOModule`. Functions are
767 // specifically commented below as well, but if you're updating this code
768 // or otherwise trying to understand it, the LLVM source will be useful in
769 // interpreting the mysteries within.
770 //
771 // Otherwise I'll apologize in advance, it probably requires a relatively
772 // significant investment on your part to "truly understand" what's going on
773 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
774 // and various online resources about ThinLTO to make heads or tails of all
775 // this.
776
777 // This is a shared data structure which *must* be threadsafe to share
778 // read-only amongst threads. This also corresponds basically to the arguments
779 // of the `ProcessThinLTOModule` function in the LLVM source.
780 struct LLVMRustThinLTOData {
781   // The combined index that is the global analysis over all modules we're
782   // performing ThinLTO for. This is mostly managed by LLVM.
783   ModuleSummaryIndex Index;
784
785   // All modules we may look at, stored as in-memory serialized versions. This
786   // is later used when inlining to ensure we can extract any module to inline
787   // from.
788   StringMap<MemoryBufferRef> ModuleMap;
789
790   // A set that we manage of everything we *don't* want internalized. Note that
791   // this includes all transitive references right now as well, but it may not
792   // always!
793   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
794
795   // Not 100% sure what these are, but they impact what's internalized and
796   // what's inlined across modules, I believe.
797   StringMap<FunctionImporter::ImportMapTy> ImportLists;
798   StringMap<FunctionImporter::ExportSetTy> ExportLists;
799   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
800
801 #if LLVM_VERSION_GE(7, 0)
802   LLVMRustThinLTOData() : Index(/* isPerformingAnalysis = */ false) {}
803 #endif
804 };
805
806 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
807 struct LLVMRustThinLTOModule {
808   const char *identifier;
809   const char *data;
810   size_t len;
811 };
812
813 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
814 // does.
815 static const GlobalValueSummary *
816 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
817   auto StrongDefForLinker = llvm::find_if(
818       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
819         auto Linkage = Summary->linkage();
820         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
821                !GlobalValue::isWeakForLinker(Linkage);
822       });
823   if (StrongDefForLinker != GVSummaryList.end())
824     return StrongDefForLinker->get();
825
826   auto FirstDefForLinker = llvm::find_if(
827       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
828         auto Linkage = Summary->linkage();
829         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
830       });
831   if (FirstDefForLinker == GVSummaryList.end())
832     return nullptr;
833   return FirstDefForLinker->get();
834 }
835
836 // The main entry point for creating the global ThinLTO analysis. The structure
837 // here is basically the same as before threads are spawned in the `run`
838 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
839 extern "C" LLVMRustThinLTOData*
840 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
841                           int num_modules,
842                           const char **preserved_symbols,
843                           int num_symbols) {
844   auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
845
846   // Load each module's summary and merge it into one combined index
847   for (int i = 0; i < num_modules; i++) {
848     auto module = &modules[i];
849     StringRef buffer(module->data, module->len);
850     MemoryBufferRef mem_buffer(buffer, module->identifier);
851
852     Ret->ModuleMap[module->identifier] = mem_buffer;
853
854     if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
855       LLVMRustSetLastError(toString(std::move(Err)).c_str());
856       return nullptr;
857     }
858   }
859
860   // Collect for each module the list of function it defines (GUID -> Summary)
861   Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
862
863   // Convert the preserved symbols set from string to GUID, this is then needed
864   // for internalization.
865   for (int i = 0; i < num_symbols; i++) {
866     auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
867     Ret->GUIDPreservedSymbols.insert(GUID);
868   }
869
870   // Collect the import/export lists for all modules from the call-graph in the
871   // combined index
872   //
873   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
874 #if LLVM_VERSION_GE(7, 0)
875   auto deadIsPrevailing = [&](GlobalValue::GUID G) {
876     return PrevailingType::Unknown;
877   };
878   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
879 #else
880   computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
881 #endif
882   ComputeCrossModuleImport(
883     Ret->Index,
884     Ret->ModuleToDefinedGVSummaries,
885     Ret->ImportLists,
886     Ret->ExportLists
887   );
888
889   // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
890   // impacts the caching.
891   //
892   // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
893   // being lifted from `lib/LTO/LTO.cpp` as well
894   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
895   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
896   for (auto &I : Ret->Index) {
897     if (I.second.SummaryList.size() > 1)
898       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
899   }
900   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
901     const auto &Prevailing = PrevailingCopy.find(GUID);
902     if (Prevailing == PrevailingCopy.end())
903       return true;
904     return Prevailing->second == S;
905   };
906   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
907                               GlobalValue::GUID GUID,
908                               GlobalValue::LinkageTypes NewLinkage) {
909     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
910   };
911 #if LLVM_VERSION_GE(8, 0)
912   thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
913 #else
914   thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
915 #endif
916
917   // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
918   // callback below. This callback below will dictate the linkage for all
919   // summaries in the index, and we basically just only want to ensure that dead
920   // symbols are internalized. Otherwise everything that's already external
921   // linkage will stay as external, and internal will stay as internal.
922   std::set<GlobalValue::GUID> ExportedGUIDs;
923   for (auto &List : Ret->Index) {
924     for (auto &GVS: List.second.SummaryList) {
925       if (GlobalValue::isLocalLinkage(GVS->linkage()))
926         continue;
927       auto GUID = GVS->getOriginalName();
928       if (GVS->flags().Live)
929         ExportedGUIDs.insert(GUID);
930     }
931   }
932   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
933     const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
934     return (ExportList != Ret->ExportLists.end() &&
935       ExportList->second.count(GUID)) ||
936       ExportedGUIDs.count(GUID);
937   };
938   thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
939
940   return Ret.release();
941 }
942
943 extern "C" void
944 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
945   delete Data;
946 }
947
948 // Below are the various passes that happen *per module* when doing ThinLTO.
949 //
950 // In other words, these are the functions that are all run concurrently
951 // with one another, one per module. The passes here correspond to the analysis
952 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
953 // `ProcessThinLTOModule` function. Here they're split up into separate steps
954 // so rustc can save off the intermediate bytecode between each step.
955
956 extern "C" bool
957 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
958   Module &Mod = *unwrap(M);
959   if (renameModuleForThinLTO(Mod, Data->Index)) {
960     LLVMRustSetLastError("renameModuleForThinLTO failed");
961     return false;
962   }
963   return true;
964 }
965
966 extern "C" bool
967 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
968   Module &Mod = *unwrap(M);
969   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
970 #if LLVM_VERSION_GE(8, 0)
971   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
972 #else
973   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
974 #endif
975   return true;
976 }
977
978 extern "C" bool
979 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
980   Module &Mod = *unwrap(M);
981   const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
982   thinLTOInternalizeModule(Mod, DefinedGlobals);
983   return true;
984 }
985
986 extern "C" bool
987 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
988   Module &Mod = *unwrap(M);
989
990   const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
991   auto Loader = [&](StringRef Identifier) {
992     const auto &Memory = Data->ModuleMap.lookup(Identifier);
993     auto &Context = Mod.getContext();
994     auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
995
996     if (!MOrErr)
997       return MOrErr;
998
999     // The rest of this closure is a workaround for
1000     // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1001     // we accidentally import wasm custom sections into different modules,
1002     // duplicating them by in the final output artifact.
1003     //
1004     // The issue is worked around here by manually removing the
1005     // `wasm.custom_sections` named metadata node from any imported module. This
1006     // we know isn't used by any optimization pass so there's no need for it to
1007     // be imported.
1008     //
1009     // Note that the metadata is currently lazily loaded, so we materialize it
1010     // here before looking up if there's metadata inside. The `FunctionImporter`
1011     // will immediately materialize metadata anyway after an import, so this
1012     // shouldn't be a perf hit.
1013     if (Error Err = (*MOrErr)->materializeMetadata()) {
1014       Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1015       return Ret;
1016     }
1017
1018     auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1019     if (WasmCustomSections)
1020       WasmCustomSections->eraseFromParent();
1021
1022     return MOrErr;
1023   };
1024   FunctionImporter Importer(Data->Index, Loader);
1025   Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1026   if (!Result) {
1027     LLVMRustSetLastError(toString(Result.takeError()).c_str());
1028     return false;
1029   }
1030   return true;
1031 }
1032
1033 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1034                                                       const char*, // importing module name
1035                                                       const char*); // imported module name
1036
1037 // Calls `module_name_callback` for each module import done by ThinLTO.
1038 // The callback is provided with regular null-terminated C strings.
1039 extern "C" void
1040 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1041                                 LLVMRustModuleNameCallback module_name_callback,
1042                                 void* callback_payload) {
1043   for (const auto& importing_module : data->ImportLists) {
1044     const std::string importing_module_id = importing_module.getKey().str();
1045     const auto& imports = importing_module.getValue();
1046     for (const auto& imported_module : imports) {
1047       const std::string imported_module_id = imported_module.getKey().str();
1048       module_name_callback(callback_payload,
1049                            importing_module_id.c_str(),
1050                            imported_module_id.c_str());
1051     }
1052   }
1053 }
1054
1055 // This struct and various functions are sort of a hack right now, but the
1056 // problem is that we've got in-memory LLVM modules after we generate and
1057 // optimize all codegen-units for one compilation in rustc. To be compatible
1058 // with the LTO support above we need to serialize the modules plus their
1059 // ThinLTO summary into memory.
1060 //
1061 // This structure is basically an owned version of a serialize module, with
1062 // a ThinLTO summary attached.
1063 struct LLVMRustThinLTOBuffer {
1064   std::string data;
1065 };
1066
1067 extern "C" LLVMRustThinLTOBuffer*
1068 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1069   auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1070   {
1071     raw_string_ostream OS(Ret->data);
1072     {
1073       legacy::PassManager PM;
1074       PM.add(createWriteThinLTOBitcodePass(OS));
1075       PM.run(*unwrap(M));
1076     }
1077   }
1078   return Ret.release();
1079 }
1080
1081 extern "C" void
1082 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1083   delete Buffer;
1084 }
1085
1086 extern "C" const void*
1087 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1088   return Buffer->data.data();
1089 }
1090
1091 extern "C" size_t
1092 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1093   return Buffer->data.length();
1094 }
1095
1096 // This is what we used to parse upstream bitcode for actual ThinLTO
1097 // processing.  We'll call this once per module optimized through ThinLTO, and
1098 // it'll be called concurrently on many threads.
1099 extern "C" LLVMModuleRef
1100 LLVMRustParseBitcodeForThinLTO(LLVMContextRef Context,
1101                                const char *data,
1102                                size_t len,
1103                                const char *identifier) {
1104   StringRef Data(data, len);
1105   MemoryBufferRef Buffer(Data, identifier);
1106   unwrap(Context)->enableDebugTypeODRUniquing();
1107   Expected<std::unique_ptr<Module>> SrcOrError =
1108       parseBitcodeFile(Buffer, *unwrap(Context));
1109   if (!SrcOrError) {
1110     LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1111     return nullptr;
1112   }
1113   return wrap(std::move(*SrcOrError).release());
1114 }
1115
1116 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1117 // the comment in `back/lto.rs` for why this exists.
1118 extern "C" void
1119 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1120                                 DICompileUnit **A,
1121                                 DICompileUnit **B) {
1122   Module *M = unwrap(Mod);
1123   DICompileUnit **Cur = A;
1124   DICompileUnit **Next = B;
1125   for (DICompileUnit *CU : M->debug_compile_units()) {
1126     *Cur = CU;
1127     Cur = Next;
1128     Next = nullptr;
1129     if (Cur == nullptr)
1130       break;
1131   }
1132 }
1133
1134 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1135 // the comment in `back/lto.rs` for why this exists.
1136 extern "C" void
1137 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1138   Module *M = unwrap(Mod);
1139
1140   // If the original source module didn't have a `DICompileUnit` then try to
1141   // merge all the existing compile units. If there aren't actually any though
1142   // then there's not much for us to do so return.
1143   if (Unit == nullptr) {
1144     for (DICompileUnit *CU : M->debug_compile_units()) {
1145       Unit = CU;
1146       break;
1147     }
1148     if (Unit == nullptr)
1149       return;
1150   }
1151
1152   // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1153   // process it recursively. Note that we specifically iterate over instructions
1154   // to ensure we feed everything into it.
1155   DebugInfoFinder Finder;
1156   Finder.processModule(*M);
1157   for (Function &F : M->functions()) {
1158     for (auto &FI : F) {
1159       for (Instruction &BI : FI) {
1160         if (auto Loc = BI.getDebugLoc())
1161           Finder.processLocation(*M, Loc);
1162         if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1163           Finder.processValue(*M, DVI);
1164         if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1165           Finder.processDeclare(*M, DDI);
1166       }
1167     }
1168   }
1169
1170   // After we've found all our debuginfo, rewrite all subprograms to point to
1171   // the same `DICompileUnit`.
1172   for (auto &F : Finder.subprograms()) {
1173     F->replaceUnit(Unit);
1174   }
1175
1176   // Erase any other references to other `DICompileUnit` instances, the verifier
1177   // will later ensure that we don't actually have any other stale references to
1178   // worry about.
1179   auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1180   MD->clearOperands();
1181   MD->addOperand(Unit);
1182 }