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