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