1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements classes used to handle lowerings specific to common 10 // object file formats. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/BinaryFormat/COFF.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/BinaryFormat/ELF.h" 23 #include "llvm/BinaryFormat/MachO.h" 24 #include "llvm/CodeGen/BasicBlockSectionUtils.h" 25 #include "llvm/CodeGen/MachineBasicBlock.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 29 #include "llvm/IR/Comdat.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/DiagnosticPrinter.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/GlobalAlias.h" 37 #include "llvm/IR/GlobalObject.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/GlobalVariable.h" 40 #include "llvm/IR/Mangler.h" 41 #include "llvm/IR/Metadata.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/MC/MCAsmInfo.h" 45 #include "llvm/MC/MCContext.h" 46 #include "llvm/MC/MCExpr.h" 47 #include "llvm/MC/MCSectionCOFF.h" 48 #include "llvm/MC/MCSectionELF.h" 49 #include "llvm/MC/MCSectionMachO.h" 50 #include "llvm/MC/MCSectionWasm.h" 51 #include "llvm/MC/MCSectionXCOFF.h" 52 #include "llvm/MC/MCStreamer.h" 53 #include "llvm/MC/MCSymbol.h" 54 #include "llvm/MC/MCSymbolELF.h" 55 #include "llvm/MC/MCValue.h" 56 #include "llvm/MC/SectionKind.h" 57 #include "llvm/ProfileData/InstrProf.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CodeGen.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/Format.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Target/TargetMachine.h" 64 #include <cassert> 65 #include <string> 66 67 using namespace llvm; 68 using namespace dwarf; 69 70 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 71 StringRef &Section) { 72 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 73 M.getModuleFlagsMetadata(ModuleFlags); 74 75 for (const auto &MFE: ModuleFlags) { 76 // Ignore flags with 'Require' behaviour. 77 if (MFE.Behavior == Module::Require) 78 continue; 79 80 StringRef Key = MFE.Key->getString(); 81 if (Key == "Objective-C Image Info Version") { 82 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 83 } else if (Key == "Objective-C Garbage Collection" || 84 Key == "Objective-C GC Only" || 85 Key == "Objective-C Is Simulated" || 86 Key == "Objective-C Class Properties" || 87 Key == "Objective-C Image Swift Version") { 88 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 89 } else if (Key == "Objective-C Image Info Section") { 90 Section = cast<MDString>(MFE.Val)->getString(); 91 } 92 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor + 93 // "Objective-C Garbage Collection". 94 else if (Key == "Swift ABI Version") { 95 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8; 96 } else if (Key == "Swift Major Version") { 97 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24; 98 } else if (Key == "Swift Minor Version") { 99 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16; 100 } 101 } 102 } 103 104 //===----------------------------------------------------------------------===// 105 // ELF 106 //===----------------------------------------------------------------------===// 107 108 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 109 const TargetMachine &TgtM) { 110 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 111 TM = &TgtM; 112 113 CodeModel::Model CM = TgtM.getCodeModel(); 114 InitializeELF(TgtM.Options.UseInitArray); 115 116 switch (TgtM.getTargetTriple().getArch()) { 117 case Triple::arm: 118 case Triple::armeb: 119 case Triple::thumb: 120 case Triple::thumbeb: 121 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) 122 break; 123 // Fallthrough if not using EHABI 124 LLVM_FALLTHROUGH; 125 case Triple::ppc: 126 case Triple::x86: 127 PersonalityEncoding = isPositionIndependent() 128 ? dwarf::DW_EH_PE_indirect | 129 dwarf::DW_EH_PE_pcrel | 130 dwarf::DW_EH_PE_sdata4 131 : dwarf::DW_EH_PE_absptr; 132 LSDAEncoding = isPositionIndependent() 133 ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 134 : dwarf::DW_EH_PE_absptr; 135 TTypeEncoding = isPositionIndependent() 136 ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 137 dwarf::DW_EH_PE_sdata4 138 : dwarf::DW_EH_PE_absptr; 139 break; 140 case Triple::x86_64: 141 if (isPositionIndependent()) { 142 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 143 ((CM == CodeModel::Small || CM == CodeModel::Medium) 144 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 145 LSDAEncoding = dwarf::DW_EH_PE_pcrel | 146 (CM == CodeModel::Small 147 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 148 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 149 ((CM == CodeModel::Small || CM == CodeModel::Medium) 150 ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4); 151 } else { 152 PersonalityEncoding = 153 (CM == CodeModel::Small || CM == CodeModel::Medium) 154 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 155 LSDAEncoding = (CM == CodeModel::Small) 156 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 157 TTypeEncoding = (CM == CodeModel::Small) 158 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 159 } 160 break; 161 case Triple::hexagon: 162 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 163 LSDAEncoding = dwarf::DW_EH_PE_absptr; 164 TTypeEncoding = dwarf::DW_EH_PE_absptr; 165 if (isPositionIndependent()) { 166 PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 167 LSDAEncoding |= dwarf::DW_EH_PE_pcrel; 168 TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 169 } 170 break; 171 case Triple::aarch64: 172 case Triple::aarch64_be: 173 case Triple::aarch64_32: 174 // The small model guarantees static code/data size < 4GB, but not where it 175 // will be in memory. Most of these could end up >2GB away so even a signed 176 // pc-relative 32-bit address is insufficient, theoretically. 177 if (isPositionIndependent()) { 178 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 179 dwarf::DW_EH_PE_sdata8; 180 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; 181 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 182 dwarf::DW_EH_PE_sdata8; 183 } else { 184 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 185 LSDAEncoding = dwarf::DW_EH_PE_absptr; 186 TTypeEncoding = dwarf::DW_EH_PE_absptr; 187 } 188 break; 189 case Triple::lanai: 190 LSDAEncoding = dwarf::DW_EH_PE_absptr; 191 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 192 TTypeEncoding = dwarf::DW_EH_PE_absptr; 193 break; 194 case Triple::mips: 195 case Triple::mipsel: 196 case Triple::mips64: 197 case Triple::mips64el: 198 // MIPS uses indirect pointer to refer personality functions and types, so 199 // that the eh_frame section can be read-only. DW.ref.personality will be 200 // generated for relocation. 201 PersonalityEncoding = dwarf::DW_EH_PE_indirect; 202 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't 203 // identify N64 from just a triple. 204 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 205 dwarf::DW_EH_PE_sdata4; 206 // We don't support PC-relative LSDA references in GAS so we use the default 207 // DW_EH_PE_absptr for those. 208 209 // FreeBSD must be explicit about the data size and using pcrel since it's 210 // assembler/linker won't do the automatic conversion that the Linux tools 211 // do. 212 if (TgtM.getTargetTriple().isOSFreeBSD()) { 213 PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 214 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 215 } 216 break; 217 case Triple::ppc64: 218 case Triple::ppc64le: 219 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 220 dwarf::DW_EH_PE_udata8; 221 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; 222 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 223 dwarf::DW_EH_PE_udata8; 224 break; 225 case Triple::sparcel: 226 case Triple::sparc: 227 if (isPositionIndependent()) { 228 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 229 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 230 dwarf::DW_EH_PE_sdata4; 231 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 232 dwarf::DW_EH_PE_sdata4; 233 } else { 234 LSDAEncoding = dwarf::DW_EH_PE_absptr; 235 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 236 TTypeEncoding = dwarf::DW_EH_PE_absptr; 237 } 238 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 239 break; 240 case Triple::riscv32: 241 case Triple::riscv64: 242 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 243 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 244 dwarf::DW_EH_PE_sdata4; 245 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 246 dwarf::DW_EH_PE_sdata4; 247 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 248 break; 249 case Triple::sparcv9: 250 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 251 if (isPositionIndependent()) { 252 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 253 dwarf::DW_EH_PE_sdata4; 254 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 255 dwarf::DW_EH_PE_sdata4; 256 } else { 257 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 258 TTypeEncoding = dwarf::DW_EH_PE_absptr; 259 } 260 break; 261 case Triple::systemz: 262 // All currently-defined code models guarantee that 4-byte PC-relative 263 // values will be in range. 264 if (isPositionIndependent()) { 265 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 266 dwarf::DW_EH_PE_sdata4; 267 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 268 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 269 dwarf::DW_EH_PE_sdata4; 270 } else { 271 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 272 LSDAEncoding = dwarf::DW_EH_PE_absptr; 273 TTypeEncoding = dwarf::DW_EH_PE_absptr; 274 } 275 break; 276 default: 277 break; 278 } 279 } 280 281 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, 282 Module &M) const { 283 auto &C = getContext(); 284 285 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 286 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, 287 ELF::SHF_EXCLUDE); 288 289 Streamer.SwitchSection(S); 290 291 for (const auto *Operand : LinkerOptions->operands()) { 292 if (cast<MDNode>(Operand)->getNumOperands() != 2) 293 report_fatal_error("invalid llvm.linker.options"); 294 for (const auto &Option : cast<MDNode>(Operand)->operands()) { 295 Streamer.emitBytes(cast<MDString>(Option)->getString()); 296 Streamer.emitInt8(0); 297 } 298 } 299 } 300 301 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) { 302 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES, 303 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 304 305 Streamer.SwitchSection(S); 306 307 for (const auto *Operand : DependentLibraries->operands()) { 308 Streamer.emitBytes( 309 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString()); 310 Streamer.emitInt8(0); 311 } 312 } 313 314 unsigned Version = 0; 315 unsigned Flags = 0; 316 StringRef Section; 317 318 GetObjCImageInfo(M, Version, Flags, Section); 319 if (!Section.empty()) { 320 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 321 Streamer.SwitchSection(S); 322 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 323 Streamer.emitInt32(Version); 324 Streamer.emitInt32(Flags); 325 Streamer.AddBlankLine(); 326 } 327 328 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 329 M.getModuleFlagsMetadata(ModuleFlags); 330 331 MDNode *CFGProfile = nullptr; 332 333 for (const auto &MFE : ModuleFlags) { 334 StringRef Key = MFE.Key->getString(); 335 if (Key == "CG Profile") { 336 CFGProfile = cast<MDNode>(MFE.Val); 337 break; 338 } 339 } 340 341 if (!CFGProfile) 342 return; 343 344 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { 345 if (!MDO) 346 return nullptr; 347 auto V = cast<ValueAsMetadata>(MDO); 348 const Function *F = cast<Function>(V->getValue()); 349 return TM->getSymbol(F); 350 }; 351 352 for (const auto &Edge : CFGProfile->operands()) { 353 MDNode *E = cast<MDNode>(Edge); 354 const MCSymbol *From = GetSym(E->getOperand(0)); 355 const MCSymbol *To = GetSym(E->getOperand(1)); 356 // Skip null functions. This can happen if functions are dead stripped after 357 // the CGProfile pass has been run. 358 if (!From || !To) 359 continue; 360 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2)) 361 ->getValue() 362 ->getUniqueInteger() 363 .getZExtValue(); 364 Streamer.emitCGProfileEntry( 365 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), 366 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); 367 } 368 } 369 370 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 371 const GlobalValue *GV, const TargetMachine &TM, 372 MachineModuleInfo *MMI) const { 373 unsigned Encoding = getPersonalityEncoding(); 374 if ((Encoding & 0x80) == DW_EH_PE_indirect) 375 return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 376 TM.getSymbol(GV)->getName()); 377 if ((Encoding & 0x70) == DW_EH_PE_absptr) 378 return TM.getSymbol(GV); 379 report_fatal_error("We do not support this DWARF encoding yet!"); 380 } 381 382 void TargetLoweringObjectFileELF::emitPersonalityValue( 383 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { 384 SmallString<64> NameData("DW.ref."); 385 NameData += Sym->getName(); 386 MCSymbolELF *Label = 387 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 388 Streamer.emitSymbolAttribute(Label, MCSA_Hidden); 389 Streamer.emitSymbolAttribute(Label, MCSA_Weak); 390 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 391 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 392 ELF::SHT_PROGBITS, Flags, 0); 393 unsigned Size = DL.getPointerSize(); 394 Streamer.SwitchSection(Sec); 395 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value()); 396 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject); 397 const MCExpr *E = MCConstantExpr::create(Size, getContext()); 398 Streamer.emitELFSize(Label, E); 399 Streamer.emitLabel(Label); 400 401 Streamer.emitSymbolValue(Sym, Size); 402 } 403 404 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 405 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 406 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 407 if (Encoding & DW_EH_PE_indirect) { 408 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 409 410 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 411 412 // Add information about the stub reference to ELFMMI so that the stub 413 // gets emitted by the asmprinter. 414 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 415 if (!StubSym.getPointer()) { 416 MCSymbol *Sym = TM.getSymbol(GV); 417 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 418 } 419 420 return TargetLoweringObjectFile:: 421 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 422 Encoding & ~DW_EH_PE_indirect, Streamer); 423 } 424 425 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 426 MMI, Streamer); 427 } 428 429 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { 430 // N.B.: The defaults used in here are not the same ones used in MC. 431 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 432 // both gas and MC will produce a section with no flags. Given 433 // section(".eh_frame") gcc will produce: 434 // 435 // .section .eh_frame,"a",@progbits 436 437 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 438 /*AddSegmentInfo=*/false) || 439 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF, 440 /*AddSegmentInfo=*/false) || 441 Name == ".llvmbc" || Name == ".llvmcmd") 442 return SectionKind::getMetadata(); 443 444 if (Name.empty() || Name[0] != '.') return K; 445 446 // Default implementation based on some magic section names. 447 if (Name == ".bss" || 448 Name.startswith(".bss.") || 449 Name.startswith(".gnu.linkonce.b.") || 450 Name.startswith(".llvm.linkonce.b.") || 451 Name == ".sbss" || 452 Name.startswith(".sbss.") || 453 Name.startswith(".gnu.linkonce.sb.") || 454 Name.startswith(".llvm.linkonce.sb.")) 455 return SectionKind::getBSS(); 456 457 if (Name == ".tdata" || 458 Name.startswith(".tdata.") || 459 Name.startswith(".gnu.linkonce.td.") || 460 Name.startswith(".llvm.linkonce.td.")) 461 return SectionKind::getThreadData(); 462 463 if (Name == ".tbss" || 464 Name.startswith(".tbss.") || 465 Name.startswith(".gnu.linkonce.tb.") || 466 Name.startswith(".llvm.linkonce.tb.")) 467 return SectionKind::getThreadBSS(); 468 469 return K; 470 } 471 472 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 473 // Use SHT_NOTE for section whose name starts with ".note" to allow 474 // emitting ELF notes from C variable declaration. 475 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 476 if (Name.startswith(".note")) 477 return ELF::SHT_NOTE; 478 479 if (Name == ".init_array") 480 return ELF::SHT_INIT_ARRAY; 481 482 if (Name == ".fini_array") 483 return ELF::SHT_FINI_ARRAY; 484 485 if (Name == ".preinit_array") 486 return ELF::SHT_PREINIT_ARRAY; 487 488 if (K.isBSS() || K.isThreadBSS()) 489 return ELF::SHT_NOBITS; 490 491 return ELF::SHT_PROGBITS; 492 } 493 494 static unsigned getELFSectionFlags(SectionKind K) { 495 unsigned Flags = 0; 496 497 if (!K.isMetadata()) 498 Flags |= ELF::SHF_ALLOC; 499 500 if (K.isText()) 501 Flags |= ELF::SHF_EXECINSTR; 502 503 if (K.isExecuteOnly()) 504 Flags |= ELF::SHF_ARM_PURECODE; 505 506 if (K.isWriteable()) 507 Flags |= ELF::SHF_WRITE; 508 509 if (K.isThreadLocal()) 510 Flags |= ELF::SHF_TLS; 511 512 if (K.isMergeableCString() || K.isMergeableConst()) 513 Flags |= ELF::SHF_MERGE; 514 515 if (K.isMergeableCString()) 516 Flags |= ELF::SHF_STRINGS; 517 518 return Flags; 519 } 520 521 static const Comdat *getELFComdat(const GlobalValue *GV) { 522 const Comdat *C = GV->getComdat(); 523 if (!C) 524 return nullptr; 525 526 if (C->getSelectionKind() != Comdat::Any) 527 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 528 C->getName() + "' cannot be lowered."); 529 530 return C; 531 } 532 533 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO, 534 const TargetMachine &TM) { 535 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 536 if (!MD) 537 return nullptr; 538 539 const MDOperand &Op = MD->getOperand(0); 540 if (!Op.get()) 541 return nullptr; 542 543 auto *VM = dyn_cast<ValueAsMetadata>(Op); 544 if (!VM) 545 report_fatal_error("MD_associated operand is not ValueAsMetadata"); 546 547 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue()); 548 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr; 549 } 550 551 static unsigned getEntrySizeForKind(SectionKind Kind) { 552 if (Kind.isMergeable1ByteCString()) 553 return 1; 554 else if (Kind.isMergeable2ByteCString()) 555 return 2; 556 else if (Kind.isMergeable4ByteCString()) 557 return 4; 558 else if (Kind.isMergeableConst4()) 559 return 4; 560 else if (Kind.isMergeableConst8()) 561 return 8; 562 else if (Kind.isMergeableConst16()) 563 return 16; 564 else if (Kind.isMergeableConst32()) 565 return 32; 566 else { 567 // We shouldn't have mergeable C strings or mergeable constants that we 568 // didn't handle above. 569 assert(!Kind.isMergeableCString() && "unknown string width"); 570 assert(!Kind.isMergeableConst() && "unknown data width"); 571 return 0; 572 } 573 } 574 575 /// Return the section prefix name used by options FunctionsSections and 576 /// DataSections. 577 static StringRef getSectionPrefixForGlobal(SectionKind Kind) { 578 if (Kind.isText()) 579 return ".text"; 580 if (Kind.isReadOnly()) 581 return ".rodata"; 582 if (Kind.isBSS()) 583 return ".bss"; 584 if (Kind.isThreadData()) 585 return ".tdata"; 586 if (Kind.isThreadBSS()) 587 return ".tbss"; 588 if (Kind.isData()) 589 return ".data"; 590 if (Kind.isReadOnlyWithRel()) 591 return ".data.rel.ro"; 592 llvm_unreachable("Unknown section kind"); 593 } 594 595 static SmallString<128> 596 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, 597 Mangler &Mang, const TargetMachine &TM, 598 unsigned EntrySize, bool UniqueSectionName) { 599 SmallString<128> Name; 600 if (Kind.isMergeableCString()) { 601 // We also need alignment here. 602 // FIXME: this is getting the alignment of the character, not the 603 // alignment of the global! 604 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign( 605 cast<GlobalVariable>(GO)); 606 607 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 608 Name = SizeSpec + utostr(Alignment.value()); 609 } else if (Kind.isMergeableConst()) { 610 Name = ".rodata.cst"; 611 Name += utostr(EntrySize); 612 } else { 613 Name = getSectionPrefixForGlobal(Kind); 614 } 615 616 bool HasPrefix = false; 617 if (const auto *F = dyn_cast<Function>(GO)) { 618 if (Optional<StringRef> Prefix = F->getSectionPrefix()) { 619 Name += *Prefix; 620 HasPrefix = true; 621 } 622 } 623 624 if (UniqueSectionName) { 625 Name.push_back('.'); 626 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true); 627 } else if (HasPrefix) 628 Name.push_back('.'); 629 return Name; 630 } 631 632 namespace { 633 class LoweringDiagnosticInfo : public DiagnosticInfo { 634 const Twine &Msg; 635 636 public: 637 LoweringDiagnosticInfo(const Twine &DiagMsg, 638 DiagnosticSeverity Severity = DS_Error) 639 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {} 640 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 641 }; 642 } 643 644 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 645 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 646 StringRef SectionName = GO->getSection(); 647 648 // Check if '#pragma clang section' name is applicable. 649 // Note that pragma directive overrides -ffunction-section, -fdata-section 650 // and so section name is exactly as user specified and not uniqued. 651 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 652 if (GV && GV->hasImplicitSection()) { 653 auto Attrs = GV->getAttributes(); 654 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { 655 SectionName = Attrs.getAttribute("bss-section").getValueAsString(); 656 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { 657 SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); 658 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) { 659 SectionName = Attrs.getAttribute("relro-section").getValueAsString(); 660 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { 661 SectionName = Attrs.getAttribute("data-section").getValueAsString(); 662 } 663 } 664 const Function *F = dyn_cast<Function>(GO); 665 if (F && F->hasFnAttribute("implicit-section-name")) { 666 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); 667 } 668 669 // Infer section flags from the section name if we can. 670 Kind = getELFKindForNamedSection(SectionName, Kind); 671 672 StringRef Group = ""; 673 unsigned Flags = getELFSectionFlags(Kind); 674 if (const Comdat *C = getELFComdat(GO)) { 675 Group = C->getName(); 676 Flags |= ELF::SHF_GROUP; 677 } 678 679 unsigned EntrySize = getEntrySizeForKind(Kind); 680 681 // A section can have at most one associated section. Put each global with 682 // MD_associated in a unique section. 683 unsigned UniqueID = MCContext::GenericSectionID; 684 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 685 if (GO->getMetadata(LLVMContext::MD_associated)) { 686 UniqueID = NextUniqueID++; 687 Flags |= ELF::SHF_LINK_ORDER; 688 } else { 689 if (getContext().getAsmInfo()->useIntegratedAssembler()) { 690 // Symbols must be placed into sections with compatible entry 691 // sizes. Generate unique sections for symbols that have not 692 // been assigned to compatible sections. 693 if (Flags & ELF::SHF_MERGE) { 694 auto maybeID = getContext().getELFUniqueIDForEntsize(SectionName, Flags, 695 EntrySize); 696 if (maybeID) 697 UniqueID = *maybeID; 698 else { 699 // If the user has specified the same section name as would be created 700 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need 701 // to unique the section as the entry size for this symbol will be 702 // compatible with implicitly created sections. 703 SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal( 704 GO, Kind, getMangler(), TM, EntrySize, false); 705 if (!(getContext().isELFImplicitMergeableSectionNamePrefix( 706 SectionName) && 707 SectionName.startswith(ImplicitSectionNameStem))) 708 UniqueID = NextUniqueID++; 709 } 710 } else { 711 // We need to unique the section if the user has explicity 712 // assigned a non-mergeable symbol to a section name for 713 // a generic mergeable section. 714 if (getContext().isELFGenericMergeableSection(SectionName)) { 715 auto maybeID = getContext().getELFUniqueIDForEntsize( 716 SectionName, Flags, EntrySize); 717 UniqueID = maybeID ? *maybeID : NextUniqueID++; 718 } 719 } 720 } else { 721 // If two symbols with differing sizes end up in the same mergeable 722 // section that section can be assigned an incorrect entry size. To avoid 723 // this we usually put symbols of the same size into distinct mergeable 724 // sections with the same name. Doing so relies on the ",unique ," 725 // assembly feature. This feature is not avalible until bintuils 726 // version 2.35 (https://sourceware.org/bugzilla/show_bug.cgi?id=25380). 727 Flags &= ~ELF::SHF_MERGE; 728 EntrySize = 0; 729 } 730 } 731 732 MCSectionELF *Section = getContext().getELFSection( 733 SectionName, getELFSectionType(SectionName, Kind), Flags, 734 EntrySize, Group, UniqueID, LinkedToSym); 735 // Make sure that we did not get some other section with incompatible sh_link. 736 // This should not be possible due to UniqueID code above. 737 assert(Section->getLinkedToSymbol() == LinkedToSym && 738 "Associated symbol mismatch between sections"); 739 740 if (!getContext().getAsmInfo()->useIntegratedAssembler()) { 741 // If we are not using the integrated assembler then this symbol might have 742 // been placed in an incompatible mergeable section. Emit an error if this 743 // is the case to avoid creating broken output. 744 if ((Section->getFlags() & ELF::SHF_MERGE) && 745 (Section->getEntrySize() != getEntrySizeForKind(Kind))) 746 GO->getContext().diagnose(LoweringDiagnosticInfo( 747 "Symbol '" + GO->getName() + "' from module '" + 748 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") + 749 "' required a section with entry-size=" + 750 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" + 751 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) + 752 ": Explicit assignment by pragma or attribute of an incompatible " 753 "symbol to this section?")); 754 } 755 756 return Section; 757 } 758 759 static MCSectionELF *selectELFSectionForGlobal( 760 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 761 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 762 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 763 764 StringRef Group = ""; 765 if (const Comdat *C = getELFComdat(GO)) { 766 Flags |= ELF::SHF_GROUP; 767 Group = C->getName(); 768 } 769 770 // Get the section entry size based on the kind. 771 unsigned EntrySize = getEntrySizeForKind(Kind); 772 773 bool UniqueSectionName = false; 774 unsigned UniqueID = MCContext::GenericSectionID; 775 if (EmitUniqueSection) { 776 if (TM.getUniqueSectionNames()) { 777 UniqueSectionName = true; 778 } else { 779 UniqueID = *NextUniqueID; 780 (*NextUniqueID)++; 781 } 782 } 783 SmallString<128> Name = getELFSectionNameForGlobal( 784 GO, Kind, Mang, TM, EntrySize, UniqueSectionName); 785 786 // Use 0 as the unique ID for execute-only text. 787 if (Kind.isExecuteOnly()) 788 UniqueID = 0; 789 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 790 EntrySize, Group, UniqueID, AssociatedSymbol); 791 } 792 793 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 794 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 795 unsigned Flags = getELFSectionFlags(Kind); 796 797 // If we have -ffunction-section or -fdata-section then we should emit the 798 // global value to a uniqued section specifically for it. 799 bool EmitUniqueSection = false; 800 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 801 if (Kind.isText()) 802 EmitUniqueSection = TM.getFunctionSections(); 803 else 804 EmitUniqueSection = TM.getDataSections(); 805 } 806 EmitUniqueSection |= GO->hasComdat(); 807 808 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 809 if (LinkedToSym) { 810 EmitUniqueSection = true; 811 Flags |= ELF::SHF_LINK_ORDER; 812 } 813 814 MCSectionELF *Section = selectELFSectionForGlobal( 815 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, 816 &NextUniqueID, LinkedToSym); 817 assert(Section->getLinkedToSymbol() == LinkedToSym); 818 return Section; 819 } 820 821 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 822 const Function &F, const TargetMachine &TM) const { 823 // If the function can be removed, produce a unique section so that 824 // the table doesn't prevent the removal. 825 const Comdat *C = F.getComdat(); 826 bool EmitUniqueSection = TM.getFunctionSections() || C; 827 if (!EmitUniqueSection) 828 return ReadOnlySection; 829 830 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 831 getMangler(), TM, EmitUniqueSection, 832 ELF::SHF_ALLOC, &NextUniqueID, 833 /* AssociatedSymbol */ nullptr); 834 } 835 836 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 837 bool UsesLabelDifference, const Function &F) const { 838 // We can always create relative relocations, so use another section 839 // that can be marked non-executable. 840 return false; 841 } 842 843 /// Given a mergeable constant with the specified size and relocation 844 /// information, return a section that it should be placed in. 845 MCSection *TargetLoweringObjectFileELF::getSectionForConstant( 846 const DataLayout &DL, SectionKind Kind, const Constant *C, 847 Align &Alignment) const { 848 if (Kind.isMergeableConst4() && MergeableConst4Section) 849 return MergeableConst4Section; 850 if (Kind.isMergeableConst8() && MergeableConst8Section) 851 return MergeableConst8Section; 852 if (Kind.isMergeableConst16() && MergeableConst16Section) 853 return MergeableConst16Section; 854 if (Kind.isMergeableConst32() && MergeableConst32Section) 855 return MergeableConst32Section; 856 if (Kind.isReadOnly()) 857 return ReadOnlySection; 858 859 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 860 return DataRelROSection; 861 } 862 863 /// Returns a unique section for the given machine basic block. 864 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock( 865 const Function &F, const MachineBasicBlock &MBB, 866 const TargetMachine &TM) const { 867 assert(MBB.isBeginSection() && "Basic block does not start a section!"); 868 unsigned UniqueID = MCContext::GenericSectionID; 869 870 // For cold sections use the .text.unlikely prefix along with the parent 871 // function name. All cold blocks for the same function go to the same 872 // section. Similarly all exception blocks are grouped by symbol name 873 // under the .text.eh prefix. For regular sections, we either use a unique 874 // name, or a unique ID for the section. 875 SmallString<128> Name; 876 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) { 877 Name += BBSectionsColdTextPrefix; 878 Name += MBB.getParent()->getName(); 879 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) { 880 Name += ".text.eh."; 881 Name += MBB.getParent()->getName(); 882 } else { 883 Name += MBB.getParent()->getSection()->getName(); 884 if (TM.getUniqueBasicBlockSectionNames()) { 885 Name += "."; 886 Name += MBB.getSymbol()->getName(); 887 } else { 888 UniqueID = NextUniqueID++; 889 } 890 } 891 892 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR; 893 std::string GroupName = ""; 894 if (F.hasComdat()) { 895 Flags |= ELF::SHF_GROUP; 896 GroupName = F.getComdat()->getName().str(); 897 } 898 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 899 0 /* Entry Size */, GroupName, UniqueID, 900 nullptr); 901 } 902 903 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 904 bool IsCtor, unsigned Priority, 905 const MCSymbol *KeySym) { 906 std::string Name; 907 unsigned Type; 908 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 909 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 910 911 if (KeySym) 912 Flags |= ELF::SHF_GROUP; 913 914 if (UseInitArray) { 915 if (IsCtor) { 916 Type = ELF::SHT_INIT_ARRAY; 917 Name = ".init_array"; 918 } else { 919 Type = ELF::SHT_FINI_ARRAY; 920 Name = ".fini_array"; 921 } 922 if (Priority != 65535) { 923 Name += '.'; 924 Name += utostr(Priority); 925 } 926 } else { 927 // The default scheme is .ctor / .dtor, so we have to invert the priority 928 // numbering. 929 if (IsCtor) 930 Name = ".ctors"; 931 else 932 Name = ".dtors"; 933 if (Priority != 65535) 934 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 935 Type = ELF::SHT_PROGBITS; 936 } 937 938 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 939 } 940 941 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 942 unsigned Priority, const MCSymbol *KeySym) const { 943 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 944 KeySym); 945 } 946 947 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 948 unsigned Priority, const MCSymbol *KeySym) const { 949 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 950 KeySym); 951 } 952 953 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 954 const GlobalValue *LHS, const GlobalValue *RHS, 955 const TargetMachine &TM) const { 956 // We may only use a PLT-relative relocation to refer to unnamed_addr 957 // functions. 958 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 959 return nullptr; 960 961 // Basic sanity checks. 962 if (LHS->getType()->getPointerAddressSpace() != 0 || 963 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 964 RHS->isThreadLocal()) 965 return nullptr; 966 967 return MCBinaryExpr::createSub( 968 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 969 getContext()), 970 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 971 } 972 973 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const { 974 // Use ".GCC.command.line" since this feature is to support clang's 975 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the 976 // same name. 977 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS, 978 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 979 } 980 981 void 982 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 983 UseInitArray = UseInitArray_; 984 MCContext &Ctx = getContext(); 985 if (!UseInitArray) { 986 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 987 ELF::SHF_ALLOC | ELF::SHF_WRITE); 988 989 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 990 ELF::SHF_ALLOC | ELF::SHF_WRITE); 991 return; 992 } 993 994 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 995 ELF::SHF_WRITE | ELF::SHF_ALLOC); 996 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 997 ELF::SHF_WRITE | ELF::SHF_ALLOC); 998 } 999 1000 //===----------------------------------------------------------------------===// 1001 // MachO 1002 //===----------------------------------------------------------------------===// 1003 1004 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 1005 : TargetLoweringObjectFile() { 1006 SupportIndirectSymViaGOTPCRel = true; 1007 } 1008 1009 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 1010 const TargetMachine &TM) { 1011 TargetLoweringObjectFile::Initialize(Ctx, TM); 1012 if (TM.getRelocationModel() == Reloc::Static) { 1013 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 1014 SectionKind::getData()); 1015 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 1016 SectionKind::getData()); 1017 } else { 1018 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 1019 MachO::S_MOD_INIT_FUNC_POINTERS, 1020 SectionKind::getData()); 1021 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 1022 MachO::S_MOD_TERM_FUNC_POINTERS, 1023 SectionKind::getData()); 1024 } 1025 1026 PersonalityEncoding = 1027 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1028 LSDAEncoding = dwarf::DW_EH_PE_pcrel; 1029 TTypeEncoding = 1030 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1031 } 1032 1033 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, 1034 Module &M) const { 1035 // Emit the linker options if present. 1036 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1037 for (const auto *Option : LinkerOptions->operands()) { 1038 SmallVector<std::string, 4> StrOptions; 1039 for (const auto &Piece : cast<MDNode>(Option)->operands()) 1040 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString())); 1041 Streamer.emitLinkerOptions(StrOptions); 1042 } 1043 } 1044 1045 unsigned VersionVal = 0; 1046 unsigned ImageInfoFlags = 0; 1047 StringRef SectionVal; 1048 1049 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 1050 1051 // The section is mandatory. If we don't have it, then we don't have GC info. 1052 if (SectionVal.empty()) 1053 return; 1054 1055 StringRef Segment, Section; 1056 unsigned TAA = 0, StubSize = 0; 1057 bool TAAParsed; 1058 std::string ErrorCode = 1059 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 1060 TAA, TAAParsed, StubSize); 1061 if (!ErrorCode.empty()) 1062 // If invalid, report the error with report_fatal_error. 1063 report_fatal_error("Invalid section specifier '" + Section + "': " + 1064 ErrorCode + "."); 1065 1066 // Get the section. 1067 MCSectionMachO *S = getContext().getMachOSection( 1068 Segment, Section, TAA, StubSize, SectionKind::getData()); 1069 Streamer.SwitchSection(S); 1070 Streamer.emitLabel(getContext(). 1071 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 1072 Streamer.emitInt32(VersionVal); 1073 Streamer.emitInt32(ImageInfoFlags); 1074 Streamer.AddBlankLine(); 1075 } 1076 1077 static void checkMachOComdat(const GlobalValue *GV) { 1078 const Comdat *C = GV->getComdat(); 1079 if (!C) 1080 return; 1081 1082 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 1083 "' cannot be lowered."); 1084 } 1085 1086 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 1087 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1088 // Parse the section specifier and create it if valid. 1089 StringRef Segment, Section; 1090 unsigned TAA = 0, StubSize = 0; 1091 bool TAAParsed; 1092 1093 checkMachOComdat(GO); 1094 1095 std::string ErrorCode = 1096 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, 1097 TAA, TAAParsed, StubSize); 1098 if (!ErrorCode.empty()) { 1099 // If invalid, report the error with report_fatal_error. 1100 report_fatal_error("Global variable '" + GO->getName() + 1101 "' has an invalid section specifier '" + 1102 GO->getSection() + "': " + ErrorCode + "."); 1103 } 1104 1105 // Get the section. 1106 MCSectionMachO *S = 1107 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 1108 1109 // If TAA wasn't set by ParseSectionSpecifier() above, 1110 // use the value returned by getMachOSection() as a default. 1111 if (!TAAParsed) 1112 TAA = S->getTypeAndAttributes(); 1113 1114 // Okay, now that we got the section, verify that the TAA & StubSize agree. 1115 // If the user declared multiple globals with different section flags, we need 1116 // to reject it here. 1117 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 1118 // If invalid, report the error with report_fatal_error. 1119 report_fatal_error("Global variable '" + GO->getName() + 1120 "' section type or attributes does not match previous" 1121 " section specifier"); 1122 } 1123 1124 return S; 1125 } 1126 1127 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 1128 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1129 checkMachOComdat(GO); 1130 1131 // Handle thread local data. 1132 if (Kind.isThreadBSS()) return TLSBSSSection; 1133 if (Kind.isThreadData()) return TLSDataSection; 1134 1135 if (Kind.isText()) 1136 return GO->isWeakForLinker() ? TextCoalSection : TextSection; 1137 1138 // If this is weak/linkonce, put this in a coalescable section, either in text 1139 // or data depending on if it is writable. 1140 if (GO->isWeakForLinker()) { 1141 if (Kind.isReadOnly()) 1142 return ConstTextCoalSection; 1143 if (Kind.isReadOnlyWithRel()) 1144 return ConstDataCoalSection; 1145 return DataCoalSection; 1146 } 1147 1148 // FIXME: Alignment check should be handled by section classifier. 1149 if (Kind.isMergeable1ByteCString() && 1150 GO->getParent()->getDataLayout().getPreferredAlign( 1151 cast<GlobalVariable>(GO)) < Align(32)) 1152 return CStringSection; 1153 1154 // Do not put 16-bit arrays in the UString section if they have an 1155 // externally visible label, this runs into issues with certain linker 1156 // versions. 1157 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 1158 GO->getParent()->getDataLayout().getPreferredAlign( 1159 cast<GlobalVariable>(GO)) < Align(32)) 1160 return UStringSection; 1161 1162 // With MachO only variables whose corresponding symbol starts with 'l' or 1163 // 'L' can be merged, so we only try merging GVs with private linkage. 1164 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 1165 if (Kind.isMergeableConst4()) 1166 return FourByteConstantSection; 1167 if (Kind.isMergeableConst8()) 1168 return EightByteConstantSection; 1169 if (Kind.isMergeableConst16()) 1170 return SixteenByteConstantSection; 1171 } 1172 1173 // Otherwise, if it is readonly, but not something we can specially optimize, 1174 // just drop it in .const. 1175 if (Kind.isReadOnly()) 1176 return ReadOnlySection; 1177 1178 // If this is marked const, put it into a const section. But if the dynamic 1179 // linker needs to write to it, put it in the data segment. 1180 if (Kind.isReadOnlyWithRel()) 1181 return ConstDataSection; 1182 1183 // Put zero initialized globals with strong external linkage in the 1184 // DATA, __common section with the .zerofill directive. 1185 if (Kind.isBSSExtern()) 1186 return DataCommonSection; 1187 1188 // Put zero initialized globals with local linkage in __DATA,__bss directive 1189 // with the .zerofill directive (aka .lcomm). 1190 if (Kind.isBSSLocal()) 1191 return DataBSSSection; 1192 1193 // Otherwise, just drop the variable in the normal data section. 1194 return DataSection; 1195 } 1196 1197 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 1198 const DataLayout &DL, SectionKind Kind, const Constant *C, 1199 Align &Alignment) const { 1200 // If this constant requires a relocation, we have to put it in the data 1201 // segment, not in the text segment. 1202 if (Kind.isData() || Kind.isReadOnlyWithRel()) 1203 return ConstDataSection; 1204 1205 if (Kind.isMergeableConst4()) 1206 return FourByteConstantSection; 1207 if (Kind.isMergeableConst8()) 1208 return EightByteConstantSection; 1209 if (Kind.isMergeableConst16()) 1210 return SixteenByteConstantSection; 1211 return ReadOnlySection; // .const 1212 } 1213 1214 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 1215 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 1216 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1217 // The mach-o version of this method defaults to returning a stub reference. 1218 1219 if (Encoding & DW_EH_PE_indirect) { 1220 MachineModuleInfoMachO &MachOMMI = 1221 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1222 1223 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1224 1225 // Add information about the stub reference to MachOMMI so that the stub 1226 // gets emitted by the asmprinter. 1227 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1228 if (!StubSym.getPointer()) { 1229 MCSymbol *Sym = TM.getSymbol(GV); 1230 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1231 } 1232 1233 return TargetLoweringObjectFile:: 1234 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 1235 Encoding & ~DW_EH_PE_indirect, Streamer); 1236 } 1237 1238 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 1239 MMI, Streamer); 1240 } 1241 1242 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 1243 const GlobalValue *GV, const TargetMachine &TM, 1244 MachineModuleInfo *MMI) const { 1245 // The mach-o version of this method defaults to returning a stub reference. 1246 MachineModuleInfoMachO &MachOMMI = 1247 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1248 1249 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1250 1251 // Add information about the stub reference to MachOMMI so that the stub 1252 // gets emitted by the asmprinter. 1253 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1254 if (!StubSym.getPointer()) { 1255 MCSymbol *Sym = TM.getSymbol(GV); 1256 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1257 } 1258 1259 return SSym; 1260 } 1261 1262 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 1263 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, 1264 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1265 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 1266 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 1267 // through a non_lazy_ptr stub instead. One advantage is that it allows the 1268 // computation of deltas to final external symbols. Example: 1269 // 1270 // _extgotequiv: 1271 // .long _extfoo 1272 // 1273 // _delta: 1274 // .long _extgotequiv-_delta 1275 // 1276 // is transformed to: 1277 // 1278 // _delta: 1279 // .long L_extfoo$non_lazy_ptr-(_delta+0) 1280 // 1281 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 1282 // L_extfoo$non_lazy_ptr: 1283 // .indirect_symbol _extfoo 1284 // .long 0 1285 // 1286 // The indirect symbol table (and sections of non_lazy_symbol_pointers type) 1287 // may point to both local (same translation unit) and global (other 1288 // translation units) symbols. Example: 1289 // 1290 // .section __DATA,__pointers,non_lazy_symbol_pointers 1291 // L1: 1292 // .indirect_symbol _myGlobal 1293 // .long 0 1294 // L2: 1295 // .indirect_symbol _myLocal 1296 // .long _myLocal 1297 // 1298 // If the symbol is local, instead of the symbol's index, the assembler 1299 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table. 1300 // Then the linker will notice the constant in the table and will look at the 1301 // content of the symbol. 1302 MachineModuleInfoMachO &MachOMMI = 1303 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1304 MCContext &Ctx = getContext(); 1305 1306 // The offset must consider the original displacement from the base symbol 1307 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 1308 Offset = -MV.getConstant(); 1309 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 1310 1311 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 1312 // non_lazy_ptr stubs. 1313 SmallString<128> Name; 1314 StringRef Suffix = "$non_lazy_ptr"; 1315 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 1316 Name += Sym->getName(); 1317 Name += Suffix; 1318 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 1319 1320 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 1321 1322 if (!StubSym.getPointer()) 1323 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym), 1324 !GV->hasLocalLinkage()); 1325 1326 const MCExpr *BSymExpr = 1327 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 1328 const MCExpr *LHS = 1329 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 1330 1331 if (!Offset) 1332 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 1333 1334 const MCExpr *RHS = 1335 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 1336 return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1337 } 1338 1339 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 1340 const MCSection &Section) { 1341 if (!AsmInfo.isSectionAtomizableBySymbols(Section)) 1342 return true; 1343 1344 // If it is not dead stripped, it is safe to use private labels. 1345 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section); 1346 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) 1347 return true; 1348 1349 return false; 1350 } 1351 1352 void TargetLoweringObjectFileMachO::getNameWithPrefix( 1353 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1354 const TargetMachine &TM) const { 1355 bool CannotUsePrivateLabel = true; 1356 if (auto *GO = GV->getBaseObject()) { 1357 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 1358 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 1359 CannotUsePrivateLabel = 1360 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 1361 } 1362 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1363 } 1364 1365 //===----------------------------------------------------------------------===// 1366 // COFF 1367 //===----------------------------------------------------------------------===// 1368 1369 static unsigned 1370 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 1371 unsigned Flags = 0; 1372 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 1373 1374 if (K.isMetadata()) 1375 Flags |= 1376 COFF::IMAGE_SCN_MEM_DISCARDABLE; 1377 else if (K.isText()) 1378 Flags |= 1379 COFF::IMAGE_SCN_MEM_EXECUTE | 1380 COFF::IMAGE_SCN_MEM_READ | 1381 COFF::IMAGE_SCN_CNT_CODE | 1382 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 1383 else if (K.isBSS()) 1384 Flags |= 1385 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 1386 COFF::IMAGE_SCN_MEM_READ | 1387 COFF::IMAGE_SCN_MEM_WRITE; 1388 else if (K.isThreadLocal()) 1389 Flags |= 1390 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1391 COFF::IMAGE_SCN_MEM_READ | 1392 COFF::IMAGE_SCN_MEM_WRITE; 1393 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 1394 Flags |= 1395 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1396 COFF::IMAGE_SCN_MEM_READ; 1397 else if (K.isWriteable()) 1398 Flags |= 1399 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1400 COFF::IMAGE_SCN_MEM_READ | 1401 COFF::IMAGE_SCN_MEM_WRITE; 1402 1403 return Flags; 1404 } 1405 1406 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 1407 const Comdat *C = GV->getComdat(); 1408 assert(C && "expected GV to have a Comdat!"); 1409 1410 StringRef ComdatGVName = C->getName(); 1411 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 1412 if (!ComdatGV) 1413 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1414 "' does not exist."); 1415 1416 if (ComdatGV->getComdat() != C) 1417 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1418 "' is not a key for its COMDAT."); 1419 1420 return ComdatGV; 1421 } 1422 1423 static int getSelectionForCOFF(const GlobalValue *GV) { 1424 if (const Comdat *C = GV->getComdat()) { 1425 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 1426 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 1427 ComdatKey = GA->getBaseObject(); 1428 if (ComdatKey == GV) { 1429 switch (C->getSelectionKind()) { 1430 case Comdat::Any: 1431 return COFF::IMAGE_COMDAT_SELECT_ANY; 1432 case Comdat::ExactMatch: 1433 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1434 case Comdat::Largest: 1435 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1436 case Comdat::NoDuplicates: 1437 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1438 case Comdat::SameSize: 1439 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1440 } 1441 } else { 1442 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1443 } 1444 } 1445 return 0; 1446 } 1447 1448 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1449 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1450 int Selection = 0; 1451 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1452 StringRef Name = GO->getSection(); 1453 StringRef COMDATSymName = ""; 1454 if (GO->hasComdat()) { 1455 Selection = getSelectionForCOFF(GO); 1456 const GlobalValue *ComdatGV; 1457 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1458 ComdatGV = getComdatGVForCOFF(GO); 1459 else 1460 ComdatGV = GO; 1461 1462 if (!ComdatGV->hasPrivateLinkage()) { 1463 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1464 COMDATSymName = Sym->getName(); 1465 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1466 } else { 1467 Selection = 0; 1468 } 1469 } 1470 1471 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1472 Selection); 1473 } 1474 1475 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1476 if (Kind.isText()) 1477 return ".text"; 1478 if (Kind.isBSS()) 1479 return ".bss"; 1480 if (Kind.isThreadLocal()) 1481 return ".tls$"; 1482 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1483 return ".rdata"; 1484 return ".data"; 1485 } 1486 1487 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1488 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1489 // If we have -ffunction-sections then we should emit the global value to a 1490 // uniqued section specifically for it. 1491 bool EmitUniquedSection; 1492 if (Kind.isText()) 1493 EmitUniquedSection = TM.getFunctionSections(); 1494 else 1495 EmitUniquedSection = TM.getDataSections(); 1496 1497 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1498 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); 1499 1500 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1501 1502 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1503 int Selection = getSelectionForCOFF(GO); 1504 if (!Selection) 1505 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1506 const GlobalValue *ComdatGV; 1507 if (GO->hasComdat()) 1508 ComdatGV = getComdatGVForCOFF(GO); 1509 else 1510 ComdatGV = GO; 1511 1512 unsigned UniqueID = MCContext::GenericSectionID; 1513 if (EmitUniquedSection) 1514 UniqueID = NextUniqueID++; 1515 1516 if (!ComdatGV->hasPrivateLinkage()) { 1517 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1518 StringRef COMDATSymName = Sym->getName(); 1519 1520 // Append "$symbol" to the section name *before* IR-level mangling is 1521 // applied when targetting mingw. This is what GCC does, and the ld.bfd 1522 // COFF linker will not properly handle comdats otherwise. 1523 if (getTargetTriple().isWindowsGNUEnvironment()) 1524 raw_svector_ostream(Name) << '$' << ComdatGV->getName(); 1525 1526 return getContext().getCOFFSection(Name, Characteristics, Kind, 1527 COMDATSymName, Selection, UniqueID); 1528 } else { 1529 SmallString<256> TmpData; 1530 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1531 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 1532 Selection, UniqueID); 1533 } 1534 } 1535 1536 if (Kind.isText()) 1537 return TextSection; 1538 1539 if (Kind.isThreadLocal()) 1540 return TLSDataSection; 1541 1542 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1543 return ReadOnlySection; 1544 1545 // Note: we claim that common symbols are put in BSSSection, but they are 1546 // really emitted with the magic .comm directive, which creates a symbol table 1547 // entry but not a section. 1548 if (Kind.isBSS() || Kind.isCommon()) 1549 return BSSSection; 1550 1551 return DataSection; 1552 } 1553 1554 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 1555 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1556 const TargetMachine &TM) const { 1557 bool CannotUsePrivateLabel = false; 1558 if (GV->hasPrivateLinkage() && 1559 ((isa<Function>(GV) && TM.getFunctionSections()) || 1560 (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1561 CannotUsePrivateLabel = true; 1562 1563 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1564 } 1565 1566 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1567 const Function &F, const TargetMachine &TM) const { 1568 // If the function can be removed, produce a unique section so that 1569 // the table doesn't prevent the removal. 1570 const Comdat *C = F.getComdat(); 1571 bool EmitUniqueSection = TM.getFunctionSections() || C; 1572 if (!EmitUniqueSection) 1573 return ReadOnlySection; 1574 1575 // FIXME: we should produce a symbol for F instead. 1576 if (F.hasPrivateLinkage()) 1577 return ReadOnlySection; 1578 1579 MCSymbol *Sym = TM.getSymbol(&F); 1580 StringRef COMDATSymName = Sym->getName(); 1581 1582 SectionKind Kind = SectionKind::getReadOnly(); 1583 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); 1584 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1585 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1586 unsigned UniqueID = NextUniqueID++; 1587 1588 return getContext().getCOFFSection( 1589 SecName, Characteristics, Kind, COMDATSymName, 1590 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 1591 } 1592 1593 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, 1594 Module &M) const { 1595 emitLinkerDirectives(Streamer, M); 1596 1597 unsigned Version = 0; 1598 unsigned Flags = 0; 1599 StringRef Section; 1600 1601 GetObjCImageInfo(M, Version, Flags, Section); 1602 if (Section.empty()) 1603 return; 1604 1605 auto &C = getContext(); 1606 auto *S = C.getCOFFSection( 1607 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1608 SectionKind::getReadOnly()); 1609 Streamer.SwitchSection(S); 1610 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1611 Streamer.emitInt32(Version); 1612 Streamer.emitInt32(Flags); 1613 Streamer.AddBlankLine(); 1614 } 1615 1616 void TargetLoweringObjectFileCOFF::emitLinkerDirectives( 1617 MCStreamer &Streamer, Module &M) const { 1618 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1619 // Emit the linker options to the linker .drectve section. According to the 1620 // spec, this section is a space-separated string containing flags for 1621 // linker. 1622 MCSection *Sec = getDrectveSection(); 1623 Streamer.SwitchSection(Sec); 1624 for (const auto *Option : LinkerOptions->operands()) { 1625 for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1626 // Lead with a space for consistency with our dllexport implementation. 1627 std::string Directive(" "); 1628 Directive.append(std::string(cast<MDString>(Piece)->getString())); 1629 Streamer.emitBytes(Directive); 1630 } 1631 } 1632 } 1633 1634 // Emit /EXPORT: flags for each exported global as necessary. 1635 std::string Flags; 1636 for (const GlobalValue &GV : M.global_values()) { 1637 raw_string_ostream OS(Flags); 1638 emitLinkerFlagsForGlobalCOFF(OS, &GV, getTargetTriple(), getMangler()); 1639 OS.flush(); 1640 if (!Flags.empty()) { 1641 Streamer.SwitchSection(getDrectveSection()); 1642 Streamer.emitBytes(Flags); 1643 } 1644 Flags.clear(); 1645 } 1646 1647 // Emit /INCLUDE: flags for each used global as necessary. 1648 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1649 assert(LU->hasInitializer() && "expected llvm.used to have an initializer"); 1650 assert(isa<ArrayType>(LU->getValueType()) && 1651 "expected llvm.used to be an array type"); 1652 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1653 for (const Value *Op : A->operands()) { 1654 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1655 // Global symbols with internal or private linkage are not visible to 1656 // the linker, and thus would cause an error when the linker tried to 1657 // preserve the symbol due to the `/include:` directive. 1658 if (GV->hasLocalLinkage()) 1659 continue; 1660 1661 raw_string_ostream OS(Flags); 1662 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler()); 1663 OS.flush(); 1664 1665 if (!Flags.empty()) { 1666 Streamer.SwitchSection(getDrectveSection()); 1667 Streamer.emitBytes(Flags); 1668 } 1669 Flags.clear(); 1670 } 1671 } 1672 } 1673 } 1674 1675 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1676 const TargetMachine &TM) { 1677 TargetLoweringObjectFile::Initialize(Ctx, TM); 1678 const Triple &T = TM.getTargetTriple(); 1679 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1680 StaticCtorSection = 1681 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1682 COFF::IMAGE_SCN_MEM_READ, 1683 SectionKind::getReadOnly()); 1684 StaticDtorSection = 1685 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1686 COFF::IMAGE_SCN_MEM_READ, 1687 SectionKind::getReadOnly()); 1688 } else { 1689 StaticCtorSection = Ctx.getCOFFSection( 1690 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1691 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1692 SectionKind::getData()); 1693 StaticDtorSection = Ctx.getCOFFSection( 1694 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1695 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1696 SectionKind::getData()); 1697 } 1698 } 1699 1700 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, 1701 const Triple &T, bool IsCtor, 1702 unsigned Priority, 1703 const MCSymbol *KeySym, 1704 MCSectionCOFF *Default) { 1705 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1706 // If the priority is the default, use .CRT$XCU, possibly associative. 1707 if (Priority == 65535) 1708 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); 1709 1710 // Otherwise, we need to compute a new section name. Low priorities should 1711 // run earlier. The linker will sort sections ASCII-betically, and we need a 1712 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we 1713 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really 1714 // low priorities need to sort before 'L', since the CRT uses that 1715 // internally, so we use ".CRT$XCA00001" for them. 1716 SmallString<24> Name; 1717 raw_svector_ostream OS(Name); 1718 OS << ".CRT$X" << (IsCtor ? "C" : "T") << 1719 (Priority < 200 ? 'A' : 'T') << format("%05u", Priority); 1720 MCSectionCOFF *Sec = Ctx.getCOFFSection( 1721 Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1722 SectionKind::getReadOnly()); 1723 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0); 1724 } 1725 1726 std::string Name = IsCtor ? ".ctors" : ".dtors"; 1727 if (Priority != 65535) 1728 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1729 1730 return Ctx.getAssociativeCOFFSection( 1731 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1732 COFF::IMAGE_SCN_MEM_READ | 1733 COFF::IMAGE_SCN_MEM_WRITE, 1734 SectionKind::getData()), 1735 KeySym, 0); 1736 } 1737 1738 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1739 unsigned Priority, const MCSymbol *KeySym) const { 1740 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true, 1741 Priority, KeySym, 1742 cast<MCSectionCOFF>(StaticCtorSection)); 1743 } 1744 1745 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1746 unsigned Priority, const MCSymbol *KeySym) const { 1747 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false, 1748 Priority, KeySym, 1749 cast<MCSectionCOFF>(StaticDtorSection)); 1750 } 1751 1752 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( 1753 const GlobalValue *LHS, const GlobalValue *RHS, 1754 const TargetMachine &TM) const { 1755 const Triple &T = TM.getTargetTriple(); 1756 if (T.isOSCygMing()) 1757 return nullptr; 1758 1759 // Our symbols should exist in address space zero, cowardly no-op if 1760 // otherwise. 1761 if (LHS->getType()->getPointerAddressSpace() != 0 || 1762 RHS->getType()->getPointerAddressSpace() != 0) 1763 return nullptr; 1764 1765 // Both ptrtoint instructions must wrap global objects: 1766 // - Only global variables are eligible for image relative relocations. 1767 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. 1768 // We expect __ImageBase to be a global variable without a section, externally 1769 // defined. 1770 // 1771 // It should look something like this: @__ImageBase = external constant i8 1772 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) || 1773 LHS->isThreadLocal() || RHS->isThreadLocal() || 1774 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || 1775 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection()) 1776 return nullptr; 1777 1778 return MCSymbolRefExpr::create(TM.getSymbol(LHS), 1779 MCSymbolRefExpr::VK_COFF_IMGREL32, 1780 getContext()); 1781 } 1782 1783 static std::string APIntToHexString(const APInt &AI) { 1784 unsigned Width = (AI.getBitWidth() / 8) * 2; 1785 std::string HexString = AI.toString(16, /*Signed=*/false); 1786 llvm::transform(HexString, HexString.begin(), tolower); 1787 unsigned Size = HexString.size(); 1788 assert(Width >= Size && "hex string is too large!"); 1789 HexString.insert(HexString.begin(), Width - Size, '0'); 1790 1791 return HexString; 1792 } 1793 1794 static std::string scalarConstantToHexString(const Constant *C) { 1795 Type *Ty = C->getType(); 1796 if (isa<UndefValue>(C)) { 1797 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits())); 1798 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) { 1799 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); 1800 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) { 1801 return APIntToHexString(CI->getValue()); 1802 } else { 1803 unsigned NumElements; 1804 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1805 NumElements = cast<FixedVectorType>(VTy)->getNumElements(); 1806 else 1807 NumElements = Ty->getArrayNumElements(); 1808 std::string HexString; 1809 for (int I = NumElements - 1, E = -1; I != E; --I) 1810 HexString += scalarConstantToHexString(C->getAggregateElement(I)); 1811 return HexString; 1812 } 1813 } 1814 1815 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( 1816 const DataLayout &DL, SectionKind Kind, const Constant *C, 1817 Align &Alignment) const { 1818 if (Kind.isMergeableConst() && C && 1819 getContext().getAsmInfo()->hasCOFFComdatConstants()) { 1820 // This creates comdat sections with the given symbol name, but unless 1821 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol 1822 // will be created with a null storage class, which makes GNU binutils 1823 // error out. 1824 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1825 COFF::IMAGE_SCN_MEM_READ | 1826 COFF::IMAGE_SCN_LNK_COMDAT; 1827 std::string COMDATSymName; 1828 if (Kind.isMergeableConst4()) { 1829 if (Alignment <= 4) { 1830 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1831 Alignment = Align(4); 1832 } 1833 } else if (Kind.isMergeableConst8()) { 1834 if (Alignment <= 8) { 1835 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1836 Alignment = Align(8); 1837 } 1838 } else if (Kind.isMergeableConst16()) { 1839 // FIXME: These may not be appropriate for non-x86 architectures. 1840 if (Alignment <= 16) { 1841 COMDATSymName = "__xmm@" + scalarConstantToHexString(C); 1842 Alignment = Align(16); 1843 } 1844 } else if (Kind.isMergeableConst32()) { 1845 if (Alignment <= 32) { 1846 COMDATSymName = "__ymm@" + scalarConstantToHexString(C); 1847 Alignment = Align(32); 1848 } 1849 } 1850 1851 if (!COMDATSymName.empty()) 1852 return getContext().getCOFFSection(".rdata", Characteristics, Kind, 1853 COMDATSymName, 1854 COFF::IMAGE_COMDAT_SELECT_ANY); 1855 } 1856 1857 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, 1858 Alignment); 1859 } 1860 1861 //===----------------------------------------------------------------------===// 1862 // Wasm 1863 //===----------------------------------------------------------------------===// 1864 1865 static const Comdat *getWasmComdat(const GlobalValue *GV) { 1866 const Comdat *C = GV->getComdat(); 1867 if (!C) 1868 return nullptr; 1869 1870 if (C->getSelectionKind() != Comdat::Any) 1871 report_fatal_error("WebAssembly COMDATs only support " 1872 "SelectionKind::Any, '" + C->getName() + "' cannot be " 1873 "lowered."); 1874 1875 return C; 1876 } 1877 1878 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 1879 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1880 // We don't support explict section names for functions in the wasm object 1881 // format. Each function has to be in its own unique section. 1882 if (isa<Function>(GO)) { 1883 return SelectSectionForGlobal(GO, Kind, TM); 1884 } 1885 1886 StringRef Name = GO->getSection(); 1887 1888 // Certain data sections we treat as named custom sections rather than 1889 // segments within the data section. 1890 // This could be avoided if all data segements (the wasm sense) were 1891 // represented as their own sections (in the llvm sense). 1892 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138 1893 if (Name == ".llvmcmd" || Name == ".llvmbc") 1894 Kind = SectionKind::getMetadata(); 1895 1896 StringRef Group = ""; 1897 if (const Comdat *C = getWasmComdat(GO)) { 1898 Group = C->getName(); 1899 } 1900 1901 MCSectionWasm* Section = 1902 getContext().getWasmSection(Name, Kind, Group, 1903 MCContext::GenericSectionID); 1904 1905 return Section; 1906 } 1907 1908 static MCSectionWasm *selectWasmSectionForGlobal( 1909 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 1910 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { 1911 StringRef Group = ""; 1912 if (const Comdat *C = getWasmComdat(GO)) { 1913 Group = C->getName(); 1914 } 1915 1916 bool UniqueSectionNames = TM.getUniqueSectionNames(); 1917 SmallString<128> Name = getSectionPrefixForGlobal(Kind); 1918 1919 if (const auto *F = dyn_cast<Function>(GO)) { 1920 const auto &OptionalPrefix = F->getSectionPrefix(); 1921 if (OptionalPrefix) 1922 Name += *OptionalPrefix; 1923 } 1924 1925 if (EmitUniqueSection && UniqueSectionNames) { 1926 Name.push_back('.'); 1927 TM.getNameWithPrefix(Name, GO, Mang, true); 1928 } 1929 unsigned UniqueID = MCContext::GenericSectionID; 1930 if (EmitUniqueSection && !UniqueSectionNames) { 1931 UniqueID = *NextUniqueID; 1932 (*NextUniqueID)++; 1933 } 1934 1935 return Ctx.getWasmSection(Name, Kind, Group, UniqueID); 1936 } 1937 1938 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 1939 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1940 1941 if (Kind.isCommon()) 1942 report_fatal_error("mergable sections not supported yet on wasm"); 1943 1944 // If we have -ffunction-section or -fdata-section then we should emit the 1945 // global value to a uniqued section specifically for it. 1946 bool EmitUniqueSection = false; 1947 if (Kind.isText()) 1948 EmitUniqueSection = TM.getFunctionSections(); 1949 else 1950 EmitUniqueSection = TM.getDataSections(); 1951 EmitUniqueSection |= GO->hasComdat(); 1952 1953 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 1954 EmitUniqueSection, &NextUniqueID); 1955 } 1956 1957 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 1958 bool UsesLabelDifference, const Function &F) const { 1959 // We can always create relative relocations, so use another section 1960 // that can be marked non-executable. 1961 return false; 1962 } 1963 1964 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 1965 const GlobalValue *LHS, const GlobalValue *RHS, 1966 const TargetMachine &TM) const { 1967 // We may only use a PLT-relative relocation to refer to unnamed_addr 1968 // functions. 1969 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1970 return nullptr; 1971 1972 // Basic sanity checks. 1973 if (LHS->getType()->getPointerAddressSpace() != 0 || 1974 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1975 RHS->isThreadLocal()) 1976 return nullptr; 1977 1978 return MCBinaryExpr::createSub( 1979 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 1980 getContext()), 1981 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1982 } 1983 1984 void TargetLoweringObjectFileWasm::InitializeWasm() { 1985 StaticCtorSection = 1986 getContext().getWasmSection(".init_array", SectionKind::getData()); 1987 1988 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit 1989 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables. 1990 TTypeEncoding = dwarf::DW_EH_PE_absptr; 1991 } 1992 1993 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( 1994 unsigned Priority, const MCSymbol *KeySym) const { 1995 return Priority == UINT16_MAX ? 1996 StaticCtorSection : 1997 getContext().getWasmSection(".init_array." + utostr(Priority), 1998 SectionKind::getData()); 1999 } 2000 2001 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( 2002 unsigned Priority, const MCSymbol *KeySym) const { 2003 llvm_unreachable("@llvm.global_dtors should have been lowered already"); 2004 return nullptr; 2005 } 2006 2007 //===----------------------------------------------------------------------===// 2008 // XCOFF 2009 //===----------------------------------------------------------------------===// 2010 MCSymbol * 2011 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV, 2012 const TargetMachine &TM) const { 2013 if (TM.getDataSections()) 2014 report_fatal_error("XCOFF unique data sections not yet implemented"); 2015 2016 // We always use a qualname symbol for a GV that represents 2017 // a declaration, a function descriptor, or a common symbol. 2018 // It is inherently ambiguous when the GO represents the address of a 2019 // function, as the GO could either represent a function descriptor or a 2020 // function entry point. We choose to always return a function descriptor 2021 // here. 2022 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) { 2023 if (GO->isDeclarationForLinker()) 2024 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM)) 2025 ->getQualNameSymbol(); 2026 2027 SectionKind GOKind = getKindForGlobal(GO, TM); 2028 if (GOKind.isText()) 2029 return cast<MCSectionXCOFF>( 2030 getSectionForFunctionDescriptor(cast<Function>(GO), TM)) 2031 ->getQualNameSymbol(); 2032 if (GOKind.isCommon() || GOKind.isBSSLocal()) 2033 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM)) 2034 ->getQualNameSymbol(); 2035 } 2036 2037 // For all other cases, fall back to getSymbol to return the unqualified name. 2038 // This could change for a GV that is a GlobalVariable when we decide to 2039 // support -fdata-sections since we could avoid having label symbols if the 2040 // linkage name is applied to the csect symbol. 2041 return nullptr; 2042 } 2043 2044 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal( 2045 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2046 report_fatal_error("XCOFF explicit sections not yet implemented."); 2047 } 2048 2049 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference( 2050 const GlobalObject *GO, const TargetMachine &TM) const { 2051 assert(GO->isDeclarationForLinker() && 2052 "Tried to get ER section for a defined global."); 2053 2054 SmallString<128> Name; 2055 getNameWithPrefix(Name, GO, TM); 2056 2057 // Externals go into a csect of type ER. 2058 return getContext().getXCOFFSection( 2059 Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER, 2060 SectionKind::getMetadata()); 2061 } 2062 2063 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal( 2064 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2065 assert(!TM.getDataSections() && 2066 "XCOFF unique data sections not yet implemented."); 2067 2068 // Common symbols go into a csect with matching name which will get mapped 2069 // into the .bss section. 2070 if (Kind.isBSSLocal() || Kind.isCommon()) { 2071 SmallString<128> Name; 2072 getNameWithPrefix(Name, GO, TM); 2073 return getContext().getXCOFFSection( 2074 Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM, 2075 Kind, /* BeginSymbolName */ nullptr); 2076 } 2077 2078 if (Kind.isMergeableCString()) { 2079 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign( 2080 cast<GlobalVariable>(GO)); 2081 2082 unsigned EntrySize = getEntrySizeForKind(Kind); 2083 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 2084 SmallString<128> Name; 2085 Name = SizeSpec + utostr(Alignment.value()); 2086 2087 return getContext().getXCOFFSection(Name, XCOFF::XMC_RO, XCOFF::XTY_SD, 2088 Kind, /*BeginSymbolName*/ nullptr); 2089 } 2090 2091 if (Kind.isText()) { 2092 if (TM.getFunctionSections()) { 2093 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM)) 2094 ->getRepresentedCsect(); 2095 } 2096 return TextSection; 2097 } 2098 2099 if (Kind.isData() || Kind.isReadOnlyWithRel()) 2100 // TODO: We may put this under option control, because user may want to 2101 // have read-only data with relocations placed into a read-only section by 2102 // the compiler. 2103 return DataSection; 2104 2105 // Zero initialized data must be emitted to the .data section because external 2106 // linkage control sections that get mapped to the .bss section will be linked 2107 // as tentative defintions, which is only appropriate for SectionKind::Common. 2108 if (Kind.isBSS()) 2109 return DataSection; 2110 2111 if (Kind.isReadOnly()) 2112 return ReadOnlySection; 2113 2114 report_fatal_error("XCOFF other section types not yet implemented."); 2115 } 2116 2117 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable( 2118 const Function &F, const TargetMachine &TM) const { 2119 assert (!F.getComdat() && "Comdat not supported on XCOFF."); 2120 2121 if (!TM.getFunctionSections()) 2122 return ReadOnlySection; 2123 2124 // If the function can be removed, produce a unique section so that 2125 // the table doesn't prevent the removal. 2126 SmallString<128> NameStr(".rodata.jmp.."); 2127 getNameWithPrefix(NameStr, &F, TM); 2128 return getContext().getXCOFFSection(NameStr, XCOFF::XMC_RO, XCOFF::XTY_SD, 2129 SectionKind::getReadOnly()); 2130 } 2131 2132 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection( 2133 bool UsesLabelDifference, const Function &F) const { 2134 return false; 2135 } 2136 2137 /// Given a mergeable constant with the specified size and relocation 2138 /// information, return a section that it should be placed in. 2139 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant( 2140 const DataLayout &DL, SectionKind Kind, const Constant *C, 2141 Align &Alignment) const { 2142 //TODO: Enable emiting constant pool to unique sections when we support it. 2143 return ReadOnlySection; 2144 } 2145 2146 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx, 2147 const TargetMachine &TgtM) { 2148 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 2149 TTypeEncoding = 0; 2150 PersonalityEncoding = 0; 2151 LSDAEncoding = 0; 2152 } 2153 2154 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection( 2155 unsigned Priority, const MCSymbol *KeySym) const { 2156 report_fatal_error("no static constructor section on AIX"); 2157 } 2158 2159 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection( 2160 unsigned Priority, const MCSymbol *KeySym) const { 2161 report_fatal_error("no static destructor section on AIX"); 2162 } 2163 2164 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference( 2165 const GlobalValue *LHS, const GlobalValue *RHS, 2166 const TargetMachine &TM) const { 2167 report_fatal_error("XCOFF not yet implemented."); 2168 } 2169 2170 XCOFF::StorageClass 2171 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) { 2172 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX."); 2173 2174 switch (GV->getLinkage()) { 2175 case GlobalValue::InternalLinkage: 2176 case GlobalValue::PrivateLinkage: 2177 return XCOFF::C_HIDEXT; 2178 case GlobalValue::ExternalLinkage: 2179 case GlobalValue::CommonLinkage: 2180 case GlobalValue::AvailableExternallyLinkage: 2181 return XCOFF::C_EXT; 2182 case GlobalValue::ExternalWeakLinkage: 2183 case GlobalValue::LinkOnceAnyLinkage: 2184 case GlobalValue::LinkOnceODRLinkage: 2185 case GlobalValue::WeakAnyLinkage: 2186 case GlobalValue::WeakODRLinkage: 2187 return XCOFF::C_WEAKEXT; 2188 case GlobalValue::AppendingLinkage: 2189 report_fatal_error( 2190 "There is no mapping that implements AppendingLinkage for XCOFF."); 2191 } 2192 llvm_unreachable("Unknown linkage type!"); 2193 } 2194 2195 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol( 2196 const GlobalValue *Func, const TargetMachine &TM) const { 2197 assert( 2198 (isa<Function>(Func) || 2199 (isa<GlobalAlias>(Func) && 2200 isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) && 2201 "Func must be a function or an alias which has a function as base " 2202 "object."); 2203 SmallString<128> NameStr; 2204 NameStr.push_back('.'); 2205 getNameWithPrefix(NameStr, Func, TM); 2206 2207 // When -function-sections is enabled, it's not necessary to emit 2208 // function entry point label any more. We will use function entry 2209 // point csect instead. And for function delcarations, the undefined symbols 2210 // gets treated as csect with XTY_ER property. 2211 if ((TM.getFunctionSections() || Func->isDeclaration()) && 2212 isa<Function>(Func)) { 2213 return cast<MCSectionXCOFF>( 2214 getContext().getXCOFFSection( 2215 NameStr, XCOFF::XMC_PR, 2216 Func->isDeclaration() ? XCOFF::XTY_ER : XCOFF::XTY_SD, 2217 SectionKind::getText())) 2218 ->getQualNameSymbol(); 2219 } 2220 2221 return getContext().getOrCreateSymbol(NameStr); 2222 } 2223 2224 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor( 2225 const Function *F, const TargetMachine &TM) const { 2226 SmallString<128> NameStr; 2227 getNameWithPrefix(NameStr, F, TM); 2228 return getContext().getXCOFFSection(NameStr, XCOFF::XMC_DS, XCOFF::XTY_SD, 2229 SectionKind::getData()); 2230 } 2231 2232 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry( 2233 const MCSymbol *Sym, const TargetMachine &TM) const { 2234 // Use TE storage-mapping class when large code model is enabled so that 2235 // the chance of needing -bbigtoc is decreased. 2236 return getContext().getXCOFFSection( 2237 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), 2238 TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC, 2239 XCOFF::XTY_SD, SectionKind::getData()); 2240 } 2241