1 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h" 15 #include "llvm/BinaryFormat/Dwarf.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DataLayout.h" 18 #include "llvm/IR/DerivedTypes.h" 19 #include "llvm/IR/Function.h" 20 #include "llvm/IR/GlobalVariable.h" 21 #include "llvm/IR/Mangler.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/MC/MCAsmInfo.h" 24 #include "llvm/MC/MCContext.h" 25 #include "llvm/MC/MCExpr.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/MC/MCSymbol.h" 28 #include "llvm/MC/SectionKind.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Target/TargetMachine.h" 32 #include "llvm/Target/TargetOptions.h" 33 using namespace llvm; 34 35 //===----------------------------------------------------------------------===// 36 // Generic Code 37 //===----------------------------------------------------------------------===// 38 39 /// Initialize - this method must be called before any actual lowering is 40 /// done. This specifies the current context for codegen, and gives the 41 /// lowering implementations a chance to set up their default sections. 42 void TargetLoweringObjectFile::Initialize(MCContext &ctx, 43 const TargetMachine &TM) { 44 // `Initialize` can be called more than once. 45 delete Mang; 46 Mang = new Mangler(); 47 InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), ctx, 48 TM.getCodeModel() == CodeModel::Large); 49 50 // Reset various EH DWARF encodings. 51 PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr; 52 CallSiteEncoding = dwarf::DW_EH_PE_uleb128; 53 } 54 55 TargetLoweringObjectFile::~TargetLoweringObjectFile() { 56 delete Mang; 57 } 58 59 unsigned TargetLoweringObjectFile::getCallSiteEncoding() const { 60 // If target does not have LEB128 directives, we would need the 61 // call site encoding to be udata4 so that the alternative path 62 // for not having LEB128 directives could work. 63 if (!getContext().getAsmInfo()->hasLEB128Directives()) 64 return dwarf::DW_EH_PE_udata4; 65 return CallSiteEncoding; 66 } 67 68 static bool isNullOrUndef(const Constant *C) { 69 // Check that the constant isn't all zeros or undefs. 70 if (C->isNullValue() || isa<UndefValue>(C)) 71 return true; 72 if (!isa<ConstantAggregate>(C)) 73 return false; 74 for (auto Operand : C->operand_values()) { 75 if (!isNullOrUndef(cast<Constant>(Operand))) 76 return false; 77 } 78 return true; 79 } 80 81 static bool isSuitableForBSS(const GlobalVariable *GV) { 82 const Constant *C = GV->getInitializer(); 83 84 // Must have zero initializer. 85 if (!isNullOrUndef(C)) 86 return false; 87 88 // Leave constant zeros in readonly constant sections, so they can be shared. 89 if (GV->isConstant()) 90 return false; 91 92 // If the global has an explicit section specified, don't put it in BSS. 93 if (GV->hasSection()) 94 return false; 95 96 // Otherwise, put it in BSS! 97 return true; 98 } 99 100 /// IsNullTerminatedString - Return true if the specified constant (which is 101 /// known to have a type that is an array of 1/2/4 byte elements) ends with a 102 /// nul value and contains no other nuls in it. Note that this is more general 103 /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings. 104 static bool IsNullTerminatedString(const Constant *C) { 105 // First check: is we have constant array terminated with zero 106 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(C)) { 107 unsigned NumElts = CDS->getNumElements(); 108 assert(NumElts != 0 && "Can't have an empty CDS"); 109 110 if (CDS->getElementAsInteger(NumElts-1) != 0) 111 return false; // Not null terminated. 112 113 // Verify that the null doesn't occur anywhere else in the string. 114 for (unsigned i = 0; i != NumElts-1; ++i) 115 if (CDS->getElementAsInteger(i) == 0) 116 return false; 117 return true; 118 } 119 120 // Another possibility: [1 x i8] zeroinitializer 121 if (isa<ConstantAggregateZero>(C)) 122 return cast<ArrayType>(C->getType())->getNumElements() == 1; 123 124 return false; 125 } 126 127 MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase( 128 const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const { 129 assert(!Suffix.empty()); 130 131 SmallString<60> NameStr; 132 NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix(); 133 TM.getNameWithPrefix(NameStr, GV, *Mang); 134 NameStr.append(Suffix.begin(), Suffix.end()); 135 return getContext().getOrCreateSymbol(NameStr); 136 } 137 138 MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol( 139 const GlobalValue *GV, const TargetMachine &TM, 140 MachineModuleInfo *MMI) const { 141 return TM.getSymbol(GV); 142 } 143 144 void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer, 145 const DataLayout &, 146 const MCSymbol *Sym) const { 147 } 148 149 150 /// getKindForGlobal - This is a top-level target-independent classifier for 151 /// a global object. Given a global variable and information from the TM, this 152 /// function classifies the global in a target independent manner. This function 153 /// may be overridden by the target implementation. 154 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO, 155 const TargetMachine &TM){ 156 assert(!GO->isDeclarationForLinker() && 157 "Can only be used for global definitions"); 158 159 // Functions are classified as text sections. 160 if (isa<Function>(GO)) 161 return SectionKind::getText(); 162 163 // Basic blocks are classified as text sections. 164 if (isa<BasicBlock>(GO)) 165 return SectionKind::getText(); 166 167 // Global variables require more detailed analysis. 168 const auto *GVar = cast<GlobalVariable>(GO); 169 170 // Handle thread-local data first. 171 if (GVar->isThreadLocal()) { 172 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) 173 return SectionKind::getThreadBSS(); 174 return SectionKind::getThreadData(); 175 } 176 177 // Variables with common linkage always get classified as common. 178 if (GVar->hasCommonLinkage()) 179 return SectionKind::getCommon(); 180 181 // Most non-mergeable zero data can be put in the BSS section unless otherwise 182 // specified. 183 if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) { 184 if (GVar->hasLocalLinkage()) 185 return SectionKind::getBSSLocal(); 186 else if (GVar->hasExternalLinkage()) 187 return SectionKind::getBSSExtern(); 188 return SectionKind::getBSS(); 189 } 190 191 // If the global is marked constant, we can put it into a mergable section, 192 // a mergable string section, or general .data if it contains relocations. 193 if (GVar->isConstant()) { 194 // If the initializer for the global contains something that requires a 195 // relocation, then we may have to drop this into a writable data section 196 // even though it is marked const. 197 const Constant *C = GVar->getInitializer(); 198 if (!C->needsRelocation()) { 199 // If the global is required to have a unique address, it can't be put 200 // into a mergable section: just drop it into the general read-only 201 // section instead. 202 if (!GVar->hasGlobalUnnamedAddr()) 203 return SectionKind::getReadOnly(); 204 205 // If initializer is a null-terminated string, put it in a "cstring" 206 // section of the right width. 207 if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) { 208 if (IntegerType *ITy = 209 dyn_cast<IntegerType>(ATy->getElementType())) { 210 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 || 211 ITy->getBitWidth() == 32) && 212 IsNullTerminatedString(C)) { 213 if (ITy->getBitWidth() == 8) 214 return SectionKind::getMergeable1ByteCString(); 215 if (ITy->getBitWidth() == 16) 216 return SectionKind::getMergeable2ByteCString(); 217 218 assert(ITy->getBitWidth() == 32 && "Unknown width"); 219 return SectionKind::getMergeable4ByteCString(); 220 } 221 } 222 } 223 224 // Otherwise, just drop it into a mergable constant section. If we have 225 // a section for this size, use it, otherwise use the arbitrary sized 226 // mergable section. 227 switch ( 228 GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) { 229 case 4: return SectionKind::getMergeableConst4(); 230 case 8: return SectionKind::getMergeableConst8(); 231 case 16: return SectionKind::getMergeableConst16(); 232 case 32: return SectionKind::getMergeableConst32(); 233 default: 234 return SectionKind::getReadOnly(); 235 } 236 237 } else { 238 // In static, ROPI and RWPI relocation models, the linker will resolve 239 // all addresses, so the relocation entries will actually be constants by 240 // the time the app starts up. However, we can't put this into a 241 // mergable section, because the linker doesn't take relocations into 242 // consideration when it tries to merge entries in the section. 243 Reloc::Model ReloModel = TM.getRelocationModel(); 244 if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI || 245 ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI) 246 return SectionKind::getReadOnly(); 247 248 // Otherwise, the dynamic linker needs to fix it up, put it in the 249 // writable data.rel section. 250 return SectionKind::getReadOnlyWithRel(); 251 } 252 } 253 254 // Okay, this isn't a constant. 255 return SectionKind::getData(); 256 } 257 258 /// This method computes the appropriate section to emit the specified global 259 /// variable or function definition. This should not be passed external (or 260 /// available externally) globals. 261 MCSection *TargetLoweringObjectFile::SectionForGlobal( 262 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 263 // Select section name. 264 if (GO->hasSection()) 265 return getExplicitSectionGlobal(GO, Kind, TM); 266 267 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 268 auto Attrs = GVar->getAttributes(); 269 if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) || 270 (Attrs.hasAttribute("data-section") && Kind.isData()) || 271 (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) || 272 (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) { 273 return getExplicitSectionGlobal(GO, Kind, TM); 274 } 275 } 276 277 if (auto *F = dyn_cast<Function>(GO)) { 278 if (F->hasFnAttribute("implicit-section-name")) 279 return getExplicitSectionGlobal(GO, Kind, TM); 280 } 281 282 // Use default section depending on the 'type' of global 283 return SelectSectionForGlobal(GO, Kind, TM); 284 } 285 286 /// This method computes the appropriate section to emit the specified global 287 /// variable or function definition. This should not be passed external (or 288 /// available externally) globals. 289 MCSection * 290 TargetLoweringObjectFile::SectionForGlobal(const GlobalObject *GO, 291 const TargetMachine &TM) const { 292 return SectionForGlobal(GO, getKindForGlobal(GO, TM), TM); 293 } 294 295 MCSection *TargetLoweringObjectFile::getSectionForJumpTable( 296 const Function &F, const TargetMachine &TM) const { 297 Align Alignment(1); 298 return getSectionForConstant(F.getParent()->getDataLayout(), 299 SectionKind::getReadOnly(), /*C=*/nullptr, 300 Alignment); 301 } 302 303 bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection( 304 bool UsesLabelDifference, const Function &F) const { 305 // In PIC mode, we need to emit the jump table to the same section as the 306 // function body itself, otherwise the label differences won't make sense. 307 // FIXME: Need a better predicate for this: what about custom entries? 308 if (UsesLabelDifference) 309 return true; 310 311 // We should also do if the section name is NULL or function is declared 312 // in discardable section 313 // FIXME: this isn't the right predicate, should be based on the MCSection 314 // for the function. 315 return F.isWeakForLinker(); 316 } 317 318 /// Given a mergable constant with the specified size and relocation 319 /// information, return a section that it should be placed in. 320 MCSection *TargetLoweringObjectFile::getSectionForConstant( 321 const DataLayout &DL, SectionKind Kind, const Constant *C, 322 Align &Alignment) const { 323 if (Kind.isReadOnly() && ReadOnlySection != nullptr) 324 return ReadOnlySection; 325 326 return DataSection; 327 } 328 329 MCSection *TargetLoweringObjectFile::getSectionForMachineBasicBlock( 330 const Function &F, const MachineBasicBlock &MBB, 331 const TargetMachine &TM) const { 332 return nullptr; 333 } 334 335 /// getTTypeGlobalReference - Return an MCExpr to use for a 336 /// reference to the specified global variable from exception 337 /// handling information. 338 const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference( 339 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 340 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 341 const MCSymbolRefExpr *Ref = 342 MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); 343 344 return getTTypeReference(Ref, Encoding, Streamer); 345 } 346 347 const MCExpr *TargetLoweringObjectFile:: 348 getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, 349 MCStreamer &Streamer) const { 350 switch (Encoding & 0x70) { 351 default: 352 report_fatal_error("We do not support this DWARF encoding yet!"); 353 case dwarf::DW_EH_PE_absptr: 354 // Do nothing special 355 return Sym; 356 case dwarf::DW_EH_PE_pcrel: { 357 // Emit a label to the streamer for the current position. This gives us 358 // .-foo addressing. 359 MCSymbol *PCSym = getContext().createTempSymbol(); 360 Streamer.emitLabel(PCSym); 361 const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext()); 362 return MCBinaryExpr::createSub(Sym, PC, getContext()); 363 } 364 } 365 } 366 367 const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const { 368 // FIXME: It's not clear what, if any, default this should have - perhaps a 369 // null return could mean 'no location' & we should just do that here. 370 return MCSymbolRefExpr::create(Sym, getContext()); 371 } 372 373 void TargetLoweringObjectFile::getNameWithPrefix( 374 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 375 const TargetMachine &TM) const { 376 Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false); 377 } 378