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