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