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