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