much simpler test case
[oota-llvm.git] / tools / lto2 / LTOModule.cpp
1 //===-LTOModule.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
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Support/SystemUtils.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/System/Path.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetMachineRegistry.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29
30
31 #include <fstream>
32
33 using namespace llvm;
34
35 bool LTOModule::isBitcodeFile(const void* mem, size_t length)
36 {
37     return ( llvm::sys::IdentifyFileType((char*)mem, length) 
38                                             == llvm::sys::Bitcode_FileType );
39 }
40
41 bool LTOModule::isBitcodeFile(const char* path)
42 {
43     return llvm::sys::Path(path).isBitcodeFile();
44 }
45
46 bool LTOModule::isBitcodeFileForTarget(const void* mem, 
47                                     size_t length, const char* triplePrefix) 
48 {
49     MemoryBuffer* buffer = MemoryBuffer::getMemBuffer((char*)mem, 
50                                                             (char*)mem+length);
51     if ( buffer == NULL )
52         return false;
53     return isTargetMatch(buffer, triplePrefix);
54 }
55
56
57 bool LTOModule::isBitcodeFileForTarget(const char* path,
58                                                 const char* triplePrefix) 
59 {
60     MemoryBuffer* buffer = MemoryBuffer::getFile(path, strlen(path));
61     if ( buffer == NULL )
62         return false;
63     return isTargetMatch(buffer, triplePrefix);
64 }
65
66 // takes ownership of buffer
67 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
68 {
69     OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer));
70     // on success, mp owns buffer and both are deleted at end of this method
71     if ( !mp ) {
72         delete buffer;
73         return false;
74     }
75     std::string actualTarget = mp->getModule()->getTargetTriple();
76     return ( strncmp(actualTarget.c_str(), triplePrefix, 
77                     strlen(triplePrefix)) == 0);
78 }
79
80
81 LTOModule::LTOModule(Module* m, TargetMachine* t) 
82  : _module(m), _target(t), _symbolsParsed(false)
83 {
84 }
85
86 LTOModule* LTOModule::makeLTOModule(const char* path, std::string& errMsg)
87 {
88     OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(
89                                                 path, strlen(path), &errMsg));
90     if ( !buffer )
91         return NULL;
92     return makeLTOModule(buffer.get(), errMsg);
93 }
94
95 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length, 
96                                                         std::string& errMsg)
97 {
98     OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getMemBuffer((char*)mem, 
99                                                             (char*)mem+length));
100     if ( !buffer )
101         return NULL;
102     return makeLTOModule(buffer.get(), errMsg);
103 }
104
105 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, std::string& errMsg)
106 {
107     // parse bitcode buffer
108     OwningPtr<Module> m(ParseBitcodeFile(buffer, &errMsg));
109     if ( !m )
110         return NULL;
111     // find machine architecture for this module
112     const TargetMachineRegistry::entry* march = 
113             TargetMachineRegistry::getClosestStaticTargetForModule(*m, errMsg);
114     if ( march == NULL ) 
115         return NULL;
116     // construct LTModule, hand over ownership of module and target
117     std::string     features;
118     TargetMachine*  target = march->CtorFn(*m, features);
119     return new LTOModule(m.take(), target);
120 }
121
122
123 const char* LTOModule::getTargetTriple()
124 {
125     return _module->getTargetTriple().c_str();
126 }
127
128 void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
129 {
130     // add to list of defined symbols
131     addDefinedSymbol(f, mangler, true); 
132
133     // add external symbols referenced by this function.
134     for (Function::iterator b = f->begin(); b != f->end(); ++b) {
135         for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
136             for (unsigned count = 0, total = i->getNumOperands(); 
137                                         count != total; ++count) {
138                 findExternalRefs(i->getOperand(count), mangler);
139             }
140         }
141     }
142 }
143
144 void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler &mangler)
145 {    
146     // add to list of defined symbols
147     addDefinedSymbol(v, mangler, false); 
148
149     // add external symbols referenced by this data.
150     for (unsigned count = 0, total = v->getNumOperands();\
151                                                 count != total; ++count) {
152         findExternalRefs(v->getOperand(count), mangler);
153     }
154 }
155
156
157 void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler, 
158                                 bool isFunction)
159 {    
160     // string is owned by _defines
161     const char* symbolName = ::strdup(mangler.getValueName(def).c_str());
162     
163     // set alignment part log2() can have rounding errors
164     uint32_t align = def->getAlignment();
165     uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
166     
167     // set permissions part
168     if ( isFunction )
169         attr |= LTO_SYMBOL_PERMISSIONS_CODE;
170     else {
171         GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
172         if ( (gv != NULL) && gv->isConstant() )
173             attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
174         else
175             attr |= LTO_SYMBOL_PERMISSIONS_DATA;
176     }
177     
178     // set definition part 
179     if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
180         // lvm bitcode does not differenciate between weak def data 
181         // and tentative definitions!
182         // HACK HACK HACK
183         // C++ does not use tentative definitions, but does use weak symbols
184         // so guess that anything that looks like a C++ symbol is weak and others
185         // are tentative definitions
186         if ( (strncmp(symbolName, "__Z", 3) == 0) )
187             attr |= LTO_SYMBOL_DEFINITION_WEAK;
188         else {
189             attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
190         }
191     }
192     else { 
193         attr |= LTO_SYMBOL_DEFINITION_REGULAR;
194     }
195     
196     // set scope part
197     if ( def->hasHiddenVisibility() )
198         attr |= LTO_SYMBOL_SCOPE_HIDDEN;
199     else if ( def->hasExternalLinkage() || def->hasWeakLinkage() )
200         attr |= LTO_SYMBOL_SCOPE_DEFAULT;
201     else
202         attr |= LTO_SYMBOL_SCOPE_INTERNAL;
203
204     // add to table of symbols
205     NameAndAttributes info;
206     info.name = symbolName;
207     info.attributes = (lto_symbol_attributes)attr;
208     _symbols.push_back(info);
209     _defines[info.name] = 1;
210 }
211
212
213 void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
214 {   
215    const char* name = mangler.getValueName(decl).c_str();
216     // ignore all llvm.* symbols
217     if ( strncmp(name, "llvm.", 5) != 0 ) {
218         _undefines[name] = 1;
219     }
220 }
221
222
223
224 // Find exeternal symbols referenced by VALUE. This is a recursive function.
225 void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
226
227     if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
228         if ( !gv->hasExternalLinkage() )
229             addPotentialUndefinedSymbol(gv, mangler);
230     }
231
232     // GlobalValue, even with InternalLinkage type, may have operands with 
233     // ExternalLinkage type. Do not ignore these operands.
234     if (Constant* c = dyn_cast<Constant>(value)) {
235         // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
236         for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
237             findExternalRefs(c->getOperand(i), mangler);
238     }
239 }
240
241 void LTOModule::lazyParseSymbols()
242 {
243     if ( !_symbolsParsed ) {
244         _symbolsParsed = true;
245         
246         // Use mangler to add GlobalPrefix to names to match linker names.
247         Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
248
249         // add functions
250         for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
251             if ( f->isDeclaration() ) 
252                 addPotentialUndefinedSymbol(f, mangler);
253             else 
254                 addDefinedFunctionSymbol(f, mangler);
255         }
256         
257         // add data 
258         for (Module::global_iterator v = _module->global_begin(), 
259                                     e = _module->global_end(); v !=  e; ++v) {
260             if ( v->isDeclaration() ) 
261                 addPotentialUndefinedSymbol(v, mangler);
262             else 
263                 addDefinedDataSymbol(v, mangler);
264         }
265
266         // make symbols for all undefines
267         for (StringSet::iterator it=_undefines.begin(); 
268                                                 it != _undefines.end(); ++it) {
269             // if this symbol also has a definition, then don't make an undefine
270             // because it is a tentative definition
271             if ( _defines.count(it->getKeyData(), it->getKeyData()+
272                                                   it->getKeyLength()) == 0 ) {
273                 NameAndAttributes info;
274                 info.name = it->getKeyData();
275                 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
276                 _symbols.push_back(info);
277             }
278         }
279     }    
280 }
281
282
283 uint32_t LTOModule::getSymbolCount()
284 {
285     lazyParseSymbols();
286     return _symbols.size();
287 }
288
289
290 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
291 {
292     lazyParseSymbols();
293     if ( index < _symbols.size() )
294         return _symbols[index].attributes;
295     else
296         return lto_symbol_attributes(0);
297 }
298
299 const char* LTOModule::getSymbolName(uint32_t index)
300 {
301     lazyParseSymbols();
302     if ( index < _symbols.size() )
303         return _symbols[index].name;
304     else
305         return NULL;
306 }
307