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