Set missing options in LTOCodeGenerator::setTargetOptions.
[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   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 = IRLinker.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   Options.DataSections = options.DataSections;
145   Options.FunctionSections = options.FunctionSections;
146
147   Options.MCOptions = options.MCOptions;
148   Options.JTType = options.JTType;
149 }
150
151 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
152   switch (debug) {
153   case LTO_DEBUG_MODEL_NONE:
154     EmitDwarfDebugInfo = false;
155     return;
156
157   case LTO_DEBUG_MODEL_DWARF:
158     EmitDwarfDebugInfo = true;
159     return;
160   }
161   llvm_unreachable("Unknown debug format!");
162 }
163
164 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
165   switch (model) {
166   case LTO_CODEGEN_PIC_MODEL_STATIC:
167   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
168   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
169   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
170     CodeModel = model;
171     return;
172   }
173   llvm_unreachable("Unknown PIC model!");
174 }
175
176 bool LTOCodeGenerator::writeMergedModules(const char *path,
177                                           std::string &errMsg) {
178   if (!determineTarget(errMsg))
179     return false;
180
181   // mark which symbols can not be internalized
182   applyScopeRestrictions();
183
184   // create output file
185   std::string ErrInfo;
186   tool_output_file Out(path, ErrInfo, sys::fs::F_None);
187   if (!ErrInfo.empty()) {
188     errMsg = "could not open bitcode file for writing: ";
189     errMsg += path;
190     return false;
191   }
192
193   // write bitcode to it
194   WriteBitcodeToFile(IRLinker.getModule(), Out.os());
195   Out.os().close();
196
197   if (Out.os().has_error()) {
198     errMsg = "could not write bitcode file: ";
199     errMsg += path;
200     Out.os().clear_error();
201     return false;
202   }
203
204   Out.keep();
205   return true;
206 }
207
208 bool LTOCodeGenerator::compile_to_file(const char** name,
209                                        bool disableOpt,
210                                        bool disableInline,
211                                        bool disableGVNLoadPRE,
212                                        std::string& errMsg) {
213   // make unique temp .o file to put generated object file
214   SmallString<128> Filename;
215   int FD;
216   std::error_code EC =
217       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
218   if (EC) {
219     errMsg = EC.message();
220     return false;
221   }
222
223   // generate object file
224   tool_output_file objFile(Filename.c_str(), FD);
225
226   bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
227                                       disableGVNLoadPRE, errMsg);
228   objFile.os().close();
229   if (objFile.os().has_error()) {
230     objFile.os().clear_error();
231     sys::fs::remove(Twine(Filename));
232     return false;
233   }
234
235   objFile.keep();
236   if (!genResult) {
237     sys::fs::remove(Twine(Filename));
238     return false;
239   }
240
241   NativeObjectPath = Filename.c_str();
242   *name = NativeObjectPath.c_str();
243   return true;
244 }
245
246 const void* LTOCodeGenerator::compile(size_t* length,
247                                       bool disableOpt,
248                                       bool disableInline,
249                                       bool disableGVNLoadPRE,
250                                       std::string& errMsg) {
251   const char *name;
252   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
253                        errMsg))
254     return nullptr;
255
256   // remove old buffer if compile() called twice
257   delete NativeObjectFile;
258
259   // read .o file into memory buffer
260   std::unique_ptr<MemoryBuffer> BuffPtr;
261   if (std::error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
262     errMsg = ec.message();
263     sys::fs::remove(NativeObjectPath);
264     return nullptr;
265   }
266   NativeObjectFile = BuffPtr.release();
267
268   // remove temp files
269   sys::fs::remove(NativeObjectPath);
270
271   // return buffer, unless error
272   if (!NativeObjectFile)
273     return nullptr;
274   *length = NativeObjectFile->getBufferSize();
275   return NativeObjectFile->getBufferStart();
276 }
277
278 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
279   if (TargetMach)
280     return true;
281
282   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
283   if (TripleStr.empty())
284     TripleStr = sys::getDefaultTargetTriple();
285   llvm::Triple Triple(TripleStr);
286
287   // create target machine from info for merged modules
288   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
289   if (!march)
290     return false;
291
292   // The relocation model is actually a static member of TargetMachine and
293   // needs to be set before the TargetMachine is instantiated.
294   Reloc::Model RelocModel = Reloc::Default;
295   switch (CodeModel) {
296   case LTO_CODEGEN_PIC_MODEL_STATIC:
297     RelocModel = Reloc::Static;
298     break;
299   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
300     RelocModel = Reloc::PIC_;
301     break;
302   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
303     RelocModel = Reloc::DynamicNoPIC;
304     break;
305   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
306     // RelocModel is already the default, so leave it that way.
307     break;
308   }
309
310   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
311   // the default set of features.
312   SubtargetFeatures Features(MAttr);
313   Features.getDefaultSubtargetFeatures(Triple);
314   std::string FeatureStr = Features.getString();
315   // Set a default CPU for Darwin triples.
316   if (MCpu.empty() && Triple.isOSDarwin()) {
317     if (Triple.getArch() == llvm::Triple::x86_64)
318       MCpu = "core2";
319     else if (Triple.getArch() == llvm::Triple::x86)
320       MCpu = "yonah";
321     else if (Triple.getArch() == llvm::Triple::arm64 ||
322              Triple.getArch() == llvm::Triple::aarch64)
323       MCpu = "cyclone";
324   }
325
326   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
327                                           RelocModel, CodeModel::Default,
328                                           CodeGenOpt::Aggressive);
329   return true;
330 }
331
332 void LTOCodeGenerator::
333 applyRestriction(GlobalValue &GV,
334                  const ArrayRef<StringRef> &Libcalls,
335                  std::vector<const char*> &MustPreserveList,
336                  SmallPtrSet<GlobalValue*, 8> &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                            SmallPtrSet<GlobalValue*, 8> &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 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
376                                       const TargetLibraryInfo& TLI,
377                                       const TargetLowering *Lowering)
378 {
379   // TargetLibraryInfo has info on C runtime library calls on the current
380   // target.
381   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
382        I != E; ++I) {
383     LibFunc::Func F = static_cast<LibFunc::Func>(I);
384     if (TLI.has(F))
385       Libcalls.push_back(TLI.getName(F));
386   }
387
388   // TargetLowering has info on library calls that CodeGen expects to be
389   // available, both from the C runtime and compiler-rt.
390   if (Lowering)
391     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
392          I != E; ++I)
393       if (const char *Name
394           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
395         Libcalls.push_back(Name);
396
397   array_pod_sort(Libcalls.begin(), Libcalls.end());
398   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
399                  Libcalls.end());
400 }
401
402 void LTOCodeGenerator::applyScopeRestrictions() {
403   if (ScopeRestrictionsDone)
404     return;
405   Module *mergedModule = IRLinker.getModule();
406
407   // Start off with a verification pass.
408   PassManager passes;
409   passes.add(createVerifierPass());
410   passes.add(createDebugInfoVerifierPass());
411
412   // mark which symbols can not be internalized
413   Mangler Mangler(TargetMach->getDataLayout());
414   std::vector<const char*> MustPreserveList;
415   SmallPtrSet<GlobalValue*, 8> AsmUsed;
416   std::vector<StringRef> Libcalls;
417   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
418   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
419
420   for (Module::iterator f = mergedModule->begin(),
421          e = mergedModule->end(); f != e; ++f)
422     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
423   for (Module::global_iterator v = mergedModule->global_begin(),
424          e = mergedModule->global_end(); v !=  e; ++v)
425     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
426   for (Module::alias_iterator a = mergedModule->alias_begin(),
427          e = mergedModule->alias_end(); a != e; ++a)
428     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
429
430   GlobalVariable *LLVMCompilerUsed =
431     mergedModule->getGlobalVariable("llvm.compiler.used");
432   findUsedValues(LLVMCompilerUsed, AsmUsed);
433   if (LLVMCompilerUsed)
434     LLVMCompilerUsed->eraseFromParent();
435
436   if (!AsmUsed.empty()) {
437     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
438     std::vector<Constant*> asmUsed2;
439     for (auto *GV : AsmUsed) {
440       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
441       asmUsed2.push_back(c);
442     }
443
444     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
445     LLVMCompilerUsed =
446       new llvm::GlobalVariable(*mergedModule, ATy, false,
447                                llvm::GlobalValue::AppendingLinkage,
448                                llvm::ConstantArray::get(ATy, asmUsed2),
449                                "llvm.compiler.used");
450
451     LLVMCompilerUsed->setSection("llvm.metadata");
452   }
453
454   passes.add(createInternalizePass(MustPreserveList));
455
456   // apply scope restrictions
457   passes.run(*mergedModule);
458
459   ScopeRestrictionsDone = true;
460 }
461
462 /// Optimize merged modules using various IPO passes
463 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
464                                           bool DisableOpt,
465                                           bool DisableInline,
466                                           bool DisableGVNLoadPRE,
467                                           std::string &errMsg) {
468   if (!this->determineTarget(errMsg))
469     return false;
470
471   Module *mergedModule = IRLinker.getModule();
472
473   // Mark which symbols can not be internalized
474   this->applyScopeRestrictions();
475
476   // Instantiate the pass manager to organize the passes.
477   PassManager passes;
478
479   // Start off with a verification pass.
480   passes.add(createVerifierPass());
481   passes.add(createDebugInfoVerifierPass());
482
483   // Add an appropriate DataLayout instance for this module...
484   mergedModule->setDataLayout(TargetMach->getDataLayout());
485   passes.add(new DataLayoutPass(mergedModule));
486
487   // Add appropriate TargetLibraryInfo for this module.
488   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
489
490   TargetMach->addAnalysisPasses(passes);
491
492   // Enabling internalize here would use its AllButMain variant. It
493   // keeps only main if it exists and does nothing for libraries. Instead
494   // we create the pass ourselves with the symbol list provided by the linker.
495   if (!DisableOpt)
496     PassManagerBuilder().populateLTOPassManager(passes,
497                                               /*Internalize=*/false,
498                                               !DisableInline,
499                                               DisableGVNLoadPRE);
500
501   // Make sure everything is still good.
502   passes.add(createVerifierPass());
503   passes.add(createDebugInfoVerifierPass());
504
505   PassManager codeGenPasses;
506
507   codeGenPasses.add(new DataLayoutPass(mergedModule));
508
509   formatted_raw_ostream Out(out);
510
511   // If the bitcode files contain ARC code and were compiled with optimization,
512   // the ObjCARCContractPass must be run, so do it unconditionally here.
513   codeGenPasses.add(createObjCARCContractPass());
514
515   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
516                                       TargetMachine::CGFT_ObjectFile)) {
517     errMsg = "target file type not supported";
518     return false;
519   }
520
521   // Run our queue of passes all at once now, efficiently.
522   passes.run(*mergedModule);
523
524   // Run the code generator, and write assembly file
525   codeGenPasses.run(*mergedModule);
526
527   return true;
528 }
529
530 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
531 /// LTO problems.
532 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
533   for (std::pair<StringRef, StringRef> o = getToken(options);
534        !o.first.empty(); o = getToken(o.second)) {
535     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
536     // that.
537     if (CodegenOptions.empty())
538       CodegenOptions.push_back(strdup("libLLVMLTO"));
539     CodegenOptions.push_back(strdup(o.first.str().c_str()));
540   }
541 }
542
543 void LTOCodeGenerator::parseCodeGenDebugOptions() {
544   // if options were requested, set them
545   if (!CodegenOptions.empty())
546     cl::ParseCommandLineOptions(CodegenOptions.size(),
547                                 const_cast<char **>(&CodegenOptions[0]));
548 }
549
550 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
551                                          void *Context) {
552   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
553 }
554
555 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
556   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
557   lto_codegen_diagnostic_severity_t Severity;
558   switch (DI.getSeverity()) {
559   case DS_Error:
560     Severity = LTO_DS_ERROR;
561     break;
562   case DS_Warning:
563     Severity = LTO_DS_WARNING;
564     break;
565   case DS_Remark:
566     Severity = LTO_DS_REMARK;
567     break;
568   case DS_Note:
569     Severity = LTO_DS_NOTE;
570     break;
571   }
572   // Create the string that will be reported to the external diagnostic handler.
573   std::string MsgStorage;
574   raw_string_ostream Stream(MsgStorage);
575   DiagnosticPrinterRawOStream DP(Stream);
576   DI.print(DP);
577   Stream.flush();
578
579   // If this method has been called it means someone has set up an external
580   // diagnostic handler. Assert on that.
581   assert(DiagHandler && "Invalid diagnostic handler");
582   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
583 }
584
585 void
586 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
587                                        void *Ctxt) {
588   this->DiagHandler = DiagHandler;
589   this->DiagContext = Ctxt;
590   if (!DiagHandler)
591     return Context.setDiagnosticHandler(nullptr, nullptr);
592   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
593   // diagnostic to the external DiagHandler.
594   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
595 }