1//===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===// 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 7//===----------------------------------------------------------------------===// 9// This file implements classes used to handle lowerings specific to common 10// object file formats. 12//===----------------------------------------------------------------------===// 33//===----------------------------------------------------------------------===// 35//===----------------------------------------------------------------------===// 37/// Initialize - this method must be called before any actual lowering is 38/// done. This specifies the current context for codegen, and gives the 39/// lowering implementations a chance to set up their default sections. 42// `Initialize` can be called more than once. 48// Reset various EH DWARF encodings. 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. 63if (!
getContext().getAsmInfo()->hasLEB128Directives())
69// Check that the constant isn't all zeros or undefs. 70if (
C->isNullValue() || isa<UndefValue>(
C))
72if (!isa<ConstantAggregate>(
C))
74for (
constauto *Operand :
C->operand_values()) {
84// Must have zero initializer. 88// Leave constant zeros in readonly constant sections, so they can be shared. 92// If the global has an explicit section specified, don't put it in BSS. 96// Otherwise, put it in BSS! 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. 105// First check: is we have constant array terminated with zero 107unsigned NumElts = CDS->getNumElements();
108assert(NumElts != 0 &&
"Can't have an empty CDS");
110if (CDS->getElementAsInteger(NumElts-1) != 0)
111returnfalse;
// Not null terminated. 113// Verify that the null doesn't occur anywhere else in the string. 114for (
unsigned i = 0; i != NumElts-1; ++i)
115if (CDS->getElementAsInteger(i) == 0)
120// Another possibility: [1 x i8] zeroinitializer 121if (isa<ConstantAggregateZero>(
C))
122return cast<ArrayType>(
C->getType())->getNumElements() == 1;
152 M.getModuleFlagsMetadata(ModuleFlags);
154MDNode *CFGProfile =
nullptr;
156for (
constauto &MFE : ModuleFlags) {
158if (Key ==
"CG Profile") {
159 CFGProfile = cast<MDNode>(MFE.Val);
170auto *V = cast<ValueAsMetadata>(MDO);
171constFunction *
F = cast<Function>(V->getValue()->stripPointerCasts());
172if (
F->hasDLLImportStorageClass())
177for (
constauto &Edge : CFGProfile->
operands()) {
178MDNode *E = cast<MDNode>(Edge);
181// Skip null functions. This can happen if functions are dead stripped after 182// the CGProfile pass has been run. 195/// getKindForGlobal - This is a top-level target-independent classifier for 196/// a global object. Given a global variable and information from the TM, this 197/// function classifies the global in a target independent manner. This function 198/// may be overridden by the target implementation. 202"Can only be used for global definitions");
204// Functions are classified as text sections. 205if (isa<Function>(GO))
208// Basic blocks are classified as text sections. 209if (isa<BasicBlock>(GO))
212// Global variables require more detailed analysis. 213constauto *GVar = cast<GlobalVariable>(GO);
215// Handle thread-local data first. 216if (GVar->isThreadLocal()) {
218// Zero-initialized TLS variables with local linkage always get classified 220if (GVar->hasLocalLinkage()) {
228// Variables with common linkage always get classified as common. 229if (GVar->hasCommonLinkage())
232// Most non-mergeable zero data can be put in the BSS section unless otherwise 235if (GVar->hasLocalLinkage())
237elseif (GVar->hasExternalLinkage())
242// Global variables with '!exclude' should get the exclude section kind if 243// they have an explicit section and no other metadata. 244if (GVar->hasSection())
245if (
MDNode *MD = GVar->getMetadata(LLVMContext::MD_exclude))
246if (!MD->getNumOperands())
249// If the global is marked constant, we can put it into a mergable section, 250// a mergable string section, or general .data if it contains relocations. 251if (GVar->isConstant()) {
252// If the initializer for the global contains something that requires a 253// relocation, then we may have to drop this into a writable data section 254// even though it is marked const. 255constConstant *
C = GVar->getInitializer();
256if (!
C->needsRelocation()) {
257// If the global is required to have a unique address, it can't be put 258// into a mergable section: just drop it into the general read-only 260if (!GVar->hasGlobalUnnamedAddr())
263// If initializer is a null-terminated string, put it in a "cstring" 264// section of the right width. 265if (
ArrayType *ATy = dyn_cast<ArrayType>(
C->getType())) {
267 dyn_cast<IntegerType>(ATy->getElementType())) {
268if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
269 ITy->getBitWidth() == 32) &&
271if (ITy->getBitWidth() == 8)
273if (ITy->getBitWidth() == 16)
276assert(ITy->getBitWidth() == 32 &&
"Unknown width");
282// Otherwise, just drop it into a mergable constant section. If we have 283// a section for this size, use it, otherwise use the arbitrary sized 286 GVar->getDataLayout().getTypeAllocSize(
C->getType())) {
296// In static, ROPI and RWPI relocation models, the linker will resolve 297// all addresses, so the relocation entries will actually be constants by 298// the time the app starts up. However, we can't put this into a 299// mergable section, because the linker doesn't take relocations into 300// consideration when it tries to merge entries in the section. 304 !
C->needsDynamicRelocation())
307// Otherwise, the dynamic linker needs to fix it up, put it in the 308// writable data.rel section. 313// Okay, this isn't a constant. 317/// This method computes the appropriate section to emit the specified global 318/// variable or function definition. This should not be passed external (or 319/// available externally) globals. 322// Select section name. 326if (
auto *GVar = dyn_cast<GlobalVariable>(GO)) {
327auto Attrs = GVar->getAttributes();
328if ((Attrs.hasAttribute(
"bss-section") && Kind.isBSS()) ||
329 (Attrs.hasAttribute(
"data-section") && Kind.isData()) ||
330 (Attrs.hasAttribute(
"relro-section") && Kind.isReadOnlyWithRel()) ||
331 (Attrs.hasAttribute(
"rodata-section") && Kind.isReadOnly())) {
336// Use default section depending on the 'type' of global 340/// This method computes the appropriate section to emit the specified global 341/// variable or function definition. This should not be passed external (or 342/// available externally) globals. 358bool UsesLabelDifference,
constFunction &
F)
const{
359// In PIC mode, we need to emit the jump table to the same section as the 360// function body itself, otherwise the label differences won't make sense. 361// FIXME: Need a better predicate for this: what about custom entries? 362if (UsesLabelDifference)
365// We should also do if the section name is NULL or function is declared 366// in discardable section 367// FIXME: this isn't the right predicate, should be based on the MCSection 369returnF.isWeakForLinker();
372/// Given a mergable constant with the specified size and relocation 373/// information, return a section that it should be placed in. 376Align &Alignment)
const{
394/// getTTypeGlobalReference - Return an MCExpr to use for a 395/// reference to the specified global variable from exception 396/// handling information. 409switch (Encoding & 0x70) {
416// Emit a label to the streamer for the current position. This gives us 427// FIXME: It's not clear what, if any, default this should have - perhaps a 428// null return could mean 'no location' & we should just do that here. MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isNullOrUndef(const Constant *C)
static bool IsNullTerminatedString(const Constant *C)
IsNullTerminatedString - Return true if the specified constant (which is known to have a type that is...
static bool isSuitableForBSS(const GlobalVariable *GV)
Class to represent array types.
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
This is an important base class in LLVM.
A parsed version of the target data layout string in and methods for querying it.
StringRef getPrivateGlobalPrefix() const
bool hasSection() const
Check if this global has a custom object file section.
bool isDeclarationForLinker() const
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
Class to represent integer types.
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Context object for machine code objects.
MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Base class for the full range of assembler expressions which are needed for parsing.
void initMCObjectFileInfo(MCContext &MCCtx, bool PIC, bool LargeCodeModel=false)
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
MCContext & getContext() const
MCSection * DataSection
Section directive for standard data.
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Streaming machine code generation interface.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitCGProfileEntry(const MCSymbolRefExpr *From, const MCSymbolRefExpr *To, uint64_t Count)
Represent a reference to a symbol from inside an expression.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
Tracking metadata reference owned by Metadata.
This class contains meta information specific to a module.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
A Module instance is used to store all the information related to an LLVM module.
SectionKind - This is a simple POD value that classifies the properties of a section.
static SectionKind getThreadData()
static SectionKind getBSSExtern()
static SectionKind getMergeable2ByteCString()
static SectionKind getExclude()
static SectionKind getBSSLocal()
static SectionKind getMergeableConst4()
static SectionKind getCommon()
static SectionKind getText()
static SectionKind getThreadBSSLocal()
static SectionKind getReadOnlyWithRel()
static SectionKind getData()
static SectionKind getMergeableConst8()
static SectionKind getBSS()
static SectionKind getThreadBSS()
static SectionKind getMergeableConst16()
static SectionKind getMergeable4ByteCString()
static SectionKind getMergeable1ByteCString()
static SectionKind getReadOnly()
static SectionKind getMergeableConst32()
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void append(StringRef RHS)
Append from a StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
void emitCGProfileMetadata(MCStreamer &Streamer, Module &M) const
Emit Call Graph Profile metadata.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
unsigned getCallSiteEncoding() const
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
virtual MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
virtual MCSection * getSectionForMachineBasicBlock(const Function &F, const MachineBasicBlock &MBB, const TargetMachine &TM) const
virtual ~TargetLoweringObjectFile()
virtual const MCExpr * getDebugThreadLocalSymbol(const MCSymbol *Sym) const
Create a symbol reference to describe the given TLS variable when emitting the address in debug info.
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
unsigned CallSiteEncoding
virtual MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const =0
Targets should implement this method to assign a section to globals with an explicit section specfied...
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
virtual void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym, const MachineModuleInfo *MMI) const
virtual MCSection * getUniqueSectionForFunction(const Function &F, const TargetMachine &TM) const
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
bool isPositionIndependent() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
MCSymbol * getSymbol(const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
unsigned NoZerosInBSS
NoZerosInBSS - By default some codegens place zero-initialized data to .bss section.
@ C
The default llvm calling convention, compatible with C.
This is an optimization pass for GlobalISel generic memory operations.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
@ Ref
The access may reference the value stored in memory.
This struct is a compact representation of a valid (non-zero power of two) alignment.