1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===// 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 classes used to handle lowerings specific to common 11 // object file formats. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Target/TargetLoweringObjectFile.h" 16 #include "llvm/Constants.h" 17 #include "llvm/DerivedTypes.h" 18 #include "llvm/Function.h" 19 #include "llvm/GlobalVariable.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCExpr.h" 22 #include "llvm/MC/MCSectionMachO.h" 23 #include "llvm/MC/MCSectionELF.h" 24 #include "llvm/MC/MCSymbol.h" 25 #include "llvm/Target/Mangler.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Target/TargetMachine.h" 28 #include "llvm/Target/TargetOptions.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/StringExtras.h" 33 using namespace llvm; 34 35 //===----------------------------------------------------------------------===// 36 // Generic Code 37 //===----------------------------------------------------------------------===// 38 39 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) { 40 TextSection = 0; 41 DataSection = 0; 42 BSSSection = 0; 43 ReadOnlySection = 0; 44 StaticCtorSection = 0; 45 StaticDtorSection = 0; 46 LSDASection = 0; 47 EHFrameSection = 0; 48 49 DwarfAbbrevSection = 0; 50 DwarfInfoSection = 0; 51 DwarfLineSection = 0; 52 DwarfFrameSection = 0; 53 DwarfPubNamesSection = 0; 54 DwarfPubTypesSection = 0; 55 DwarfDebugInlineSection = 0; 56 DwarfStrSection = 0; 57 DwarfLocSection = 0; 58 DwarfARangesSection = 0; 59 DwarfRangesSection = 0; 60 DwarfMacroInfoSection = 0; 61 } 62 63 TargetLoweringObjectFile::~TargetLoweringObjectFile() { 64 } 65 66 static bool isSuitableForBSS(const GlobalVariable *GV) { 67 Constant *C = GV->getInitializer(); 68 69 // Must have zero initializer. 70 if (!C->isNullValue()) 71 return false; 72 73 // Leave constant zeros in readonly constant sections, so they can be shared. 74 if (GV->isConstant()) 75 return false; 76 77 // If the global has an explicit section specified, don't put it in BSS. 78 if (!GV->getSection().empty()) 79 return false; 80 81 // If -nozero-initialized-in-bss is specified, don't ever use BSS. 82 if (NoZerosInBSS) 83 return false; 84 85 // Otherwise, put it in BSS! 86 return true; 87 } 88 89 /// IsNullTerminatedString - Return true if the specified constant (which is 90 /// known to have a type that is an array of 1/2/4 byte elements) ends with a 91 /// nul value and contains no other nuls in it. 92 static bool IsNullTerminatedString(const Constant *C) { 93 const ArrayType *ATy = cast<ArrayType>(C->getType()); 94 95 // First check: is we have constant array of i8 terminated with zero 96 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) { 97 if (ATy->getNumElements() == 0) return false; 98 99 ConstantInt *Null = 100 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1)); 101 if (Null == 0 || Null->getZExtValue() != 0) 102 return false; // Not null terminated. 103 104 // Verify that the null doesn't occur anywhere else in the string. 105 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i) 106 // Reject constantexpr elements etc. 107 if (!isa<ConstantInt>(CVA->getOperand(i)) || 108 CVA->getOperand(i) == Null) 109 return false; 110 return true; 111 } 112 113 // Another possibility: [1 x i8] zeroinitializer 114 if (isa<ConstantAggregateZero>(C)) 115 return ATy->getNumElements() == 1; 116 117 return false; 118 } 119 120 /// getKindForGlobal - This is a top-level target-independent classifier for 121 /// a global variable. Given an global variable and information from TM, it 122 /// classifies the global in a variety of ways that make various target 123 /// implementations simpler. The target implementation is free to ignore this 124 /// extra info of course. 125 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV, 126 const TargetMachine &TM){ 127 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() && 128 "Can only be used for global definitions"); 129 130 Reloc::Model ReloModel = TM.getRelocationModel(); 131 132 // Early exit - functions should be always in text sections. 133 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 134 if (GVar == 0) 135 return SectionKind::getText(); 136 137 // Handle thread-local data first. 138 if (GVar->isThreadLocal()) { 139 if (isSuitableForBSS(GVar)) 140 return SectionKind::getThreadBSS(); 141 return SectionKind::getThreadData(); 142 } 143 144 // Variables with common linkage always get classified as common. 145 if (GVar->hasCommonLinkage()) 146 return SectionKind::getCommon(); 147 148 // Variable can be easily put to BSS section. 149 if (isSuitableForBSS(GVar)) { 150 if (GVar->hasLocalLinkage()) 151 return SectionKind::getBSSLocal(); 152 else if (GVar->hasExternalLinkage()) 153 return SectionKind::getBSSExtern(); 154 return SectionKind::getBSS(); 155 } 156 157 Constant *C = GVar->getInitializer(); 158 159 // If the global is marked constant, we can put it into a mergable section, 160 // a mergable string section, or general .data if it contains relocations. 161 if (GVar->isConstant()) { 162 // If the initializer for the global contains something that requires a 163 // relocation, then we may have to drop this into a wriable data section 164 // even though it is marked const. 165 switch (C->getRelocationInfo()) { 166 default: assert(0 && "unknown relocation info kind"); 167 case Constant::NoRelocation: 168 // If initializer is a null-terminated string, put it in a "cstring" 169 // section of the right width. 170 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) { 171 if (const IntegerType *ITy = 172 dyn_cast<IntegerType>(ATy->getElementType())) { 173 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 || 174 ITy->getBitWidth() == 32) && 175 IsNullTerminatedString(C)) { 176 if (ITy->getBitWidth() == 8) 177 return SectionKind::getMergeable1ByteCString(); 178 if (ITy->getBitWidth() == 16) 179 return SectionKind::getMergeable2ByteCString(); 180 181 assert(ITy->getBitWidth() == 32 && "Unknown width"); 182 return SectionKind::getMergeable4ByteCString(); 183 } 184 } 185 } 186 187 // Otherwise, just drop it into a mergable constant section. If we have 188 // a section for this size, use it, otherwise use the arbitrary sized 189 // mergable section. 190 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) { 191 case 4: return SectionKind::getMergeableConst4(); 192 case 8: return SectionKind::getMergeableConst8(); 193 case 16: return SectionKind::getMergeableConst16(); 194 default: return SectionKind::getMergeableConst(); 195 } 196 197 case Constant::LocalRelocation: 198 // In static relocation model, the linker will resolve all addresses, so 199 // the relocation entries will actually be constants by the time the app 200 // starts up. However, we can't put this into a mergable section, because 201 // the linker doesn't take relocations into consideration when it tries to 202 // merge entries in the section. 203 if (ReloModel == Reloc::Static) 204 return SectionKind::getReadOnly(); 205 206 // Otherwise, the dynamic linker needs to fix it up, put it in the 207 // writable data.rel.local section. 208 return SectionKind::getReadOnlyWithRelLocal(); 209 210 case Constant::GlobalRelocations: 211 // In static relocation model, the linker will resolve all addresses, so 212 // the relocation entries will actually be constants by the time the app 213 // starts up. However, we can't put this into a mergable section, because 214 // the linker doesn't take relocations into consideration when it tries to 215 // merge entries in the section. 216 if (ReloModel == Reloc::Static) 217 return SectionKind::getReadOnly(); 218 219 // Otherwise, the dynamic linker needs to fix it up, put it in the 220 // writable data.rel section. 221 return SectionKind::getReadOnlyWithRel(); 222 } 223 } 224 225 // Okay, this isn't a constant. If the initializer for the global is going 226 // to require a runtime relocation by the dynamic linker, put it into a more 227 // specific section to improve startup time of the app. This coalesces these 228 // globals together onto fewer pages, improving the locality of the dynamic 229 // linker. 230 if (ReloModel == Reloc::Static) 231 return SectionKind::getDataNoRel(); 232 233 switch (C->getRelocationInfo()) { 234 default: assert(0 && "unknown relocation info kind"); 235 case Constant::NoRelocation: 236 return SectionKind::getDataNoRel(); 237 case Constant::LocalRelocation: 238 return SectionKind::getDataRelLocal(); 239 case Constant::GlobalRelocations: 240 return SectionKind::getDataRel(); 241 } 242 } 243 244 /// SectionForGlobal - This method computes the appropriate section to emit 245 /// the specified global variable or function definition. This should not 246 /// be passed external (or available externally) globals. 247 const MCSection *TargetLoweringObjectFile:: 248 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, 249 const TargetMachine &TM) const { 250 // Select section name. 251 if (GV->hasSection()) 252 return getExplicitSectionGlobal(GV, Kind, Mang, TM); 253 254 255 // Use default section depending on the 'type' of global 256 return SelectSectionForGlobal(GV, Kind, Mang, TM); 257 } 258 259 260 // Lame default implementation. Calculate the section name for global. 261 const MCSection * 262 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV, 263 SectionKind Kind, 264 Mangler *Mang, 265 const TargetMachine &TM) const{ 266 assert(!Kind.isThreadLocal() && "Doesn't support TLS"); 267 268 if (Kind.isText()) 269 return getTextSection(); 270 271 if (Kind.isBSS() && BSSSection != 0) 272 return BSSSection; 273 274 if (Kind.isReadOnly() && ReadOnlySection != 0) 275 return ReadOnlySection; 276 277 return getDataSection(); 278 } 279 280 /// getSectionForConstant - Given a mergable constant with the 281 /// specified size and relocation information, return a section that it 282 /// should be placed in. 283 const MCSection * 284 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const { 285 if (Kind.isReadOnly() && ReadOnlySection != 0) 286 return ReadOnlySection; 287 288 return DataSection; 289 } 290 291 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a 292 /// pc-relative reference to the specified global variable from exception 293 /// handling information. In addition to the symbol, this returns 294 /// by-reference: 295 /// 296 /// IsIndirect - True if the returned symbol is actually a stub that contains 297 /// the address of the symbol, false if the symbol is the global itself. 298 /// 299 /// IsPCRel - True if the symbol reference is already pc-relative, false if 300 /// the caller needs to subtract off the address of the reference from the 301 /// symbol. 302 /// 303 const MCExpr *TargetLoweringObjectFile:: 304 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang, 305 MachineModuleInfo *MMI, 306 bool &IsIndirect, bool &IsPCRel) const { 307 // The generic implementation of this just returns a direct reference to the 308 // symbol. 309 IsIndirect = false; 310 IsPCRel = false; 311 312 // FIXME: Use GetGlobalValueSymbol. 313 SmallString<128> Name; 314 Mang->getNameWithPrefix(Name, GV, false); 315 return MCSymbolRefExpr::Create(Name.str(), getContext()); 316 } 317 318 319 //===----------------------------------------------------------------------===// 320 // ELF 321 //===----------------------------------------------------------------------===// 322 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy; 323 324 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() { 325 // If we have the section uniquing map, free it. 326 delete (ELFUniqueMapTy*)UniquingMap; 327 } 328 329 const MCSection *TargetLoweringObjectFileELF:: 330 getELFSection(StringRef Section, unsigned Type, unsigned Flags, 331 SectionKind Kind, bool IsExplicit) const { 332 if (UniquingMap == 0) 333 UniquingMap = new ELFUniqueMapTy(); 334 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap; 335 336 // Do the lookup, if we have a hit, return it. 337 const MCSectionELF *&Entry = Map[Section]; 338 if (Entry) return Entry; 339 340 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit, 341 getContext()); 342 } 343 344 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 345 const TargetMachine &TM) { 346 if (UniquingMap != 0) 347 ((ELFUniqueMapTy*)UniquingMap)->clear(); 348 TargetLoweringObjectFile::Initialize(Ctx, TM); 349 350 BSSSection = 351 getELFSection(".bss", MCSectionELF::SHT_NOBITS, 352 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 353 SectionKind::getBSS()); 354 355 TextSection = 356 getELFSection(".text", MCSectionELF::SHT_PROGBITS, 357 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC, 358 SectionKind::getText()); 359 360 DataSection = 361 getELFSection(".data", MCSectionELF::SHT_PROGBITS, 362 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC, 363 SectionKind::getDataRel()); 364 365 ReadOnlySection = 366 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS, 367 MCSectionELF::SHF_ALLOC, 368 SectionKind::getReadOnly()); 369 370 TLSDataSection = 371 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS, 372 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 373 MCSectionELF::SHF_WRITE, SectionKind::getThreadData()); 374 375 TLSBSSSection = 376 getELFSection(".tbss", MCSectionELF::SHT_NOBITS, 377 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 378 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS()); 379 380 DataRelSection = 381 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS, 382 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 383 SectionKind::getDataRel()); 384 385 DataRelLocalSection = 386 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS, 387 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 388 SectionKind::getDataRelLocal()); 389 390 DataRelROSection = 391 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS, 392 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 393 SectionKind::getReadOnlyWithRel()); 394 395 DataRelROLocalSection = 396 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS, 397 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 398 SectionKind::getReadOnlyWithRelLocal()); 399 400 MergeableConst4Section = 401 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS, 402 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 403 SectionKind::getMergeableConst4()); 404 405 MergeableConst8Section = 406 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS, 407 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 408 SectionKind::getMergeableConst8()); 409 410 MergeableConst16Section = 411 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS, 412 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE, 413 SectionKind::getMergeableConst16()); 414 415 StaticCtorSection = 416 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS, 417 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 418 SectionKind::getDataRel()); 419 420 StaticDtorSection = 421 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS, 422 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 423 SectionKind::getDataRel()); 424 425 // Exception Handling Sections. 426 427 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though 428 // it contains relocatable pointers. In PIC mode, this is probably a big 429 // runtime hit for C++ apps. Either the contents of the LSDA need to be 430 // adjusted or this should be a data section. 431 LSDASection = 432 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS, 433 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly()); 434 EHFrameSection = 435 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS, 436 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE, 437 SectionKind::getDataRel()); 438 439 // Debug Info Sections. 440 DwarfAbbrevSection = 441 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0, 442 SectionKind::getMetadata()); 443 DwarfInfoSection = 444 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0, 445 SectionKind::getMetadata()); 446 DwarfLineSection = 447 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0, 448 SectionKind::getMetadata()); 449 DwarfFrameSection = 450 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0, 451 SectionKind::getMetadata()); 452 DwarfPubNamesSection = 453 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0, 454 SectionKind::getMetadata()); 455 DwarfPubTypesSection = 456 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0, 457 SectionKind::getMetadata()); 458 DwarfStrSection = 459 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0, 460 SectionKind::getMetadata()); 461 DwarfLocSection = 462 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0, 463 SectionKind::getMetadata()); 464 DwarfARangesSection = 465 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0, 466 SectionKind::getMetadata()); 467 DwarfRangesSection = 468 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0, 469 SectionKind::getMetadata()); 470 DwarfMacroInfoSection = 471 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0, 472 SectionKind::getMetadata()); 473 } 474 475 476 static SectionKind 477 getELFKindForNamedSection(const char *Name, SectionKind K) { 478 if (Name[0] != '.') return K; 479 480 // Some lame default implementation based on some magic section names. 481 if (strcmp(Name, ".bss") == 0 || 482 strncmp(Name, ".bss.", 5) == 0 || 483 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 || 484 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 || 485 strcmp(Name, ".sbss") == 0 || 486 strncmp(Name, ".sbss.", 6) == 0 || 487 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 || 488 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0) 489 return SectionKind::getBSS(); 490 491 if (strcmp(Name, ".tdata") == 0 || 492 strncmp(Name, ".tdata.", 7) == 0 || 493 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 || 494 strncmp(Name, ".llvm.linkonce.td.", 18) == 0) 495 return SectionKind::getThreadData(); 496 497 if (strcmp(Name, ".tbss") == 0 || 498 strncmp(Name, ".tbss.", 6) == 0 || 499 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 || 500 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0) 501 return SectionKind::getThreadBSS(); 502 503 return K; 504 } 505 506 507 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 508 509 if (Name == ".init_array") 510 return MCSectionELF::SHT_INIT_ARRAY; 511 512 if (Name == ".fini_array") 513 return MCSectionELF::SHT_FINI_ARRAY; 514 515 if (Name == ".preinit_array") 516 return MCSectionELF::SHT_PREINIT_ARRAY; 517 518 if (K.isBSS() || K.isThreadBSS()) 519 return MCSectionELF::SHT_NOBITS; 520 521 return MCSectionELF::SHT_PROGBITS; 522 } 523 524 525 static unsigned 526 getELFSectionFlags(SectionKind K) { 527 unsigned Flags = 0; 528 529 if (!K.isMetadata()) 530 Flags |= MCSectionELF::SHF_ALLOC; 531 532 if (K.isText()) 533 Flags |= MCSectionELF::SHF_EXECINSTR; 534 535 if (K.isWriteable()) 536 Flags |= MCSectionELF::SHF_WRITE; 537 538 if (K.isThreadLocal()) 539 Flags |= MCSectionELF::SHF_TLS; 540 541 // K.isMergeableConst() is left out to honour PR4650 542 if (K.isMergeableCString() || K.isMergeableConst4() || 543 K.isMergeableConst8() || K.isMergeableConst16()) 544 Flags |= MCSectionELF::SHF_MERGE; 545 546 if (K.isMergeableCString()) 547 Flags |= MCSectionELF::SHF_STRINGS; 548 549 return Flags; 550 } 551 552 553 const MCSection *TargetLoweringObjectFileELF:: 554 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 555 Mangler *Mang, const TargetMachine &TM) const { 556 const char *SectionName = GV->getSection().c_str(); 557 558 // Infer section flags from the section name if we can. 559 Kind = getELFKindForNamedSection(SectionName, Kind); 560 561 return getELFSection(SectionName, 562 getELFSectionType(SectionName, Kind), 563 getELFSectionFlags(Kind), Kind, true); 564 } 565 566 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) { 567 if (Kind.isText()) return ".gnu.linkonce.t."; 568 if (Kind.isReadOnly()) return ".gnu.linkonce.r."; 569 570 if (Kind.isThreadData()) return ".gnu.linkonce.td."; 571 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb."; 572 573 if (Kind.isDataNoRel()) return ".gnu.linkonce.d."; 574 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local."; 575 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel."; 576 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local."; 577 578 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 579 return ".gnu.linkonce.d.rel.ro."; 580 } 581 582 const MCSection *TargetLoweringObjectFileELF:: 583 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 584 Mangler *Mang, const TargetMachine &TM) const { 585 586 // If this global is linkonce/weak and the target handles this by emitting it 587 // into a 'uniqued' section name, create and return the section now. 588 if (GV->isWeakForLinker() && !Kind.isCommon() && !Kind.isBSS()) { 589 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind); 590 SmallString<128> Name; 591 Name.append(Prefix, Prefix+strlen(Prefix)); 592 Mang->getNameWithPrefix(Name, GV, false); 593 return getELFSection(Name.str(), getELFSectionType(Name.str(), Kind), 594 getELFSectionFlags(Kind), Kind); 595 } 596 597 if (Kind.isText()) return TextSection; 598 599 if (Kind.isMergeable1ByteCString() || 600 Kind.isMergeable2ByteCString() || 601 Kind.isMergeable4ByteCString()) { 602 603 // We also need alignment here. 604 // FIXME: this is getting the alignment of the character, not the 605 // alignment of the global! 606 unsigned Align = 607 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)); 608 609 const char *SizeSpec = ".rodata.str1."; 610 if (Kind.isMergeable2ByteCString()) 611 SizeSpec = ".rodata.str2."; 612 else if (Kind.isMergeable4ByteCString()) 613 SizeSpec = ".rodata.str4."; 614 else 615 assert(Kind.isMergeable1ByteCString() && "unknown string width"); 616 617 618 std::string Name = SizeSpec + utostr(Align); 619 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS, 620 MCSectionELF::SHF_ALLOC | 621 MCSectionELF::SHF_MERGE | 622 MCSectionELF::SHF_STRINGS, 623 Kind); 624 } 625 626 if (Kind.isMergeableConst()) { 627 if (Kind.isMergeableConst4() && MergeableConst4Section) 628 return MergeableConst4Section; 629 if (Kind.isMergeableConst8() && MergeableConst8Section) 630 return MergeableConst8Section; 631 if (Kind.isMergeableConst16() && MergeableConst16Section) 632 return MergeableConst16Section; 633 return ReadOnlySection; // .const 634 } 635 636 if (Kind.isReadOnly()) return ReadOnlySection; 637 638 if (Kind.isThreadData()) return TLSDataSection; 639 if (Kind.isThreadBSS()) return TLSBSSSection; 640 641 // Note: we claim that common symbols are put in BSSSection, but they are 642 // really emitted with the magic .comm directive, which creates a symbol table 643 // entry but not a section. 644 if (Kind.isBSS() || Kind.isCommon()) return BSSSection; 645 646 if (Kind.isDataNoRel()) return DataSection; 647 if (Kind.isDataRelLocal()) return DataRelLocalSection; 648 if (Kind.isDataRel()) return DataRelSection; 649 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 650 651 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 652 return DataRelROSection; 653 } 654 655 /// getSectionForConstant - Given a mergeable constant with the 656 /// specified size and relocation information, return a section that it 657 /// should be placed in. 658 const MCSection *TargetLoweringObjectFileELF:: 659 getSectionForConstant(SectionKind Kind) const { 660 if (Kind.isMergeableConst4() && MergeableConst4Section) 661 return MergeableConst4Section; 662 if (Kind.isMergeableConst8() && MergeableConst8Section) 663 return MergeableConst8Section; 664 if (Kind.isMergeableConst16() && MergeableConst16Section) 665 return MergeableConst16Section; 666 if (Kind.isReadOnly()) 667 return ReadOnlySection; 668 669 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection; 670 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 671 return DataRelROSection; 672 } 673 674 //===----------------------------------------------------------------------===// 675 // MachO 676 //===----------------------------------------------------------------------===// 677 678 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy; 679 680 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() { 681 // If we have the MachO uniquing map, free it. 682 delete (MachOUniqueMapTy*)UniquingMap; 683 } 684 685 686 const MCSectionMachO *TargetLoweringObjectFileMachO:: 687 getMachOSection(StringRef Segment, StringRef Section, 688 unsigned TypeAndAttributes, 689 unsigned Reserved2, SectionKind Kind) const { 690 // We unique sections by their segment/section pair. The returned section 691 // may not have the same flags as the requested section, if so this should be 692 // diagnosed by the client as an error. 693 694 // Create the map if it doesn't already exist. 695 if (UniquingMap == 0) 696 UniquingMap = new MachOUniqueMapTy(); 697 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap; 698 699 // Form the name to look up. 700 SmallString<64> Name; 701 Name += Segment; 702 Name.push_back(','); 703 Name += Section; 704 705 // Do the lookup, if we have a hit, return it. 706 const MCSectionMachO *&Entry = Map[Name.str()]; 707 if (Entry) return Entry; 708 709 // Otherwise, return a new section. 710 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes, 711 Reserved2, Kind, getContext()); 712 } 713 714 715 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 716 const TargetMachine &TM) { 717 if (UniquingMap != 0) 718 ((MachOUniqueMapTy*)UniquingMap)->clear(); 719 TargetLoweringObjectFile::Initialize(Ctx, TM); 720 721 TextSection // .text 722 = getMachOSection("__TEXT", "__text", 723 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 724 SectionKind::getText()); 725 DataSection // .data 726 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel()); 727 728 CStringSection // .cstring 729 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS, 730 SectionKind::getMergeable1ByteCString()); 731 UStringSection 732 = getMachOSection("__TEXT","__ustring", 0, 733 SectionKind::getMergeable2ByteCString()); 734 FourByteConstantSection // .literal4 735 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS, 736 SectionKind::getMergeableConst4()); 737 EightByteConstantSection // .literal8 738 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS, 739 SectionKind::getMergeableConst8()); 740 741 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back 742 // to using it in -static mode. 743 SixteenByteConstantSection = 0; 744 if (TM.getRelocationModel() != Reloc::Static && 745 TM.getTargetData()->getPointerSize() == 32) 746 SixteenByteConstantSection = // .literal16 747 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS, 748 SectionKind::getMergeableConst16()); 749 750 ReadOnlySection // .const 751 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly()); 752 753 TextCoalSection 754 = getMachOSection("__TEXT", "__textcoal_nt", 755 MCSectionMachO::S_COALESCED | 756 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 757 SectionKind::getText()); 758 ConstTextCoalSection 759 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED, 760 SectionKind::getText()); 761 ConstDataCoalSection 762 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED, 763 SectionKind::getText()); 764 DataCommonSection 765 = getMachOSection("__DATA","__common", MCSectionMachO::S_ZEROFILL, 766 SectionKind::getBSS()); 767 ConstDataSection // .const_data 768 = getMachOSection("__DATA", "__const", 0, 769 SectionKind::getReadOnlyWithRel()); 770 DataCoalSection 771 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED, 772 SectionKind::getDataRel()); 773 774 775 LazySymbolPointerSection 776 = getMachOSection("__DATA", "__la_symbol_ptr", 777 MCSectionMachO::S_LAZY_SYMBOL_POINTERS, 778 SectionKind::getMetadata()); 779 NonLazySymbolPointerSection 780 = getMachOSection("__DATA", "__nl_symbol_ptr", 781 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS, 782 SectionKind::getMetadata()); 783 784 if (TM.getRelocationModel() == Reloc::Static) { 785 StaticCtorSection 786 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel()); 787 StaticDtorSection 788 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel()); 789 } else { 790 StaticCtorSection 791 = getMachOSection("__DATA", "__mod_init_func", 792 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS, 793 SectionKind::getDataRel()); 794 StaticDtorSection 795 = getMachOSection("__DATA", "__mod_term_func", 796 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS, 797 SectionKind::getDataRel()); 798 } 799 800 // Exception Handling. 801 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0, 802 SectionKind::getDataRel()); 803 EHFrameSection = 804 getMachOSection("__TEXT", "__eh_frame", 805 MCSectionMachO::S_COALESCED | 806 MCSectionMachO::S_ATTR_NO_TOC | 807 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS | 808 MCSectionMachO::S_ATTR_LIVE_SUPPORT, 809 SectionKind::getReadOnly()); 810 811 // Debug Information. 812 DwarfAbbrevSection = 813 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG, 814 SectionKind::getMetadata()); 815 DwarfInfoSection = 816 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG, 817 SectionKind::getMetadata()); 818 DwarfLineSection = 819 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG, 820 SectionKind::getMetadata()); 821 DwarfFrameSection = 822 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG, 823 SectionKind::getMetadata()); 824 DwarfPubNamesSection = 825 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG, 826 SectionKind::getMetadata()); 827 DwarfPubTypesSection = 828 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG, 829 SectionKind::getMetadata()); 830 DwarfStrSection = 831 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG, 832 SectionKind::getMetadata()); 833 DwarfLocSection = 834 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG, 835 SectionKind::getMetadata()); 836 DwarfARangesSection = 837 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG, 838 SectionKind::getMetadata()); 839 DwarfRangesSection = 840 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG, 841 SectionKind::getMetadata()); 842 DwarfMacroInfoSection = 843 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG, 844 SectionKind::getMetadata()); 845 DwarfDebugInlineSection = 846 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG, 847 SectionKind::getMetadata()); 848 } 849 850 const MCSection *TargetLoweringObjectFileMachO:: 851 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 852 Mangler *Mang, const TargetMachine &TM) const { 853 // Parse the section specifier and create it if valid. 854 StringRef Segment, Section; 855 unsigned TAA, StubSize; 856 std::string ErrorCode = 857 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section, 858 TAA, StubSize); 859 if (!ErrorCode.empty()) { 860 // If invalid, report the error with llvm_report_error. 861 llvm_report_error("Global variable '" + GV->getNameStr() + 862 "' has an invalid section specifier '" + GV->getSection()+ 863 "': " + ErrorCode + "."); 864 // Fall back to dropping it into the data section. 865 return DataSection; 866 } 867 868 // Get the section. 869 const MCSectionMachO *S = 870 getMachOSection(Segment, Section, TAA, StubSize, Kind); 871 872 // Okay, now that we got the section, verify that the TAA & StubSize agree. 873 // If the user declared multiple globals with different section flags, we need 874 // to reject it here. 875 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 876 // If invalid, report the error with llvm_report_error. 877 llvm_report_error("Global variable '" + GV->getNameStr() + 878 "' section type or attributes does not match previous" 879 " section specifier"); 880 } 881 882 return S; 883 } 884 885 const MCSection *TargetLoweringObjectFileMachO:: 886 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 887 Mangler *Mang, const TargetMachine &TM) const { 888 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS"); 889 890 if (Kind.isText()) 891 return GV->isWeakForLinker() ? TextCoalSection : TextSection; 892 893 // If this is weak/linkonce, put this in a coalescable section, either in text 894 // or data depending on if it is writable. 895 if (GV->isWeakForLinker()) { 896 if (Kind.isReadOnly()) 897 return ConstTextCoalSection; 898 return DataCoalSection; 899 } 900 901 // FIXME: Alignment check should be handled by section classifier. 902 if (Kind.isMergeable1ByteCString() || 903 Kind.isMergeable2ByteCString()) { 904 if (TM.getTargetData()->getPreferredAlignment( 905 cast<GlobalVariable>(GV)) < 32) { 906 if (Kind.isMergeable1ByteCString()) 907 return CStringSection; 908 assert(Kind.isMergeable2ByteCString()); 909 return UStringSection; 910 } 911 } 912 913 if (Kind.isMergeableConst()) { 914 if (Kind.isMergeableConst4()) 915 return FourByteConstantSection; 916 if (Kind.isMergeableConst8()) 917 return EightByteConstantSection; 918 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 919 return SixteenByteConstantSection; 920 } 921 922 // Otherwise, if it is readonly, but not something we can specially optimize, 923 // just drop it in .const. 924 if (Kind.isReadOnly()) 925 return ReadOnlySection; 926 927 // If this is marked const, put it into a const section. But if the dynamic 928 // linker needs to write to it, put it in the data segment. 929 if (Kind.isReadOnlyWithRel()) 930 return ConstDataSection; 931 932 // Put zero initialized globals with strong external linkage in the 933 // DATA, __common section with the .zerofill directive. 934 if (Kind.isBSSExtern()) 935 return DataCommonSection; 936 937 // Otherwise, just drop the variable in the normal data section. 938 return DataSection; 939 } 940 941 const MCSection * 942 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const { 943 // If this constant requires a relocation, we have to put it in the data 944 // segment, not in the text segment. 945 if (Kind.isDataRel() || Kind.isReadOnlyWithRel()) 946 return ConstDataSection; 947 948 if (Kind.isMergeableConst4()) 949 return FourByteConstantSection; 950 if (Kind.isMergeableConst8()) 951 return EightByteConstantSection; 952 if (Kind.isMergeableConst16() && SixteenByteConstantSection) 953 return SixteenByteConstantSection; 954 return ReadOnlySection; // .const 955 } 956 957 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide 958 /// not to emit the UsedDirective for some symbols in llvm.used. 959 // FIXME: REMOVE this (rdar://7071300) 960 bool TargetLoweringObjectFileMachO:: 961 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const { 962 /// On Darwin, internally linked data beginning with "L" or "l" does not have 963 /// the directive emitted (this occurs in ObjC metadata). 964 if (!GV) return false; 965 966 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix. 967 if (GV->hasLocalLinkage() && !isa<Function>(GV)) { 968 // FIXME: ObjC metadata is currently emitted as internal symbols that have 969 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and 970 // this horrible hack can go away. 971 SmallString<64> Name; 972 Mang->getNameWithPrefix(Name, GV, false); 973 if (Name[0] == 'L' || Name[0] == 'l') 974 return false; 975 } 976 977 return true; 978 } 979 980 const MCExpr *TargetLoweringObjectFileMachO:: 981 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang, 982 MachineModuleInfo *MMI, 983 bool &IsIndirect, bool &IsPCRel) const { 984 // The mach-o version of this method defaults to returning a stub reference. 985 IsIndirect = true; 986 IsPCRel = false; 987 988 SmallString<128> Name; 989 Mang->getNameWithPrefix(Name, GV, true); 990 Name += "$non_lazy_ptr"; 991 return MCSymbolRefExpr::Create(Name.str(), getContext()); 992 } 993 994 995 //===----------------------------------------------------------------------===// 996 // COFF 997 //===----------------------------------------------------------------------===// 998 999 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy; 1000 1001 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() { 1002 delete (COFFUniqueMapTy*)UniquingMap; 1003 } 1004 1005 1006 const MCSection *TargetLoweringObjectFileCOFF:: 1007 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const { 1008 // Create the map if it doesn't already exist. 1009 if (UniquingMap == 0) 1010 UniquingMap = new MachOUniqueMapTy(); 1011 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap; 1012 1013 // Do the lookup, if we have a hit, return it. 1014 const MCSectionCOFF *&Entry = Map[Name]; 1015 if (Entry) return Entry; 1016 1017 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext()); 1018 } 1019 1020 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1021 const TargetMachine &TM) { 1022 if (UniquingMap != 0) 1023 ((COFFUniqueMapTy*)UniquingMap)->clear(); 1024 TargetLoweringObjectFile::Initialize(Ctx, TM); 1025 TextSection = getCOFFSection("\t.text", true, SectionKind::getText()); 1026 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel()); 1027 StaticCtorSection = 1028 getCOFFSection(".ctors", false, SectionKind::getDataRel()); 1029 StaticDtorSection = 1030 getCOFFSection(".dtors", false, SectionKind::getDataRel()); 1031 1032 // FIXME: We're emitting LSDA info into a readonly section on COFF, even 1033 // though it contains relocatable pointers. In PIC mode, this is probably a 1034 // big runtime hit for C++ apps. Either the contents of the LSDA need to be 1035 // adjusted or this should be a data section. 1036 LSDASection = 1037 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly()); 1038 EHFrameSection = 1039 getCOFFSection(".eh_frame", false, SectionKind::getDataRel()); 1040 1041 // Debug info. 1042 // FIXME: Don't use 'directive' mode here. 1043 DwarfAbbrevSection = 1044 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"", 1045 true, SectionKind::getMetadata()); 1046 DwarfInfoSection = 1047 getCOFFSection("\t.section\t.debug_info,\"dr\"", 1048 true, SectionKind::getMetadata()); 1049 DwarfLineSection = 1050 getCOFFSection("\t.section\t.debug_line,\"dr\"", 1051 true, SectionKind::getMetadata()); 1052 DwarfFrameSection = 1053 getCOFFSection("\t.section\t.debug_frame,\"dr\"", 1054 true, SectionKind::getMetadata()); 1055 DwarfPubNamesSection = 1056 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"", 1057 true, SectionKind::getMetadata()); 1058 DwarfPubTypesSection = 1059 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"", 1060 true, SectionKind::getMetadata()); 1061 DwarfStrSection = 1062 getCOFFSection("\t.section\t.debug_str,\"dr\"", 1063 true, SectionKind::getMetadata()); 1064 DwarfLocSection = 1065 getCOFFSection("\t.section\t.debug_loc,\"dr\"", 1066 true, SectionKind::getMetadata()); 1067 DwarfARangesSection = 1068 getCOFFSection("\t.section\t.debug_aranges,\"dr\"", 1069 true, SectionKind::getMetadata()); 1070 DwarfRangesSection = 1071 getCOFFSection("\t.section\t.debug_ranges,\"dr\"", 1072 true, SectionKind::getMetadata()); 1073 DwarfMacroInfoSection = 1074 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"", 1075 true, SectionKind::getMetadata()); 1076 } 1077 1078 const MCSection *TargetLoweringObjectFileCOFF:: 1079 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 1080 Mangler *Mang, const TargetMachine &TM) const { 1081 return getCOFFSection(GV->getSection().c_str(), false, Kind); 1082 } 1083 1084 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) { 1085 if (Kind.isText()) 1086 return ".text$linkonce"; 1087 if (Kind.isWriteable()) 1088 return ".data$linkonce"; 1089 return ".rdata$linkonce"; 1090 } 1091 1092 1093 const MCSection *TargetLoweringObjectFileCOFF:: 1094 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, 1095 Mangler *Mang, const TargetMachine &TM) const { 1096 assert(!Kind.isThreadLocal() && "Doesn't support TLS"); 1097 1098 // If this global is linkonce/weak and the target handles this by emitting it 1099 // into a 'uniqued' section name, create and return the section now. 1100 if (GV->isWeakForLinker()) { 1101 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind); 1102 SmallString<128> Name(Prefix, Prefix+strlen(Prefix)); 1103 Mang->getNameWithPrefix(Name, GV, false); 1104 return getCOFFSection(Name.str(), false, Kind); 1105 } 1106 1107 if (Kind.isText()) 1108 return getTextSection(); 1109 1110 return getDataSection(); 1111 } 1112 1113