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