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