Revert "Reapply "LTO: add API to set strategy for -internalize""
[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(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
68       CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL),
69       DiagHandler(NULL), DiagContext(NULL) {
70   initializeLTOPasses();
71 }
72
73 LTOCodeGenerator::~LTOCodeGenerator() {
74   delete TargetMach;
75   delete NativeObjectFile;
76   TargetMach = NULL;
77   NativeObjectFile = NULL;
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.EnableSegmentedStacks = options.EnableSegmentedStacks;
144   Options.UseInitArray = options.UseInitArray;
145 }
146
147 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
148   switch (debug) {
149   case LTO_DEBUG_MODEL_NONE:
150     EmitDwarfDebugInfo = false;
151     return;
152
153   case LTO_DEBUG_MODEL_DWARF:
154     EmitDwarfDebugInfo = true;
155     return;
156   }
157   llvm_unreachable("Unknown debug format!");
158 }
159
160 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
161   switch (model) {
162   case LTO_CODEGEN_PIC_MODEL_STATIC:
163   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
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 NULL;
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 NULL;
259   }
260   NativeObjectFile = BuffPtr.release();
261
262   // remove temp files
263   sys::fs::remove(NativeObjectPath);
264
265   // return buffer, unless error
266   if (NativeObjectFile == NULL)
267     return NULL;
268   *length = NativeObjectFile->getBufferSize();
269   return NativeObjectFile->getBufferStart();
270 }
271
272 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
273   if (TargetMach != NULL)
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 == NULL)
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   }
300
301   // construct LTOModule, hand over ownership of module and target
302   SubtargetFeatures Features;
303   Features.getDefaultSubtargetFeatures(Triple);
304   std::string FeatureStr = Features.getString();
305   // Set a default CPU for Darwin triples.
306   if (MCpu.empty() && Triple.isOSDarwin()) {
307     if (Triple.getArch() == llvm::Triple::x86_64)
308       MCpu = "core2";
309     else if (Triple.getArch() == llvm::Triple::x86)
310       MCpu = "yonah";
311     else if (Triple.getArch() == llvm::Triple::arm64)
312       MCpu = "cyclone";
313   }
314
315   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
316                                           RelocModel, CodeModel::Default,
317                                           CodeGenOpt::Aggressive);
318   return true;
319 }
320
321 void LTOCodeGenerator::
322 applyRestriction(GlobalValue &GV,
323                  const ArrayRef<StringRef> &Libcalls,
324                  std::vector<const char*> &MustPreserveList,
325                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
326                  Mangler &Mangler) {
327   // There are no restrictions to apply to declarations.
328   if (GV.isDeclaration())
329     return;
330
331   // There is nothing more restrictive than private linkage.
332   if (GV.hasPrivateLinkage())
333     return;
334
335   SmallString<64> Buffer;
336   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
337
338   if (MustPreserveSymbols.count(Buffer))
339     MustPreserveList.push_back(GV.getName().data());
340   if (AsmUndefinedRefs.count(Buffer))
341     AsmUsed.insert(&GV);
342
343   // Conservatively append user-supplied runtime library functions to
344   // llvm.compiler.used.  These could be internalized and deleted by
345   // optimizations like -globalopt, causing problems when later optimizations
346   // add new library calls (e.g., llvm.memset => memset and printf => puts).
347   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
348   if (isa<Function>(GV) &&
349       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
350     AsmUsed.insert(&GV);
351 }
352
353 static void findUsedValues(GlobalVariable *LLVMUsed,
354                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
355   if (LLVMUsed == 0) return;
356
357   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
358   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
359     if (GlobalValue *GV =
360         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
361       UsedValues.insert(GV);
362 }
363
364 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
365                                       const TargetLibraryInfo& TLI,
366                                       const TargetLowering *Lowering)
367 {
368   // TargetLibraryInfo has info on C runtime library calls on the current
369   // target.
370   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
371        I != E; ++I) {
372     LibFunc::Func F = static_cast<LibFunc::Func>(I);
373     if (TLI.has(F))
374       Libcalls.push_back(TLI.getName(F));
375   }
376
377   // TargetLowering has info on library calls that CodeGen expects to be
378   // available, both from the C runtime and compiler-rt.
379   if (Lowering)
380     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
381          I != E; ++I)
382       if (const char *Name
383           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
384         Libcalls.push_back(Name);
385
386   array_pod_sort(Libcalls.begin(), Libcalls.end());
387   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
388                  Libcalls.end());
389 }
390
391 void LTOCodeGenerator::applyScopeRestrictions() {
392   if (ScopeRestrictionsDone)
393     return;
394   Module *mergedModule = Linker.getModule();
395
396   // Start off with a verification pass.
397   PassManager passes;
398   passes.add(createVerifierPass());
399
400   // mark which symbols can not be internalized
401   Mangler Mangler(TargetMach->getDataLayout());
402   std::vector<const char*> MustPreserveList;
403   SmallPtrSet<GlobalValue*, 8> AsmUsed;
404   std::vector<StringRef> Libcalls;
405   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
406   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
407
408   for (Module::iterator f = mergedModule->begin(),
409          e = mergedModule->end(); f != e; ++f)
410     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
411   for (Module::global_iterator v = mergedModule->global_begin(),
412          e = mergedModule->global_end(); v !=  e; ++v)
413     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
414   for (Module::alias_iterator a = mergedModule->alias_begin(),
415          e = mergedModule->alias_end(); a != e; ++a)
416     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
417
418   GlobalVariable *LLVMCompilerUsed =
419     mergedModule->getGlobalVariable("llvm.compiler.used");
420   findUsedValues(LLVMCompilerUsed, AsmUsed);
421   if (LLVMCompilerUsed)
422     LLVMCompilerUsed->eraseFromParent();
423
424   if (!AsmUsed.empty()) {
425     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
426     std::vector<Constant*> asmUsed2;
427     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
428            e = AsmUsed.end(); i !=e; ++i) {
429       GlobalValue *GV = *i;
430       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
431       asmUsed2.push_back(c);
432     }
433
434     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
435     LLVMCompilerUsed =
436       new llvm::GlobalVariable(*mergedModule, ATy, false,
437                                llvm::GlobalValue::AppendingLinkage,
438                                llvm::ConstantArray::get(ATy, asmUsed2),
439                                "llvm.compiler.used");
440
441     LLVMCompilerUsed->setSection("llvm.metadata");
442   }
443
444   passes.add(createInternalizePass(MustPreserveList));
445
446   // apply scope restrictions
447   passes.run(*mergedModule);
448
449   ScopeRestrictionsDone = true;
450 }
451
452 /// Optimize merged modules using various IPO passes
453 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
454                                           bool DisableOpt,
455                                           bool DisableInline,
456                                           bool DisableGVNLoadPRE,
457                                           std::string &errMsg) {
458   if (!this->determineTarget(errMsg))
459     return false;
460
461   Module *mergedModule = Linker.getModule();
462
463   // Mark which symbols can not be internalized
464   this->applyScopeRestrictions();
465
466   // Instantiate the pass manager to organize the passes.
467   PassManager passes;
468
469   // Start off with a verification pass.
470   passes.add(createVerifierPass());
471
472   // Add an appropriate DataLayout instance for this module...
473   mergedModule->setDataLayout(TargetMach->getDataLayout());
474   passes.add(new DataLayoutPass(mergedModule));
475
476   // Add appropriate TargetLibraryInfo for this module.
477   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
478
479   TargetMach->addAnalysisPasses(passes);
480
481   // Enabling internalize here would use its AllButMain variant. It
482   // keeps only main if it exists and does nothing for libraries. Instead
483   // we create the pass ourselves with the symbol list provided by the linker.
484   if (!DisableOpt)
485     PassManagerBuilder().populateLTOPassManager(passes,
486                                               /*Internalize=*/false,
487                                               !DisableInline,
488                                               DisableGVNLoadPRE);
489
490   // Make sure everything is still good.
491   passes.add(createVerifierPass());
492
493   PassManager codeGenPasses;
494
495   codeGenPasses.add(new DataLayoutPass(mergedModule));
496
497   formatted_raw_ostream Out(out);
498
499   // If the bitcode files contain ARC code and were compiled with optimization,
500   // the ObjCARCContractPass must be run, so do it unconditionally here.
501   codeGenPasses.add(createObjCARCContractPass());
502
503   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
504                                       TargetMachine::CGFT_ObjectFile)) {
505     errMsg = "target file type not supported";
506     return false;
507   }
508
509   // Run our queue of passes all at once now, efficiently.
510   passes.run(*mergedModule);
511
512   // Run the code generator, and write assembly file
513   codeGenPasses.run(*mergedModule);
514
515   return true;
516 }
517
518 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
519 /// LTO problems.
520 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
521   for (std::pair<StringRef, StringRef> o = getToken(options);
522        !o.first.empty(); o = getToken(o.second)) {
523     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
524     // that.
525     if (CodegenOptions.empty())
526       CodegenOptions.push_back(strdup("libLLVMLTO"));
527     CodegenOptions.push_back(strdup(o.first.str().c_str()));
528   }
529 }
530
531 void LTOCodeGenerator::parseCodeGenDebugOptions() {
532   // if options were requested, set them
533   if (!CodegenOptions.empty())
534     cl::ParseCommandLineOptions(CodegenOptions.size(),
535                                 const_cast<char **>(&CodegenOptions[0]));
536 }
537
538 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
539                                          void *Context) {
540   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
541 }
542
543 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
544   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
545   lto_codegen_diagnostic_severity_t Severity;
546   switch (DI.getSeverity()) {
547   case DS_Error:
548     Severity = LTO_DS_ERROR;
549     break;
550   case DS_Warning:
551     Severity = LTO_DS_WARNING;
552     break;
553   case DS_Remark:
554     Severity = LTO_DS_REMARK;
555     break;
556   case DS_Note:
557     Severity = LTO_DS_NOTE;
558     break;
559   }
560   // Create the string that will be reported to the external diagnostic handler.
561   std::string MsgStorage;
562   raw_string_ostream Stream(MsgStorage);
563   DiagnosticPrinterRawOStream DP(Stream);
564   DI.print(DP);
565   Stream.flush();
566
567   // If this method has been called it means someone has set up an external
568   // diagnostic handler. Assert on that.
569   assert(DiagHandler && "Invalid diagnostic handler");
570   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
571 }
572
573 void
574 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
575                                        void *Ctxt) {
576   this->DiagHandler = DiagHandler;
577   this->DiagContext = Ctxt;
578   if (!DiagHandler)
579     return Context.setDiagnosticHandler(NULL, NULL);
580   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
581   // diagnostic to the external DiagHandler.
582   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
583 }