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