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