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