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