LTO: Rename mergedModule variables to MergedModule to prepare for ownership change.
[oota-llvm.git] / lib / LTO / LTOCodeGenerator.cpp
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
56 using namespace llvm;
57
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 #else
62   return PACKAGE_NAME " version " PACKAGE_VERSION;
63 #endif
64 }
65
66 LTOCodeGenerator::LTOCodeGenerator()
67     : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
68   initializeLTOPasses();
69 }
70
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72     : OwnedContext(std::move(Context)), Context(*OwnedContext),
73       IRLinker(new Module("ld-temp.o", *OwnedContext)) {
74   initializeLTOPasses();
75 }
76
77 void LTOCodeGenerator::destroyMergedModule() {
78   if (OwnedModule) {
79     assert(IRLinker.getModule() == &OwnedModule->getModule() &&
80            "The linker's module should be the same as the owned module");
81     delete OwnedModule;
82     OwnedModule = nullptr;
83   } else if (IRLinker.getModule())
84     IRLinker.deleteModule();
85 }
86
87 LTOCodeGenerator::~LTOCodeGenerator() {
88   destroyMergedModule();
89 }
90
91 // Initialize LTO passes. Please keep this funciton in sync with
92 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
93 // passes are initialized.
94 void LTOCodeGenerator::initializeLTOPasses() {
95   PassRegistry &R = *PassRegistry::getPassRegistry();
96
97   initializeInternalizePassPass(R);
98   initializeIPSCCPPass(R);
99   initializeGlobalOptPass(R);
100   initializeConstantMergePass(R);
101   initializeDAHPass(R);
102   initializeInstructionCombiningPassPass(R);
103   initializeSimpleInlinerPass(R);
104   initializePruneEHPass(R);
105   initializeGlobalDCEPass(R);
106   initializeArgPromotionPass(R);
107   initializeJumpThreadingPass(R);
108   initializeSROAPass(R);
109   initializeSROA_DTPass(R);
110   initializeSROA_SSAUpPass(R);
111   initializeFunctionAttrsPass(R);
112   initializeGlobalsModRefPass(R);
113   initializeLICMPass(R);
114   initializeMergedLoadStoreMotionPass(R);
115   initializeGVNPass(R);
116   initializeMemCpyOptPass(R);
117   initializeDCEPass(R);
118   initializeCFGSimplifyPassPass(R);
119 }
120
121 bool LTOCodeGenerator::addModule(LTOModule *mod) {
122   assert(&mod->getModule().getContext() == &Context &&
123          "Expected module in same context");
124
125   bool ret = IRLinker.linkInModule(&mod->getModule());
126
127   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
128   for (int i = 0, e = undefs.size(); i != e; ++i)
129     AsmUndefinedRefs[undefs[i]] = 1;
130
131   return !ret;
132 }
133
134 void LTOCodeGenerator::setModule(LTOModule *Mod) {
135   assert(&Mod->getModule().getContext() == &Context &&
136          "Expected module in same context");
137
138   // Delete the old merged module.
139   destroyMergedModule();
140   AsmUndefinedRefs.clear();
141
142   OwnedModule = Mod;
143   IRLinker.setModule(&Mod->getModule());
144
145   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
146   for (int I = 0, E = Undefs.size(); I != E; ++I)
147     AsmUndefinedRefs[Undefs[I]] = 1;
148 }
149
150 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
151   Options = options;
152 }
153
154 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
155   switch (debug) {
156   case LTO_DEBUG_MODEL_NONE:
157     EmitDwarfDebugInfo = false;
158     return;
159
160   case LTO_DEBUG_MODEL_DWARF:
161     EmitDwarfDebugInfo = true;
162     return;
163   }
164   llvm_unreachable("Unknown debug format!");
165 }
166
167 void LTOCodeGenerator::setOptLevel(unsigned level) {
168   OptLevel = level;
169   switch (OptLevel) {
170   case 0:
171     CGOptLevel = CodeGenOpt::None;
172     break;
173   case 1:
174     CGOptLevel = CodeGenOpt::Less;
175     break;
176   case 2:
177     CGOptLevel = CodeGenOpt::Default;
178     break;
179   case 3:
180     CGOptLevel = CodeGenOpt::Aggressive;
181     break;
182   }
183 }
184
185 bool LTOCodeGenerator::writeMergedModules(const char *path,
186                                           std::string &errMsg) {
187   if (!determineTarget(errMsg))
188     return false;
189
190   // mark which symbols can not be internalized
191   applyScopeRestrictions();
192
193   // create output file
194   std::error_code EC;
195   tool_output_file Out(path, EC, sys::fs::F_None);
196   if (EC) {
197     errMsg = "could not open bitcode file for writing: ";
198     errMsg += path;
199     return false;
200   }
201
202   // write bitcode to it
203   WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
204   Out.os().close();
205
206   if (Out.os().has_error()) {
207     errMsg = "could not write bitcode file: ";
208     errMsg += path;
209     Out.os().clear_error();
210     return false;
211   }
212
213   Out.keep();
214   return true;
215 }
216
217 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
218                                               std::string &errMsg) {
219   // make unique temp .o file to put generated object file
220   SmallString<128> Filename;
221   int FD;
222   std::error_code EC =
223       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
224   if (EC) {
225     errMsg = EC.message();
226     return false;
227   }
228
229   // generate object file
230   tool_output_file objFile(Filename.c_str(), FD);
231
232   bool genResult = compileOptimized(objFile.os(), errMsg);
233   objFile.os().close();
234   if (objFile.os().has_error()) {
235     objFile.os().clear_error();
236     sys::fs::remove(Twine(Filename));
237     return false;
238   }
239
240   objFile.keep();
241   if (!genResult) {
242     sys::fs::remove(Twine(Filename));
243     return false;
244   }
245
246   NativeObjectPath = Filename.c_str();
247   *name = NativeObjectPath.c_str();
248   return true;
249 }
250
251 std::unique_ptr<MemoryBuffer>
252 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
253   const char *name;
254   if (!compileOptimizedToFile(&name, errMsg))
255     return nullptr;
256
257   // read .o file into memory buffer
258   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
259       MemoryBuffer::getFile(name, -1, false);
260   if (std::error_code EC = BufferOrErr.getError()) {
261     errMsg = EC.message();
262     sys::fs::remove(NativeObjectPath);
263     return nullptr;
264   }
265
266   // remove temp files
267   sys::fs::remove(NativeObjectPath);
268
269   return std::move(*BufferOrErr);
270 }
271
272
273 bool LTOCodeGenerator::compile_to_file(const char **name,
274                                        bool disableInline,
275                                        bool disableGVNLoadPRE,
276                                        bool disableVectorization,
277                                        std::string &errMsg) {
278   if (!optimize(disableInline, disableGVNLoadPRE,
279                 disableVectorization, errMsg))
280     return false;
281
282   return compileOptimizedToFile(name, errMsg);
283 }
284
285 std::unique_ptr<MemoryBuffer>
286 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
287                           bool disableVectorization, std::string &errMsg) {
288   if (!optimize(disableInline, disableGVNLoadPRE,
289                 disableVectorization, errMsg))
290     return nullptr;
291
292   return compileOptimized(errMsg);
293 }
294
295 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
296   if (TargetMach)
297     return true;
298
299   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
300   if (TripleStr.empty()) {
301     TripleStr = sys::getDefaultTargetTriple();
302     IRLinker.getModule()->setTargetTriple(TripleStr);
303   }
304   llvm::Triple Triple(TripleStr);
305
306   // create target machine from info for merged modules
307   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
308   if (!march)
309     return false;
310
311   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
312   // the default set of features.
313   SubtargetFeatures Features(MAttr);
314   Features.getDefaultSubtargetFeatures(Triple);
315   FeatureStr = Features.getString();
316   // Set a default CPU for Darwin triples.
317   if (MCpu.empty() && Triple.isOSDarwin()) {
318     if (Triple.getArch() == llvm::Triple::x86_64)
319       MCpu = "core2";
320     else if (Triple.getArch() == llvm::Triple::x86)
321       MCpu = "yonah";
322     else if (Triple.getArch() == llvm::Triple::aarch64)
323       MCpu = "cyclone";
324   }
325
326   TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
327                                               Options, RelocModel,
328                                               CodeModel::Default, CGOptLevel));
329   return true;
330 }
331
332 void LTOCodeGenerator::
333 applyRestriction(GlobalValue &GV,
334                  ArrayRef<StringRef> Libcalls,
335                  std::vector<const char*> &MustPreserveList,
336                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
337                  Mangler &Mangler) {
338   // There are no restrictions to apply to declarations.
339   if (GV.isDeclaration())
340     return;
341
342   // There is nothing more restrictive than private linkage.
343   if (GV.hasPrivateLinkage())
344     return;
345
346   SmallString<64> Buffer;
347   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
348
349   if (MustPreserveSymbols.count(Buffer))
350     MustPreserveList.push_back(GV.getName().data());
351   if (AsmUndefinedRefs.count(Buffer))
352     AsmUsed.insert(&GV);
353
354   // Conservatively append user-supplied runtime library functions to
355   // llvm.compiler.used.  These could be internalized and deleted by
356   // optimizations like -globalopt, causing problems when later optimizations
357   // add new library calls (e.g., llvm.memset => memset and printf => puts).
358   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
359   if (isa<Function>(GV) &&
360       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
361     AsmUsed.insert(&GV);
362 }
363
364 static void findUsedValues(GlobalVariable *LLVMUsed,
365                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
366   if (!LLVMUsed) return;
367
368   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
369   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
370     if (GlobalValue *GV =
371         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
372       UsedValues.insert(GV);
373 }
374
375 // Collect names of runtime library functions. User-defined functions with the
376 // same names are added to llvm.compiler.used to prevent them from being
377 // deleted by optimizations.
378 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
379                                       const TargetLibraryInfo& TLI,
380                                       const Module &Mod,
381                                       const TargetMachine &TM) {
382   // TargetLibraryInfo has info on C runtime library calls on the current
383   // target.
384   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
385        I != E; ++I) {
386     LibFunc::Func F = static_cast<LibFunc::Func>(I);
387     if (TLI.has(F))
388       Libcalls.push_back(TLI.getName(F));
389   }
390
391   SmallPtrSet<const TargetLowering *, 1> TLSet;
392
393   for (const Function &F : Mod) {
394     const TargetLowering *Lowering =
395         TM.getSubtargetImpl(F)->getTargetLowering();
396
397     if (Lowering && TLSet.insert(Lowering).second)
398       // TargetLowering has info on library calls that CodeGen expects to be
399       // available, both from the C runtime and compiler-rt.
400       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
401            I != E; ++I)
402         if (const char *Name =
403                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
404           Libcalls.push_back(Name);
405   }
406
407   array_pod_sort(Libcalls.begin(), Libcalls.end());
408   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
409                  Libcalls.end());
410 }
411
412 void LTOCodeGenerator::applyScopeRestrictions() {
413   if (ScopeRestrictionsDone || !ShouldInternalize)
414     return;
415   Module *MergedModule = IRLinker.getModule();
416
417   // Start off with a verification pass.
418   legacy::PassManager passes;
419   passes.add(createVerifierPass());
420
421   // mark which symbols can not be internalized
422   Mangler Mangler;
423   std::vector<const char*> MustPreserveList;
424   SmallPtrSet<GlobalValue*, 8> AsmUsed;
425   std::vector<StringRef> Libcalls;
426   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
427   TargetLibraryInfo TLI(TLII);
428
429   accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
430
431   for (Function &f : *MergedModule)
432     applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
433   for (GlobalVariable &v : MergedModule->globals())
434     applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
435   for (GlobalAlias &a : MergedModule->aliases())
436     applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
437
438   GlobalVariable *LLVMCompilerUsed =
439     MergedModule->getGlobalVariable("llvm.compiler.used");
440   findUsedValues(LLVMCompilerUsed, AsmUsed);
441   if (LLVMCompilerUsed)
442     LLVMCompilerUsed->eraseFromParent();
443
444   if (!AsmUsed.empty()) {
445     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
446     std::vector<Constant*> asmUsed2;
447     for (auto *GV : AsmUsed) {
448       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
449       asmUsed2.push_back(c);
450     }
451
452     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
453     LLVMCompilerUsed =
454       new llvm::GlobalVariable(*MergedModule, ATy, false,
455                                llvm::GlobalValue::AppendingLinkage,
456                                llvm::ConstantArray::get(ATy, asmUsed2),
457                                "llvm.compiler.used");
458
459     LLVMCompilerUsed->setSection("llvm.metadata");
460   }
461
462   passes.add(createInternalizePass(MustPreserveList));
463
464   // apply scope restrictions
465   passes.run(*MergedModule);
466
467   ScopeRestrictionsDone = true;
468 }
469
470 /// Optimize merged modules using various IPO passes
471 bool LTOCodeGenerator::optimize(bool DisableInline,
472                                 bool DisableGVNLoadPRE,
473                                 bool DisableVectorization,
474                                 std::string &errMsg) {
475   if (!this->determineTarget(errMsg))
476     return false;
477
478   Module *MergedModule = IRLinker.getModule();
479
480   // Mark which symbols can not be internalized
481   this->applyScopeRestrictions();
482
483   // Instantiate the pass manager to organize the passes.
484   legacy::PassManager passes;
485
486   // Add an appropriate DataLayout instance for this module...
487   MergedModule->setDataLayout(TargetMach->createDataLayout());
488
489   passes.add(
490       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
491
492   Triple TargetTriple(TargetMach->getTargetTriple());
493   PassManagerBuilder PMB;
494   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
495   PMB.LoopVectorize = !DisableVectorization;
496   PMB.SLPVectorize = !DisableVectorization;
497   if (!DisableInline)
498     PMB.Inliner = createFunctionInliningPass();
499   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
500   PMB.OptLevel = OptLevel;
501   PMB.VerifyInput = true;
502   PMB.VerifyOutput = true;
503
504   PMB.populateLTOPassManager(passes);
505
506   // Run our queue of passes all at once now, efficiently.
507   passes.run(*MergedModule);
508
509   return true;
510 }
511
512 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
513                                         std::string &errMsg) {
514   if (!this->determineTarget(errMsg))
515     return false;
516
517   Module *MergedModule = IRLinker.getModule();
518
519   legacy::PassManager codeGenPasses;
520
521   // If the bitcode files contain ARC code and were compiled with optimization,
522   // the ObjCARCContractPass must be run, so do it unconditionally here.
523   codeGenPasses.add(createObjCARCContractPass());
524
525   if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
526                                       TargetMachine::CGFT_ObjectFile)) {
527     errMsg = "target file type not supported";
528     return false;
529   }
530
531   // Run the code generator, and write object file
532   codeGenPasses.run(*MergedModule);
533
534   return true;
535 }
536
537 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
538 /// LTO problems.
539 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
540   for (std::pair<StringRef, StringRef> o = getToken(options);
541        !o.first.empty(); o = getToken(o.second))
542     CodegenOptions.push_back(o.first);
543 }
544
545 void LTOCodeGenerator::parseCodeGenDebugOptions() {
546   // if options were requested, set them
547   if (!CodegenOptions.empty()) {
548     // ParseCommandLineOptions() expects argv[0] to be program name.
549     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
550     for (std::string &Arg : CodegenOptions)
551       CodegenArgv.push_back(Arg.c_str());
552     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
553   }
554 }
555
556 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
557                                          void *Context) {
558   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
559 }
560
561 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
562   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
563   lto_codegen_diagnostic_severity_t Severity;
564   switch (DI.getSeverity()) {
565   case DS_Error:
566     Severity = LTO_DS_ERROR;
567     break;
568   case DS_Warning:
569     Severity = LTO_DS_WARNING;
570     break;
571   case DS_Remark:
572     Severity = LTO_DS_REMARK;
573     break;
574   case DS_Note:
575     Severity = LTO_DS_NOTE;
576     break;
577   }
578   // Create the string that will be reported to the external diagnostic handler.
579   std::string MsgStorage;
580   raw_string_ostream Stream(MsgStorage);
581   DiagnosticPrinterRawOStream DP(Stream);
582   DI.print(DP);
583   Stream.flush();
584
585   // If this method has been called it means someone has set up an external
586   // diagnostic handler. Assert on that.
587   assert(DiagHandler && "Invalid diagnostic handler");
588   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
589 }
590
591 void
592 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
593                                        void *Ctxt) {
594   this->DiagHandler = DiagHandler;
595   this->DiagContext = Ctxt;
596   if (!DiagHandler)
597     return Context.setDiagnosticHandler(nullptr, nullptr);
598   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
599   // diagnostic to the external DiagHandler.
600   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
601                                /* RespectFilters */ true);
602 }