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