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/BinaryFormat/COFF.h" 20 #include "llvm/BinaryFormat/Dwarf.h" 21 #include "llvm/BinaryFormat/ELF.h" 22 #include "llvm/BinaryFormat/MachO.h" 23 #include "llvm/BinaryFormat/Wasm.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/PseudoProbe.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/MC/MCAsmInfo.h" 46 #include "llvm/MC/MCAsmInfoDarwin.h" 47 #include "llvm/MC/MCContext.h" 48 #include "llvm/MC/MCExpr.h" 49 #include "llvm/MC/MCSectionCOFF.h" 50 #include "llvm/MC/MCSectionELF.h" 51 #include "llvm/MC/MCSectionGOFF.h" 52 #include "llvm/MC/MCSectionMachO.h" 53 #include "llvm/MC/MCSectionWasm.h" 54 #include "llvm/MC/MCSectionXCOFF.h" 55 #include "llvm/MC/MCStreamer.h" 56 #include "llvm/MC/MCSymbol.h" 57 #include "llvm/MC/MCSymbolELF.h" 58 #include "llvm/MC/MCValue.h" 59 #include "llvm/MC/SectionKind.h" 60 #include "llvm/ProfileData/InstrProf.h" 61 #include "llvm/Support/Base64.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CodeGen.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/Format.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/TargetParser/Triple.h" 69 #include <cassert> 70 #include <string> 71 72 using namespace llvm; 73 using namespace dwarf; 74 75 static cl::opt<bool> JumpTableInFunctionSection( 76 "jumptable-in-function-section", cl::Hidden, cl::init(false), 77 cl::desc("Putting Jump Table in function section")); 78 79 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 80 StringRef &Section) { 81 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 82 M.getModuleFlagsMetadata(ModuleFlags); 83 84 for (const auto &MFE: ModuleFlags) { 85 // Ignore flags with 'Require' behaviour. 86 if (MFE.Behavior == Module::Require) 87 continue; 88 89 StringRef Key = MFE.Key->getString(); 90 if (Key == "Objective-C Image Info Version") { 91 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 92 } else if (Key == "Objective-C Garbage Collection" || 93 Key == "Objective-C GC Only" || 94 Key == "Objective-C Is Simulated" || 95 Key == "Objective-C Class Properties" || 96 Key == "Objective-C Image Swift Version") { 97 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 98 } else if (Key == "Objective-C Image Info Section") { 99 Section = cast<MDString>(MFE.Val)->getString(); 100 } 101 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor + 102 // "Objective-C Garbage Collection". 103 else if (Key == "Swift ABI Version") { 104 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8; 105 } else if (Key == "Swift Major Version") { 106 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24; 107 } else if (Key == "Swift Minor Version") { 108 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16; 109 } 110 } 111 } 112 113 //===----------------------------------------------------------------------===// 114 // ELF 115 //===----------------------------------------------------------------------===// 116 117 TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() { 118 SupportDSOLocalEquivalentLowering = true; 119 } 120 121 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 122 const TargetMachine &TgtM) { 123 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 124 125 CodeModel::Model CM = TgtM.getCodeModel(); 126 InitializeELF(TgtM.Options.UseInitArray); 127 128 switch (TgtM.getTargetTriple().getArch()) { 129 case Triple::arm: 130 case Triple::armeb: 131 case Triple::thumb: 132 case Triple::thumbeb: 133 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) 134 break; 135 // Fallthrough if not using EHABI 136 [[fallthrough]]; 137 case Triple::ppc: 138 case Triple::ppcle: 139 case Triple::x86: 140 PersonalityEncoding = isPositionIndependent() 141 ? dwarf::DW_EH_PE_indirect | 142 dwarf::DW_EH_PE_pcrel | 143 dwarf::DW_EH_PE_sdata4 144 : dwarf::DW_EH_PE_absptr; 145 LSDAEncoding = isPositionIndependent() 146 ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 147 : dwarf::DW_EH_PE_absptr; 148 TTypeEncoding = isPositionIndependent() 149 ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 150 dwarf::DW_EH_PE_sdata4 151 : dwarf::DW_EH_PE_absptr; 152 break; 153 case Triple::x86_64: 154 if (isPositionIndependent()) { 155 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 156 ((CM == CodeModel::Small || CM == CodeModel::Medium) 157 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 158 LSDAEncoding = dwarf::DW_EH_PE_pcrel | 159 (CM == CodeModel::Small 160 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 161 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 162 ((CM == CodeModel::Small || CM == CodeModel::Medium) 163 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 164 } else { 165 PersonalityEncoding = 166 (CM == CodeModel::Small || CM == CodeModel::Medium) 167 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 168 LSDAEncoding = (CM == CodeModel::Small) 169 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 170 TTypeEncoding = (CM == CodeModel::Small) 171 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 172 } 173 break; 174 case Triple::hexagon: 175 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 176 LSDAEncoding = dwarf::DW_EH_PE_absptr; 177 TTypeEncoding = dwarf::DW_EH_PE_absptr; 178 if (isPositionIndependent()) { 179 PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 180 LSDAEncoding |= dwarf::DW_EH_PE_pcrel; 181 TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 182 } 183 break; 184 case Triple::aarch64: 185 case Triple::aarch64_be: 186 case Triple::aarch64_32: 187 // The small model guarantees static code/data size < 4GB, but not where it 188 // will be in memory. Most of these could end up >2GB away so even a signed 189 // pc-relative 32-bit address is insufficient, theoretically. 190 // 191 // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations. 192 LSDAEncoding = dwarf::DW_EH_PE_pcrel | 193 (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32 194 ? dwarf::DW_EH_PE_sdata4 195 : dwarf::DW_EH_PE_sdata8); 196 PersonalityEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect; 197 TTypeEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect; 198 break; 199 case Triple::lanai: 200 LSDAEncoding = dwarf::DW_EH_PE_absptr; 201 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 202 TTypeEncoding = dwarf::DW_EH_PE_absptr; 203 break; 204 case Triple::mips: 205 case Triple::mipsel: 206 case Triple::mips64: 207 case Triple::mips64el: 208 // MIPS uses indirect pointer to refer personality functions and types, so 209 // that the eh_frame section can be read-only. DW.ref.personality will be 210 // generated for relocation. 211 PersonalityEncoding = dwarf::DW_EH_PE_indirect; 212 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't 213 // identify N64 from just a triple. 214 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 215 dwarf::DW_EH_PE_sdata4; 216 217 // FreeBSD must be explicit about the data size and using pcrel since it's 218 // assembler/linker won't do the automatic conversion that the Linux tools 219 // do. 220 if (isPositionIndependent() || TgtM.getTargetTriple().isOSFreeBSD()) { 221 PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 222 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 223 } 224 break; 225 case Triple::ppc64: 226 case Triple::ppc64le: 227 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 228 dwarf::DW_EH_PE_udata8; 229 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; 230 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 231 dwarf::DW_EH_PE_udata8; 232 break; 233 case Triple::sparcel: 234 case Triple::sparc: 235 if (isPositionIndependent()) { 236 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 237 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 238 dwarf::DW_EH_PE_sdata4; 239 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 240 dwarf::DW_EH_PE_sdata4; 241 } else { 242 LSDAEncoding = dwarf::DW_EH_PE_absptr; 243 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 244 TTypeEncoding = dwarf::DW_EH_PE_absptr; 245 } 246 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 247 break; 248 case Triple::riscv32: 249 case Triple::riscv64: 250 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 251 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 252 dwarf::DW_EH_PE_sdata4; 253 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 254 dwarf::DW_EH_PE_sdata4; 255 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 256 break; 257 case Triple::sparcv9: 258 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 259 if (isPositionIndependent()) { 260 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 261 dwarf::DW_EH_PE_sdata4; 262 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 263 dwarf::DW_EH_PE_sdata4; 264 } else { 265 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 266 TTypeEncoding = dwarf::DW_EH_PE_absptr; 267 } 268 break; 269 case Triple::systemz: 270 // All currently-defined code models guarantee that 4-byte PC-relative 271 // values will be in range. 272 if (isPositionIndependent()) { 273 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 274 dwarf::DW_EH_PE_sdata4; 275 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 276 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 277 dwarf::DW_EH_PE_sdata4; 278 } else { 279 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 280 LSDAEncoding = dwarf::DW_EH_PE_absptr; 281 TTypeEncoding = dwarf::DW_EH_PE_absptr; 282 } 283 break; 284 case Triple::loongarch32: 285 case Triple::loongarch64: 286 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 287 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 288 dwarf::DW_EH_PE_sdata4; 289 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 290 dwarf::DW_EH_PE_sdata4; 291 break; 292 default: 293 break; 294 } 295 } 296 297 void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) { 298 SmallVector<GlobalValue *, 4> Vec; 299 collectUsedGlobalVariables(M, Vec, false); 300 for (GlobalValue *GV : Vec) 301 if (auto *GO = dyn_cast<GlobalObject>(GV)) 302 Used.insert(GO); 303 } 304 305 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, 306 Module &M) const { 307 auto &C = getContext(); 308 309 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 310 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, 311 ELF::SHF_EXCLUDE); 312 313 Streamer.switchSection(S); 314 315 for (const auto *Operand : LinkerOptions->operands()) { 316 if (cast<MDNode>(Operand)->getNumOperands() != 2) 317 report_fatal_error("invalid llvm.linker.options"); 318 for (const auto &Option : cast<MDNode>(Operand)->operands()) { 319 Streamer.emitBytes(cast<MDString>(Option)->getString()); 320 Streamer.emitInt8(0); 321 } 322 } 323 } 324 325 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) { 326 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES, 327 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1); 328 329 Streamer.switchSection(S); 330 331 for (const auto *Operand : DependentLibraries->operands()) { 332 Streamer.emitBytes( 333 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString()); 334 Streamer.emitInt8(0); 335 } 336 } 337 338 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) { 339 // Emit a descriptor for every function including functions that have an 340 // available external linkage. We may not want this for imported functions 341 // that has code in another thinLTO module but we don't have a good way to 342 // tell them apart from inline functions defined in header files. Therefore 343 // we put each descriptor in a separate comdat section and rely on the 344 // linker to deduplicate. 345 for (const auto *Operand : FuncInfo->operands()) { 346 const auto *MD = cast<MDNode>(Operand); 347 auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 348 auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); 349 auto *Name = cast<MDString>(MD->getOperand(2)); 350 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection( 351 TM->getFunctionSections() ? Name->getString() : StringRef()); 352 353 Streamer.switchSection(S); 354 Streamer.emitInt64(GUID->getZExtValue()); 355 Streamer.emitInt64(Hash->getZExtValue()); 356 Streamer.emitULEB128IntValue(Name->getString().size()); 357 Streamer.emitBytes(Name->getString()); 358 } 359 } 360 361 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) { 362 // Emit the metadata for llvm statistics into .llvm_stats section, which is 363 // formatted as a list of key/value pair, the value is base64 encoded. 364 auto *S = C.getObjectFileInfo()->getLLVMStatsSection(); 365 Streamer.switchSection(S); 366 for (const auto *Operand : LLVMStats->operands()) { 367 const auto *MD = cast<MDNode>(Operand); 368 assert(MD->getNumOperands() % 2 == 0 && 369 ("Operand num should be even for a list of key/value pair")); 370 for (size_t I = 0; I < MD->getNumOperands(); I += 2) { 371 // Encode the key string size. 372 auto *Key = cast<MDString>(MD->getOperand(I)); 373 Streamer.emitULEB128IntValue(Key->getString().size()); 374 Streamer.emitBytes(Key->getString()); 375 // Encode the value into a Base64 string. 376 std::string Value = encodeBase64( 377 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1)) 378 ->getZExtValue()) 379 .str()); 380 Streamer.emitULEB128IntValue(Value.size()); 381 Streamer.emitBytes(Value); 382 } 383 } 384 } 385 386 unsigned Version = 0; 387 unsigned Flags = 0; 388 StringRef Section; 389 390 GetObjCImageInfo(M, Version, Flags, Section); 391 if (!Section.empty()) { 392 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 393 Streamer.switchSection(S); 394 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 395 Streamer.emitInt32(Version); 396 Streamer.emitInt32(Flags); 397 Streamer.addBlankLine(); 398 } 399 400 emitCGProfileMetadata(Streamer, M); 401 } 402 403 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 404 const GlobalValue *GV, const TargetMachine &TM, 405 MachineModuleInfo *MMI) const { 406 unsigned Encoding = getPersonalityEncoding(); 407 if ((Encoding & 0x80) == DW_EH_PE_indirect) 408 return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 409 TM.getSymbol(GV)->getName()); 410 if ((Encoding & 0x70) == DW_EH_PE_absptr) 411 return TM.getSymbol(GV); 412 report_fatal_error("We do not support this DWARF encoding yet!"); 413 } 414 415 void TargetLoweringObjectFileELF::emitPersonalityValue( 416 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, 417 const MachineModuleInfo *MMI) const { 418 SmallString<64> NameData("DW.ref."); 419 NameData += Sym->getName(); 420 MCSymbolELF *Label = 421 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 422 Streamer.emitSymbolAttribute(Label, MCSA_Hidden); 423 Streamer.emitSymbolAttribute(Label, MCSA_Weak); 424 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 425 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 426 ELF::SHT_PROGBITS, Flags, 0); 427 unsigned Size = DL.getPointerSize(); 428 Streamer.switchSection(Sec); 429 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0)); 430 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject); 431 const MCExpr *E = MCConstantExpr::create(Size, getContext()); 432 Streamer.emitELFSize(Label, E); 433 Streamer.emitLabel(Label); 434 435 emitPersonalityValueImpl(Streamer, DL, Sym, MMI); 436 } 437 438 void TargetLoweringObjectFileELF::emitPersonalityValueImpl( 439 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, 440 const MachineModuleInfo *MMI) const { 441 Streamer.emitSymbolValue(Sym, DL.getPointerSize()); 442 } 443 444 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 445 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 446 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 447 if (Encoding & DW_EH_PE_indirect) { 448 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 449 450 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 451 452 // Add information about the stub reference to ELFMMI so that the stub 453 // gets emitted by the asmprinter. 454 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 455 if (!StubSym.getPointer()) { 456 MCSymbol *Sym = TM.getSymbol(GV); 457 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 458 } 459 460 return TargetLoweringObjectFile:: 461 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 462 Encoding & ~DW_EH_PE_indirect, Streamer); 463 } 464 465 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 466 MMI, Streamer); 467 } 468 469 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { 470 // N.B.: The defaults used in here are not the same ones used in MC. 471 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 472 // both gas and MC will produce a section with no flags. Given 473 // section(".eh_frame") gcc will produce: 474 // 475 // .section .eh_frame,"a",@progbits 476 477 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 478 /*AddSegmentInfo=*/false) || 479 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF, 480 /*AddSegmentInfo=*/false) || 481 Name == getInstrProfSectionName(IPSK_covdata, Triple::ELF, 482 /*AddSegmentInfo=*/false) || 483 Name == getInstrProfSectionName(IPSK_covname, Triple::ELF, 484 /*AddSegmentInfo=*/false) || 485 Name == ".llvmbc" || Name == ".llvmcmd") 486 return SectionKind::getMetadata(); 487 488 if (!Name.starts_with(".")) return K; 489 490 // Default implementation based on some magic section names. 491 if (Name == ".bss" || Name.starts_with(".bss.") || 492 Name.starts_with(".gnu.linkonce.b.") || 493 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" || 494 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") || 495 Name.starts_with(".llvm.linkonce.sb.")) 496 return SectionKind::getBSS(); 497 498 if (Name == ".tdata" || Name.starts_with(".tdata.") || 499 Name.starts_with(".gnu.linkonce.td.") || 500 Name.starts_with(".llvm.linkonce.td.")) 501 return SectionKind::getThreadData(); 502 503 if (Name == ".tbss" || Name.starts_with(".tbss.") || 504 Name.starts_with(".gnu.linkonce.tb.") || 505 Name.starts_with(".llvm.linkonce.tb.")) 506 return SectionKind::getThreadBSS(); 507 508 return K; 509 } 510 511 static bool hasPrefix(StringRef SectionName, StringRef Prefix) { 512 return SectionName.consume_front(Prefix) && 513 (SectionName.empty() || SectionName[0] == '.'); 514 } 515 516 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 517 // Use SHT_NOTE for section whose name starts with ".note" to allow 518 // emitting ELF notes from C variable declaration. 519 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 520 if (Name.starts_with(".note")) 521 return ELF::SHT_NOTE; 522 523 if (hasPrefix(Name, ".init_array")) 524 return ELF::SHT_INIT_ARRAY; 525 526 if (hasPrefix(Name, ".fini_array")) 527 return ELF::SHT_FINI_ARRAY; 528 529 if (hasPrefix(Name, ".preinit_array")) 530 return ELF::SHT_PREINIT_ARRAY; 531 532 if (hasPrefix(Name, ".llvm.offloading")) 533 return ELF::SHT_LLVM_OFFLOADING; 534 if (Name == ".llvm.lto") 535 return ELF::SHT_LLVM_LTO; 536 537 if (K.isBSS() || K.isThreadBSS()) 538 return ELF::SHT_NOBITS; 539 540 return ELF::SHT_PROGBITS; 541 } 542 543 static unsigned getELFSectionFlags(SectionKind K) { 544 unsigned Flags = 0; 545 546 if (!K.isMetadata() && !K.isExclude()) 547 Flags |= ELF::SHF_ALLOC; 548 549 if (K.isExclude()) 550 Flags |= ELF::SHF_EXCLUDE; 551 552 if (K.isText()) 553 Flags |= ELF::SHF_EXECINSTR; 554 555 if (K.isExecuteOnly()) 556 Flags |= ELF::SHF_ARM_PURECODE; 557 558 if (K.isWriteable()) 559 Flags |= ELF::SHF_WRITE; 560 561 if (K.isThreadLocal()) 562 Flags |= ELF::SHF_TLS; 563 564 if (K.isMergeableCString() || K.isMergeableConst()) 565 Flags |= ELF::SHF_MERGE; 566 567 if (K.isMergeableCString()) 568 Flags |= ELF::SHF_STRINGS; 569 570 return Flags; 571 } 572 573 static const Comdat *getELFComdat(const GlobalValue *GV) { 574 const Comdat *C = GV->getComdat(); 575 if (!C) 576 return nullptr; 577 578 if (C->getSelectionKind() != Comdat::Any && 579 C->getSelectionKind() != Comdat::NoDeduplicate) 580 report_fatal_error("ELF COMDATs only support SelectionKind::Any and " 581 "SelectionKind::NoDeduplicate, '" + 582 C->getName() + "' cannot be lowered."); 583 584 return C; 585 } 586 587 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO, 588 const TargetMachine &TM) { 589 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 590 if (!MD) 591 return nullptr; 592 593 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get()); 594 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue()); 595 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr; 596 } 597 598 static unsigned getEntrySizeForKind(SectionKind Kind) { 599 if (Kind.isMergeable1ByteCString()) 600 return 1; 601 else if (Kind.isMergeable2ByteCString()) 602 return 2; 603 else if (Kind.isMergeable4ByteCString()) 604 return 4; 605 else if (Kind.isMergeableConst4()) 606 return 4; 607 else if (Kind.isMergeableConst8()) 608 return 8; 609 else if (Kind.isMergeableConst16()) 610 return 16; 611 else if (Kind.isMergeableConst32()) 612 return 32; 613 else { 614 // We shouldn't have mergeable C strings or mergeable constants that we 615 // didn't handle above. 616 assert(!Kind.isMergeableCString() && "unknown string width"); 617 assert(!Kind.isMergeableConst() && "unknown data width"); 618 return 0; 619 } 620 } 621 622 /// Return the section prefix name used by options FunctionsSections and 623 /// DataSections. 624 static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge) { 625 if (Kind.isText()) 626 return IsLarge ? ".ltext" : ".text"; 627 if (Kind.isReadOnly()) 628 return IsLarge ? ".lrodata" : ".rodata"; 629 if (Kind.isBSS()) 630 return IsLarge ? ".lbss" : ".bss"; 631 if (Kind.isThreadData()) 632 return ".tdata"; 633 if (Kind.isThreadBSS()) 634 return ".tbss"; 635 if (Kind.isData()) 636 return IsLarge ? ".ldata" : ".data"; 637 if (Kind.isReadOnlyWithRel()) 638 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro"; 639 llvm_unreachable("Unknown section kind"); 640 } 641 642 static SmallString<128> 643 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, 644 Mangler &Mang, const TargetMachine &TM, 645 unsigned EntrySize, bool UniqueSectionName) { 646 SmallString<128> Name = 647 getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO)); 648 if (Kind.isMergeableCString()) { 649 // We also need alignment here. 650 // FIXME: this is getting the alignment of the character, not the 651 // alignment of the global! 652 Align Alignment = GO->getDataLayout().getPreferredAlign( 653 cast<GlobalVariable>(GO)); 654 655 Name += ".str"; 656 Name += utostr(EntrySize); 657 Name += "."; 658 Name += utostr(Alignment.value()); 659 } else if (Kind.isMergeableConst()) { 660 Name += ".cst"; 661 Name += utostr(EntrySize); 662 } 663 664 bool HasPrefix = false; 665 if (const auto *F = dyn_cast<Function>(GO)) { 666 if (std::optional<StringRef> Prefix = F->getSectionPrefix()) { 667 raw_svector_ostream(Name) << '.' << *Prefix; 668 HasPrefix = true; 669 } 670 } 671 672 if (UniqueSectionName) { 673 Name.push_back('.'); 674 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true); 675 } else if (HasPrefix) 676 // For distinguishing between .text.${text-section-prefix}. (with trailing 677 // dot) and .text.${function-name} 678 Name.push_back('.'); 679 return Name; 680 } 681 682 namespace { 683 class LoweringDiagnosticInfo : public DiagnosticInfo { 684 const Twine &Msg; 685 686 public: 687 LoweringDiagnosticInfo(const Twine &DiagMsg, 688 DiagnosticSeverity Severity = DS_Error) 689 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {} 690 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 691 }; 692 } 693 694 /// Calculate an appropriate unique ID for a section, and update Flags, 695 /// EntrySize and NextUniqueID where appropriate. 696 static unsigned 697 calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName, 698 SectionKind Kind, const TargetMachine &TM, 699 MCContext &Ctx, Mangler &Mang, unsigned &Flags, 700 unsigned &EntrySize, unsigned &NextUniqueID, 701 const bool Retain, const bool ForceUnique) { 702 // Increment uniqueID if we are forced to emit a unique section. 703 // This works perfectly fine with section attribute or pragma section as the 704 // sections with the same name are grouped together by the assembler. 705 if (ForceUnique) 706 return NextUniqueID++; 707 708 // A section can have at most one associated section. Put each global with 709 // MD_associated in a unique section. 710 const bool Associated = GO->getMetadata(LLVMContext::MD_associated); 711 if (Associated) { 712 Flags |= ELF::SHF_LINK_ORDER; 713 return NextUniqueID++; 714 } 715 716 if (Retain) { 717 if (TM.getTargetTriple().isOSSolaris()) 718 Flags |= ELF::SHF_SUNW_NODISCARD; 719 else if (Ctx.getAsmInfo()->useIntegratedAssembler() || 720 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) 721 Flags |= ELF::SHF_GNU_RETAIN; 722 return NextUniqueID++; 723 } 724 725 // If two symbols with differing sizes end up in the same mergeable section 726 // that section can be assigned an incorrect entry size. To avoid this we 727 // usually put symbols of the same size into distinct mergeable sections with 728 // the same name. Doing so relies on the ",unique ," assembly feature. This 729 // feature is not avalible until bintuils version 2.35 730 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380). 731 const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() || 732 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35); 733 if (!SupportsUnique) { 734 Flags &= ~ELF::SHF_MERGE; 735 EntrySize = 0; 736 return MCContext::GenericSectionID; 737 } 738 739 const bool SymbolMergeable = Flags & ELF::SHF_MERGE; 740 const bool SeenSectionNameBefore = 741 Ctx.isELFGenericMergeableSection(SectionName); 742 // If this is the first ocurrence of this section name, treat it as the 743 // generic section 744 if (!SymbolMergeable && !SeenSectionNameBefore) { 745 if (TM.getSeparateNamedSections()) 746 return NextUniqueID++; 747 else 748 return MCContext::GenericSectionID; 749 } 750 751 // Symbols must be placed into sections with compatible entry sizes. Generate 752 // unique sections for symbols that have not been assigned to compatible 753 // sections. 754 const auto PreviousID = 755 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize); 756 if (PreviousID && (!TM.getSeparateNamedSections() || 757 *PreviousID == MCContext::GenericSectionID)) 758 return *PreviousID; 759 760 // If the user has specified the same section name as would be created 761 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need 762 // to unique the section as the entry size for this symbol will be 763 // compatible with implicitly created sections. 764 SmallString<128> ImplicitSectionNameStem = 765 getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false); 766 if (SymbolMergeable && 767 Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) && 768 SectionName.starts_with(ImplicitSectionNameStem)) 769 return MCContext::GenericSectionID; 770 771 // We have seen this section name before, but with different flags or entity 772 // size. Create a new unique ID. 773 return NextUniqueID++; 774 } 775 776 static std::tuple<StringRef, bool, unsigned> 777 getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM) { 778 StringRef Group = ""; 779 bool IsComdat = false; 780 unsigned Flags = 0; 781 if (const Comdat *C = getELFComdat(GO)) { 782 Flags |= ELF::SHF_GROUP; 783 Group = C->getName(); 784 IsComdat = C->getSelectionKind() == Comdat::Any; 785 } 786 if (TM.isLargeGlobalValue(GO)) 787 Flags |= ELF::SHF_X86_64_LARGE; 788 return {Group, IsComdat, Flags}; 789 } 790 791 static StringRef handlePragmaClangSection(const GlobalObject *GO, 792 SectionKind Kind) { 793 // Check if '#pragma clang section' name is applicable. 794 // Note that pragma directive overrides -ffunction-section, -fdata-section 795 // and so section name is exactly as user specified and not uniqued. 796 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 797 if (GV && GV->hasImplicitSection()) { 798 auto Attrs = GV->getAttributes(); 799 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) 800 return Attrs.getAttribute("bss-section").getValueAsString(); 801 else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) 802 return Attrs.getAttribute("rodata-section").getValueAsString(); 803 else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) 804 return Attrs.getAttribute("relro-section").getValueAsString(); 805 else if (Attrs.hasAttribute("data-section") && Kind.isData()) 806 return Attrs.getAttribute("data-section").getValueAsString(); 807 } 808 809 return GO->getSection(); 810 } 811 812 static MCSection *selectExplicitSectionGlobal(const GlobalObject *GO, 813 SectionKind Kind, 814 const TargetMachine &TM, 815 MCContext &Ctx, Mangler &Mang, 816 unsigned &NextUniqueID, 817 bool Retain, bool ForceUnique) { 818 StringRef SectionName = handlePragmaClangSection(GO, Kind); 819 820 // Infer section flags from the section name if we can. 821 Kind = getELFKindForNamedSection(SectionName, Kind); 822 823 unsigned Flags = getELFSectionFlags(Kind); 824 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM); 825 Flags |= ExtraFlags; 826 827 unsigned EntrySize = getEntrySizeForKind(Kind); 828 const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize( 829 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID, 830 Retain, ForceUnique); 831 832 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 833 MCSectionELF *Section = Ctx.getELFSection( 834 SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize, 835 Group, IsComdat, UniqueID, LinkedToSym); 836 // Make sure that we did not get some other section with incompatible sh_link. 837 // This should not be possible due to UniqueID code above. 838 assert(Section->getLinkedToSymbol() == LinkedToSym && 839 "Associated symbol mismatch between sections"); 840 841 if (!(Ctx.getAsmInfo()->useIntegratedAssembler() || 842 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) { 843 // If we are using GNU as before 2.35, then this symbol might have 844 // been placed in an incompatible mergeable section. Emit an error if this 845 // is the case to avoid creating broken output. 846 if ((Section->getFlags() & ELF::SHF_MERGE) && 847 (Section->getEntrySize() != getEntrySizeForKind(Kind))) 848 GO->getContext().diagnose(LoweringDiagnosticInfo( 849 "Symbol '" + GO->getName() + "' from module '" + 850 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") + 851 "' required a section with entry-size=" + 852 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" + 853 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) + 854 ": Explicit assignment by pragma or attribute of an incompatible " 855 "symbol to this section?")); 856 } 857 858 return Section; 859 } 860 861 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 862 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 863 return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(), 864 NextUniqueID, Used.count(GO), 865 /* ForceUnique = */false); 866 } 867 868 static MCSectionELF *selectELFSectionForGlobal( 869 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 870 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 871 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 872 873 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM); 874 Flags |= ExtraFlags; 875 876 // Get the section entry size based on the kind. 877 unsigned EntrySize = getEntrySizeForKind(Kind); 878 879 bool UniqueSectionName = false; 880 unsigned UniqueID = MCContext::GenericSectionID; 881 if (EmitUniqueSection) { 882 if (TM.getUniqueSectionNames()) { 883 UniqueSectionName = true; 884 } else { 885 UniqueID = *NextUniqueID; 886 (*NextUniqueID)++; 887 } 888 } 889 SmallString<128> Name = getELFSectionNameForGlobal( 890 GO, Kind, Mang, TM, EntrySize, UniqueSectionName); 891 892 // Use 0 as the unique ID for execute-only text. 893 if (Kind.isExecuteOnly()) 894 UniqueID = 0; 895 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 896 EntrySize, Group, IsComdat, UniqueID, 897 AssociatedSymbol); 898 } 899 900 static MCSection *selectELFSectionForGlobal( 901 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 902 const TargetMachine &TM, bool Retain, bool EmitUniqueSection, 903 unsigned Flags, unsigned *NextUniqueID) { 904 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 905 if (LinkedToSym) { 906 EmitUniqueSection = true; 907 Flags |= ELF::SHF_LINK_ORDER; 908 } 909 if (Retain) { 910 if (TM.getTargetTriple().isOSSolaris()) { 911 EmitUniqueSection = true; 912 Flags |= ELF::SHF_SUNW_NODISCARD; 913 } else if (Ctx.getAsmInfo()->useIntegratedAssembler() || 914 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) { 915 EmitUniqueSection = true; 916 Flags |= ELF::SHF_GNU_RETAIN; 917 } 918 } 919 920 MCSectionELF *Section = selectELFSectionForGlobal( 921 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags, 922 NextUniqueID, LinkedToSym); 923 assert(Section->getLinkedToSymbol() == LinkedToSym); 924 return Section; 925 } 926 927 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 928 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 929 unsigned Flags = getELFSectionFlags(Kind); 930 931 // If we have -ffunction-section or -fdata-section then we should emit the 932 // global value to a uniqued section specifically for it. 933 bool EmitUniqueSection = false; 934 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 935 if (Kind.isText()) 936 EmitUniqueSection = TM.getFunctionSections(); 937 else 938 EmitUniqueSection = TM.getDataSections(); 939 } 940 EmitUniqueSection |= GO->hasComdat(); 941 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 942 Used.count(GO), EmitUniqueSection, Flags, 943 &NextUniqueID); 944 } 945 946 MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction( 947 const Function &F, const TargetMachine &TM) const { 948 SectionKind Kind = SectionKind::getText(); 949 unsigned Flags = getELFSectionFlags(Kind); 950 // If the function's section names is pre-determined via pragma or a 951 // section attribute, call selectExplicitSectionGlobal. 952 if (F.hasSection()) 953 return selectExplicitSectionGlobal( 954 &F, Kind, TM, getContext(), getMangler(), NextUniqueID, 955 Used.count(&F), /* ForceUnique = */true); 956 else 957 return selectELFSectionForGlobal( 958 getContext(), &F, Kind, getMangler(), TM, Used.count(&F), 959 /*EmitUniqueSection=*/true, Flags, &NextUniqueID); 960 } 961 962 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 963 const Function &F, const TargetMachine &TM) const { 964 // If the function can be removed, produce a unique section so that 965 // the table doesn't prevent the removal. 966 const Comdat *C = F.getComdat(); 967 bool EmitUniqueSection = TM.getFunctionSections() || C; 968 if (!EmitUniqueSection) 969 return ReadOnlySection; 970 971 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 972 getMangler(), TM, EmitUniqueSection, 973 ELF::SHF_ALLOC, &NextUniqueID, 974 /* AssociatedSymbol */ nullptr); 975 } 976 977 MCSection *TargetLoweringObjectFileELF::getSectionForLSDA( 978 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const { 979 // If neither COMDAT nor function sections, use the monolithic LSDA section. 980 // Re-use this path if LSDASection is null as in the Arm EHABI. 981 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections())) 982 return LSDASection; 983 984 const auto *LSDA = cast<MCSectionELF>(LSDASection); 985 unsigned Flags = LSDA->getFlags(); 986 const MCSymbolELF *LinkedToSym = nullptr; 987 StringRef Group; 988 bool IsComdat = false; 989 if (const Comdat *C = getELFComdat(&F)) { 990 Flags |= ELF::SHF_GROUP; 991 Group = C->getName(); 992 IsComdat = C->getSelectionKind() == Comdat::Any; 993 } 994 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36 995 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER. 996 if (TM.getFunctionSections() && 997 (getContext().getAsmInfo()->useIntegratedAssembler() && 998 getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) { 999 Flags |= ELF::SHF_LINK_ORDER; 1000 LinkedToSym = cast<MCSymbolELF>(&FnSym); 1001 } 1002 1003 // Append the function name as the suffix like GCC, assuming 1004 // -funique-section-names applies to .gcc_except_table sections. 1005 return getContext().getELFSection( 1006 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName() 1007 : LSDA->getName()), 1008 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID, 1009 LinkedToSym); 1010 } 1011 1012 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 1013 bool UsesLabelDifference, const Function &F) const { 1014 // We can always create relative relocations, so use another section 1015 // that can be marked non-executable. 1016 return false; 1017 } 1018 1019 /// Given a mergeable constant with the specified size and relocation 1020 /// information, return a section that it should be placed in. 1021 MCSection *TargetLoweringObjectFileELF::getSectionForConstant( 1022 const DataLayout &DL, SectionKind Kind, const Constant *C, 1023 Align &Alignment) const { 1024 if (Kind.isMergeableConst4() && MergeableConst4Section) 1025 return MergeableConst4Section; 1026 if (Kind.isMergeableConst8() && MergeableConst8Section) 1027 return MergeableConst8Section; 1028 if (Kind.isMergeableConst16() && MergeableConst16Section) 1029 return MergeableConst16Section; 1030 if (Kind.isMergeableConst32() && MergeableConst32Section) 1031 return MergeableConst32Section; 1032 if (Kind.isReadOnly()) 1033 return ReadOnlySection; 1034 1035 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 1036 return DataRelROSection; 1037 } 1038 1039 /// Returns a unique section for the given machine basic block. 1040 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock( 1041 const Function &F, const MachineBasicBlock &MBB, 1042 const TargetMachine &TM) const { 1043 assert(MBB.isBeginSection() && "Basic block does not start a section!"); 1044 unsigned UniqueID = MCContext::GenericSectionID; 1045 1046 // For cold sections use the .text.split. prefix along with the parent 1047 // function name. All cold blocks for the same function go to the same 1048 // section. Similarly all exception blocks are grouped by symbol name 1049 // under the .text.eh prefix. For regular sections, we either use a unique 1050 // name, or a unique ID for the section. 1051 SmallString<128> Name; 1052 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName(); 1053 if (FunctionSectionName == ".text" || 1054 FunctionSectionName.starts_with(".text.")) { 1055 // Function is in a regular .text section. 1056 StringRef FunctionName = MBB.getParent()->getName(); 1057 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) { 1058 Name += BBSectionsColdTextPrefix; 1059 Name += FunctionName; 1060 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) { 1061 Name += ".text.eh."; 1062 Name += FunctionName; 1063 } else { 1064 Name += FunctionSectionName; 1065 if (TM.getUniqueBasicBlockSectionNames()) { 1066 if (!Name.ends_with(".")) 1067 Name += "."; 1068 Name += MBB.getSymbol()->getName(); 1069 } else { 1070 UniqueID = NextUniqueID++; 1071 } 1072 } 1073 } else { 1074 // If the original function has a custom non-dot-text section, then emit 1075 // all basic block sections into that section too, each with a unique id. 1076 Name = FunctionSectionName; 1077 UniqueID = NextUniqueID++; 1078 } 1079 1080 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR; 1081 std::string GroupName; 1082 if (F.hasComdat()) { 1083 Flags |= ELF::SHF_GROUP; 1084 GroupName = F.getComdat()->getName().str(); 1085 } 1086 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 1087 0 /* Entry Size */, GroupName, 1088 F.hasComdat(), UniqueID, nullptr); 1089 } 1090 1091 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 1092 bool IsCtor, unsigned Priority, 1093 const MCSymbol *KeySym) { 1094 std::string Name; 1095 unsigned Type; 1096 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 1097 StringRef Comdat = KeySym ? KeySym->getName() : ""; 1098 1099 if (KeySym) 1100 Flags |= ELF::SHF_GROUP; 1101 1102 if (UseInitArray) { 1103 if (IsCtor) { 1104 Type = ELF::SHT_INIT_ARRAY; 1105 Name = ".init_array"; 1106 } else { 1107 Type = ELF::SHT_FINI_ARRAY; 1108 Name = ".fini_array"; 1109 } 1110 if (Priority != 65535) { 1111 Name += '.'; 1112 Name += utostr(Priority); 1113 } 1114 } else { 1115 // The default scheme is .ctor / .dtor, so we have to invert the priority 1116 // numbering. 1117 if (IsCtor) 1118 Name = ".ctors"; 1119 else 1120 Name = ".dtors"; 1121 if (Priority != 65535) 1122 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1123 Type = ELF::SHT_PROGBITS; 1124 } 1125 1126 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true); 1127 } 1128 1129 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 1130 unsigned Priority, const MCSymbol *KeySym) const { 1131 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 1132 KeySym); 1133 } 1134 1135 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 1136 unsigned Priority, const MCSymbol *KeySym) const { 1137 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 1138 KeySym); 1139 } 1140 1141 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 1142 const GlobalValue *LHS, const GlobalValue *RHS, 1143 const TargetMachine &TM) const { 1144 // We may only use a PLT-relative relocation to refer to unnamed_addr 1145 // functions. 1146 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1147 return nullptr; 1148 1149 // Basic correctness checks. 1150 if (LHS->getType()->getPointerAddressSpace() != 0 || 1151 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1152 RHS->isThreadLocal()) 1153 return nullptr; 1154 1155 return MCBinaryExpr::createSub( 1156 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 1157 getContext()), 1158 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1159 } 1160 1161 const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent( 1162 const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const { 1163 assert(supportDSOLocalEquivalentLowering()); 1164 1165 const auto *GV = Equiv->getGlobalValue(); 1166 1167 // A PLT entry is not needed for dso_local globals. 1168 if (GV->isDSOLocal() || GV->isImplicitDSOLocal()) 1169 return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); 1170 1171 return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind, 1172 getContext()); 1173 } 1174 1175 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const { 1176 // Use ".GCC.command.line" since this feature is to support clang's 1177 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the 1178 // same name. 1179 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS, 1180 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1); 1181 } 1182 1183 void 1184 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 1185 UseInitArray = UseInitArray_; 1186 MCContext &Ctx = getContext(); 1187 if (!UseInitArray) { 1188 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 1189 ELF::SHF_ALLOC | ELF::SHF_WRITE); 1190 1191 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 1192 ELF::SHF_ALLOC | ELF::SHF_WRITE); 1193 return; 1194 } 1195 1196 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 1197 ELF::SHF_WRITE | ELF::SHF_ALLOC); 1198 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 1199 ELF::SHF_WRITE | ELF::SHF_ALLOC); 1200 } 1201 1202 //===----------------------------------------------------------------------===// 1203 // MachO 1204 //===----------------------------------------------------------------------===// 1205 1206 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() { 1207 SupportIndirectSymViaGOTPCRel = true; 1208 } 1209 1210 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 1211 const TargetMachine &TM) { 1212 TargetLoweringObjectFile::Initialize(Ctx, TM); 1213 if (TM.getRelocationModel() == Reloc::Static) { 1214 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 1215 SectionKind::getData()); 1216 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 1217 SectionKind::getData()); 1218 } else { 1219 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 1220 MachO::S_MOD_INIT_FUNC_POINTERS, 1221 SectionKind::getData()); 1222 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 1223 MachO::S_MOD_TERM_FUNC_POINTERS, 1224 SectionKind::getData()); 1225 } 1226 1227 PersonalityEncoding = 1228 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1229 LSDAEncoding = dwarf::DW_EH_PE_pcrel; 1230 TTypeEncoding = 1231 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1232 } 1233 1234 MCSection *TargetLoweringObjectFileMachO::getStaticDtorSection( 1235 unsigned Priority, const MCSymbol *KeySym) const { 1236 return StaticDtorSection; 1237 // In userspace, we lower global destructors via atexit(), but kernel/kext 1238 // environments do not provide this function so we still need to support the 1239 // legacy way here. 1240 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more 1241 // context. 1242 } 1243 1244 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, 1245 Module &M) const { 1246 // Emit the linker options if present. 1247 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1248 for (const auto *Option : LinkerOptions->operands()) { 1249 SmallVector<std::string, 4> StrOptions; 1250 for (const auto &Piece : cast<MDNode>(Option)->operands()) 1251 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString())); 1252 Streamer.emitLinkerOptions(StrOptions); 1253 } 1254 } 1255 1256 unsigned VersionVal = 0; 1257 unsigned ImageInfoFlags = 0; 1258 StringRef SectionVal; 1259 1260 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 1261 emitCGProfileMetadata(Streamer, M); 1262 1263 // The section is mandatory. If we don't have it, then we don't have GC info. 1264 if (SectionVal.empty()) 1265 return; 1266 1267 StringRef Segment, Section; 1268 unsigned TAA = 0, StubSize = 0; 1269 bool TAAParsed; 1270 if (Error E = MCSectionMachO::ParseSectionSpecifier( 1271 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) { 1272 // If invalid, report the error with report_fatal_error. 1273 report_fatal_error("Invalid section specifier '" + Section + 1274 "': " + toString(std::move(E)) + "."); 1275 } 1276 1277 // Get the section. 1278 MCSectionMachO *S = getContext().getMachOSection( 1279 Segment, Section, TAA, StubSize, SectionKind::getData()); 1280 Streamer.switchSection(S); 1281 Streamer.emitLabel(getContext(). 1282 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 1283 Streamer.emitInt32(VersionVal); 1284 Streamer.emitInt32(ImageInfoFlags); 1285 Streamer.addBlankLine(); 1286 } 1287 1288 static void checkMachOComdat(const GlobalValue *GV) { 1289 const Comdat *C = GV->getComdat(); 1290 if (!C) 1291 return; 1292 1293 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 1294 "' cannot be lowered."); 1295 } 1296 1297 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 1298 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1299 1300 StringRef SectionName = handlePragmaClangSection(GO, Kind); 1301 1302 // Parse the section specifier and create it if valid. 1303 StringRef Segment, Section; 1304 unsigned TAA = 0, StubSize = 0; 1305 bool TAAParsed; 1306 1307 checkMachOComdat(GO); 1308 1309 if (Error E = MCSectionMachO::ParseSectionSpecifier( 1310 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) { 1311 // If invalid, report the error with report_fatal_error. 1312 report_fatal_error("Global variable '" + GO->getName() + 1313 "' has an invalid section specifier '" + 1314 GO->getSection() + "': " + toString(std::move(E)) + "."); 1315 } 1316 1317 // Get the section. 1318 MCSectionMachO *S = 1319 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 1320 1321 // If TAA wasn't set by ParseSectionSpecifier() above, 1322 // use the value returned by getMachOSection() as a default. 1323 if (!TAAParsed) 1324 TAA = S->getTypeAndAttributes(); 1325 1326 // Okay, now that we got the section, verify that the TAA & StubSize agree. 1327 // If the user declared multiple globals with different section flags, we need 1328 // to reject it here. 1329 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 1330 // If invalid, report the error with report_fatal_error. 1331 report_fatal_error("Global variable '" + GO->getName() + 1332 "' section type or attributes does not match previous" 1333 " section specifier"); 1334 } 1335 1336 return S; 1337 } 1338 1339 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 1340 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1341 checkMachOComdat(GO); 1342 1343 // Handle thread local data. 1344 if (Kind.isThreadBSS()) return TLSBSSSection; 1345 if (Kind.isThreadData()) return TLSDataSection; 1346 1347 if (Kind.isText()) 1348 return GO->isWeakForLinker() ? TextCoalSection : TextSection; 1349 1350 // If this is weak/linkonce, put this in a coalescable section, either in text 1351 // or data depending on if it is writable. 1352 if (GO->isWeakForLinker()) { 1353 if (Kind.isReadOnly()) 1354 return ConstTextCoalSection; 1355 if (Kind.isReadOnlyWithRel()) 1356 return ConstDataCoalSection; 1357 return DataCoalSection; 1358 } 1359 1360 // FIXME: Alignment check should be handled by section classifier. 1361 if (Kind.isMergeable1ByteCString() && 1362 GO->getDataLayout().getPreferredAlign( 1363 cast<GlobalVariable>(GO)) < Align(32)) 1364 return CStringSection; 1365 1366 // Do not put 16-bit arrays in the UString section if they have an 1367 // externally visible label, this runs into issues with certain linker 1368 // versions. 1369 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 1370 GO->getDataLayout().getPreferredAlign( 1371 cast<GlobalVariable>(GO)) < Align(32)) 1372 return UStringSection; 1373 1374 // With MachO only variables whose corresponding symbol starts with 'l' or 1375 // 'L' can be merged, so we only try merging GVs with private linkage. 1376 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 1377 if (Kind.isMergeableConst4()) 1378 return FourByteConstantSection; 1379 if (Kind.isMergeableConst8()) 1380 return EightByteConstantSection; 1381 if (Kind.isMergeableConst16()) 1382 return SixteenByteConstantSection; 1383 } 1384 1385 // Otherwise, if it is readonly, but not something we can specially optimize, 1386 // just drop it in .const. 1387 if (Kind.isReadOnly()) 1388 return ReadOnlySection; 1389 1390 // If this is marked const, put it into a const section. But if the dynamic 1391 // linker needs to write to it, put it in the data segment. 1392 if (Kind.isReadOnlyWithRel()) 1393 return ConstDataSection; 1394 1395 // Put zero initialized globals with strong external linkage in the 1396 // DATA, __common section with the .zerofill directive. 1397 if (Kind.isBSSExtern()) 1398 return DataCommonSection; 1399 1400 // Put zero initialized globals with local linkage in __DATA,__bss directive 1401 // with the .zerofill directive (aka .lcomm). 1402 if (Kind.isBSSLocal()) 1403 return DataBSSSection; 1404 1405 // Otherwise, just drop the variable in the normal data section. 1406 return DataSection; 1407 } 1408 1409 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 1410 const DataLayout &DL, SectionKind Kind, const Constant *C, 1411 Align &Alignment) const { 1412 // If this constant requires a relocation, we have to put it in the data 1413 // segment, not in the text segment. 1414 if (Kind.isData() || Kind.isReadOnlyWithRel()) 1415 return ConstDataSection; 1416 1417 if (Kind.isMergeableConst4()) 1418 return FourByteConstantSection; 1419 if (Kind.isMergeableConst8()) 1420 return EightByteConstantSection; 1421 if (Kind.isMergeableConst16()) 1422 return SixteenByteConstantSection; 1423 return ReadOnlySection; // .const 1424 } 1425 1426 MCSection *TargetLoweringObjectFileMachO::getSectionForCommandLines() const { 1427 return getContext().getMachOSection("__TEXT", "__command_line", 0, 1428 SectionKind::getReadOnly()); 1429 } 1430 1431 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 1432 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 1433 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1434 // The mach-o version of this method defaults to returning a stub reference. 1435 1436 if (Encoding & DW_EH_PE_indirect) { 1437 MachineModuleInfoMachO &MachOMMI = 1438 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1439 1440 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1441 1442 // Add information about the stub reference to MachOMMI so that the stub 1443 // gets emitted by the asmprinter. 1444 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1445 if (!StubSym.getPointer()) { 1446 MCSymbol *Sym = TM.getSymbol(GV); 1447 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1448 } 1449 1450 return TargetLoweringObjectFile:: 1451 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 1452 Encoding & ~DW_EH_PE_indirect, Streamer); 1453 } 1454 1455 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 1456 MMI, Streamer); 1457 } 1458 1459 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 1460 const GlobalValue *GV, const TargetMachine &TM, 1461 MachineModuleInfo *MMI) const { 1462 // The mach-o version of this method defaults to returning a stub reference. 1463 MachineModuleInfoMachO &MachOMMI = 1464 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1465 1466 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1467 1468 // Add information about the stub reference to MachOMMI so that the stub 1469 // gets emitted by the asmprinter. 1470 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1471 if (!StubSym.getPointer()) { 1472 MCSymbol *Sym = TM.getSymbol(GV); 1473 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1474 } 1475 1476 return SSym; 1477 } 1478 1479 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 1480 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, 1481 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1482 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 1483 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 1484 // through a non_lazy_ptr stub instead. One advantage is that it allows the 1485 // computation of deltas to final external symbols. Example: 1486 // 1487 // _extgotequiv: 1488 // .long _extfoo 1489 // 1490 // _delta: 1491 // .long _extgotequiv-_delta 1492 // 1493 // is transformed to: 1494 // 1495 // _delta: 1496 // .long L_extfoo$non_lazy_ptr-(_delta+0) 1497 // 1498 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 1499 // L_extfoo$non_lazy_ptr: 1500 // .indirect_symbol _extfoo 1501 // .long 0 1502 // 1503 // The indirect symbol table (and sections of non_lazy_symbol_pointers type) 1504 // may point to both local (same translation unit) and global (other 1505 // translation units) symbols. Example: 1506 // 1507 // .section __DATA,__pointers,non_lazy_symbol_pointers 1508 // L1: 1509 // .indirect_symbol _myGlobal 1510 // .long 0 1511 // L2: 1512 // .indirect_symbol _myLocal 1513 // .long _myLocal 1514 // 1515 // If the symbol is local, instead of the symbol's index, the assembler 1516 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table. 1517 // Then the linker will notice the constant in the table and will look at the 1518 // content of the symbol. 1519 MachineModuleInfoMachO &MachOMMI = 1520 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1521 MCContext &Ctx = getContext(); 1522 1523 // The offset must consider the original displacement from the base symbol 1524 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 1525 Offset = -MV.getConstant(); 1526 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 1527 1528 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 1529 // non_lazy_ptr stubs. 1530 SmallString<128> Name; 1531 StringRef Suffix = "$non_lazy_ptr"; 1532 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 1533 Name += Sym->getName(); 1534 Name += Suffix; 1535 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 1536 1537 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 1538 1539 if (!StubSym.getPointer()) 1540 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym), 1541 !GV->hasLocalLinkage()); 1542 1543 const MCExpr *BSymExpr = 1544 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 1545 const MCExpr *LHS = 1546 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 1547 1548 if (!Offset) 1549 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 1550 1551 const MCExpr *RHS = 1552 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 1553 return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1554 } 1555 1556 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 1557 const MCSection &Section) { 1558 if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols(Section)) 1559 return true; 1560 1561 // FIXME: we should be able to use private labels for sections that can't be 1562 // dead-stripped (there's no issue with blocking atomization there), but `ld 1563 // -r` sometimes drops the no_dead_strip attribute from sections so for safety 1564 // we don't allow it. 1565 return false; 1566 } 1567 1568 void TargetLoweringObjectFileMachO::getNameWithPrefix( 1569 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1570 const TargetMachine &TM) const { 1571 bool CannotUsePrivateLabel = true; 1572 if (auto *GO = GV->getAliaseeObject()) { 1573 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 1574 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 1575 CannotUsePrivateLabel = 1576 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 1577 } 1578 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1579 } 1580 1581 //===----------------------------------------------------------------------===// 1582 // COFF 1583 //===----------------------------------------------------------------------===// 1584 1585 static unsigned 1586 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 1587 unsigned Flags = 0; 1588 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 1589 1590 if (K.isMetadata()) 1591 Flags |= 1592 COFF::IMAGE_SCN_MEM_DISCARDABLE; 1593 else if (K.isExclude()) 1594 Flags |= 1595 COFF::IMAGE_SCN_LNK_REMOVE | COFF::IMAGE_SCN_MEM_DISCARDABLE; 1596 else if (K.isText()) 1597 Flags |= 1598 COFF::IMAGE_SCN_MEM_EXECUTE | 1599 COFF::IMAGE_SCN_MEM_READ | 1600 COFF::IMAGE_SCN_CNT_CODE | 1601 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 1602 else if (K.isBSS()) 1603 Flags |= 1604 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 1605 COFF::IMAGE_SCN_MEM_READ | 1606 COFF::IMAGE_SCN_MEM_WRITE; 1607 else if (K.isThreadLocal()) 1608 Flags |= 1609 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1610 COFF::IMAGE_SCN_MEM_READ | 1611 COFF::IMAGE_SCN_MEM_WRITE; 1612 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 1613 Flags |= 1614 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1615 COFF::IMAGE_SCN_MEM_READ; 1616 else if (K.isWriteable()) 1617 Flags |= 1618 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1619 COFF::IMAGE_SCN_MEM_READ | 1620 COFF::IMAGE_SCN_MEM_WRITE; 1621 1622 return Flags; 1623 } 1624 1625 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 1626 const Comdat *C = GV->getComdat(); 1627 assert(C && "expected GV to have a Comdat!"); 1628 1629 StringRef ComdatGVName = C->getName(); 1630 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 1631 if (!ComdatGV) 1632 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1633 "' does not exist."); 1634 1635 if (ComdatGV->getComdat() != C) 1636 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1637 "' is not a key for its COMDAT."); 1638 1639 return ComdatGV; 1640 } 1641 1642 static int getSelectionForCOFF(const GlobalValue *GV) { 1643 if (const Comdat *C = GV->getComdat()) { 1644 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 1645 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 1646 ComdatKey = GA->getAliaseeObject(); 1647 if (ComdatKey == GV) { 1648 switch (C->getSelectionKind()) { 1649 case Comdat::Any: 1650 return COFF::IMAGE_COMDAT_SELECT_ANY; 1651 case Comdat::ExactMatch: 1652 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1653 case Comdat::Largest: 1654 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1655 case Comdat::NoDeduplicate: 1656 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1657 case Comdat::SameSize: 1658 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1659 } 1660 } else { 1661 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1662 } 1663 } 1664 return 0; 1665 } 1666 1667 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1668 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1669 StringRef Name = handlePragmaClangSection(GO, Kind); 1670 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF, 1671 /*AddSegmentInfo=*/false) || 1672 Name == getInstrProfSectionName(IPSK_covfun, Triple::COFF, 1673 /*AddSegmentInfo=*/false) || 1674 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF, 1675 /*AddSegmentInfo=*/false) || 1676 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF, 1677 /*AddSegmentInfo=*/false)) 1678 Kind = SectionKind::getMetadata(); 1679 int Selection = 0; 1680 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1681 StringRef COMDATSymName = ""; 1682 if (GO->hasComdat()) { 1683 Selection = getSelectionForCOFF(GO); 1684 const GlobalValue *ComdatGV; 1685 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1686 ComdatGV = getComdatGVForCOFF(GO); 1687 else 1688 ComdatGV = GO; 1689 1690 if (!ComdatGV->hasPrivateLinkage()) { 1691 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1692 COMDATSymName = Sym->getName(); 1693 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1694 } else { 1695 Selection = 0; 1696 } 1697 } 1698 1699 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName, 1700 Selection); 1701 } 1702 1703 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1704 if (Kind.isText()) 1705 return ".text"; 1706 if (Kind.isBSS()) 1707 return ".bss"; 1708 if (Kind.isThreadLocal()) 1709 return ".tls$"; 1710 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1711 return ".rdata"; 1712 return ".data"; 1713 } 1714 1715 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1716 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1717 // If we have -ffunction-sections then we should emit the global value to a 1718 // uniqued section specifically for it. 1719 bool EmitUniquedSection; 1720 if (Kind.isText()) 1721 EmitUniquedSection = TM.getFunctionSections(); 1722 else 1723 EmitUniquedSection = TM.getDataSections(); 1724 1725 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1726 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); 1727 1728 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1729 1730 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1731 int Selection = getSelectionForCOFF(GO); 1732 if (!Selection) 1733 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1734 const GlobalValue *ComdatGV; 1735 if (GO->hasComdat()) 1736 ComdatGV = getComdatGVForCOFF(GO); 1737 else 1738 ComdatGV = GO; 1739 1740 unsigned UniqueID = MCContext::GenericSectionID; 1741 if (EmitUniquedSection) 1742 UniqueID = NextUniqueID++; 1743 1744 if (!ComdatGV->hasPrivateLinkage()) { 1745 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1746 StringRef COMDATSymName = Sym->getName(); 1747 1748 if (const auto *F = dyn_cast<Function>(GO)) 1749 if (std::optional<StringRef> Prefix = F->getSectionPrefix()) 1750 raw_svector_ostream(Name) << '$' << *Prefix; 1751 1752 // Append "$symbol" to the section name *before* IR-level mangling is 1753 // applied when targetting mingw. This is what GCC does, and the ld.bfd 1754 // COFF linker will not properly handle comdats otherwise. 1755 if (getContext().getTargetTriple().isWindowsGNUEnvironment()) 1756 raw_svector_ostream(Name) << '$' << ComdatGV->getName(); 1757 1758 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName, 1759 Selection, UniqueID); 1760 } else { 1761 SmallString<256> TmpData; 1762 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1763 return getContext().getCOFFSection(Name, Characteristics, TmpData, 1764 Selection, UniqueID); 1765 } 1766 } 1767 1768 if (Kind.isText()) 1769 return TextSection; 1770 1771 if (Kind.isThreadLocal()) 1772 return TLSDataSection; 1773 1774 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1775 return ReadOnlySection; 1776 1777 // Note: we claim that common symbols are put in BSSSection, but they are 1778 // really emitted with the magic .comm directive, which creates a symbol table 1779 // entry but not a section. 1780 if (Kind.isBSS() || Kind.isCommon()) 1781 return BSSSection; 1782 1783 return DataSection; 1784 } 1785 1786 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 1787 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1788 const TargetMachine &TM) const { 1789 bool CannotUsePrivateLabel = false; 1790 if (GV->hasPrivateLinkage() && 1791 ((isa<Function>(GV) && TM.getFunctionSections()) || 1792 (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1793 CannotUsePrivateLabel = true; 1794 1795 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1796 } 1797 1798 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1799 const Function &F, const TargetMachine &TM) const { 1800 // If the function can be removed, produce a unique section so that 1801 // the table doesn't prevent the removal. 1802 const Comdat *C = F.getComdat(); 1803 bool EmitUniqueSection = TM.getFunctionSections() || C; 1804 if (!EmitUniqueSection) 1805 return ReadOnlySection; 1806 1807 // FIXME: we should produce a symbol for F instead. 1808 if (F.hasPrivateLinkage()) 1809 return ReadOnlySection; 1810 1811 MCSymbol *Sym = TM.getSymbol(&F); 1812 StringRef COMDATSymName = Sym->getName(); 1813 1814 SectionKind Kind = SectionKind::getReadOnly(); 1815 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); 1816 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1817 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1818 unsigned UniqueID = NextUniqueID++; 1819 1820 return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName, 1821 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, 1822 UniqueID); 1823 } 1824 1825 bool TargetLoweringObjectFileCOFF::shouldPutJumpTableInFunctionSection( 1826 bool UsesLabelDifference, const Function &F) const { 1827 if (TM->getTargetTriple().getArch() == Triple::x86_64) { 1828 if (!JumpTableInFunctionSection) { 1829 // We can always create relative relocations, so use another section 1830 // that can be marked non-executable. 1831 return false; 1832 } 1833 } 1834 return TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection( 1835 UsesLabelDifference, F); 1836 } 1837 1838 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, 1839 Module &M) const { 1840 emitLinkerDirectives(Streamer, M); 1841 1842 unsigned Version = 0; 1843 unsigned Flags = 0; 1844 StringRef Section; 1845 1846 GetObjCImageInfo(M, Version, Flags, Section); 1847 if (!Section.empty()) { 1848 auto &C = getContext(); 1849 auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1850 COFF::IMAGE_SCN_MEM_READ); 1851 Streamer.switchSection(S); 1852 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1853 Streamer.emitInt32(Version); 1854 Streamer.emitInt32(Flags); 1855 Streamer.addBlankLine(); 1856 } 1857 1858 emitCGProfileMetadata(Streamer, M); 1859 } 1860 1861 void TargetLoweringObjectFileCOFF::emitLinkerDirectives( 1862 MCStreamer &Streamer, Module &M) const { 1863 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1864 // Emit the linker options to the linker .drectve section. According to the 1865 // spec, this section is a space-separated string containing flags for 1866 // linker. 1867 MCSection *Sec = getDrectveSection(); 1868 Streamer.switchSection(Sec); 1869 for (const auto *Option : LinkerOptions->operands()) { 1870 for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1871 // Lead with a space for consistency with our dllexport implementation. 1872 std::string Directive(" "); 1873 Directive.append(std::string(cast<MDString>(Piece)->getString())); 1874 Streamer.emitBytes(Directive); 1875 } 1876 } 1877 } 1878 1879 // Emit /EXPORT: flags for each exported global as necessary. 1880 std::string Flags; 1881 for (const GlobalValue &GV : M.global_values()) { 1882 raw_string_ostream OS(Flags); 1883 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(), 1884 getMangler()); 1885 OS.flush(); 1886 if (!Flags.empty()) { 1887 Streamer.switchSection(getDrectveSection()); 1888 Streamer.emitBytes(Flags); 1889 } 1890 Flags.clear(); 1891 } 1892 1893 // Emit /INCLUDE: flags for each used global as necessary. 1894 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1895 assert(LU->hasInitializer() && "expected llvm.used to have an initializer"); 1896 assert(isa<ArrayType>(LU->getValueType()) && 1897 "expected llvm.used to be an array type"); 1898 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1899 for (const Value *Op : A->operands()) { 1900 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1901 // Global symbols with internal or private linkage are not visible to 1902 // the linker, and thus would cause an error when the linker tried to 1903 // preserve the symbol due to the `/include:` directive. 1904 if (GV->hasLocalLinkage()) 1905 continue; 1906 1907 raw_string_ostream OS(Flags); 1908 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(), 1909 getMangler()); 1910 OS.flush(); 1911 1912 if (!Flags.empty()) { 1913 Streamer.switchSection(getDrectveSection()); 1914 Streamer.emitBytes(Flags); 1915 } 1916 Flags.clear(); 1917 } 1918 } 1919 } 1920 } 1921 1922 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1923 const TargetMachine &TM) { 1924 TargetLoweringObjectFile::Initialize(Ctx, TM); 1925 this->TM = &TM; 1926 const Triple &T = TM.getTargetTriple(); 1927 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1928 StaticCtorSection = 1929 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1930 COFF::IMAGE_SCN_MEM_READ); 1931 StaticDtorSection = 1932 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1933 COFF::IMAGE_SCN_MEM_READ); 1934 } else { 1935 StaticCtorSection = Ctx.getCOFFSection( 1936 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1937 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE); 1938 StaticDtorSection = Ctx.getCOFFSection( 1939 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1940 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE); 1941 } 1942 } 1943 1944 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, 1945 const Triple &T, bool IsCtor, 1946 unsigned Priority, 1947 const MCSymbol *KeySym, 1948 MCSectionCOFF *Default) { 1949 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1950 // If the priority is the default, use .CRT$XCU, possibly associative. 1951 if (Priority == 65535) 1952 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); 1953 1954 // Otherwise, we need to compute a new section name. Low priorities should 1955 // run earlier. The linker will sort sections ASCII-betically, and we need a 1956 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we 1957 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really 1958 // low priorities need to sort before 'L', since the CRT uses that 1959 // internally, so we use ".CRT$XCA00001" for them. We have a contract with 1960 // the frontend that "init_seg(compiler)" corresponds to priority 200 and 1961 // "init_seg(lib)" corresponds to priority 400, and those respectively use 1962 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400 1963 // use 'C' with the priority as a suffix. 1964 SmallString<24> Name; 1965 char LastLetter = 'T'; 1966 bool AddPrioritySuffix = Priority != 200 && Priority != 400; 1967 if (Priority < 200) 1968 LastLetter = 'A'; 1969 else if (Priority < 400) 1970 LastLetter = 'C'; 1971 else if (Priority == 400) 1972 LastLetter = 'L'; 1973 raw_svector_ostream OS(Name); 1974 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter; 1975 if (AddPrioritySuffix) 1976 OS << format("%05u", Priority); 1977 MCSectionCOFF *Sec = Ctx.getCOFFSection( 1978 Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ); 1979 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0); 1980 } 1981 1982 std::string Name = IsCtor ? ".ctors" : ".dtors"; 1983 if (Priority != 65535) 1984 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1985 1986 return Ctx.getAssociativeCOFFSection( 1987 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1988 COFF::IMAGE_SCN_MEM_READ | 1989 COFF::IMAGE_SCN_MEM_WRITE), 1990 KeySym, 0); 1991 } 1992 1993 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1994 unsigned Priority, const MCSymbol *KeySym) const { 1995 return getCOFFStaticStructorSection( 1996 getContext(), getContext().getTargetTriple(), true, Priority, KeySym, 1997 cast<MCSectionCOFF>(StaticCtorSection)); 1998 } 1999 2000 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 2001 unsigned Priority, const MCSymbol *KeySym) const { 2002 return getCOFFStaticStructorSection( 2003 getContext(), getContext().getTargetTriple(), false, Priority, KeySym, 2004 cast<MCSectionCOFF>(StaticDtorSection)); 2005 } 2006 2007 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( 2008 const GlobalValue *LHS, const GlobalValue *RHS, 2009 const TargetMachine &TM) const { 2010 const Triple &T = TM.getTargetTriple(); 2011 if (T.isOSCygMing()) 2012 return nullptr; 2013 2014 // Our symbols should exist in address space zero, cowardly no-op if 2015 // otherwise. 2016 if (LHS->getType()->getPointerAddressSpace() != 0 || 2017 RHS->getType()->getPointerAddressSpace() != 0) 2018 return nullptr; 2019 2020 // Both ptrtoint instructions must wrap global objects: 2021 // - Only global variables are eligible for image relative relocations. 2022 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. 2023 // We expect __ImageBase to be a global variable without a section, externally 2024 // defined. 2025 // 2026 // It should look something like this: @__ImageBase = external constant i8 2027 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) || 2028 LHS->isThreadLocal() || RHS->isThreadLocal() || 2029 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || 2030 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection()) 2031 return nullptr; 2032 2033 return MCSymbolRefExpr::create(TM.getSymbol(LHS), 2034 MCSymbolRefExpr::VK_COFF_IMGREL32, 2035 getContext()); 2036 } 2037 2038 static std::string APIntToHexString(const APInt &AI) { 2039 unsigned Width = (AI.getBitWidth() / 8) * 2; 2040 std::string HexString = toString(AI, 16, /*Signed=*/false); 2041 llvm::transform(HexString, HexString.begin(), tolower); 2042 unsigned Size = HexString.size(); 2043 assert(Width >= Size && "hex string is too large!"); 2044 HexString.insert(HexString.begin(), Width - Size, '0'); 2045 2046 return HexString; 2047 } 2048 2049 static std::string scalarConstantToHexString(const Constant *C) { 2050 Type *Ty = C->getType(); 2051 if (isa<UndefValue>(C)) { 2052 return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits())); 2053 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) { 2054 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); 2055 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) { 2056 return APIntToHexString(CI->getValue()); 2057 } else { 2058 unsigned NumElements; 2059 if (auto *VTy = dyn_cast<VectorType>(Ty)) 2060 NumElements = cast<FixedVectorType>(VTy)->getNumElements(); 2061 else 2062 NumElements = Ty->getArrayNumElements(); 2063 std::string HexString; 2064 for (int I = NumElements - 1, E = -1; I != E; --I) 2065 HexString += scalarConstantToHexString(C->getAggregateElement(I)); 2066 return HexString; 2067 } 2068 } 2069 2070 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( 2071 const DataLayout &DL, SectionKind Kind, const Constant *C, 2072 Align &Alignment) const { 2073 if (Kind.isMergeableConst() && C && 2074 getContext().getAsmInfo()->hasCOFFComdatConstants()) { 2075 // This creates comdat sections with the given symbol name, but unless 2076 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol 2077 // will be created with a null storage class, which makes GNU binutils 2078 // error out. 2079 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 2080 COFF::IMAGE_SCN_MEM_READ | 2081 COFF::IMAGE_SCN_LNK_COMDAT; 2082 std::string COMDATSymName; 2083 if (Kind.isMergeableConst4()) { 2084 if (Alignment <= 4) { 2085 COMDATSymName = "__real@" + scalarConstantToHexString(C); 2086 Alignment = Align(4); 2087 } 2088 } else if (Kind.isMergeableConst8()) { 2089 if (Alignment <= 8) { 2090 COMDATSymName = "__real@" + scalarConstantToHexString(C); 2091 Alignment = Align(8); 2092 } 2093 } else if (Kind.isMergeableConst16()) { 2094 // FIXME: These may not be appropriate for non-x86 architectures. 2095 if (Alignment <= 16) { 2096 COMDATSymName = "__xmm@" + scalarConstantToHexString(C); 2097 Alignment = Align(16); 2098 } 2099 } else if (Kind.isMergeableConst32()) { 2100 if (Alignment <= 32) { 2101 COMDATSymName = "__ymm@" + scalarConstantToHexString(C); 2102 Alignment = Align(32); 2103 } 2104 } 2105 2106 if (!COMDATSymName.empty()) 2107 return getContext().getCOFFSection(".rdata", Characteristics, 2108 COMDATSymName, 2109 COFF::IMAGE_COMDAT_SELECT_ANY); 2110 } 2111 2112 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, 2113 Alignment); 2114 } 2115 2116 //===----------------------------------------------------------------------===// 2117 // Wasm 2118 //===----------------------------------------------------------------------===// 2119 2120 static const Comdat *getWasmComdat(const GlobalValue *GV) { 2121 const Comdat *C = GV->getComdat(); 2122 if (!C) 2123 return nullptr; 2124 2125 if (C->getSelectionKind() != Comdat::Any) 2126 report_fatal_error("WebAssembly COMDATs only support " 2127 "SelectionKind::Any, '" + C->getName() + "' cannot be " 2128 "lowered."); 2129 2130 return C; 2131 } 2132 2133 static unsigned getWasmSectionFlags(SectionKind K, bool Retain) { 2134 unsigned Flags = 0; 2135 2136 if (K.isThreadLocal()) 2137 Flags |= wasm::WASM_SEG_FLAG_TLS; 2138 2139 if (K.isMergeableCString()) 2140 Flags |= wasm::WASM_SEG_FLAG_STRINGS; 2141 2142 if (Retain) 2143 Flags |= wasm::WASM_SEG_FLAG_RETAIN; 2144 2145 // TODO(sbc): Add suport for K.isMergeableConst() 2146 2147 return Flags; 2148 } 2149 2150 void TargetLoweringObjectFileWasm::getModuleMetadata(Module &M) { 2151 SmallVector<GlobalValue *, 4> Vec; 2152 collectUsedGlobalVariables(M, Vec, false); 2153 for (GlobalValue *GV : Vec) 2154 if (auto *GO = dyn_cast<GlobalObject>(GV)) 2155 Used.insert(GO); 2156 } 2157 2158 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 2159 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2160 // We don't support explict section names for functions in the wasm object 2161 // format. Each function has to be in its own unique section. 2162 if (isa<Function>(GO)) { 2163 return SelectSectionForGlobal(GO, Kind, TM); 2164 } 2165 2166 StringRef Name = GO->getSection(); 2167 2168 // Certain data sections we treat as named custom sections rather than 2169 // segments within the data section. 2170 // This could be avoided if all data segements (the wasm sense) were 2171 // represented as their own sections (in the llvm sense). 2172 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138 2173 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::Wasm, 2174 /*AddSegmentInfo=*/false) || 2175 Name == getInstrProfSectionName(IPSK_covfun, Triple::Wasm, 2176 /*AddSegmentInfo=*/false) || 2177 Name == ".llvmbc" || Name == ".llvmcmd") 2178 Kind = SectionKind::getMetadata(); 2179 2180 StringRef Group = ""; 2181 if (const Comdat *C = getWasmComdat(GO)) { 2182 Group = C->getName(); 2183 } 2184 2185 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO)); 2186 MCSectionWasm *Section = getContext().getWasmSection( 2187 Name, Kind, Flags, Group, MCContext::GenericSectionID); 2188 2189 return Section; 2190 } 2191 2192 static MCSectionWasm * 2193 selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, 2194 SectionKind Kind, Mangler &Mang, 2195 const TargetMachine &TM, bool EmitUniqueSection, 2196 unsigned *NextUniqueID, bool Retain) { 2197 StringRef Group = ""; 2198 if (const Comdat *C = getWasmComdat(GO)) { 2199 Group = C->getName(); 2200 } 2201 2202 bool UniqueSectionNames = TM.getUniqueSectionNames(); 2203 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false); 2204 2205 if (const auto *F = dyn_cast<Function>(GO)) { 2206 const auto &OptionalPrefix = F->getSectionPrefix(); 2207 if (OptionalPrefix) 2208 raw_svector_ostream(Name) << '.' << *OptionalPrefix; 2209 } 2210 2211 if (EmitUniqueSection && UniqueSectionNames) { 2212 Name.push_back('.'); 2213 TM.getNameWithPrefix(Name, GO, Mang, true); 2214 } 2215 unsigned UniqueID = MCContext::GenericSectionID; 2216 if (EmitUniqueSection && !UniqueSectionNames) { 2217 UniqueID = *NextUniqueID; 2218 (*NextUniqueID)++; 2219 } 2220 2221 unsigned Flags = getWasmSectionFlags(Kind, Retain); 2222 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID); 2223 } 2224 2225 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 2226 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2227 2228 if (Kind.isCommon()) 2229 report_fatal_error("mergable sections not supported yet on wasm"); 2230 2231 // If we have -ffunction-section or -fdata-section then we should emit the 2232 // global value to a uniqued section specifically for it. 2233 bool EmitUniqueSection = false; 2234 if (Kind.isText()) 2235 EmitUniqueSection = TM.getFunctionSections(); 2236 else 2237 EmitUniqueSection = TM.getDataSections(); 2238 EmitUniqueSection |= GO->hasComdat(); 2239 bool Retain = Used.count(GO); 2240 EmitUniqueSection |= Retain; 2241 2242 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 2243 EmitUniqueSection, &NextUniqueID, Retain); 2244 } 2245 2246 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 2247 bool UsesLabelDifference, const Function &F) const { 2248 // We can always create relative relocations, so use another section 2249 // that can be marked non-executable. 2250 return false; 2251 } 2252 2253 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 2254 const GlobalValue *LHS, const GlobalValue *RHS, 2255 const TargetMachine &TM) const { 2256 // We may only use a PLT-relative relocation to refer to unnamed_addr 2257 // functions. 2258 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 2259 return nullptr; 2260 2261 // Basic correctness checks. 2262 if (LHS->getType()->getPointerAddressSpace() != 0 || 2263 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 2264 RHS->isThreadLocal()) 2265 return nullptr; 2266 2267 return MCBinaryExpr::createSub( 2268 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 2269 getContext()), 2270 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 2271 } 2272 2273 void TargetLoweringObjectFileWasm::InitializeWasm() { 2274 StaticCtorSection = 2275 getContext().getWasmSection(".init_array", SectionKind::getData()); 2276 2277 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit 2278 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables. 2279 TTypeEncoding = dwarf::DW_EH_PE_absptr; 2280 } 2281 2282 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( 2283 unsigned Priority, const MCSymbol *KeySym) const { 2284 return Priority == UINT16_MAX ? 2285 StaticCtorSection : 2286 getContext().getWasmSection(".init_array." + utostr(Priority), 2287 SectionKind::getData()); 2288 } 2289 2290 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( 2291 unsigned Priority, const MCSymbol *KeySym) const { 2292 report_fatal_error("@llvm.global_dtors should have been lowered already"); 2293 } 2294 2295 //===----------------------------------------------------------------------===// 2296 // XCOFF 2297 //===----------------------------------------------------------------------===// 2298 bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock( 2299 const MachineFunction *MF) { 2300 if (!MF->getLandingPads().empty()) 2301 return true; 2302 2303 const Function &F = MF->getFunction(); 2304 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry()) 2305 return false; 2306 2307 const GlobalValue *Per = 2308 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts()); 2309 assert(Per && "Personality routine is not a GlobalValue type."); 2310 if (isNoOpWithoutInvoke(classifyEHPersonality(Per))) 2311 return false; 2312 2313 return true; 2314 } 2315 2316 bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB( 2317 const MachineFunction *MF) { 2318 const Function &F = MF->getFunction(); 2319 if (!F.hasStackProtectorFnAttr()) 2320 return false; 2321 // FIXME: check presence of canary word 2322 // There are cases that the stack protectors are not really inserted even if 2323 // the attributes are on. 2324 return true; 2325 } 2326 2327 MCSymbol * 2328 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) { 2329 MCSymbol *EHInfoSym = MF->getContext().getOrCreateSymbol( 2330 "__ehinfo." + Twine(MF->getFunctionNumber())); 2331 cast<MCSymbolXCOFF>(EHInfoSym)->setEHInfo(); 2332 return EHInfoSym; 2333 } 2334 2335 MCSymbol * 2336 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV, 2337 const TargetMachine &TM) const { 2338 // We always use a qualname symbol for a GV that represents 2339 // a declaration, a function descriptor, or a common symbol. 2340 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we 2341 // also return a qualname so that a label symbol could be avoided. 2342 // It is inherently ambiguous when the GO represents the address of a 2343 // function, as the GO could either represent a function descriptor or a 2344 // function entry point. We choose to always return a function descriptor 2345 // here. 2346 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) { 2347 if (GO->isDeclarationForLinker()) 2348 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM)) 2349 ->getQualNameSymbol(); 2350 2351 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 2352 if (GVar->hasAttribute("toc-data")) 2353 return cast<MCSectionXCOFF>( 2354 SectionForGlobal(GVar, SectionKind::getData(), TM)) 2355 ->getQualNameSymbol(); 2356 2357 SectionKind GOKind = getKindForGlobal(GO, TM); 2358 if (GOKind.isText()) 2359 return cast<MCSectionXCOFF>( 2360 getSectionForFunctionDescriptor(cast<Function>(GO), TM)) 2361 ->getQualNameSymbol(); 2362 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() || 2363 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal()) 2364 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM)) 2365 ->getQualNameSymbol(); 2366 } 2367 2368 // For all other cases, fall back to getSymbol to return the unqualified name. 2369 return nullptr; 2370 } 2371 2372 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal( 2373 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2374 if (!GO->hasSection()) 2375 report_fatal_error("#pragma clang section is not yet supported"); 2376 2377 StringRef SectionName = GO->getSection(); 2378 2379 // Handle the XCOFF::TD case first, then deal with the rest. 2380 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO)) 2381 if (GVar->hasAttribute("toc-data")) 2382 return getContext().getXCOFFSection( 2383 SectionName, Kind, 2384 XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD), 2385 /* MultiSymbolsAllowed*/ true); 2386 2387 XCOFF::StorageMappingClass MappingClass; 2388 if (Kind.isText()) 2389 MappingClass = XCOFF::XMC_PR; 2390 else if (Kind.isData() || Kind.isBSS()) 2391 MappingClass = XCOFF::XMC_RW; 2392 else if (Kind.isReadOnlyWithRel()) 2393 MappingClass = 2394 TM.Options.XCOFFReadOnlyPointers ? XCOFF::XMC_RO : XCOFF::XMC_RW; 2395 else if (Kind.isReadOnly()) 2396 MappingClass = XCOFF::XMC_RO; 2397 else 2398 report_fatal_error("XCOFF other section types not yet implemented."); 2399 2400 return getContext().getXCOFFSection( 2401 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD), 2402 /* MultiSymbolsAllowed*/ true); 2403 } 2404 2405 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference( 2406 const GlobalObject *GO, const TargetMachine &TM) const { 2407 assert(GO->isDeclarationForLinker() && 2408 "Tried to get ER section for a defined global."); 2409 2410 SmallString<128> Name; 2411 getNameWithPrefix(Name, GO, TM); 2412 2413 // AIX TLS local-dynamic does not need the external reference for the 2414 // "_$TLSML" symbol. 2415 if (GO->getThreadLocalMode() == GlobalVariable::LocalDynamicTLSModel && 2416 GO->hasName() && GO->getName() == "_$TLSML") { 2417 return getContext().getXCOFFSection( 2418 Name, SectionKind::getData(), 2419 XCOFF::CsectProperties(XCOFF::XMC_TC, XCOFF::XTY_SD)); 2420 } 2421 2422 XCOFF::StorageMappingClass SMC = 2423 isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA; 2424 if (GO->isThreadLocal()) 2425 SMC = XCOFF::XMC_UL; 2426 2427 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO)) 2428 if (GVar->hasAttribute("toc-data")) 2429 SMC = XCOFF::XMC_TD; 2430 2431 // Externals go into a csect of type ER. 2432 return getContext().getXCOFFSection( 2433 Name, SectionKind::getMetadata(), 2434 XCOFF::CsectProperties(SMC, XCOFF::XTY_ER)); 2435 } 2436 2437 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal( 2438 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2439 // Handle the XCOFF::TD case first, then deal with the rest. 2440 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO)) 2441 if (GVar->hasAttribute("toc-data")) { 2442 SmallString<128> Name; 2443 getNameWithPrefix(Name, GO, TM); 2444 XCOFF::SymbolType symType = 2445 GO->hasCommonLinkage() ? XCOFF::XTY_CM : XCOFF::XTY_SD; 2446 return getContext().getXCOFFSection( 2447 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType), 2448 /* MultiSymbolsAllowed*/ true); 2449 } 2450 2451 // Common symbols go into a csect with matching name which will get mapped 2452 // into the .bss section. 2453 // Zero-initialized local TLS symbols go into a csect with matching name which 2454 // will get mapped into the .tbss section. 2455 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) { 2456 SmallString<128> Name; 2457 getNameWithPrefix(Name, GO, TM); 2458 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS 2459 : Kind.isCommon() ? XCOFF::XMC_RW 2460 : XCOFF::XMC_UL; 2461 return getContext().getXCOFFSection( 2462 Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM)); 2463 } 2464 2465 if (Kind.isText()) { 2466 if (TM.getFunctionSections()) { 2467 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM)) 2468 ->getRepresentedCsect(); 2469 } 2470 return TextSection; 2471 } 2472 2473 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) { 2474 if (!TM.getDataSections()) 2475 report_fatal_error( 2476 "ReadOnlyPointers is supported only if data sections is turned on"); 2477 2478 SmallString<128> Name; 2479 getNameWithPrefix(Name, GO, TM); 2480 return getContext().getXCOFFSection( 2481 Name, SectionKind::getReadOnly(), 2482 XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)); 2483 } 2484 2485 // For BSS kind, zero initialized data must be emitted to the .data section 2486 // because external linkage control sections that get mapped to the .bss 2487 // section will be linked as tentative defintions, which is only appropriate 2488 // for SectionKind::Common. 2489 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) { 2490 if (TM.getDataSections()) { 2491 SmallString<128> Name; 2492 getNameWithPrefix(Name, GO, TM); 2493 return getContext().getXCOFFSection( 2494 Name, SectionKind::getData(), 2495 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)); 2496 } 2497 return DataSection; 2498 } 2499 2500 if (Kind.isReadOnly()) { 2501 if (TM.getDataSections()) { 2502 SmallString<128> Name; 2503 getNameWithPrefix(Name, GO, TM); 2504 return getContext().getXCOFFSection( 2505 Name, SectionKind::getReadOnly(), 2506 XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)); 2507 } 2508 return ReadOnlySection; 2509 } 2510 2511 // External/weak TLS data and initialized local TLS data are not eligible 2512 // to be put into common csect. If data sections are enabled, thread 2513 // data are emitted into separate sections. Otherwise, thread data 2514 // are emitted into the .tdata section. 2515 if (Kind.isThreadLocal()) { 2516 if (TM.getDataSections()) { 2517 SmallString<128> Name; 2518 getNameWithPrefix(Name, GO, TM); 2519 return getContext().getXCOFFSection( 2520 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD)); 2521 } 2522 return TLSDataSection; 2523 } 2524 2525 report_fatal_error("XCOFF other section types not yet implemented."); 2526 } 2527 2528 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable( 2529 const Function &F, const TargetMachine &TM) const { 2530 assert (!F.getComdat() && "Comdat not supported on XCOFF."); 2531 2532 if (!TM.getFunctionSections()) 2533 return ReadOnlySection; 2534 2535 // If the function can be removed, produce a unique section so that 2536 // the table doesn't prevent the removal. 2537 SmallString<128> NameStr(".rodata.jmp.."); 2538 getNameWithPrefix(NameStr, &F, TM); 2539 return getContext().getXCOFFSection( 2540 NameStr, SectionKind::getReadOnly(), 2541 XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)); 2542 } 2543 2544 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection( 2545 bool UsesLabelDifference, const Function &F) const { 2546 return false; 2547 } 2548 2549 /// Given a mergeable constant with the specified size and relocation 2550 /// information, return a section that it should be placed in. 2551 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant( 2552 const DataLayout &DL, SectionKind Kind, const Constant *C, 2553 Align &Alignment) const { 2554 // TODO: Enable emiting constant pool to unique sections when we support it. 2555 if (Alignment > Align(16)) 2556 report_fatal_error("Alignments greater than 16 not yet supported."); 2557 2558 if (Alignment == Align(8)) { 2559 assert(ReadOnly8Section && "Section should always be initialized."); 2560 return ReadOnly8Section; 2561 } 2562 2563 if (Alignment == Align(16)) { 2564 assert(ReadOnly16Section && "Section should always be initialized."); 2565 return ReadOnly16Section; 2566 } 2567 2568 return ReadOnlySection; 2569 } 2570 2571 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx, 2572 const TargetMachine &TgtM) { 2573 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 2574 TTypeEncoding = 2575 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel | 2576 (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4 2577 : dwarf::DW_EH_PE_sdata8); 2578 PersonalityEncoding = 0; 2579 LSDAEncoding = 0; 2580 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 2581 2582 // AIX debug for thread local location is not ready. And for integrated as 2583 // mode, the relocatable address for the thread local variable will cause 2584 // linker error. So disable the location attribute generation for thread local 2585 // variables for now. 2586 // FIXME: when TLS debug on AIX is ready, remove this setting. 2587 SupportDebugThreadLocalLocation = false; 2588 } 2589 2590 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection( 2591 unsigned Priority, const MCSymbol *KeySym) const { 2592 report_fatal_error("no static constructor section on AIX"); 2593 } 2594 2595 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection( 2596 unsigned Priority, const MCSymbol *KeySym) const { 2597 report_fatal_error("no static destructor section on AIX"); 2598 } 2599 2600 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference( 2601 const GlobalValue *LHS, const GlobalValue *RHS, 2602 const TargetMachine &TM) const { 2603 /* Not implemented yet, but don't crash, return nullptr. */ 2604 return nullptr; 2605 } 2606 2607 XCOFF::StorageClass 2608 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) { 2609 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX."); 2610 2611 switch (GV->getLinkage()) { 2612 case GlobalValue::InternalLinkage: 2613 case GlobalValue::PrivateLinkage: 2614 return XCOFF::C_HIDEXT; 2615 case GlobalValue::ExternalLinkage: 2616 case GlobalValue::CommonLinkage: 2617 case GlobalValue::AvailableExternallyLinkage: 2618 return XCOFF::C_EXT; 2619 case GlobalValue::ExternalWeakLinkage: 2620 case GlobalValue::LinkOnceAnyLinkage: 2621 case GlobalValue::LinkOnceODRLinkage: 2622 case GlobalValue::WeakAnyLinkage: 2623 case GlobalValue::WeakODRLinkage: 2624 return XCOFF::C_WEAKEXT; 2625 case GlobalValue::AppendingLinkage: 2626 report_fatal_error( 2627 "There is no mapping that implements AppendingLinkage for XCOFF."); 2628 } 2629 llvm_unreachable("Unknown linkage type!"); 2630 } 2631 2632 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol( 2633 const GlobalValue *Func, const TargetMachine &TM) const { 2634 assert((isa<Function>(Func) || 2635 (isa<GlobalAlias>(Func) && 2636 isa_and_nonnull<Function>( 2637 cast<GlobalAlias>(Func)->getAliaseeObject()))) && 2638 "Func must be a function or an alias which has a function as base " 2639 "object."); 2640 2641 SmallString<128> NameStr; 2642 NameStr.push_back('.'); 2643 getNameWithPrefix(NameStr, Func, TM); 2644 2645 // When -function-sections is enabled and explicit section is not specified, 2646 // it's not necessary to emit function entry point label any more. We will use 2647 // function entry point csect instead. And for function delcarations, the 2648 // undefined symbols gets treated as csect with XTY_ER property. 2649 if (((TM.getFunctionSections() && !Func->hasSection()) || 2650 Func->isDeclarationForLinker()) && 2651 isa<Function>(Func)) { 2652 return getContext() 2653 .getXCOFFSection( 2654 NameStr, SectionKind::getText(), 2655 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker() 2656 ? XCOFF::XTY_ER 2657 : XCOFF::XTY_SD)) 2658 ->getQualNameSymbol(); 2659 } 2660 2661 return getContext().getOrCreateSymbol(NameStr); 2662 } 2663 2664 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor( 2665 const Function *F, const TargetMachine &TM) const { 2666 SmallString<128> NameStr; 2667 getNameWithPrefix(NameStr, F, TM); 2668 return getContext().getXCOFFSection( 2669 NameStr, SectionKind::getData(), 2670 XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD)); 2671 } 2672 2673 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry( 2674 const MCSymbol *Sym, const TargetMachine &TM) const { 2675 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym, 2676 const TargetMachine &TM) { 2677 const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(Sym); 2678 2679 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC, 2680 // otherwise the AIX assembler will complain. 2681 if (XSym->getSymbolTableName() == "_$TLSML") 2682 return XCOFF::XMC_TC; 2683 2684 // Use large code model toc entries for ehinfo symbols as they are 2685 // never referenced directly. The runtime loads their TOC entry 2686 // addresses from the trace-back table. 2687 if (XSym->isEHInfo()) 2688 return XCOFF::XMC_TE; 2689 2690 // If the symbol does not have a code model specified use the module value. 2691 if (!XSym->hasPerSymbolCodeModel()) 2692 return TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE 2693 : XCOFF::XMC_TC; 2694 2695 return XSym->getPerSymbolCodeModel() == MCSymbolXCOFF::CM_Large 2696 ? XCOFF::XMC_TE 2697 : XCOFF::XMC_TC; 2698 }(Sym, TM); 2699 2700 return getContext().getXCOFFSection( 2701 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(), 2702 XCOFF::CsectProperties(SMC, XCOFF::XTY_SD)); 2703 } 2704 2705 MCSection *TargetLoweringObjectFileXCOFF::getSectionForLSDA( 2706 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const { 2707 auto *LSDA = cast<MCSectionXCOFF>(LSDASection); 2708 if (TM.getFunctionSections()) { 2709 // If option -ffunction-sections is on, append the function name to the 2710 // name of the LSDA csect so that each function has its own LSDA csect. 2711 // This helps the linker to garbage-collect EH info of unused functions. 2712 SmallString<128> NameStr = LSDA->getName(); 2713 raw_svector_ostream(NameStr) << '.' << F.getName(); 2714 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(), 2715 LSDA->getCsectProp()); 2716 } 2717 return LSDA; 2718 } 2719 //===----------------------------------------------------------------------===// 2720 // GOFF 2721 //===----------------------------------------------------------------------===// 2722 TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() = default; 2723 2724 MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal( 2725 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2726 return SelectSectionForGlobal(GO, Kind, TM); 2727 } 2728 2729 MCSection *TargetLoweringObjectFileGOFF::getSectionForLSDA( 2730 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const { 2731 std::string Name = ".gcc_exception_table." + F.getName().str(); 2732 return getContext().getGOFFSection(Name, SectionKind::getData(), nullptr, 0); 2733 } 2734 2735 MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal( 2736 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2737 auto *Symbol = TM.getSymbol(GO); 2738 if (Kind.isBSS()) 2739 return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(), 2740 nullptr, 0); 2741 2742 return getContext().getObjectFileInfo()->getTextSection(); 2743 } 2744