verify-di: Implement DebugInfoVerifier
[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/Support/system_error.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
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()), Linker(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   Linker.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   initializeGVNPass(R);
111   initializeMemCpyOptPass(R);
112   initializeDCEPass(R);
113   initializeCFGSimplifyPassPass(R);
114 }
115
116 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
117   bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
118
119   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
120   for (int i = 0, e = undefs.size(); i != e; ++i)
121     AsmUndefinedRefs[undefs[i]] = 1;
122
123   return !ret;
124 }
125
126 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
127   Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
128   Options.NoFramePointerElim = options.NoFramePointerElim;
129   Options.AllowFPOpFusion = options.AllowFPOpFusion;
130   Options.UnsafeFPMath = options.UnsafeFPMath;
131   Options.NoInfsFPMath = options.NoInfsFPMath;
132   Options.NoNaNsFPMath = options.NoNaNsFPMath;
133   Options.HonorSignDependentRoundingFPMathOption =
134     options.HonorSignDependentRoundingFPMathOption;
135   Options.UseSoftFloat = options.UseSoftFloat;
136   Options.FloatABIType = options.FloatABIType;
137   Options.NoZerosInBSS = options.NoZerosInBSS;
138   Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
139   Options.DisableTailCalls = options.DisableTailCalls;
140   Options.StackAlignmentOverride = options.StackAlignmentOverride;
141   Options.TrapFuncName = options.TrapFuncName;
142   Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
143   Options.UseInitArray = options.UseInitArray;
144 }
145
146 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
147   switch (debug) {
148   case LTO_DEBUG_MODEL_NONE:
149     EmitDwarfDebugInfo = false;
150     return;
151
152   case LTO_DEBUG_MODEL_DWARF:
153     EmitDwarfDebugInfo = true;
154     return;
155   }
156   llvm_unreachable("Unknown debug format!");
157 }
158
159 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
160   switch (model) {
161   case LTO_CODEGEN_PIC_MODEL_STATIC:
162   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
163   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
164   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
165     CodeModel = model;
166     return;
167   }
168   llvm_unreachable("Unknown PIC model!");
169 }
170
171 bool LTOCodeGenerator::writeMergedModules(const char *path,
172                                           std::string &errMsg) {
173   if (!determineTarget(errMsg))
174     return false;
175
176   // mark which symbols can not be internalized
177   applyScopeRestrictions();
178
179   // create output file
180   std::string ErrInfo;
181   tool_output_file Out(path, ErrInfo, sys::fs::F_None);
182   if (!ErrInfo.empty()) {
183     errMsg = "could not open bitcode file for writing: ";
184     errMsg += path;
185     return false;
186   }
187
188   // write bitcode to it
189   WriteBitcodeToFile(Linker.getModule(), Out.os());
190   Out.os().close();
191
192   if (Out.os().has_error()) {
193     errMsg = "could not write bitcode file: ";
194     errMsg += path;
195     Out.os().clear_error();
196     return false;
197   }
198
199   Out.keep();
200   return true;
201 }
202
203 bool LTOCodeGenerator::compile_to_file(const char** name,
204                                        bool disableOpt,
205                                        bool disableInline,
206                                        bool disableGVNLoadPRE,
207                                        std::string& errMsg) {
208   // make unique temp .o file to put generated object file
209   SmallString<128> Filename;
210   int FD;
211   error_code EC = 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 = generateObjectFile(objFile.os(), disableOpt, disableInline,
221                                       disableGVNLoadPRE, errMsg);
222   objFile.os().close();
223   if (objFile.os().has_error()) {
224     objFile.os().clear_error();
225     sys::fs::remove(Twine(Filename));
226     return false;
227   }
228
229   objFile.keep();
230   if (!genResult) {
231     sys::fs::remove(Twine(Filename));
232     return false;
233   }
234
235   NativeObjectPath = Filename.c_str();
236   *name = NativeObjectPath.c_str();
237   return true;
238 }
239
240 const void* LTOCodeGenerator::compile(size_t* length,
241                                       bool disableOpt,
242                                       bool disableInline,
243                                       bool disableGVNLoadPRE,
244                                       std::string& errMsg) {
245   const char *name;
246   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
247                        errMsg))
248     return nullptr;
249
250   // remove old buffer if compile() called twice
251   delete NativeObjectFile;
252
253   // read .o file into memory buffer
254   std::unique_ptr<MemoryBuffer> BuffPtr;
255   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
256     errMsg = ec.message();
257     sys::fs::remove(NativeObjectPath);
258     return nullptr;
259   }
260   NativeObjectFile = BuffPtr.release();
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 = Linker.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
305   SubtargetFeatures Features;
306   Features.getDefaultSubtargetFeatures(Triple);
307   std::string FeatureStr = Features.getString();
308   // Set a default CPU for Darwin triples.
309   if (MCpu.empty() && Triple.isOSDarwin()) {
310     if (Triple.getArch() == llvm::Triple::x86_64)
311       MCpu = "core2";
312     else if (Triple.getArch() == llvm::Triple::x86)
313       MCpu = "yonah";
314     else if (Triple.getArch() == llvm::Triple::arm64)
315       MCpu = "cyclone";
316   }
317
318   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
319                                           RelocModel, CodeModel::Default,
320                                           CodeGenOpt::Aggressive);
321   return true;
322 }
323
324 void LTOCodeGenerator::
325 applyRestriction(GlobalValue &GV,
326                  const ArrayRef<StringRef> &Libcalls,
327                  std::vector<const char*> &MustPreserveList,
328                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
329                  Mangler &Mangler) {
330   // There are no restrictions to apply to declarations.
331   if (GV.isDeclaration())
332     return;
333
334   // There is nothing more restrictive than private linkage.
335   if (GV.hasPrivateLinkage())
336     return;
337
338   SmallString<64> Buffer;
339   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
340
341   if (MustPreserveSymbols.count(Buffer))
342     MustPreserveList.push_back(GV.getName().data());
343   if (AsmUndefinedRefs.count(Buffer))
344     AsmUsed.insert(&GV);
345
346   // Conservatively append user-supplied runtime library functions to
347   // llvm.compiler.used.  These could be internalized and deleted by
348   // optimizations like -globalopt, causing problems when later optimizations
349   // add new library calls (e.g., llvm.memset => memset and printf => puts).
350   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
351   if (isa<Function>(GV) &&
352       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
353     AsmUsed.insert(&GV);
354 }
355
356 static void findUsedValues(GlobalVariable *LLVMUsed,
357                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
358   if (!LLVMUsed) return;
359
360   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
361   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
362     if (GlobalValue *GV =
363         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
364       UsedValues.insert(GV);
365 }
366
367 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
368                                       const TargetLibraryInfo& TLI,
369                                       const TargetLowering *Lowering)
370 {
371   // TargetLibraryInfo has info on C runtime library calls on the current
372   // target.
373   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
374        I != E; ++I) {
375     LibFunc::Func F = static_cast<LibFunc::Func>(I);
376     if (TLI.has(F))
377       Libcalls.push_back(TLI.getName(F));
378   }
379
380   // TargetLowering has info on library calls that CodeGen expects to be
381   // available, both from the C runtime and compiler-rt.
382   if (Lowering)
383     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
384          I != E; ++I)
385       if (const char *Name
386           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
387         Libcalls.push_back(Name);
388
389   array_pod_sort(Libcalls.begin(), Libcalls.end());
390   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
391                  Libcalls.end());
392 }
393
394 void LTOCodeGenerator::applyScopeRestrictions() {
395   if (ScopeRestrictionsDone)
396     return;
397   Module *mergedModule = Linker.getModule();
398
399   // Start off with a verification pass.
400   PassManager passes;
401   passes.add(createVerifierPass());
402   passes.add(createDebugInfoVerifierPass());
403
404   // mark which symbols can not be internalized
405   Mangler Mangler(TargetMach->getDataLayout());
406   std::vector<const char*> MustPreserveList;
407   SmallPtrSet<GlobalValue*, 8> AsmUsed;
408   std::vector<StringRef> Libcalls;
409   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
410   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
411
412   for (Module::iterator f = mergedModule->begin(),
413          e = mergedModule->end(); f != e; ++f)
414     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
415   for (Module::global_iterator v = mergedModule->global_begin(),
416          e = mergedModule->global_end(); v !=  e; ++v)
417     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
418   for (Module::alias_iterator a = mergedModule->alias_begin(),
419          e = mergedModule->alias_end(); a != e; ++a)
420     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
421
422   GlobalVariable *LLVMCompilerUsed =
423     mergedModule->getGlobalVariable("llvm.compiler.used");
424   findUsedValues(LLVMCompilerUsed, AsmUsed);
425   if (LLVMCompilerUsed)
426     LLVMCompilerUsed->eraseFromParent();
427
428   if (!AsmUsed.empty()) {
429     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
430     std::vector<Constant*> asmUsed2;
431     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
432            e = AsmUsed.end(); i !=e; ++i) {
433       GlobalValue *GV = *i;
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                                           std::string &errMsg) {
462   if (!this->determineTarget(errMsg))
463     return false;
464
465   Module *mergedModule = Linker.getModule();
466
467   // Mark which symbols can not be internalized
468   this->applyScopeRestrictions();
469
470   // Instantiate the pass manager to organize the passes.
471   PassManager passes;
472
473   // Start off with a verification pass.
474   passes.add(createVerifierPass());
475   passes.add(createDebugInfoVerifierPass());
476
477   // Add an appropriate DataLayout instance for this module...
478   mergedModule->setDataLayout(TargetMach->getDataLayout());
479   passes.add(new DataLayoutPass(mergedModule));
480
481   // Add appropriate TargetLibraryInfo for this module.
482   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
483
484   TargetMach->addAnalysisPasses(passes);
485
486   // Enabling internalize here would use its AllButMain variant. It
487   // keeps only main if it exists and does nothing for libraries. Instead
488   // we create the pass ourselves with the symbol list provided by the linker.
489   if (!DisableOpt)
490     PassManagerBuilder().populateLTOPassManager(passes,
491                                               /*Internalize=*/false,
492                                               !DisableInline,
493                                               DisableGVNLoadPRE);
494
495   // Make sure everything is still good.
496   passes.add(createVerifierPass());
497   passes.add(createDebugInfoVerifierPass());
498
499   PassManager codeGenPasses;
500
501   codeGenPasses.add(new DataLayoutPass(mergedModule));
502
503   formatted_raw_ostream Out(out);
504
505   // If the bitcode files contain ARC code and were compiled with optimization,
506   // the ObjCARCContractPass must be run, so do it unconditionally here.
507   codeGenPasses.add(createObjCARCContractPass());
508
509   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
510                                       TargetMachine::CGFT_ObjectFile)) {
511     errMsg = "target file type not supported";
512     return false;
513   }
514
515   // Run our queue of passes all at once now, efficiently.
516   passes.run(*mergedModule);
517
518   // Run the code generator, and write assembly file
519   codeGenPasses.run(*mergedModule);
520
521   return true;
522 }
523
524 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
525 /// LTO problems.
526 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
527   for (std::pair<StringRef, StringRef> o = getToken(options);
528        !o.first.empty(); o = getToken(o.second)) {
529     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
530     // that.
531     if (CodegenOptions.empty())
532       CodegenOptions.push_back(strdup("libLLVMLTO"));
533     CodegenOptions.push_back(strdup(o.first.str().c_str()));
534   }
535 }
536
537 void LTOCodeGenerator::parseCodeGenDebugOptions() {
538   // if options were requested, set them
539   if (!CodegenOptions.empty())
540     cl::ParseCommandLineOptions(CodegenOptions.size(),
541                                 const_cast<char **>(&CodegenOptions[0]));
542 }
543
544 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
545                                          void *Context) {
546   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
547 }
548
549 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
550   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
551   lto_codegen_diagnostic_severity_t Severity;
552   switch (DI.getSeverity()) {
553   case DS_Error:
554     Severity = LTO_DS_ERROR;
555     break;
556   case DS_Warning:
557     Severity = LTO_DS_WARNING;
558     break;
559   case DS_Remark:
560     Severity = LTO_DS_REMARK;
561     break;
562   case DS_Note:
563     Severity = LTO_DS_NOTE;
564     break;
565   }
566   // Create the string that will be reported to the external diagnostic handler.
567   std::string MsgStorage;
568   raw_string_ostream Stream(MsgStorage);
569   DiagnosticPrinterRawOStream DP(Stream);
570   DI.print(DP);
571   Stream.flush();
572
573   // If this method has been called it means someone has set up an external
574   // diagnostic handler. Assert on that.
575   assert(DiagHandler && "Invalid diagnostic handler");
576   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
577 }
578
579 void
580 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
581                                        void *Ctxt) {
582   this->DiagHandler = DiagHandler;
583   this->DiagContext = Ctxt;
584   if (!DiagHandler)
585     return Context.setDiagnosticHandler(nullptr, nullptr);
586   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
587   // diagnostic to the external DiagHandler.
588   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
589 }