6626eaac47a8a7ab44d206cc1a0ecda04cb7bbf4
[oota-llvm.git] / tools / lto / 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 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 using namespace llvm;
41
42 static cl::opt<bool>
43 EnableFPMAD("enable-fp-mad",
44   cl::desc("Enable less precise MAD instructions to be generated"),
45   cl::init(false));
46
47 static cl::opt<bool>
48 DisableFPElim("disable-fp-elim",
49   cl::desc("Disable frame pointer elimination optimization"),
50   cl::init(false));
51
52 static cl::opt<bool>
53 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
54   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
55   cl::init(false));
56
57 static cl::opt<bool>
58 EnableUnsafeFPMath("enable-unsafe-fp-math",
59   cl::desc("Enable optimizations that may decrease FP precision"),
60   cl::init(false));
61
62 static cl::opt<bool>
63 EnableNoInfsFPMath("enable-no-infs-fp-math",
64   cl::desc("Enable FP math optimizations that assume no +-Infs"),
65   cl::init(false));
66
67 static cl::opt<bool>
68 EnableNoNaNsFPMath("enable-no-nans-fp-math",
69   cl::desc("Enable FP math optimizations that assume no NaNs"),
70   cl::init(false));
71
72 static cl::opt<bool>
73 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
74   cl::Hidden,
75   cl::desc("Force codegen to assume rounding mode can change dynamically"),
76   cl::init(false));
77
78 static cl::opt<bool>
79 GenerateSoftFloatCalls("soft-float",
80   cl::desc("Generate software floating point library calls"),
81   cl::init(false));
82
83 static cl::opt<llvm::FloatABI::ABIType>
84 FloatABIForCalls("float-abi",
85   cl::desc("Choose float ABI type"),
86   cl::init(FloatABI::Default),
87   cl::values(
88     clEnumValN(FloatABI::Default, "default",
89                "Target default float ABI type"),
90     clEnumValN(FloatABI::Soft, "soft",
91                "Soft float ABI (implied by -soft-float)"),
92     clEnumValN(FloatABI::Hard, "hard",
93                "Hard float ABI (uses FP registers)"),
94     clEnumValEnd));
95
96 static cl::opt<llvm::FPOpFusion::FPOpFusionMode>
97 FuseFPOps("fp-contract",
98   cl::desc("Enable aggresive formation of fused FP ops"),
99   cl::init(FPOpFusion::Standard),
100   cl::values(
101     clEnumValN(FPOpFusion::Fast, "fast",
102                "Fuse FP ops whenever profitable"),
103     clEnumValN(FPOpFusion::Standard, "on",
104                "Only fuse 'blessed' FP ops."),
105     clEnumValN(FPOpFusion::Strict, "off",
106                "Only fuse FP ops when the result won't be effected."),
107     clEnumValEnd));
108
109 static cl::opt<bool>
110 DontPlaceZerosInBSS("nozero-initialized-in-bss",
111   cl::desc("Don't place zero-initialized symbols into bss section"),
112   cl::init(false));
113
114 static cl::opt<bool>
115 EnableGuaranteedTailCallOpt("tailcallopt",
116   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
117   cl::init(false));
118
119 static cl::opt<bool>
120 DisableTailCalls("disable-tail-calls",
121   cl::desc("Never emit tail calls"),
122   cl::init(false));
123
124 static cl::opt<unsigned>
125 OverrideStackAlignment("stack-alignment",
126   cl::desc("Override default stack alignment"),
127   cl::init(0));
128
129 static cl::opt<bool>
130 EnableRealignStack("realign-stack",
131   cl::desc("Realign stack if needed"),
132   cl::init(true));
133
134 static cl::opt<std::string>
135 TrapFuncName("trap-func", cl::Hidden,
136   cl::desc("Emit a call to trap function rather than a trap instruction"),
137   cl::init(""));
138
139 static cl::opt<bool>
140 EnablePIE("enable-pie",
141   cl::desc("Assume the creation of a position independent executable."),
142   cl::init(false));
143
144 static cl::opt<bool>
145 SegmentedStacks("segmented-stacks",
146   cl::desc("Use segmented stacks if possible."),
147   cl::init(false));
148
149 static cl::opt<bool>
150 UseInitArray("use-init-array",
151   cl::desc("Use .init_array instead of .ctors."),
152   cl::init(false));
153
154 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
155   : _module(m), _target(t),
156     _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
157     _mangler(_context, t) {}
158
159 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
160 /// bitcode.
161 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
162   return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
163          sys::fs::file_magic::bitcode;
164 }
165
166 bool LTOModule::isBitcodeFile(const char *path) {
167   sys::fs::file_magic type;
168   if (sys::fs::identify_magic(path, type))
169     return false;
170   return type == sys::fs::file_magic::bitcode;
171 }
172
173 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
174 /// LLVM bitcode for the specified triple.
175 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
176                                        const char *triplePrefix) {
177   MemoryBuffer *buffer = makeBuffer(mem, length);
178   if (!buffer)
179     return false;
180   return isTargetMatch(buffer, triplePrefix);
181 }
182
183 bool LTOModule::isBitcodeFileForTarget(const char *path,
184                                        const char *triplePrefix) {
185   OwningPtr<MemoryBuffer> buffer;
186   if (MemoryBuffer::getFile(path, buffer))
187     return false;
188   return isTargetMatch(buffer.take(), triplePrefix);
189 }
190
191 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
192 /// target triple.
193 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
194   std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
195   delete buffer;
196   return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
197 }
198
199 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
200 /// the buffer.
201 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
202   OwningPtr<MemoryBuffer> buffer;
203   if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
204     errMsg = ec.message();
205     return NULL;
206   }
207   return makeLTOModule(buffer.take(), errMsg);
208 }
209
210 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
211                                     size_t size, std::string &errMsg) {
212   return makeLTOModule(fd, path, size, 0, errMsg);
213 }
214
215 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
216                                     size_t map_size,
217                                     off_t offset,
218                                     std::string &errMsg) {
219   OwningPtr<MemoryBuffer> buffer;
220   if (error_code ec =
221           MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
222     errMsg = ec.message();
223     return NULL;
224   }
225   return makeLTOModule(buffer.take(), errMsg);
226 }
227
228 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
229                                     std::string &errMsg) {
230   OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
231   if (!buffer)
232     return NULL;
233   return makeLTOModule(buffer.take(), errMsg);
234 }
235
236 void LTOModule::getTargetOptions(TargetOptions &Options) {
237   Options.LessPreciseFPMADOption = EnableFPMAD;
238   Options.NoFramePointerElim = DisableFPElim;
239   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
240   Options.AllowFPOpFusion = FuseFPOps;
241   Options.UnsafeFPMath = EnableUnsafeFPMath;
242   Options.NoInfsFPMath = EnableNoInfsFPMath;
243   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
244   Options.HonorSignDependentRoundingFPMathOption =
245     EnableHonorSignDependentRoundingFPMath;
246   Options.UseSoftFloat = GenerateSoftFloatCalls;
247   if (FloatABIForCalls != FloatABI::Default)
248     Options.FloatABIType = FloatABIForCalls;
249   Options.NoZerosInBSS = DontPlaceZerosInBSS;
250   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
251   Options.DisableTailCalls = DisableTailCalls;
252   Options.StackAlignmentOverride = OverrideStackAlignment;
253   Options.RealignStack = EnableRealignStack;
254   Options.TrapFuncName = TrapFuncName;
255   Options.PositionIndependentExecutable = EnablePIE;
256   Options.EnableSegmentedStacks = SegmentedStacks;
257   Options.UseInitArray = UseInitArray;
258 }
259
260 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
261                                     std::string &errMsg) {
262   static bool Initialized = false;
263   if (!Initialized) {
264     InitializeAllTargets();
265     InitializeAllTargetMCs();
266     InitializeAllAsmParsers();
267     Initialized = true;
268   }
269
270   // parse bitcode buffer
271   OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(),
272                                            &errMsg));
273   if (!m) {
274     delete buffer;
275     return NULL;
276   }
277
278   std::string TripleStr = m->getTargetTriple();
279   if (TripleStr.empty())
280     TripleStr = sys::getDefaultTargetTriple();
281   llvm::Triple Triple(TripleStr);
282
283   // find machine architecture for this module
284   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
285   if (!march)
286     return NULL;
287
288   // construct LTOModule, hand over ownership of module and target
289   SubtargetFeatures Features;
290   Features.getDefaultSubtargetFeatures(Triple);
291   std::string FeatureStr = Features.getString();
292   // Set a default CPU for Darwin triples.
293   std::string CPU;
294   if (Triple.isOSDarwin()) {
295     if (Triple.getArch() == llvm::Triple::x86_64)
296       CPU = "core2";
297     else if (Triple.getArch() == llvm::Triple::x86)
298       CPU = "yonah";
299   }
300   TargetOptions Options;
301   getTargetOptions(Options);
302   TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
303                                                      Options);
304   LTOModule *Ret = new LTOModule(m.take(), target);
305   if (Ret->parseSymbols(errMsg)) {
306     delete Ret;
307     return NULL;
308   }
309
310   return Ret;
311 }
312
313 /// makeBuffer - Create a MemoryBuffer from a memory range.
314 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
315   const char *startPtr = (const char*)mem;
316   return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
317 }
318
319 /// objcClassNameFromExpression - Get string that the data pointer points to.
320 bool
321 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
322   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
323     Constant *op = ce->getOperand(0);
324     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
325       Constant *cn = gvn->getInitializer();
326       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
327         if (ca->isCString()) {
328           name = ".objc_class_name_" + ca->getAsCString().str();
329           return true;
330         }
331       }
332     }
333   }
334   return false;
335 }
336
337 /// addObjCClass - Parse i386/ppc ObjC class data structure.
338 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
339   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
340   if (!c) return;
341
342   // second slot in __OBJC,__class is pointer to superclass name
343   std::string superclassName;
344   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
345     NameAndAttributes info;
346     StringMap<NameAndAttributes>::value_type &entry =
347       _undefines.GetOrCreateValue(superclassName);
348     if (!entry.getValue().name) {
349       const char *symbolName = entry.getKey().data();
350       info.name = symbolName;
351       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
352       info.isFunction = false;
353       info.symbol = clgv;
354       entry.setValue(info);
355     }
356   }
357
358   // third slot in __OBJC,__class is pointer to class name
359   std::string className;
360   if (objcClassNameFromExpression(c->getOperand(2), className)) {
361     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
362     entry.setValue(1);
363
364     NameAndAttributes info;
365     info.name = entry.getKey().data();
366     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
367       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
368     info.isFunction = false;
369     info.symbol = clgv;
370     _symbols.push_back(info);
371   }
372 }
373
374 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
375 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
376   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
377   if (!c) return;
378
379   // second slot in __OBJC,__category is pointer to target class name
380   std::string targetclassName;
381   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
382     return;
383
384   NameAndAttributes info;
385   StringMap<NameAndAttributes>::value_type &entry =
386     _undefines.GetOrCreateValue(targetclassName);
387
388   if (entry.getValue().name)
389     return;
390
391   const char *symbolName = entry.getKey().data();
392   info.name = symbolName;
393   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
394   info.isFunction = false;
395   info.symbol = clgv;
396   entry.setValue(info);
397 }
398
399 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
400 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
401   std::string targetclassName;
402   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
403     return;
404
405   NameAndAttributes info;
406   StringMap<NameAndAttributes>::value_type &entry =
407     _undefines.GetOrCreateValue(targetclassName);
408   if (entry.getValue().name)
409     return;
410
411   const char *symbolName = entry.getKey().data();
412   info.name = symbolName;
413   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
414   info.isFunction = false;
415   info.symbol = clgv;
416   entry.setValue(info);
417 }
418
419 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
420 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
421   // Add to list of defined symbols.
422   addDefinedSymbol(v, false);
423
424   if (!v->hasSection() /* || !isTargetDarwin */)
425     return;
426
427   // Special case i386/ppc ObjC data structures in magic sections:
428   // The issue is that the old ObjC object format did some strange
429   // contortions to avoid real linker symbols.  For instance, the
430   // ObjC class data structure is allocated statically in the executable
431   // that defines that class.  That data structures contains a pointer to
432   // its superclass.  But instead of just initializing that part of the
433   // struct to the address of its superclass, and letting the static and
434   // dynamic linkers do the rest, the runtime works by having that field
435   // instead point to a C-string that is the name of the superclass.
436   // At runtime the objc initialization updates that pointer and sets
437   // it to point to the actual super class.  As far as the linker
438   // knows it is just a pointer to a string.  But then someone wanted the
439   // linker to issue errors at build time if the superclass was not found.
440   // So they figured out a way in mach-o object format to use an absolute
441   // symbols (.objc_class_name_Foo = 0) and a floating reference
442   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
443   // a class was missing.
444   // The following synthesizes the implicit .objc_* symbols for the linker
445   // from the ObjC data structures generated by the front end.
446
447   // special case if this data blob is an ObjC class definition
448   if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
449     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
450       addObjCClass(gv);
451     }
452   }
453
454   // special case if this data blob is an ObjC category definition
455   else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
456     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
457       addObjCCategory(gv);
458     }
459   }
460
461   // special case if this data blob is the list of referenced classes
462   else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
463     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
464       addObjCClassRef(gv);
465     }
466   }
467 }
468
469 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
470 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
471   // add to list of defined symbols
472   addDefinedSymbol(f, true);
473 }
474
475 /// addDefinedSymbol - Add a defined symbol to the list.
476 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
477   // ignore all llvm.* symbols
478   if (def->getName().startswith("llvm."))
479     return;
480
481   // string is owned by _defines
482   SmallString<64> Buffer;
483   _mangler.getNameWithPrefix(Buffer, def, false);
484
485   // set alignment part log2() can have rounding errors
486   uint32_t align = def->getAlignment();
487   uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
488
489   // set permissions part
490   if (isFunction) {
491     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
492   } else {
493     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
494     if (gv && gv->isConstant())
495       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
496     else
497       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
498   }
499
500   // set definition part
501   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
502       def->hasLinkerPrivateWeakLinkage())
503     attr |= LTO_SYMBOL_DEFINITION_WEAK;
504   else if (def->hasCommonLinkage())
505     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
506   else
507     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
508
509   // set scope part
510   if (def->hasHiddenVisibility())
511     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
512   else if (def->hasProtectedVisibility())
513     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
514   else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
515            def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
516            def->hasLinkerPrivateWeakLinkage())
517     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
518   else if (def->hasLinkOnceODRAutoHideLinkage())
519     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
520   else
521     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
522
523   StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
524   entry.setValue(1);
525
526   // fill information structure
527   NameAndAttributes info;
528   StringRef Name = entry.getKey();
529   info.name = Name.data();
530   assert(info.name[Name.size()] == '\0');
531   info.attributes = attr;
532   info.isFunction = isFunction;
533   info.symbol = def;
534
535   // add to table of symbols
536   _symbols.push_back(info);
537 }
538
539 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
540 /// defined list.
541 void LTOModule::addAsmGlobalSymbol(const char *name,
542                                    lto_symbol_attributes scope) {
543   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
544
545   // only add new define if not already defined
546   if (entry.getValue())
547     return;
548
549   entry.setValue(1);
550
551   NameAndAttributes &info = _undefines[entry.getKey().data()];
552
553   if (info.symbol == 0) {
554     // FIXME: This is trying to take care of module ASM like this:
555     //
556     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
557     //
558     // but is gross and its mother dresses it funny. Have the ASM parser give us
559     // more details for this type of situation so that we're not guessing so
560     // much.
561
562     // fill information structure
563     info.name = entry.getKey().data();
564     info.attributes =
565       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
566     info.isFunction = false;
567     info.symbol = 0;
568
569     // add to table of symbols
570     _symbols.push_back(info);
571     return;
572   }
573
574   if (info.isFunction)
575     addDefinedFunctionSymbol(cast<Function>(info.symbol));
576   else
577     addDefinedDataSymbol(info.symbol);
578
579   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
580   _symbols.back().attributes |= scope;
581 }
582
583 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
584 /// undefined list.
585 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
586   StringMap<NameAndAttributes>::value_type &entry =
587     _undefines.GetOrCreateValue(name);
588
589   _asm_undefines.push_back(entry.getKey().data());
590
591   // we already have the symbol
592   if (entry.getValue().name)
593     return;
594
595   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
596   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
597   NameAndAttributes info;
598   info.name = entry.getKey().data();
599   info.attributes = attr;
600   info.isFunction = false;
601   info.symbol = 0;
602
603   entry.setValue(info);
604 }
605
606 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
607 /// list to be resolved later.
608 void
609 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
610   // ignore all llvm.* symbols
611   if (decl->getName().startswith("llvm."))
612     return;
613
614   // ignore all aliases
615   if (isa<GlobalAlias>(decl))
616     return;
617
618   SmallString<64> name;
619   _mangler.getNameWithPrefix(name, decl, false);
620
621   StringMap<NameAndAttributes>::value_type &entry =
622     _undefines.GetOrCreateValue(name);
623
624   // we already have the symbol
625   if (entry.getValue().name)
626     return;
627
628   NameAndAttributes info;
629
630   info.name = entry.getKey().data();
631
632   if (decl->hasExternalWeakLinkage())
633     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
634   else
635     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
636
637   info.isFunction = isFunc;
638   info.symbol = decl;
639
640   entry.setValue(info);
641 }
642
643 namespace {
644   class RecordStreamer : public MCStreamer {
645   public:
646     enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
647
648   private:
649     StringMap<State> Symbols;
650
651     void markDefined(const MCSymbol &Symbol) {
652       State &S = Symbols[Symbol.getName()];
653       switch (S) {
654       case DefinedGlobal:
655       case Global:
656         S = DefinedGlobal;
657         break;
658       case NeverSeen:
659       case Defined:
660       case Used:
661         S = Defined;
662         break;
663       }
664     }
665     void markGlobal(const MCSymbol &Symbol) {
666       State &S = Symbols[Symbol.getName()];
667       switch (S) {
668       case DefinedGlobal:
669       case Defined:
670         S = DefinedGlobal;
671         break;
672
673       case NeverSeen:
674       case Global:
675       case Used:
676         S = Global;
677         break;
678       }
679     }
680     void markUsed(const MCSymbol &Symbol) {
681       State &S = Symbols[Symbol.getName()];
682       switch (S) {
683       case DefinedGlobal:
684       case Defined:
685       case Global:
686         break;
687
688       case NeverSeen:
689       case Used:
690         S = Used;
691         break;
692       }
693     }
694
695     // FIXME: mostly copied for the obj streamer.
696     void AddValueSymbols(const MCExpr *Value) {
697       switch (Value->getKind()) {
698       case MCExpr::Target:
699         // FIXME: What should we do in here?
700         break;
701
702       case MCExpr::Constant:
703         break;
704
705       case MCExpr::Binary: {
706         const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
707         AddValueSymbols(BE->getLHS());
708         AddValueSymbols(BE->getRHS());
709         break;
710       }
711
712       case MCExpr::SymbolRef:
713         markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol());
714         break;
715
716       case MCExpr::Unary:
717         AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
718         break;
719       }
720     }
721
722   public:
723     typedef StringMap<State>::const_iterator const_iterator;
724
725     const_iterator begin() {
726       return Symbols.begin();
727     }
728
729     const_iterator end() {
730       return Symbols.end();
731     }
732
733     RecordStreamer(MCContext &Context)
734         : MCStreamer(SK_RecordStreamer, Context) {}
735
736     virtual void EmitInstruction(const MCInst &Inst) {
737       // Scan for values.
738       for (unsigned i = Inst.getNumOperands(); i--; )
739         if (Inst.getOperand(i).isExpr())
740           AddValueSymbols(Inst.getOperand(i).getExpr());
741     }
742     virtual void EmitLabel(MCSymbol *Symbol) {
743       Symbol->setSection(*getCurrentSection().first);
744       markDefined(*Symbol);
745     }
746     virtual void EmitDebugLabel(MCSymbol *Symbol) {
747       EmitLabel(Symbol);
748     }
749     virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
750       // FIXME: should we handle aliases?
751       markDefined(*Symbol);
752     }
753     virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
754       if (Attribute == MCSA_Global)
755         markGlobal(*Symbol);
756     }
757     virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
758                               uint64_t Size , unsigned ByteAlignment) {
759       markDefined(*Symbol);
760     }
761     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
762                                   unsigned ByteAlignment) {
763       markDefined(*Symbol);
764     }
765
766     virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
767     virtual void EmitBundleLock(bool AlignToEnd) {}
768     virtual void EmitBundleUnlock() {}
769
770     // Noop calls.
771     virtual void ChangeSection(const MCSection *Section,
772                                const MCExpr *Subsection) {}
773     virtual void InitToTextSection() {}
774     virtual void InitSections() {}
775     virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
776     virtual void EmitThumbFunc(MCSymbol *Func) {}
777     virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
778     virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
779     virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
780     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
781     virtual void EmitCOFFSymbolType(int Type) {}
782     virtual void EndCOFFSymbolDef() {}
783     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
784     virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
785                                        unsigned ByteAlignment) {}
786     virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
787                                 uint64_t Size, unsigned ByteAlignment) {}
788     virtual void EmitBytes(StringRef Data) {}
789     virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
790     virtual void EmitULEB128Value(const MCExpr *Value) {}
791     virtual void EmitSLEB128Value(const MCExpr *Value) {}
792     virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
793                                       unsigned ValueSize,
794                                       unsigned MaxBytesToEmit) {}
795     virtual void EmitCodeAlignment(unsigned ByteAlignment,
796                                    unsigned MaxBytesToEmit) {}
797     virtual bool EmitValueToOffset(const MCExpr *Offset,
798                                    unsigned char Value ) { return false; }
799     virtual void EmitFileDirective(StringRef Filename) {}
800     virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
801                                           const MCSymbol *LastLabel,
802                                           const MCSymbol *Label,
803                                           unsigned PointerSize) {}
804     virtual void FinishImpl() {}
805
806     static bool classof(const MCStreamer *S) {
807       return S->getKind() == SK_RecordStreamer;
808     }
809   };
810 } // end anonymous namespace
811
812 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
813 /// defined or undefined lists.
814 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
815   const std::string &inlineAsm = _module->getModuleInlineAsm();
816   if (inlineAsm.empty())
817     return false;
818
819   OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context));
820   MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
821   SourceMgr SrcMgr;
822   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
823   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
824                                                   _context, *Streamer,
825                                                   *_target->getMCAsmInfo()));
826   const Target &T = _target->getTarget();
827   OwningPtr<MCSubtargetInfo>
828     STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
829                                 _target->getTargetCPU(),
830                                 _target->getTargetFeatureString()));
831   OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get()));
832   if (!TAP) {
833     errMsg = "target " + std::string(T.getName()) +
834       " does not define AsmParser.";
835     return true;
836   }
837
838   Parser->setTargetParser(*TAP);
839   if (Parser->Run(false))
840     return true;
841
842   for (RecordStreamer::const_iterator i = Streamer->begin(),
843          e = Streamer->end(); i != e; ++i) {
844     StringRef Key = i->first();
845     RecordStreamer::State Value = i->second;
846     if (Value == RecordStreamer::DefinedGlobal)
847       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
848     else if (Value == RecordStreamer::Defined)
849       addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
850     else if (Value == RecordStreamer::Global ||
851              Value == RecordStreamer::Used)
852       addAsmGlobalSymbolUndef(Key.data());
853   }
854
855   return false;
856 }
857
858 /// isDeclaration - Return 'true' if the global value is a declaration.
859 static bool isDeclaration(const GlobalValue &V) {
860   if (V.hasAvailableExternallyLinkage())
861     return true;
862
863   if (V.isMaterializable())
864     return false;
865
866   return V.isDeclaration();
867 }
868
869 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
870 /// them to either the defined or undefined lists.
871 bool LTOModule::parseSymbols(std::string &errMsg) {
872   // add functions
873   for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
874     if (isDeclaration(*f))
875       addPotentialUndefinedSymbol(f, true);
876     else
877       addDefinedFunctionSymbol(f);
878   }
879
880   // add data
881   for (Module::global_iterator v = _module->global_begin(),
882          e = _module->global_end(); v !=  e; ++v) {
883     if (isDeclaration(*v))
884       addPotentialUndefinedSymbol(v, false);
885     else
886       addDefinedDataSymbol(v);
887   }
888
889   // add asm globals
890   if (addAsmGlobalSymbols(errMsg))
891     return true;
892
893   // add aliases
894   for (Module::alias_iterator a = _module->alias_begin(),
895          e = _module->alias_end(); a != e; ++a) {
896     if (isDeclaration(*a->getAliasedGlobal()))
897       // Is an alias to a declaration.
898       addPotentialUndefinedSymbol(a, false);
899     else
900       addDefinedDataSymbol(a);
901   }
902
903   // make symbols for all undefines
904   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
905          e = _undefines.end(); u != e; ++u) {
906     // If this symbol also has a definition, then don't make an undefine because
907     // it is a tentative definition.
908     if (_defines.count(u->getKey())) continue;
909     NameAndAttributes info = u->getValue();
910     _symbols.push_back(info);
911   }
912
913   return false;
914 }