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