]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tools/lto/LTOCodeGenerator.cpp
Import LLVM, at r72805, which fixes PR4315 and PR4316.
[FreeBSD/FreeBSD.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
19 #include "llvm/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/StandardPasses.h"
30 #include "llvm/Support/SystemUtils.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/System/Signals.h"
33 #include "llvm/Analysis/Passes.h"
34 #include "llvm/Analysis/LoopPass.h"
35 #include "llvm/Analysis/Verifier.h"
36 #include "llvm/CodeGen/FileWriters.h"
37 #include "llvm/Target/SubtargetFeature.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetMachineRegistry.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Transforms/IPO.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Config/config.h"
47
48
49 #include <fstream>
50 #include <unistd.h>
51 #include <stdlib.h>
52 #include <fcntl.h>
53
54
55 using namespace llvm;
56
57 static cl::opt<bool> DisableInline("disable-inlining",
58   cl::desc("Do not run the inliner pass"));
59
60
61 const char* LTOCodeGenerator::getVersionString()
62 {
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
71 LTOCodeGenerator::LTOCodeGenerator() 
72     : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
73       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
74       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
75       _nativeObjectFile(NULL), _gccPath(NULL)
76 {
77
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     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
91 }
92     
93
94 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
95 {
96     switch (debug) {
97         case LTO_DEBUG_MODEL_NONE:
98             _emitDwarfDebugInfo = false;
99             return false;
100             
101         case LTO_DEBUG_MODEL_DWARF:
102             _emitDwarfDebugInfo = true;
103             return false;
104     }
105     errMsg = "unknown debug format";
106     return true;
107 }
108
109
110 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
111                                                         std::string& errMsg)
112 {
113     switch (model) {
114         case LTO_CODEGEN_PIC_MODEL_STATIC:
115         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
116         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
117             _codeModel = model;
118             return false;
119     }
120     errMsg = "unknown pic model";
121     return true;
122 }
123
124 void LTOCodeGenerator::setGccPath(const char* path)
125 {
126     if ( _gccPath )
127         delete _gccPath;
128     _gccPath = new sys::Path(path);
129 }
130
131 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
132 {
133     _mustPreserveSymbols[sym] = 1;
134 }
135
136
137 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
138 {
139     if ( this->determineTarget(errMsg) ) 
140         return true;
141
142     // mark which symbols can not be internalized 
143     this->applyScopeRestrictions();
144
145     // create output file
146     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
147     if ( out.fail() ) {
148         errMsg = "could not open bitcode file for writing: ";
149         errMsg += path;
150         return true;
151     }
152     
153     // write bitcode to it
154     WriteBitcodeToFile(_linker.getModule(), out);
155     if ( out.fail() ) {
156         errMsg = "could not write bitcode file: ";
157         errMsg += path;
158         return true;
159     }
160     
161     return false;
162 }
163
164
165 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
166 {
167     // make unique temp .s file to put generated assembly code
168     sys::Path uniqueAsmPath("lto-llvm.s");
169     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
170         return NULL;
171     sys::RemoveFileOnSignal(uniqueAsmPath);
172        
173     // generate assembly code
174     bool genResult = false;
175     {
176       raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
177       if (!errMsg.empty())
178         return NULL;
179       genResult = this->generateAssemblyCode(asmFile, errMsg);
180     }
181     if ( genResult ) {
182         if ( uniqueAsmPath.exists() )
183             uniqueAsmPath.eraseFromDisk();
184         return NULL;
185     }
186     
187     // make unique temp .o file to put generated object file
188     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
189     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
190         if ( uniqueAsmPath.exists() )
191             uniqueAsmPath.eraseFromDisk();
192         return NULL;
193     }
194     sys::RemoveFileOnSignal(uniqueObjPath);
195
196     // assemble the assembly code
197     const std::string& uniqueObjStr = uniqueObjPath.toString();
198     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
199                                                         uniqueObjStr, errMsg);
200     if ( !asmResult ) {
201         // remove old buffer if compile() called twice
202         delete _nativeObjectFile;
203         
204         // read .o file into memory buffer
205         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
206     }
207
208     // remove temp files
209     uniqueAsmPath.eraseFromDisk();
210     uniqueObjPath.eraseFromDisk();
211
212     // return buffer, unless error
213     if ( _nativeObjectFile == NULL )
214         return NULL;
215     *length = _nativeObjectFile->getBufferSize();
216     return _nativeObjectFile->getBufferStart();
217 }
218
219
220 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
221                                 const std::string& objPath, std::string& errMsg)
222 {
223     sys::Path gcc;
224     if ( _gccPath ) {
225         gcc = *_gccPath;
226     } else {
227         // find compiler driver
228         gcc = sys::Program::FindProgramByName("gcc");
229         if ( gcc.isEmpty() ) {
230             errMsg = "can't locate gcc";
231             return true;
232         }
233     }
234
235     // build argument list
236     std::vector<const char*> args;
237     std::string targetTriple = _linker.getModule()->getTargetTriple();
238     args.push_back(gcc.c_str());
239     if ( targetTriple.find("darwin") != targetTriple.size() ) {
240         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
241             args.push_back("-arch");
242             args.push_back("i386");
243         }
244         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
245             args.push_back("-arch");
246             args.push_back("x86_64");
247         }
248         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
249             args.push_back("-arch");
250             args.push_back("ppc");
251         }
252         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
253             args.push_back("-arch");
254             args.push_back("ppc64");
255         }
256         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
257             args.push_back("-arch");
258             args.push_back("arm");
259         }
260         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
261                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
262             args.push_back("-arch");
263             args.push_back("armv4t");
264         }
265         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
266                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
267                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
268                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
269             args.push_back("-arch");
270             args.push_back("armv5");
271         }
272         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
273                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
274             args.push_back("-arch");
275             args.push_back("armv6");
276         }
277     }
278     args.push_back("-c");
279     args.push_back("-x");
280     args.push_back("assembler");
281     args.push_back("-o");
282     args.push_back(objPath.c_str());
283     args.push_back(asmPath.c_str());
284     args.push_back(0);
285
286     // invoke assembler
287     if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
288         errMsg = "error in assembly";    
289         return true;
290     }
291     return false; // success
292 }
293
294
295
296 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
297 {
298     if ( _target == NULL ) {
299         // create target machine from info for merged modules
300         Module* mergedModule = _linker.getModule();
301         const TargetMachineRegistry::entry* march = 
302           TargetMachineRegistry::getClosestStaticTargetForModule(
303                                                        *mergedModule, errMsg);
304         if ( march == NULL )
305             return true;
306
307         // construct LTModule, hand over ownership of module and target
308         std::string FeatureStr =
309           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
310         _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
311     }
312     return false;
313 }
314
315 void LTOCodeGenerator::applyScopeRestrictions()
316 {
317     if ( !_scopeRestrictionsDone ) {
318         Module* mergedModule = _linker.getModule();
319
320         // Start off with a verification pass.
321         PassManager passes;
322         passes.add(createVerifierPass());
323
324         // mark which symbols can not be internalized 
325         if ( !_mustPreserveSymbols.empty() ) {
326             Mangler mangler(*mergedModule, 
327                                 _target->getTargetAsmInfo()->getGlobalPrefix());
328             std::vector<const char*> mustPreserveList;
329             for (Module::iterator f = mergedModule->begin(), 
330                                         e = mergedModule->end(); f != e; ++f) {
331                 if ( !f->isDeclaration() 
332                   && _mustPreserveSymbols.count(mangler.getValueName(f)) )
333                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
334             }
335             for (Module::global_iterator v = mergedModule->global_begin(), 
336                                  e = mergedModule->global_end(); v !=  e; ++v) {
337                 if ( !v->isDeclaration()
338                   && _mustPreserveSymbols.count(mangler.getValueName(v)) )
339                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
340             }
341             passes.add(createInternalizePass(mustPreserveList));
342         }
343         // apply scope restrictions
344         passes.run(*mergedModule);
345         
346         _scopeRestrictionsDone = true;
347     }
348 }
349
350 /// Optimize merged modules using various IPO passes
351 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
352                                             std::string& errMsg)
353 {
354     if (  this->determineTarget(errMsg) ) 
355         return true;
356
357     // mark which symbols can not be internalized 
358     this->applyScopeRestrictions();
359
360     Module* mergedModule = _linker.getModule();
361
362      // If target supports exception handling then enable it now.
363     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
364         llvm::ExceptionHandling = true;
365
366     // set codegen model
367     switch( _codeModel ) {
368         case LTO_CODEGEN_PIC_MODEL_STATIC:
369             _target->setRelocationModel(Reloc::Static);
370             break;
371         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
372             _target->setRelocationModel(Reloc::PIC_);
373             break;
374         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
375             _target->setRelocationModel(Reloc::DynamicNoPIC);
376             break;
377     }
378
379     // if options were requested, set them
380     if ( !_codegenOptions.empty() )
381         cl::ParseCommandLineOptions(_codegenOptions.size(), 
382                                                 (char**)&_codegenOptions[0]);
383
384     // Instantiate the pass manager to organize the passes.
385     PassManager passes;
386
387     // Start off with a verification pass.
388     passes.add(createVerifierPass());
389
390     // Add an appropriate TargetData instance for this module...
391     passes.add(new TargetData(*_target->getTargetData()));
392     
393     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
394                             /*RunSecondGlobalOpt=*/ false, 
395                             /*VerifyEach=*/ false);
396
397     // Make sure everything is still good.
398     passes.add(createVerifierPass());
399
400     FunctionPassManager* codeGenPasses =
401             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
402
403     codeGenPasses->add(new TargetData(*_target->getTargetData()));
404
405     MachineCodeEmitter* mce = NULL;
406
407     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
408                                          TargetMachine::AssemblyFile,
409                                          CodeGenOpt::Aggressive)) {
410         case FileModel::MachOFile:
411             mce = AddMachOWriter(*codeGenPasses, out, *_target);
412             break;
413         case FileModel::ElfFile:
414             mce = AddELFWriter(*codeGenPasses, out, *_target);
415             break;
416         case FileModel::AsmFile:
417             break;
418         case FileModel::Error:
419         case FileModel::None:
420             errMsg = "target file type not supported";
421             return true;
422     }
423
424     if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
425                                            CodeGenOpt::Aggressive)) {
426         errMsg = "target does not support generation of this file type";
427         return true;
428     }
429
430     // Run our queue of passes all at once now, efficiently.
431     passes.run(*mergedModule);
432
433     // Run the code generator, and write assembly file
434     codeGenPasses->doInitialization();
435
436     for (Module::iterator
437            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
438       if (!it->isDeclaration())
439         codeGenPasses->run(*it);
440
441     codeGenPasses->doFinalization();
442     return false; // success
443 }
444
445
446 /// Optimize merged modules using various IPO passes
447 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
448 {
449     std::string ops(options);
450     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
451         // ParseCommandLineOptions() expects argv[0] to be program name.
452         // Lazily add that.
453         if ( _codegenOptions.empty() ) 
454             _codegenOptions.push_back("libLTO");
455         _codegenOptions.push_back(strdup(o.c_str()));
456     }
457 }