Index: llvm/trunk/include/llvm/Target/TargetLoweringObjectFile.h =================================================================== --- llvm/trunk/include/llvm/Target/TargetLoweringObjectFile.h (revision 366328) +++ llvm/trunk/include/llvm/Target/TargetLoweringObjectFile.h (revision 366329) @@ -1,220 +1,222 @@ //===-- llvm/Target/TargetLoweringObjectFile.h - Object Info ----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements classes used to handle lowerings specific to common // object file formats. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_TARGETLOWERINGOBJECTFILE_H #define LLVM_CODEGEN_TARGETLOWERINGOBJECTFILE_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/SectionKind.h" #include namespace llvm { class GlobalValue; class MachineModuleInfo; class Mangler; class MCContext; class MCExpr; class MCSection; class MCSymbol; class MCSymbolRefExpr; class MCStreamer; class MCValue; class TargetMachine; class TargetLoweringObjectFile : public MCObjectFileInfo { MCContext *Ctx = nullptr; /// Name-mangler for global names. Mangler *Mang = nullptr; protected: bool SupportIndirectSymViaGOTPCRel = false; bool SupportGOTPCRelWithOffset = true; bool SupportDebugThreadLocalLocation = true; /// PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values /// for EH. unsigned PersonalityEncoding = 0; unsigned LSDAEncoding = 0; unsigned TTypeEncoding = 0; + unsigned CallSiteEncoding = 0; /// This section contains the static constructor pointer list. MCSection *StaticCtorSection = nullptr; /// This section contains the static destructor pointer list. MCSection *StaticDtorSection = nullptr; public: TargetLoweringObjectFile() = default; TargetLoweringObjectFile(const TargetLoweringObjectFile &) = delete; TargetLoweringObjectFile & operator=(const TargetLoweringObjectFile &) = delete; virtual ~TargetLoweringObjectFile(); MCContext &getContext() const { return *Ctx; } Mangler &getMangler() const { return *Mang; } /// This method must be called before any actual lowering is done. This /// specifies the current context for codegen, and gives the lowering /// implementations a chance to set up their default sections. virtual void Initialize(MCContext &ctx, const TargetMachine &TM); virtual void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym) const; /// Emit the module-level metadata that the platform cares about. virtual void emitModuleMetadata(MCStreamer &Streamer, Module &M) const {} /// Get the module-level metadata that the platform cares about. virtual void getModuleMetadata(Module &M) {} /// Given a constant with the SectionKind, return a section that it should be /// placed in. virtual MCSection *getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const; /// Classify the specified global variable into a set of target independent /// categories embodied in SectionKind. static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM); /// This method computes the appropriate section to emit the specified global /// variable or function definition. This should not be passed external (or /// available externally) globals. 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 definition. This should not be passed external (or /// available externally) globals. MCSection *SectionForGlobal(const GlobalObject *GO, const TargetMachine &TM) const { return SectionForGlobal(GO, getKindForGlobal(GO, TM), TM); } virtual void getNameWithPrefix(SmallVectorImpl &OutName, const GlobalValue *GV, const TargetMachine &TM) const; virtual MCSection *getSectionForJumpTable(const Function &F, const TargetMachine &TM) const; virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const; /// Targets should implement this method to assign a section to globals with /// an explicit section specfied. The implementation of this method can /// assume that GO->hasSection() is true. virtual MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const = 0; /// Return an MCExpr to use for a reference to the specified global variable /// from exception handling information. virtual const MCExpr *getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const; /// Return the MCSymbol for a private symbol with global value name as its /// base, with the specified suffix. MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const; // The symbol that gets passed to .cfi_personality. virtual MCSymbol *getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const; unsigned getPersonalityEncoding() const { return PersonalityEncoding; } unsigned getLSDAEncoding() const { return LSDAEncoding; } unsigned getTTypeEncoding() const { return TTypeEncoding; } + unsigned getCallSiteEncoding() const { return CallSiteEncoding; } const MCExpr *getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const; virtual MCSection *getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const { return StaticCtorSection; } virtual MCSection *getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const { return StaticDtorSection; } /// Create a symbol reference to describe the given TLS variable when /// emitting the address in debug info. virtual const MCExpr *getDebugThreadLocalSymbol(const MCSymbol *Sym) const; virtual const MCExpr *lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const { return nullptr; } /// Target supports replacing a data "PC"-relative access to a symbol /// through another symbol, by accessing the later via a GOT entry instead? bool supportIndirectSymViaGOTPCRel() const { return SupportIndirectSymViaGOTPCRel; } /// Target GOT "PC"-relative relocation supports encoding an additional /// binary expression with an offset? bool supportGOTPCRelWithOffset() const { return SupportGOTPCRelWithOffset; } /// Target supports TLS offset relocation in debug section? bool supportDebugThreadLocalLocation() const { return SupportDebugThreadLocalLocation; } /// Get the target specific PC relative GOT entry relocation virtual const MCExpr *getIndirectSymViaGOTPCRel(const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { return nullptr; } virtual void emitLinkerFlagsForGlobal(raw_ostream &OS, const GlobalValue *GV) const {} virtual void emitLinkerFlagsForUsed(raw_ostream &OS, const GlobalValue *GV) const {} /// If supported, return the section to use for the llvm.commandline /// metadata. Otherwise, return nullptr. virtual MCSection *getSectionForCommandLines() const { return nullptr; } protected: virtual MCSection *SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const = 0; }; } // end namespace llvm #endif // LLVM_CODEGEN_TARGETLOWERINGOBJECTFILE_H Index: llvm/trunk/include/llvm/CodeGen/AsmPrinter.h =================================================================== --- llvm/trunk/include/llvm/CodeGen/AsmPrinter.h (revision 366328) +++ llvm/trunk/include/llvm/CodeGen/AsmPrinter.h (revision 366329) @@ -1,681 +1,687 @@ //===- llvm/CodeGen/AsmPrinter.h - AsmPrinter Framework ---------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains a class to be used as the base class for target specific // asm writers. This class primarily handles common functionality used by // all asm writers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_ASMPRINTER_H #define LLVM_CODEGEN_ASMPRINTER_H #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/AsmPrinterHandler.h" #include "llvm/CodeGen/DwarfStringPoolEntry.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SourceMgr.h" #include #include #include #include namespace llvm { class BasicBlock; class BlockAddress; class Constant; class ConstantArray; class DataLayout; class DIE; class DIEAbbrev; class DwarfDebug; class GCMetadataPrinter; class GCStrategy; class GlobalIndirectSymbol; class GlobalObject; class GlobalValue; class GlobalVariable; class MachineBasicBlock; class MachineConstantPoolValue; class MachineDominatorTree; class MachineFunction; class MachineInstr; class MachineJumpTableInfo; class MachineLoopInfo; class MachineModuleInfo; class MachineOptimizationRemarkEmitter; class MCAsmInfo; class MCCFIInstruction; struct MCCodePaddingContext; class MCContext; class MCExpr; class MCInst; class MCSection; class MCStreamer; class MCSubtargetInfo; class MCSymbol; class MCTargetOptions; class MDNode; class Module; class raw_ostream; class StackMaps; class TargetLoweringObjectFile; class TargetMachine; /// This class is intended to be used as a driving class for all asm writers. class AsmPrinter : public MachineFunctionPass { public: /// Target machine description. TargetMachine &TM; /// Target Asm Printer information. const MCAsmInfo *MAI; /// This is the context for the output file that we are streaming. This owns /// all of the global MC-related objects for the generated translation unit. MCContext &OutContext; /// This is the MCStreamer object for the file we are generating. This /// contains the transient state for the current translation unit that we are /// generating (such as the current section etc). std::unique_ptr OutStreamer; /// The current machine function. MachineFunction *MF = nullptr; /// This is a pointer to the current MachineModuleInfo. MachineModuleInfo *MMI = nullptr; /// This is a pointer to the current MachineLoopInfo. MachineDominatorTree *MDT = nullptr; /// This is a pointer to the current MachineLoopInfo. MachineLoopInfo *MLI = nullptr; /// Optimization remark emitter. MachineOptimizationRemarkEmitter *ORE; /// The symbol for the current function. This is recalculated at the beginning /// of each call to runOnMachineFunction(). MCSymbol *CurrentFnSym = nullptr; /// The symbol used to represent the start of the current function for the /// purpose of calculating its size (e.g. using the .size directive). By /// default, this is equal to CurrentFnSym. MCSymbol *CurrentFnSymForSize = nullptr; /// Map global GOT equivalent MCSymbols to GlobalVariables and keep track of /// its number of uses by other globals. using GOTEquivUsePair = std::pair; MapVector GlobalGOTEquivs; private: MCSymbol *CurrentFnBegin = nullptr; MCSymbol *CurrentFnEnd = nullptr; MCSymbol *CurExceptionSym = nullptr; // The garbage collection metadata printer table. void *GCMetadataPrinters = nullptr; // Really a DenseMap. /// Emit comments in assembly output if this is true. bool VerboseAsm; static char ID; protected: /// Protected struct HandlerInfo and Handlers permit target extended /// AsmPrinter adds their own handlers. struct HandlerInfo { std::unique_ptr Handler; const char *TimerName; const char *TimerDescription; const char *TimerGroupName; const char *TimerGroupDescription; HandlerInfo(std::unique_ptr Handler, const char *TimerName, const char *TimerDescription, const char *TimerGroupName, const char *TimerGroupDescription) : Handler(std::move(Handler)), TimerName(TimerName), TimerDescription(TimerDescription), TimerGroupName(TimerGroupName), TimerGroupDescription(TimerGroupDescription) {} }; /// A vector of all debug/EH info emitters we should use. This vector /// maintains ownership of the emitters. SmallVector Handlers; public: struct SrcMgrDiagInfo { SourceMgr SrcMgr; std::vector LocInfos; LLVMContext::InlineAsmDiagHandlerTy DiagHandler; void *DiagContext; }; private: /// If generated on the fly this own the instance. std::unique_ptr OwnedMDT; /// If generated on the fly this own the instance. std::unique_ptr OwnedMLI; /// Structure for generating diagnostics for inline assembly. Only initialised /// when necessary. mutable std::unique_ptr DiagInfo; /// If the target supports dwarf debug info, this pointer is non-null. DwarfDebug *DD = nullptr; /// If the current module uses dwarf CFI annotations strictly for debugging. bool isCFIMoveForDebugging = false; protected: explicit AsmPrinter(TargetMachine &TM, std::unique_ptr Streamer); public: ~AsmPrinter() override; DwarfDebug *getDwarfDebug() { return DD; } DwarfDebug *getDwarfDebug() const { return DD; } uint16_t getDwarfVersion() const; void setDwarfVersion(uint16_t Version); bool isPositionIndependent() const; /// Return true if assembly output should contain comments. bool isVerbose() const { return VerboseAsm; } /// Return a unique ID for the current function. unsigned getFunctionNumber() const; /// Return symbol for the function pseudo stack if the stack frame is not a /// register based. virtual const MCSymbol *getFunctionFrameSymbol() const { return nullptr; } MCSymbol *getFunctionBegin() const { return CurrentFnBegin; } MCSymbol *getFunctionEnd() const { return CurrentFnEnd; } MCSymbol *getCurExceptionSym(); /// Return information about object file lowering. const TargetLoweringObjectFile &getObjFileLowering() const; /// Return information about data layout. const DataLayout &getDataLayout() const; /// Return the pointer size from the TargetMachine unsigned getPointerSize() const; /// Return information about subtarget. const MCSubtargetInfo &getSubtargetInfo() const; void EmitToStreamer(MCStreamer &S, const MCInst &Inst); /// Emits inital debug location directive. void emitInitialRawDwarfLocDirective(const MachineFunction &MF); /// Return the current section we are emitting to. const MCSection *getCurrentSection() const; void getNameWithPrefix(SmallVectorImpl &Name, const GlobalValue *GV) const; MCSymbol *getSymbol(const GlobalValue *GV) const; //===------------------------------------------------------------------===// // XRay instrumentation implementation. //===------------------------------------------------------------------===// public: // This describes the kind of sled we're storing in the XRay table. enum class SledKind : uint8_t { FUNCTION_ENTER = 0, FUNCTION_EXIT = 1, TAIL_CALL = 2, LOG_ARGS_ENTER = 3, CUSTOM_EVENT = 4, TYPED_EVENT = 5, }; // The table will contain these structs that point to the sled, the function // containing the sled, and what kind of sled (and whether they should always // be instrumented). We also use a version identifier that the runtime can use // to decide what to do with the sled, depending on the version of the sled. struct XRayFunctionEntry { const MCSymbol *Sled; const MCSymbol *Function; SledKind Kind; bool AlwaysInstrument; const class Function *Fn; uint8_t Version; void emit(int, MCStreamer *, const MCSymbol *) const; }; // All the sleds to be emitted. SmallVector Sleds; // A unique ID used for ELF sections associated with a particular function. unsigned XRayFnUniqueID = 0; // Helper function to record a given XRay sled. void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version = 0); /// Emit a table with all XRay instrumentation points. void emitXRayTable(); //===------------------------------------------------------------------===// // MachineFunctionPass Implementation. //===------------------------------------------------------------------===// /// Record analysis usage. void getAnalysisUsage(AnalysisUsage &AU) const override; /// Set up the AsmPrinter when we are working on a new module. If your pass /// overrides this, it must make sure to explicitly call this implementation. bool doInitialization(Module &M) override; /// Shut down the asmprinter. If you override this in your pass, you must make /// sure to call it explicitly. bool doFinalization(Module &M) override; /// Emit the specified function out to the OutStreamer. bool runOnMachineFunction(MachineFunction &MF) override { SetupMachineFunction(MF); EmitFunctionBody(); return false; } //===------------------------------------------------------------------===// // Coarse grained IR lowering routines. //===------------------------------------------------------------------===// /// This should be called when a new MachineFunction is being processed from /// runOnMachineFunction. void SetupMachineFunction(MachineFunction &MF); /// This method emits the body and trailer for a function. void EmitFunctionBody(); void emitCFIInstruction(const MachineInstr &MI); void emitFrameAlloc(const MachineInstr &MI); void emitStackSizeSection(const MachineFunction &MF); void emitRemarksSection(Module &M); enum CFIMoveType { CFI_M_None, CFI_M_EH, CFI_M_Debug }; CFIMoveType needsCFIMoves() const; /// Returns false if needsCFIMoves() == CFI_M_EH for any function /// in the module. bool needsOnlyDebugCFIMoves() const { return isCFIMoveForDebugging; } bool needsSEHMoves(); /// Print to the current output stream assembly representations of the /// constants in the constant pool MCP. This is used to print out constants /// which have been "spilled to memory" by the code generator. virtual void EmitConstantPool(); /// Print assembly representations of the jump tables used by the current /// function to the current output stream. virtual void EmitJumpTableInfo(); /// Emit the specified global variable to the .s file. virtual void EmitGlobalVariable(const GlobalVariable *GV); /// Check to see if the specified global is a special global used by LLVM. If /// so, emit it and return true, otherwise do nothing and return false. bool EmitSpecialLLVMGlobal(const GlobalVariable *GV); /// Emit an alignment directive to the specified power of two boundary. For /// example, if you pass in 3 here, you will get an 8 byte alignment. If a /// global value is specified, and if that global has an explicit alignment /// requested, it will override the alignment request if required for /// correctness. void EmitAlignment(unsigned NumBits, const GlobalObject *GV = nullptr) const; /// Lower the specified LLVM Constant to an MCExpr. virtual const MCExpr *lowerConstant(const Constant *CV); /// Print a general LLVM constant to the .s file. void EmitGlobalConstant(const DataLayout &DL, const Constant *CV); /// Unnamed constant global variables solely contaning a pointer to /// another globals variable act like a global variable "proxy", or GOT /// equivalents, i.e., it's only used to hold the address of the latter. One /// optimization is to replace accesses to these proxies by using the GOT /// entry for the final global instead. Hence, we select GOT equivalent /// candidates among all the module global variables, avoid emitting them /// unnecessarily and finally replace references to them by pc relative /// accesses to GOT entries. void computeGlobalGOTEquivs(Module &M); /// Constant expressions using GOT equivalent globals may not be /// eligible for PC relative GOT entry conversion, in such cases we need to /// emit the proxies we previously omitted in EmitGlobalVariable. void emitGlobalGOTEquivs(); /// Emit the stack maps. void emitStackMaps(StackMaps &SM); //===------------------------------------------------------------------===// // Overridable Hooks //===------------------------------------------------------------------===// // Targets can, or in the case of EmitInstruction, must implement these to // customize output. /// This virtual method can be overridden by targets that want to emit /// something at the start of their file. virtual void EmitStartOfAsmFile(Module &) {} /// This virtual method can be overridden by targets that want to emit /// something at the end of their file. virtual void EmitEndOfAsmFile(Module &) {} /// Targets can override this to emit stuff before the first basic block in /// the function. virtual void EmitFunctionBodyStart() {} /// Targets can override this to emit stuff after the last basic block in the /// function. virtual void EmitFunctionBodyEnd() {} /// Targets can override this to emit stuff at the start of a basic block. /// By default, this method prints the label for the specified /// MachineBasicBlock, an alignment (if present) and a comment describing it /// if appropriate. virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const; /// Targets can override this to emit stuff at the end of a basic block. virtual void EmitBasicBlockEnd(const MachineBasicBlock &MBB); /// Targets should implement this to emit instructions. virtual void EmitInstruction(const MachineInstr *) { llvm_unreachable("EmitInstruction not implemented"); } /// Return the symbol for the specified constant pool entry. virtual MCSymbol *GetCPISymbol(unsigned CPID) const; virtual void EmitFunctionEntryLabel(); virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV); /// Targets can override this to change how global constants that are part of /// a C++ static/global constructor list are emitted. virtual void EmitXXStructor(const DataLayout &DL, const Constant *CV) { EmitGlobalConstant(DL, CV); } /// Return true if the basic block has exactly one predecessor and the control /// transfer mechanism between the predecessor and this block is a /// fall-through. virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const; /// Targets can override this to customize the output of IMPLICIT_DEF /// instructions in verbose mode. virtual void emitImplicitDef(const MachineInstr *MI) const; //===------------------------------------------------------------------===// // Symbol Lowering Routines. //===------------------------------------------------------------------===// MCSymbol *createTempSymbol(const Twine &Name) const; /// Return the MCSymbol for a private symbol with global value name as its /// base, with the specified suffix. MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix) const; /// Return the MCSymbol for the specified ExternalSymbol. MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const; /// Return the symbol for the specified jump table entry. MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const; /// Return the symbol for the specified jump table .set /// FIXME: privatize to AsmPrinter. MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const; /// Return the MCSymbol used to satisfy BlockAddress uses of the specified /// basic block. MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const; MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const; //===------------------------------------------------------------------===// // Emission Helper Routines. //===------------------------------------------------------------------===// /// This is just convenient handler for printing offsets. void printOffset(int64_t Offset, raw_ostream &OS) const; /// Emit a byte directive and value. void emitInt8(int Value) const; /// Emit a short directive and value. void emitInt16(int Value) const; /// Emit a long directive and value. void emitInt32(int Value) const; /// Emit a long long directive and value. void emitInt64(uint64_t Value) const; /// Emit something like ".long Hi-Lo" where the size in bytes of the directive /// is specified by Size and Hi/Lo specify the labels. This implicitly uses /// .set if it is available. void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size) const; /// Emit something like ".uleb128 Hi-Lo". void EmitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const; /// Emit something like ".long Label+Offset" where the size in bytes of the /// directive is specified by Size and Label specifies the label. This /// implicitly uses .set if it is available. void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, unsigned Size, bool IsSectionRelative = false) const; /// Emit something like ".long Label" where the size in bytes of the directive /// is specified by Size and Label specifies the label. void EmitLabelReference(const MCSymbol *Label, unsigned Size, bool IsSectionRelative = false) const { EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative); } /// Emit something like ".long Label + Offset". void EmitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const; //===------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===------------------------------------------------------------------===// /// Emit the specified signed leb128 value. void EmitSLEB128(int64_t Value, const char *Desc = nullptr) const; /// Emit the specified unsigned leb128 value. void EmitULEB128(uint64_t Value, const char *Desc = nullptr, unsigned PadTo = 0) const; /// Emit a .byte 42 directive that corresponds to an encoding. If verbose /// assembly output is enabled, we output comments describing the encoding. /// Desc is a string saying what the encoding is specifying (e.g. "LSDA"). void EmitEncodingByte(unsigned Val, const char *Desc = nullptr) const; /// Return the size of the encoding in bytes. unsigned GetSizeOfEncodedValue(unsigned Encoding) const; /// Emit reference to a ttype global with a specified encoding. void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const; /// Emit a reference to a symbol for use in dwarf. Different object formats /// represent this in different ways. Some use a relocation others encode /// the label offset in its section. void emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset = false) const; /// Emit the 4-byte offset of a string from the start of its section. /// /// When possible, emit a DwarfStringPool section offset without any /// relocations, and without using the symbol. Otherwise, defers to \a /// emitDwarfSymbolReference(). void emitDwarfStringOffset(DwarfStringPoolEntry S) const; /// Emit the 4-byte offset of a string from the start of its section. void emitDwarfStringOffset(DwarfStringPoolEntryRef S) const { emitDwarfStringOffset(S.getEntry()); } + /// Emit reference to a call site with a specified encoding + void EmitCallSiteOffset(const MCSymbol *Hi, const MCSymbol *Lo, + unsigned Encoding) const; + /// Emit an integer value corresponding to the call site encoding + void EmitCallSiteValue(uint64_t Value, unsigned Encoding) const; + /// Get the value for DW_AT_APPLE_isa. Zero if no isa encoding specified. virtual unsigned getISAEncoding() { return 0; } /// Emit the directive and value for debug thread local expression /// /// \p Value - The value to emit. /// \p Size - The size of the integer (in bytes) to emit. virtual void EmitDebugValue(const MCExpr *Value, unsigned Size) const; //===------------------------------------------------------------------===// // Dwarf Lowering Routines //===------------------------------------------------------------------===// /// Emit frame instruction to describe the layout of the frame. void emitCFIInstruction(const MCCFIInstruction &Inst) const; /// Emit Dwarf abbreviation table. template void emitDwarfAbbrevs(const T &Abbrevs) const { // For each abbreviation. for (const auto &Abbrev : Abbrevs) emitDwarfAbbrev(*Abbrev); // Mark end of abbreviations. EmitULEB128(0, "EOM(3)"); } void emitDwarfAbbrev(const DIEAbbrev &Abbrev) const; /// Recursively emit Dwarf DIE tree. void emitDwarfDIE(const DIE &Die) const; //===------------------------------------------------------------------===// // Inline Asm Support //===------------------------------------------------------------------===// // These are hooks that targets can override to implement inline asm // support. These should probably be moved out of AsmPrinter someday. /// Print information related to the specified machine instr that is /// independent of the operand, and may be independent of the instr itself. /// This can be useful for portably encoding the comment character or other /// bits of target-specific knowledge into the asmstrings. The syntax used is /// ${:comment}. Targets can override this to add support for their own /// strange codes. virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const; /// Print the MachineOperand as a symbol. Targets with complex handling of /// symbol references should override the base implementation. virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS); /// Print the specified operand of MI, an INLINEASM instruction, using the /// specified assembler variant. Targets should override this to format as /// appropriate. This method can return true if the operand is erroneous. virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS); /// Print the specified operand of MI, an INLINEASM instruction, using the /// specified assembler variant as an address. Targets should override this to /// format as appropriate. This method can return true if the operand is /// erroneous. virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS); /// Let the target do anything it needs to do before emitting inlineasm. /// \p StartInfo - the subtarget info before parsing inline asm virtual void emitInlineAsmStart() const; /// Let the target do anything it needs to do after emitting inlineasm. /// This callback can be used restore the original mode in case the /// inlineasm contains directives to switch modes. /// \p StartInfo - the original subtarget info before inline asm /// \p EndInfo - the final subtarget info after parsing the inline asm, /// or NULL if the value is unknown. virtual void emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, const MCSubtargetInfo *EndInfo) const; /// This emits visibility information about symbol, if this is supported by /// the target. void EmitVisibility(MCSymbol *Sym, unsigned Visibility, bool IsDefinition = true) const; /// This emits linkage information about \p GVSym based on \p GV, if this is /// supported by the target. void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const; private: /// Private state for PrintSpecial() // Assign a unique ID to this machine instruction. mutable const MachineInstr *LastMI = nullptr; mutable unsigned LastFn = 0; mutable unsigned Counter = ~0U; /// This method emits the header for the current function. virtual void EmitFunctionHeader(); /// Emit a blob of inline asm to the output streamer. void EmitInlineAsm(StringRef Str, const MCSubtargetInfo &STI, const MCTargetOptions &MCOptions, const MDNode *LocMDNode = nullptr, InlineAsm::AsmDialect AsmDialect = InlineAsm::AD_ATT) const; /// This method formats and emits the specified machine instruction that is an /// inline asm. void EmitInlineAsm(const MachineInstr *MI) const; /// Add inline assembly info to the diagnostics machinery, so we can /// emit file and position info. Returns SrcMgr memory buffer position. unsigned addInlineAsmDiagBuffer(StringRef AsmStr, const MDNode *LocMDNode) const; //===------------------------------------------------------------------===// // Internal Implementation Details //===------------------------------------------------------------------===// void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, unsigned uid) const; void EmitLLVMUsedList(const ConstantArray *InitList); /// Emit llvm.ident metadata in an '.ident' directive. void EmitModuleIdents(Module &M); /// Emit bytes for llvm.commandline metadata. void EmitModuleCommandLines(Module &M); void EmitXXStructorList(const DataLayout &DL, const Constant *List, bool isCtor); GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy &S); /// Emit GlobalAlias or GlobalIFunc. void emitGlobalIndirectSymbol(Module &M, const GlobalIndirectSymbol &GIS); void setupCodePaddingContext(const MachineBasicBlock &MBB, MCCodePaddingContext &Context) const; }; } // end namespace llvm #endif // LLVM_CODEGEN_ASMPRINTER_H Index: llvm/trunk/lib/CodeGen/TargetLoweringObjectFileImpl.cpp =================================================================== --- llvm/trunk/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 366328) +++ llvm/trunk/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 366329) @@ -1,1819 +1,1821 @@ //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements classes used to handle lowerings specific to common // object file formats. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/BinaryFormat/COFF.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/BinaryFormat/MachO.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineModuleInfoImpls.h" #include "llvm/IR/Comdat.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalObject.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Mangler.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCSectionWasm.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCSymbolELF.h" #include "llvm/MC/MCValue.h" #include "llvm/MC/SectionKind.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/Format.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include #include using namespace llvm; using namespace dwarf; static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, StringRef &Section) { SmallVector ModuleFlags; M.getModuleFlagsMetadata(ModuleFlags); for (const auto &MFE: ModuleFlags) { // Ignore flags with 'Require' behaviour. if (MFE.Behavior == Module::Require) continue; StringRef Key = MFE.Key->getString(); if (Key == "Objective-C Image Info Version") { Version = mdconst::extract(MFE.Val)->getZExtValue(); } else if (Key == "Objective-C Garbage Collection" || Key == "Objective-C GC Only" || Key == "Objective-C Is Simulated" || Key == "Objective-C Class Properties" || Key == "Objective-C Image Swift Version") { Flags |= mdconst::extract(MFE.Val)->getZExtValue(); } else if (Key == "Objective-C Image Info Section") { Section = cast(MFE.Val)->getString(); } } } //===----------------------------------------------------------------------===// // ELF //===----------------------------------------------------------------------===// void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, const TargetMachine &TgtM) { TargetLoweringObjectFile::Initialize(Ctx, TgtM); TM = &TgtM; CodeModel::Model CM = TgtM.getCodeModel(); switch (TgtM.getTargetTriple().getArch()) { case Triple::arm: case Triple::armeb: case Triple::thumb: case Triple::thumbeb: if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) break; // Fallthrough if not using EHABI LLVM_FALLTHROUGH; case Triple::ppc: case Triple::x86: PersonalityEncoding = isPositionIndependent() ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_absptr; LSDAEncoding = isPositionIndependent() ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_absptr; TTypeEncoding = isPositionIndependent() ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_absptr; break; case Triple::x86_64: if (isPositionIndependent()) { PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | ((CM == CodeModel::Small || CM == CodeModel::Medium) ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); LSDAEncoding = dwarf::DW_EH_PE_pcrel | (CM == CodeModel::Small ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | ((CM == CodeModel::Small || CM == CodeModel::Medium) ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4); } else { PersonalityEncoding = (CM == CodeModel::Small || CM == CodeModel::Medium) ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; LSDAEncoding = (CM == CodeModel::Small) ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; TTypeEncoding = (CM == CodeModel::Small) ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; } break; case Triple::hexagon: PersonalityEncoding = dwarf::DW_EH_PE_absptr; LSDAEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; if (isPositionIndependent()) { PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; LSDAEncoding |= dwarf::DW_EH_PE_pcrel; TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; } break; case Triple::aarch64: case Triple::aarch64_be: // The small model guarantees static code/data size < 4GB, but not where it // will be in memory. Most of these could end up >2GB away so even a signed // pc-relative 32-bit address is insufficient, theoretically. if (isPositionIndependent()) { PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; } else { PersonalityEncoding = dwarf::DW_EH_PE_absptr; LSDAEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; } break; case Triple::lanai: LSDAEncoding = dwarf::DW_EH_PE_absptr; PersonalityEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; break; case Triple::mips: case Triple::mipsel: case Triple::mips64: case Triple::mips64el: // MIPS uses indirect pointer to refer personality functions and types, so // that the eh_frame section can be read-only. DW.ref.personality will be // generated for relocation. PersonalityEncoding = dwarf::DW_EH_PE_indirect; // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't // identify N64 from just a triple. TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; // We don't support PC-relative LSDA references in GAS so we use the default // DW_EH_PE_absptr for those. // FreeBSD must be explicit about the data size and using pcrel since it's // assembler/linker won't do the automatic conversion that the Linux tools // do. if (TgtM.getTargetTriple().isOSFreeBSD()) { PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; } break; case Triple::ppc64: case Triple::ppc64le: PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; break; case Triple::sparcel: case Triple::sparc: if (isPositionIndependent()) { LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; } else { LSDAEncoding = dwarf::DW_EH_PE_absptr; PersonalityEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; } + CallSiteEncoding = dwarf::DW_EH_PE_udata4; break; case Triple::riscv32: case Triple::riscv64: LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; + CallSiteEncoding = dwarf::DW_EH_PE_udata4; break; case Triple::sparcv9: LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; if (isPositionIndependent()) { PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; } else { PersonalityEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; } break; case Triple::systemz: // All currently-defined code models guarantee that 4-byte PC-relative // values will be in range. if (isPositionIndependent()) { PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; } else { PersonalityEncoding = dwarf::DW_EH_PE_absptr; LSDAEncoding = dwarf::DW_EH_PE_absptr; TTypeEncoding = dwarf::DW_EH_PE_absptr; } break; default: break; } } void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, Module &M) const { auto &C = getContext(); if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, ELF::SHF_EXCLUDE); Streamer.SwitchSection(S); for (const auto &Operand : LinkerOptions->operands()) { if (cast(Operand)->getNumOperands() != 2) report_fatal_error("invalid llvm.linker.options"); for (const auto &Option : cast(Operand)->operands()) { Streamer.EmitBytes(cast(Option)->getString()); Streamer.EmitIntValue(0, 1); } } } if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) { auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); Streamer.SwitchSection(S); for (const auto &Operand : DependentLibraries->operands()) { Streamer.EmitBytes( cast(cast(Operand)->getOperand(0))->getString()); Streamer.EmitIntValue(0, 1); } } unsigned Version = 0; unsigned Flags = 0; StringRef Section; GetObjCImageInfo(M, Version, Flags, Section); if (!Section.empty()) { auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); Streamer.SwitchSection(S); Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); Streamer.EmitIntValue(Version, 4); Streamer.EmitIntValue(Flags, 4); Streamer.AddBlankLine(); } SmallVector ModuleFlags; M.getModuleFlagsMetadata(ModuleFlags); MDNode *CFGProfile = nullptr; for (const auto &MFE : ModuleFlags) { StringRef Key = MFE.Key->getString(); if (Key == "CG Profile") { CFGProfile = cast(MFE.Val); break; } } if (!CFGProfile) return; auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { if (!MDO) return nullptr; auto V = cast(MDO); const Function *F = cast(V->getValue()); return TM->getSymbol(F); }; for (const auto &Edge : CFGProfile->operands()) { MDNode *E = cast(Edge); const MCSymbol *From = GetSym(E->getOperand(0)); const MCSymbol *To = GetSym(E->getOperand(1)); // Skip null functions. This can happen if functions are dead stripped after // the CGProfile pass has been run. if (!From || !To) continue; uint64_t Count = cast(E->getOperand(2)) ->getValue() ->getUniqueInteger() .getZExtValue(); Streamer.emitCGProfileEntry( MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); } } MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const { unsigned Encoding = getPersonalityEncoding(); if ((Encoding & 0x80) == DW_EH_PE_indirect) return getContext().getOrCreateSymbol(StringRef("DW.ref.") + TM.getSymbol(GV)->getName()); if ((Encoding & 0x70) == DW_EH_PE_absptr) return TM.getSymbol(GV); report_fatal_error("We do not support this DWARF encoding yet!"); } void TargetLoweringObjectFileELF::emitPersonalityValue( MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { SmallString<64> NameData("DW.ref."); NameData += Sym->getName(); MCSymbolELF *Label = cast(getContext().getOrCreateSymbol(NameData)); Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); Streamer.EmitSymbolAttribute(Label, MCSA_Weak); unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), ELF::SHT_PROGBITS, Flags, 0); unsigned Size = DL.getPointerSize(); Streamer.SwitchSection(Sec); Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0)); Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); const MCExpr *E = MCConstantExpr::create(Size, getContext()); Streamer.emitELFSize(Label, E); Streamer.EmitLabel(Label); Streamer.EmitSymbolValue(Sym, Size); } const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const { if (Encoding & DW_EH_PE_indirect) { MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo(); MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); // Add information about the stub reference to ELFMMI so that the stub // gets emitted by the asmprinter. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); if (!StubSym.getPointer()) { MCSymbol *Sym = TM.getSymbol(GV); StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); } return TargetLoweringObjectFile:: getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), Encoding & ~DW_EH_PE_indirect, Streamer); } return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, MMI, Streamer); } static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { // N.B.: The defaults used in here are not the same ones used in MC. // We follow gcc, MC follows gas. For example, given ".section .eh_frame", // both gas and MC will produce a section with no flags. Given // section(".eh_frame") gcc will produce: // // .section .eh_frame,"a",@progbits if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, /*AddSegmentInfo=*/false)) return SectionKind::getMetadata(); if (Name.empty() || Name[0] != '.') return K; // Default implementation based on some magic section names. if (Name == ".bss" || Name.startswith(".bss.") || Name.startswith(".gnu.linkonce.b.") || Name.startswith(".llvm.linkonce.b.") || Name == ".sbss" || Name.startswith(".sbss.") || Name.startswith(".gnu.linkonce.sb.") || Name.startswith(".llvm.linkonce.sb.")) return SectionKind::getBSS(); if (Name == ".tdata" || Name.startswith(".tdata.") || Name.startswith(".gnu.linkonce.td.") || Name.startswith(".llvm.linkonce.td.")) return SectionKind::getThreadData(); if (Name == ".tbss" || Name.startswith(".tbss.") || Name.startswith(".gnu.linkonce.tb.") || Name.startswith(".llvm.linkonce.tb.")) return SectionKind::getThreadBSS(); return K; } static unsigned getELFSectionType(StringRef Name, SectionKind K) { // Use SHT_NOTE for section whose name starts with ".note" to allow // emitting ELF notes from C variable declaration. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 if (Name.startswith(".note")) return ELF::SHT_NOTE; if (Name == ".init_array") return ELF::SHT_INIT_ARRAY; if (Name == ".fini_array") return ELF::SHT_FINI_ARRAY; if (Name == ".preinit_array") return ELF::SHT_PREINIT_ARRAY; if (K.isBSS() || K.isThreadBSS()) return ELF::SHT_NOBITS; return ELF::SHT_PROGBITS; } static unsigned getELFSectionFlags(SectionKind K) { unsigned Flags = 0; if (!K.isMetadata()) Flags |= ELF::SHF_ALLOC; if (K.isText()) Flags |= ELF::SHF_EXECINSTR; if (K.isExecuteOnly()) Flags |= ELF::SHF_ARM_PURECODE; if (K.isWriteable()) Flags |= ELF::SHF_WRITE; if (K.isThreadLocal()) Flags |= ELF::SHF_TLS; if (K.isMergeableCString() || K.isMergeableConst()) Flags |= ELF::SHF_MERGE; if (K.isMergeableCString()) Flags |= ELF::SHF_STRINGS; return Flags; } static const Comdat *getELFComdat(const GlobalValue *GV) { const Comdat *C = GV->getComdat(); if (!C) return nullptr; if (C->getSelectionKind() != Comdat::Any) report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + C->getName() + "' cannot be lowered."); return C; } static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO, const TargetMachine &TM) { MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); if (!MD) return nullptr; const MDOperand &Op = MD->getOperand(0); if (!Op.get()) return nullptr; auto *VM = dyn_cast(Op); if (!VM) report_fatal_error("MD_associated operand is not ValueAsMetadata"); GlobalObject *OtherGO = dyn_cast(VM->getValue()); return OtherGO ? dyn_cast(TM.getSymbol(OtherGO)) : nullptr; } static unsigned getEntrySizeForKind(SectionKind Kind) { if (Kind.isMergeable1ByteCString()) return 1; else if (Kind.isMergeable2ByteCString()) return 2; else if (Kind.isMergeable4ByteCString()) return 4; else if (Kind.isMergeableConst4()) return 4; else if (Kind.isMergeableConst8()) return 8; else if (Kind.isMergeableConst16()) return 16; else if (Kind.isMergeableConst32()) return 32; else { // We shouldn't have mergeable C strings or mergeable constants that we // didn't handle above. assert(!Kind.isMergeableCString() && "unknown string width"); assert(!Kind.isMergeableConst() && "unknown data width"); return 0; } } MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { StringRef SectionName = GO->getSection(); // Check if '#pragma clang section' name is applicable. // Note that pragma directive overrides -ffunction-section, -fdata-section // and so section name is exactly as user specified and not uniqued. const GlobalVariable *GV = dyn_cast(GO); if (GV && GV->hasImplicitSection()) { auto Attrs = GV->getAttributes(); if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { SectionName = Attrs.getAttribute("bss-section").getValueAsString(); } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { SectionName = Attrs.getAttribute("data-section").getValueAsString(); } } const Function *F = dyn_cast(GO); if (F && F->hasFnAttribute("implicit-section-name")) { SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); } // Infer section flags from the section name if we can. Kind = getELFKindForNamedSection(SectionName, Kind); StringRef Group = ""; unsigned Flags = getELFSectionFlags(Kind); if (const Comdat *C = getELFComdat(GO)) { Group = C->getName(); Flags |= ELF::SHF_GROUP; } // A section can have at most one associated section. Put each global with // MD_associated in a unique section. unsigned UniqueID = MCContext::GenericSectionID; const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); if (AssociatedSymbol) { UniqueID = NextUniqueID++; Flags |= ELF::SHF_LINK_ORDER; } MCSectionELF *Section = getContext().getELFSection( SectionName, getELFSectionType(SectionName, Kind), Flags, getEntrySizeForKind(Kind), Group, UniqueID, AssociatedSymbol); // Make sure that we did not get some other section with incompatible sh_link. // This should not be possible due to UniqueID code above. assert(Section->getAssociatedSymbol() == AssociatedSymbol && "Associated symbol mismatch between sections"); return Section; } /// Return the section prefix name used by options FunctionsSections and /// DataSections. static StringRef getSectionPrefixForGlobal(SectionKind Kind) { if (Kind.isText()) return ".text"; if (Kind.isReadOnly()) return ".rodata"; if (Kind.isBSS()) return ".bss"; if (Kind.isThreadData()) return ".tdata"; if (Kind.isThreadBSS()) return ".tbss"; if (Kind.isData()) return ".data"; assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); return ".data.rel.ro"; } static MCSectionELF *selectELFSectionForGlobal( MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { StringRef Group = ""; if (const Comdat *C = getELFComdat(GO)) { Flags |= ELF::SHF_GROUP; Group = C->getName(); } // Get the section entry size based on the kind. unsigned EntrySize = getEntrySizeForKind(Kind); SmallString<128> Name; if (Kind.isMergeableCString()) { // We also need alignment here. // FIXME: this is getting the alignment of the character, not the // alignment of the global! unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment( cast(GO)); std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; Name = SizeSpec + utostr(Align); } else if (Kind.isMergeableConst()) { Name = ".rodata.cst"; Name += utostr(EntrySize); } else { Name = getSectionPrefixForGlobal(Kind); } if (const auto *F = dyn_cast(GO)) { const auto &OptionalPrefix = F->getSectionPrefix(); if (OptionalPrefix) Name += *OptionalPrefix; } unsigned UniqueID = MCContext::GenericSectionID; if (EmitUniqueSection) { if (TM.getUniqueSectionNames()) { Name.push_back('.'); TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/); } else { UniqueID = *NextUniqueID; (*NextUniqueID)++; } } // Use 0 as the unique ID for execute-only text. if (Kind.isExecuteOnly()) UniqueID = 0; return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, EntrySize, Group, UniqueID, AssociatedSymbol); } MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { unsigned Flags = getELFSectionFlags(Kind); // If we have -ffunction-section or -fdata-section then we should emit the // global value to a uniqued section specifically for it. bool EmitUniqueSection = false; if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { if (Kind.isText()) EmitUniqueSection = TM.getFunctionSections(); else EmitUniqueSection = TM.getDataSections(); } EmitUniqueSection |= GO->hasComdat(); const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); if (AssociatedSymbol) { EmitUniqueSection = true; Flags |= ELF::SHF_LINK_ORDER; } MCSectionELF *Section = selectELFSectionForGlobal( getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, &NextUniqueID, AssociatedSymbol); assert(Section->getAssociatedSymbol() == AssociatedSymbol); return Section; } MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( const Function &F, const TargetMachine &TM) const { // If the function can be removed, produce a unique section so that // the table doesn't prevent the removal. const Comdat *C = F.getComdat(); bool EmitUniqueSection = TM.getFunctionSections() || C; if (!EmitUniqueSection) return ReadOnlySection; return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), getMangler(), TM, EmitUniqueSection, ELF::SHF_ALLOC, &NextUniqueID, /* AssociatedSymbol */ nullptr); } bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( bool UsesLabelDifference, const Function &F) const { // We can always create relative relocations, so use another section // that can be marked non-executable. return false; } /// Given a mergeable constant with the specified size and relocation /// information, return a section that it should be placed in. MCSection *TargetLoweringObjectFileELF::getSectionForConstant( const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const { if (Kind.isMergeableConst4() && MergeableConst4Section) return MergeableConst4Section; if (Kind.isMergeableConst8() && MergeableConst8Section) return MergeableConst8Section; if (Kind.isMergeableConst16() && MergeableConst16Section) return MergeableConst16Section; if (Kind.isMergeableConst32() && MergeableConst32Section) return MergeableConst32Section; if (Kind.isReadOnly()) return ReadOnlySection; assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); return DataRelROSection; } static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, bool IsCtor, unsigned Priority, const MCSymbol *KeySym) { std::string Name; unsigned Type; unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; StringRef COMDAT = KeySym ? KeySym->getName() : ""; if (KeySym) Flags |= ELF::SHF_GROUP; if (UseInitArray) { if (IsCtor) { Type = ELF::SHT_INIT_ARRAY; Name = ".init_array"; } else { Type = ELF::SHT_FINI_ARRAY; Name = ".fini_array"; } if (Priority != 65535) { Name += '.'; Name += utostr(Priority); } } else { // The default scheme is .ctor / .dtor, so we have to invert the priority // numbering. if (IsCtor) Name = ".ctors"; else Name = ".dtors"; if (Priority != 65535) raw_string_ostream(Name) << format(".%05u", 65535 - Priority); Type = ELF::SHT_PROGBITS; } return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); } MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( unsigned Priority, const MCSymbol *KeySym) const { return getStaticStructorSection(getContext(), UseInitArray, true, Priority, KeySym); } MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( unsigned Priority, const MCSymbol *KeySym) const { return getStaticStructorSection(getContext(), UseInitArray, false, Priority, KeySym); } const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const { // We may only use a PLT-relative relocation to refer to unnamed_addr // functions. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) return nullptr; // Basic sanity checks. if (LHS->getType()->getPointerAddressSpace() != 0 || RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || RHS->isThreadLocal()) return nullptr; return MCBinaryExpr::createSub( MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, getContext()), MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); } MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const { // Use ".GCC.command.line" since this feature is to support clang's // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the // same name. return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); } void TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { UseInitArray = UseInitArray_; MCContext &Ctx = getContext(); if (!UseInitArray) { StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, ELF::SHF_ALLOC | ELF::SHF_WRITE); StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, ELF::SHF_ALLOC | ELF::SHF_WRITE); return; } StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC); } //===----------------------------------------------------------------------===// // MachO //===----------------------------------------------------------------------===// TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() : TargetLoweringObjectFile() { SupportIndirectSymViaGOTPCRel = true; } void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, const TargetMachine &TM) { TargetLoweringObjectFile::Initialize(Ctx, TM); if (TM.getRelocationModel() == Reloc::Static) { StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, SectionKind::getData()); StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, SectionKind::getData()); } else { StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", MachO::S_MOD_INIT_FUNC_POINTERS, SectionKind::getData()); StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", MachO::S_MOD_TERM_FUNC_POINTERS, SectionKind::getData()); } PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; LSDAEncoding = dwarf::DW_EH_PE_pcrel; TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; } void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, Module &M) const { // Emit the linker options if present. if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { for (const auto &Option : LinkerOptions->operands()) { SmallVector StrOptions; for (const auto &Piece : cast(Option)->operands()) StrOptions.push_back(cast(Piece)->getString()); Streamer.EmitLinkerOptions(StrOptions); } } unsigned VersionVal = 0; unsigned ImageInfoFlags = 0; StringRef SectionVal; GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); // The section is mandatory. If we don't have it, then we don't have GC info. if (SectionVal.empty()) return; StringRef Segment, Section; unsigned TAA = 0, StubSize = 0; bool TAAParsed; std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, TAA, TAAParsed, StubSize); if (!ErrorCode.empty()) // If invalid, report the error with report_fatal_error. report_fatal_error("Invalid section specifier '" + Section + "': " + ErrorCode + "."); // Get the section. MCSectionMachO *S = getContext().getMachOSection( Segment, Section, TAA, StubSize, SectionKind::getData()); Streamer.SwitchSection(S); Streamer.EmitLabel(getContext(). getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); Streamer.EmitIntValue(VersionVal, 4); Streamer.EmitIntValue(ImageInfoFlags, 4); Streamer.AddBlankLine(); } static void checkMachOComdat(const GlobalValue *GV) { const Comdat *C = GV->getComdat(); if (!C) return; report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + "' cannot be lowered."); } MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { // Parse the section specifier and create it if valid. StringRef Segment, Section; unsigned TAA = 0, StubSize = 0; bool TAAParsed; checkMachOComdat(GO); std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, TAA, TAAParsed, StubSize); if (!ErrorCode.empty()) { // If invalid, report the error with report_fatal_error. report_fatal_error("Global variable '" + GO->getName() + "' has an invalid section specifier '" + GO->getSection() + "': " + ErrorCode + "."); } // Get the section. MCSectionMachO *S = getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); // If TAA wasn't set by ParseSectionSpecifier() above, // use the value returned by getMachOSection() as a default. if (!TAAParsed) TAA = S->getTypeAndAttributes(); // Okay, now that we got the section, verify that the TAA & StubSize agree. // If the user declared multiple globals with different section flags, we need // to reject it here. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { // If invalid, report the error with report_fatal_error. report_fatal_error("Global variable '" + GO->getName() + "' section type or attributes does not match previous" " section specifier"); } return S; } MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { checkMachOComdat(GO); // Handle thread local data. if (Kind.isThreadBSS()) return TLSBSSSection; if (Kind.isThreadData()) return TLSDataSection; if (Kind.isText()) return GO->isWeakForLinker() ? TextCoalSection : TextSection; // If this is weak/linkonce, put this in a coalescable section, either in text // or data depending on if it is writable. if (GO->isWeakForLinker()) { if (Kind.isReadOnly()) return ConstTextCoalSection; if (Kind.isReadOnlyWithRel()) return ConstDataCoalSection; return DataCoalSection; } // FIXME: Alignment check should be handled by section classifier. if (Kind.isMergeable1ByteCString() && GO->getParent()->getDataLayout().getPreferredAlignment( cast(GO)) < 32) return CStringSection; // Do not put 16-bit arrays in the UString section if they have an // externally visible label, this runs into issues with certain linker // versions. if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && GO->getParent()->getDataLayout().getPreferredAlignment( cast(GO)) < 32) return UStringSection; // With MachO only variables whose corresponding symbol starts with 'l' or // 'L' can be merged, so we only try merging GVs with private linkage. if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { if (Kind.isMergeableConst4()) return FourByteConstantSection; if (Kind.isMergeableConst8()) return EightByteConstantSection; if (Kind.isMergeableConst16()) return SixteenByteConstantSection; } // Otherwise, if it is readonly, but not something we can specially optimize, // just drop it in .const. if (Kind.isReadOnly()) return ReadOnlySection; // If this is marked const, put it into a const section. But if the dynamic // linker needs to write to it, put it in the data segment. if (Kind.isReadOnlyWithRel()) return ConstDataSection; // Put zero initialized globals with strong external linkage in the // DATA, __common section with the .zerofill directive. if (Kind.isBSSExtern()) return DataCommonSection; // Put zero initialized globals with local linkage in __DATA,__bss directive // with the .zerofill directive (aka .lcomm). if (Kind.isBSSLocal()) return DataBSSSection; // Otherwise, just drop the variable in the normal data section. return DataSection; } MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const { // If this constant requires a relocation, we have to put it in the data // segment, not in the text segment. if (Kind.isData() || Kind.isReadOnlyWithRel()) return ConstDataSection; if (Kind.isMergeableConst4()) return FourByteConstantSection; if (Kind.isMergeableConst8()) return EightByteConstantSection; if (Kind.isMergeableConst16()) return SixteenByteConstantSection; return ReadOnlySection; // .const } const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const { // The mach-o version of this method defaults to returning a stub reference. if (Encoding & DW_EH_PE_indirect) { MachineModuleInfoMachO &MachOMMI = MMI->getObjFileInfo(); MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); // Add information about the stub reference to MachOMMI so that the stub // gets emitted by the asmprinter. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); if (!StubSym.getPointer()) { MCSymbol *Sym = TM.getSymbol(GV); StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); } return TargetLoweringObjectFile:: getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), Encoding & ~DW_EH_PE_indirect, Streamer); } return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, MMI, Streamer); } MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const { // The mach-o version of this method defaults to returning a stub reference. MachineModuleInfoMachO &MachOMMI = MMI->getObjFileInfo(); MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); // Add information about the stub reference to MachOMMI so that the stub // gets emitted by the asmprinter. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); if (!StubSym.getPointer()) { MCSymbol *Sym = TM.getSymbol(GV); StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); } return SSym; } const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation // as 64-bit do, we replace the GOT equivalent by accessing the final symbol // through a non_lazy_ptr stub instead. One advantage is that it allows the // computation of deltas to final external symbols. Example: // // _extgotequiv: // .long _extfoo // // _delta: // .long _extgotequiv-_delta // // is transformed to: // // _delta: // .long L_extfoo$non_lazy_ptr-(_delta+0) // // .section __IMPORT,__pointers,non_lazy_symbol_pointers // L_extfoo$non_lazy_ptr: // .indirect_symbol _extfoo // .long 0 // // The indirect symbol table (and sections of non_lazy_symbol_pointers type) // may point to both local (same translation unit) and global (other // translation units) symbols. Example: // // .section __DATA,__pointers,non_lazy_symbol_pointers // L1: // .indirect_symbol _myGlobal // .long 0 // L2: // .indirect_symbol _myLocal // .long _myLocal // // If the symbol is local, instead of the symbol's index, the assembler // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table. // Then the linker will notice the constant in the table and will look at the // content of the symbol. MachineModuleInfoMachO &MachOMMI = MMI->getObjFileInfo(); MCContext &Ctx = getContext(); // The offset must consider the original displacement from the base symbol // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. Offset = -MV.getConstant(); const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); // Access the final symbol via sym$non_lazy_ptr and generate the appropriated // non_lazy_ptr stubs. SmallString<128> Name; StringRef Suffix = "$non_lazy_ptr"; Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); Name += Sym->getName(); Name += Suffix; MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); if (!StubSym.getPointer()) { bool IsIndirectLocal = Sym->isDefined() && !Sym->isExternal(); // With the assumption that IsIndirectLocal == GV->hasLocalLinkage(). StubSym = MachineModuleInfoImpl::StubValueTy(const_cast(Sym), !IsIndirectLocal); } const MCExpr *BSymExpr = MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); const MCExpr *LHS = MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); if (!Offset) return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); const MCExpr *RHS = MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); return MCBinaryExpr::createSub(LHS, RHS, Ctx); } static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section) { if (!AsmInfo.isSectionAtomizableBySymbols(Section)) return true; // If it is not dead stripped, it is safe to use private labels. const MCSectionMachO &SMO = cast(Section); if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) return true; return false; } void TargetLoweringObjectFileMachO::getNameWithPrefix( SmallVectorImpl &OutName, const GlobalValue *GV, const TargetMachine &TM) const { bool CannotUsePrivateLabel = true; if (auto *GO = GV->getBaseObject()) { SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); CannotUsePrivateLabel = !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); } getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); } //===----------------------------------------------------------------------===// // COFF //===----------------------------------------------------------------------===// static unsigned getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { unsigned Flags = 0; bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; if (K.isMetadata()) Flags |= COFF::IMAGE_SCN_MEM_DISCARDABLE; else if (K.isText()) Flags |= COFF::IMAGE_SCN_MEM_EXECUTE | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_CNT_CODE | (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); else if (K.isBSS()) Flags |= COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE; else if (K.isThreadLocal()) Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE; else if (K.isReadOnly() || K.isReadOnlyWithRel()) Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ; else if (K.isWriteable()) Flags |= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE; return Flags; } static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { const Comdat *C = GV->getComdat(); assert(C && "expected GV to have a Comdat!"); StringRef ComdatGVName = C->getName(); const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); if (!ComdatGV) report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + "' does not exist."); if (ComdatGV->getComdat() != C) report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + "' is not a key for its COMDAT."); return ComdatGV; } static int getSelectionForCOFF(const GlobalValue *GV) { if (const Comdat *C = GV->getComdat()) { const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); if (const auto *GA = dyn_cast(ComdatKey)) ComdatKey = GA->getBaseObject(); if (ComdatKey == GV) { switch (C->getSelectionKind()) { case Comdat::Any: return COFF::IMAGE_COMDAT_SELECT_ANY; case Comdat::ExactMatch: return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; case Comdat::Largest: return COFF::IMAGE_COMDAT_SELECT_LARGEST; case Comdat::NoDuplicates: return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; case Comdat::SameSize: return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; } } else { return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; } } return 0; } MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { int Selection = 0; unsigned Characteristics = getCOFFSectionFlags(Kind, TM); StringRef Name = GO->getSection(); StringRef COMDATSymName = ""; if (GO->hasComdat()) { Selection = getSelectionForCOFF(GO); const GlobalValue *ComdatGV; if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) ComdatGV = getComdatGVForCOFF(GO); else ComdatGV = GO; if (!ComdatGV->hasPrivateLinkage()) { MCSymbol *Sym = TM.getSymbol(ComdatGV); COMDATSymName = Sym->getName(); Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; } else { Selection = 0; } } return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, Selection); } static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { if (Kind.isText()) return ".text"; if (Kind.isBSS()) return ".bss"; if (Kind.isThreadLocal()) return ".tls$"; if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) return ".rdata"; return ".data"; } MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { // If we have -ffunction-sections then we should emit the global value to a // uniqued section specifically for it. bool EmitUniquedSection; if (Kind.isText()) EmitUniquedSection = TM.getFunctionSections(); else EmitUniquedSection = TM.getDataSections(); if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); unsigned Characteristics = getCOFFSectionFlags(Kind, TM); Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; int Selection = getSelectionForCOFF(GO); if (!Selection) Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; const GlobalValue *ComdatGV; if (GO->hasComdat()) ComdatGV = getComdatGVForCOFF(GO); else ComdatGV = GO; unsigned UniqueID = MCContext::GenericSectionID; if (EmitUniquedSection) UniqueID = NextUniqueID++; if (!ComdatGV->hasPrivateLinkage()) { MCSymbol *Sym = TM.getSymbol(ComdatGV); StringRef COMDATSymName = Sym->getName(); // Append "$symbol" to the section name *before* IR-level mangling is // applied when targetting mingw. This is what GCC does, and the ld.bfd // COFF linker will not properly handle comdats otherwise. if (getTargetTriple().isWindowsGNUEnvironment()) raw_svector_ostream(Name) << '$' << ComdatGV->getName(); return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, Selection, UniqueID); } else { SmallString<256> TmpData; getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, Selection, UniqueID); } } if (Kind.isText()) return TextSection; if (Kind.isThreadLocal()) return TLSDataSection; if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) return ReadOnlySection; // Note: we claim that common symbols are put in BSSSection, but they are // really emitted with the magic .comm directive, which creates a symbol table // entry but not a section. if (Kind.isBSS() || Kind.isCommon()) return BSSSection; return DataSection; } void TargetLoweringObjectFileCOFF::getNameWithPrefix( SmallVectorImpl &OutName, const GlobalValue *GV, const TargetMachine &TM) const { bool CannotUsePrivateLabel = false; if (GV->hasPrivateLinkage() && ((isa(GV) && TM.getFunctionSections()) || (isa(GV) && TM.getDataSections()))) CannotUsePrivateLabel = true; getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); } MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( const Function &F, const TargetMachine &TM) const { // If the function can be removed, produce a unique section so that // the table doesn't prevent the removal. const Comdat *C = F.getComdat(); bool EmitUniqueSection = TM.getFunctionSections() || C; if (!EmitUniqueSection) return ReadOnlySection; // FIXME: we should produce a symbol for F instead. if (F.hasPrivateLinkage()) return ReadOnlySection; MCSymbol *Sym = TM.getSymbol(&F); StringRef COMDATSymName = Sym->getName(); SectionKind Kind = SectionKind::getReadOnly(); StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); unsigned Characteristics = getCOFFSectionFlags(Kind, TM); Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; unsigned UniqueID = NextUniqueID++; return getContext().getCOFFSection( SecName, Characteristics, Kind, COMDATSymName, COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); } void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, Module &M) const { if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { // Emit the linker options to the linker .drectve section. According to the // spec, this section is a space-separated string containing flags for // linker. MCSection *Sec = getDrectveSection(); Streamer.SwitchSection(Sec); for (const auto &Option : LinkerOptions->operands()) { for (const auto &Piece : cast(Option)->operands()) { // Lead with a space for consistency with our dllexport implementation. std::string Directive(" "); Directive.append(cast(Piece)->getString()); Streamer.EmitBytes(Directive); } } } unsigned Version = 0; unsigned Flags = 0; StringRef Section; GetObjCImageInfo(M, Version, Flags, Section); if (Section.empty()) return; auto &C = getContext(); auto *S = C.getCOFFSection( Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, SectionKind::getReadOnly()); Streamer.SwitchSection(S); Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); Streamer.EmitIntValue(Version, 4); Streamer.EmitIntValue(Flags, 4); Streamer.AddBlankLine(); } void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, const TargetMachine &TM) { TargetLoweringObjectFile::Initialize(Ctx, TM); const Triple &T = TM.getTargetTriple(); if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { StaticCtorSection = Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, SectionKind::getReadOnly()); StaticDtorSection = Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, SectionKind::getReadOnly()); } else { StaticCtorSection = Ctx.getCOFFSection( ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, SectionKind::getData()); StaticDtorSection = Ctx.getCOFFSection( ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, SectionKind::getData()); } } static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, const Triple &T, bool IsCtor, unsigned Priority, const MCSymbol *KeySym, MCSectionCOFF *Default) { if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { // If the priority is the default, use .CRT$XCU, possibly associative. if (Priority == 65535) return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); // Otherwise, we need to compute a new section name. Low priorities should // run earlier. The linker will sort sections ASCII-betically, and we need a // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really // low priorities need to sort before 'L', since the CRT uses that // internally, so we use ".CRT$XCA00001" for them. SmallString<24> Name; raw_svector_ostream OS(Name); OS << ".CRT$XC" << (Priority < 200 ? 'A' : 'T') << format("%05u", Priority); MCSectionCOFF *Sec = Ctx.getCOFFSection( Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, SectionKind::getReadOnly()); return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0); } std::string Name = IsCtor ? ".ctors" : ".dtors"; if (Priority != 65535) raw_string_ostream(Name) << format(".%05u", 65535 - Priority); return Ctx.getAssociativeCOFFSection( Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, SectionKind::getData()), KeySym, 0); } MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( unsigned Priority, const MCSymbol *KeySym) const { return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true, Priority, KeySym, cast(StaticCtorSection)); } MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( unsigned Priority, const MCSymbol *KeySym) const { return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false, Priority, KeySym, cast(StaticDtorSection)); } void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal( raw_ostream &OS, const GlobalValue *GV) const { emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler()); } void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed( raw_ostream &OS, const GlobalValue *GV) const { emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler()); } const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const { const Triple &T = TM.getTargetTriple(); if (T.isOSCygMing()) return nullptr; // Our symbols should exist in address space zero, cowardly no-op if // otherwise. if (LHS->getType()->getPointerAddressSpace() != 0 || RHS->getType()->getPointerAddressSpace() != 0) return nullptr; // Both ptrtoint instructions must wrap global objects: // - Only global variables are eligible for image relative relocations. // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. // We expect __ImageBase to be a global variable without a section, externally // defined. // // It should look something like this: @__ImageBase = external constant i8 if (!isa(LHS) || !isa(RHS) || LHS->isThreadLocal() || RHS->isThreadLocal() || RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || cast(RHS)->hasInitializer() || RHS->hasSection()) return nullptr; return MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_COFF_IMGREL32, getContext()); } static std::string APIntToHexString(const APInt &AI) { unsigned Width = (AI.getBitWidth() / 8) * 2; std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true); unsigned Size = HexString.size(); assert(Width >= Size && "hex string is too large!"); HexString.insert(HexString.begin(), Width - Size, '0'); return HexString; } static std::string scalarConstantToHexString(const Constant *C) { Type *Ty = C->getType(); if (isa(C)) { return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits())); } else if (const auto *CFP = dyn_cast(C)) { return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); } else if (const auto *CI = dyn_cast(C)) { return APIntToHexString(CI->getValue()); } else { unsigned NumElements; if (isa(Ty)) NumElements = Ty->getVectorNumElements(); else NumElements = Ty->getArrayNumElements(); std::string HexString; for (int I = NumElements - 1, E = -1; I != E; --I) HexString += scalarConstantToHexString(C->getAggregateElement(I)); return HexString; } } MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const { if (Kind.isMergeableConst() && C && getContext().getAsmInfo()->hasCOFFComdatConstants()) { // This creates comdat sections with the given symbol name, but unless // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol // will be created with a null storage class, which makes GNU binutils // error out. const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_LNK_COMDAT; std::string COMDATSymName; if (Kind.isMergeableConst4()) { if (Align <= 4) { COMDATSymName = "__real@" + scalarConstantToHexString(C); Align = 4; } } else if (Kind.isMergeableConst8()) { if (Align <= 8) { COMDATSymName = "__real@" + scalarConstantToHexString(C); Align = 8; } } else if (Kind.isMergeableConst16()) { // FIXME: These may not be appropriate for non-x86 architectures. if (Align <= 16) { COMDATSymName = "__xmm@" + scalarConstantToHexString(C); Align = 16; } } else if (Kind.isMergeableConst32()) { if (Align <= 32) { COMDATSymName = "__ymm@" + scalarConstantToHexString(C); Align = 32; } } if (!COMDATSymName.empty()) return getContext().getCOFFSection(".rdata", Characteristics, Kind, COMDATSymName, COFF::IMAGE_COMDAT_SELECT_ANY); } return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align); } //===----------------------------------------------------------------------===// // Wasm //===----------------------------------------------------------------------===// static const Comdat *getWasmComdat(const GlobalValue *GV) { const Comdat *C = GV->getComdat(); if (!C) return nullptr; if (C->getSelectionKind() != Comdat::Any) report_fatal_error("WebAssembly COMDATs only support " "SelectionKind::Any, '" + C->getName() + "' cannot be " "lowered."); return C; } static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) { // If we're told we have function data, then use that. if (K.isText()) return SectionKind::getText(); // Otherwise, ignore whatever section type the generic impl detected and use // a plain data section. return SectionKind::getData(); } MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { // We don't support explict section names for functions in the wasm object // format. Each function has to be in its own unique section. if (isa(GO)) { return SelectSectionForGlobal(GO, Kind, TM); } StringRef Name = GO->getSection(); Kind = getWasmKindForNamedSection(Name, Kind); StringRef Group = ""; if (const Comdat *C = getWasmComdat(GO)) { Group = C->getName(); } MCSectionWasm* Section = getContext().getWasmSection(Name, Kind, Group, MCContext::GenericSectionID); return Section; } static MCSectionWasm *selectWasmSectionForGlobal( MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { StringRef Group = ""; if (const Comdat *C = getWasmComdat(GO)) { Group = C->getName(); } bool UniqueSectionNames = TM.getUniqueSectionNames(); SmallString<128> Name = getSectionPrefixForGlobal(Kind); if (const auto *F = dyn_cast(GO)) { const auto &OptionalPrefix = F->getSectionPrefix(); if (OptionalPrefix) Name += *OptionalPrefix; } if (EmitUniqueSection && UniqueSectionNames) { Name.push_back('.'); TM.getNameWithPrefix(Name, GO, Mang, true); } unsigned UniqueID = MCContext::GenericSectionID; if (EmitUniqueSection && !UniqueSectionNames) { UniqueID = *NextUniqueID; (*NextUniqueID)++; } return Ctx.getWasmSection(Name, Kind, Group, UniqueID); } MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { if (Kind.isCommon()) report_fatal_error("mergable sections not supported yet on wasm"); // If we have -ffunction-section or -fdata-section then we should emit the // global value to a uniqued section specifically for it. bool EmitUniqueSection = false; if (Kind.isText()) EmitUniqueSection = TM.getFunctionSections(); else EmitUniqueSection = TM.getDataSections(); EmitUniqueSection |= GO->hasComdat(); return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, &NextUniqueID); } bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( bool UsesLabelDifference, const Function &F) const { // We can always create relative relocations, so use another section // that can be marked non-executable. return false; } const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const { // We may only use a PLT-relative relocation to refer to unnamed_addr // functions. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) return nullptr; // Basic sanity checks. if (LHS->getType()->getPointerAddressSpace() != 0 || RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || RHS->isThreadLocal()) return nullptr; return MCBinaryExpr::createSub( MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, getContext()), MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); } void TargetLoweringObjectFileWasm::InitializeWasm() { StaticCtorSection = getContext().getWasmSection(".init_array", SectionKind::getData()); // We don't use PersonalityEncoding and LSDAEncoding because we don't emit // .cfi directives. We use TTypeEncoding to encode typeinfo global variables. TTypeEncoding = dwarf::DW_EH_PE_absptr; } MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( unsigned Priority, const MCSymbol *KeySym) const { return Priority == UINT16_MAX ? StaticCtorSection : getContext().getWasmSection(".init_array." + utostr(Priority), SectionKind::getData()); } MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( unsigned Priority, const MCSymbol *KeySym) const { llvm_unreachable("@llvm.global_dtors should have been lowered already"); return nullptr; } Index: llvm/trunk/lib/CodeGen/AsmPrinter/EHStreamer.cpp =================================================================== --- llvm/trunk/lib/CodeGen/AsmPrinter/EHStreamer.cpp (revision 366328) +++ llvm/trunk/lib/CodeGen/AsmPrinter/EHStreamer.cpp (revision 366329) @@ -1,653 +1,654 @@ //===- CodeGen/AsmPrinter/EHStreamer.cpp - Exception Directive Streamer ---===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains support for writing exception info into assembly files. // //===----------------------------------------------------------------------===// #include "EHStreamer.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Twine.h" #include "llvm/ADT/iterator_range.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Support/Casting.h" #include "llvm/Support/LEB128.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include #include #include #include using namespace llvm; EHStreamer::EHStreamer(AsmPrinter *A) : Asm(A), MMI(Asm->MMI) {} EHStreamer::~EHStreamer() = default; /// How many leading type ids two landing pads have in common. unsigned EHStreamer::sharedTypeIDs(const LandingPadInfo *L, const LandingPadInfo *R) { const std::vector &LIds = L->TypeIds, &RIds = R->TypeIds; unsigned LSize = LIds.size(), RSize = RIds.size(); unsigned MinSize = LSize < RSize ? LSize : RSize; unsigned Count = 0; for (; Count != MinSize; ++Count) if (LIds[Count] != RIds[Count]) return Count; return Count; } /// Compute the actions table and gather the first action index for each landing /// pad site. void EHStreamer::computeActionsTable( const SmallVectorImpl &LandingPads, SmallVectorImpl &Actions, SmallVectorImpl &FirstActions) { // The action table follows the call-site table in the LSDA. The individual // records are of two types: // // * Catch clause // * Exception specification // // The two record kinds have the same format, with only small differences. // They are distinguished by the "switch value" field: Catch clauses // (TypeInfos) have strictly positive switch values, and exception // specifications (FilterIds) have strictly negative switch values. Value 0 // indicates a catch-all clause. // // Negative type IDs index into FilterIds. Positive type IDs index into // TypeInfos. The value written for a positive type ID is just the type ID // itself. For a negative type ID, however, the value written is the // (negative) byte offset of the corresponding FilterIds entry. The byte // offset is usually equal to the type ID (because the FilterIds entries are // written using a variable width encoding, which outputs one byte per entry // as long as the value written is not too large) but can differ. This kind // of complication does not occur for positive type IDs because type infos are // output using a fixed width encoding. FilterOffsets[i] holds the byte // offset corresponding to FilterIds[i]. const std::vector &FilterIds = Asm->MF->getFilterIds(); SmallVector FilterOffsets; FilterOffsets.reserve(FilterIds.size()); int Offset = -1; for (std::vector::const_iterator I = FilterIds.begin(), E = FilterIds.end(); I != E; ++I) { FilterOffsets.push_back(Offset); Offset -= getULEB128Size(*I); } FirstActions.reserve(LandingPads.size()); int FirstAction = 0; unsigned SizeActions = 0; // Total size of all action entries for a function const LandingPadInfo *PrevLPI = nullptr; for (SmallVectorImpl::const_iterator I = LandingPads.begin(), E = LandingPads.end(); I != E; ++I) { const LandingPadInfo *LPI = *I; const std::vector &TypeIds = LPI->TypeIds; unsigned NumShared = PrevLPI ? sharedTypeIDs(LPI, PrevLPI) : 0; unsigned SizeSiteActions = 0; // Total size of all entries for a landingpad if (NumShared < TypeIds.size()) { // Size of one action entry (typeid + next action) unsigned SizeActionEntry = 0; unsigned PrevAction = (unsigned)-1; if (NumShared) { unsigned SizePrevIds = PrevLPI->TypeIds.size(); assert(Actions.size()); PrevAction = Actions.size() - 1; SizeActionEntry = getSLEB128Size(Actions[PrevAction].NextAction) + getSLEB128Size(Actions[PrevAction].ValueForTypeID); for (unsigned j = NumShared; j != SizePrevIds; ++j) { assert(PrevAction != (unsigned)-1 && "PrevAction is invalid!"); SizeActionEntry -= getSLEB128Size(Actions[PrevAction].ValueForTypeID); SizeActionEntry += -Actions[PrevAction].NextAction; PrevAction = Actions[PrevAction].Previous; } } // Compute the actions. for (unsigned J = NumShared, M = TypeIds.size(); J != M; ++J) { int TypeID = TypeIds[J]; assert(-1 - TypeID < (int)FilterOffsets.size() && "Unknown filter id!"); int ValueForTypeID = isFilterEHSelector(TypeID) ? FilterOffsets[-1 - TypeID] : TypeID; unsigned SizeTypeID = getSLEB128Size(ValueForTypeID); int NextAction = SizeActionEntry ? -(SizeActionEntry + SizeTypeID) : 0; SizeActionEntry = SizeTypeID + getSLEB128Size(NextAction); SizeSiteActions += SizeActionEntry; ActionEntry Action = { ValueForTypeID, NextAction, PrevAction }; Actions.push_back(Action); PrevAction = Actions.size() - 1; } // Record the first action of the landing pad site. FirstAction = SizeActions + SizeSiteActions - SizeActionEntry + 1; } // else identical - re-use previous FirstAction // Information used when creating the call-site table. The action record // field of the call site record is the offset of the first associated // action record, relative to the start of the actions table. This value is // biased by 1 (1 indicating the start of the actions table), and 0 // indicates that there are no actions. FirstActions.push_back(FirstAction); // Compute this sites contribution to size. SizeActions += SizeSiteActions; PrevLPI = LPI; } } /// Return `true' if this is a call to a function marked `nounwind'. Return /// `false' otherwise. bool EHStreamer::callToNoUnwindFunction(const MachineInstr *MI) { assert(MI->isCall() && "This should be a call instruction!"); bool MarkedNoUnwind = false; bool SawFunc = false; for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { const MachineOperand &MO = MI->getOperand(I); if (!MO.isGlobal()) continue; const Function *F = dyn_cast(MO.getGlobal()); if (!F) continue; if (SawFunc) { // Be conservative. If we have more than one function operand for this // call, then we can't make the assumption that it's the callee and // not a parameter to the call. // // FIXME: Determine if there's a way to say that `F' is the callee or // parameter. MarkedNoUnwind = false; break; } MarkedNoUnwind = F->doesNotThrow(); SawFunc = true; } return MarkedNoUnwind; } void EHStreamer::computePadMap( const SmallVectorImpl &LandingPads, RangeMapType &PadMap) { // Invokes and nounwind calls have entries in PadMap (due to being bracketed // by try-range labels when lowered). Ordinary calls do not, so appropriate // try-ranges for them need be deduced so we can put them in the LSDA. for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) { const LandingPadInfo *LandingPad = LandingPads[i]; for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) { MCSymbol *BeginLabel = LandingPad->BeginLabels[j]; assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!"); PadRange P = { i, j }; PadMap[BeginLabel] = P; } } } /// Compute the call-site table. The entry for an invoke has a try-range /// containing the call, a non-zero landing pad, and an appropriate action. The /// entry for an ordinary call has a try-range containing the call and zero for /// the landing pad and the action. Calls marked 'nounwind' have no entry and /// must not be contained in the try-range of any entry - they form gaps in the /// table. Entries must be ordered by try-range address. void EHStreamer:: computeCallSiteTable(SmallVectorImpl &CallSites, const SmallVectorImpl &LandingPads, const SmallVectorImpl &FirstActions) { RangeMapType PadMap; computePadMap(LandingPads, PadMap); // The end label of the previous invoke or nounwind try-range. MCSymbol *LastLabel = nullptr; // Whether there is a potentially throwing instruction (currently this means // an ordinary call) between the end of the previous try-range and now. bool SawPotentiallyThrowing = false; // Whether the last CallSite entry was for an invoke. bool PreviousIsInvoke = false; bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj; // Visit all instructions in order of address. for (const auto &MBB : *Asm->MF) { for (const auto &MI : MBB) { if (!MI.isEHLabel()) { if (MI.isCall()) SawPotentiallyThrowing |= !callToNoUnwindFunction(&MI); continue; } // End of the previous try-range? MCSymbol *BeginLabel = MI.getOperand(0).getMCSymbol(); if (BeginLabel == LastLabel) SawPotentiallyThrowing = false; // Beginning of a new try-range? RangeMapType::const_iterator L = PadMap.find(BeginLabel); if (L == PadMap.end()) // Nope, it was just some random label. continue; const PadRange &P = L->second; const LandingPadInfo *LandingPad = LandingPads[P.PadIndex]; assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] && "Inconsistent landing pad map!"); // For Dwarf exception handling (SjLj handling doesn't use this). If some // instruction between the previous try-range and this one may throw, // create a call-site entry with no landing pad for the region between the // try-ranges. if (SawPotentiallyThrowing && Asm->MAI->usesCFIForEH()) { CallSiteEntry Site = { LastLabel, BeginLabel, nullptr, 0 }; CallSites.push_back(Site); PreviousIsInvoke = false; } LastLabel = LandingPad->EndLabels[P.RangeIndex]; assert(BeginLabel && LastLabel && "Invalid landing pad!"); if (!LandingPad->LandingPadLabel) { // Create a gap. PreviousIsInvoke = false; } else { // This try-range is for an invoke. CallSiteEntry Site = { BeginLabel, LastLabel, LandingPad, FirstActions[P.PadIndex] }; // Try to merge with the previous call-site. SJLJ doesn't do this if (PreviousIsInvoke && !IsSJLJ) { CallSiteEntry &Prev = CallSites.back(); if (Site.LPad == Prev.LPad && Site.Action == Prev.Action) { // Extend the range of the previous entry. Prev.EndLabel = Site.EndLabel; continue; } } // Otherwise, create a new call-site. if (!IsSJLJ) CallSites.push_back(Site); else { // SjLj EH must maintain the call sites in the order assigned // to them by the SjLjPrepare pass. unsigned SiteNo = Asm->MF->getCallSiteBeginLabel(BeginLabel); if (CallSites.size() < SiteNo) CallSites.resize(SiteNo); CallSites[SiteNo - 1] = Site; } PreviousIsInvoke = true; } } } // If some instruction between the previous try-range and the end of the // function may throw, create a call-site entry with no landing pad for the // region following the try-range. if (SawPotentiallyThrowing && !IsSJLJ) { CallSiteEntry Site = { LastLabel, nullptr, nullptr, 0 }; CallSites.push_back(Site); } } /// Emit landing pads and actions. /// /// The general organization of the table is complex, but the basic concepts are /// easy. First there is a header which describes the location and organization /// of the three components that follow. /// /// 1. The landing pad site information describes the range of code covered by /// the try. In our case it's an accumulation of the ranges covered by the /// invokes in the try. There is also a reference to the landing pad that /// handles the exception once processed. Finally an index into the actions /// table. /// 2. The action table, in our case, is composed of pairs of type IDs and next /// action offset. Starting with the action index from the landing pad /// site, each type ID is checked for a match to the current exception. If /// it matches then the exception and type id are passed on to the landing /// pad. Otherwise the next action is looked up. This chain is terminated /// with a next action of zero. If no type id is found then the frame is /// unwound and handling continues. /// 3. Type ID table contains references to all the C++ typeinfo for all /// catches in the function. This tables is reverse indexed base 1. /// /// Returns the starting symbol of an exception table. MCSymbol *EHStreamer::emitExceptionTable() { const MachineFunction *MF = Asm->MF; const std::vector &TypeInfos = MF->getTypeInfos(); const std::vector &FilterIds = MF->getFilterIds(); const std::vector &PadInfos = MF->getLandingPads(); // Sort the landing pads in order of their type ids. This is used to fold // duplicate actions. SmallVector LandingPads; LandingPads.reserve(PadInfos.size()); for (unsigned i = 0, N = PadInfos.size(); i != N; ++i) LandingPads.push_back(&PadInfos[i]); // Order landing pads lexicographically by type id. llvm::sort(LandingPads, [](const LandingPadInfo *L, const LandingPadInfo *R) { return L->TypeIds < R->TypeIds; }); // Compute the actions table and gather the first action index for each // landing pad site. SmallVector Actions; SmallVector FirstActions; computeActionsTable(LandingPads, Actions, FirstActions); // Compute the call-site table. SmallVector CallSites; computeCallSiteTable(CallSites, LandingPads, FirstActions); bool IsSJLJ = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::SjLj; bool IsWasm = Asm->MAI->getExceptionHandlingType() == ExceptionHandling::Wasm; unsigned CallSiteEncoding = - IsSJLJ ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_uleb128; + IsSJLJ ? static_cast(dwarf::DW_EH_PE_udata4) : + Asm->getObjFileLowering().getCallSiteEncoding(); bool HaveTTData = !TypeInfos.empty() || !FilterIds.empty(); // Type infos. MCSection *LSDASection = Asm->getObjFileLowering().getLSDASection(); unsigned TTypeEncoding; if (!HaveTTData) { // If there is no TypeInfo, then we just explicitly say that we're omitting // that bit. TTypeEncoding = dwarf::DW_EH_PE_omit; } else { // Okay, we have actual filters or typeinfos to emit. As such, we need to // pick a type encoding for them. We're about to emit a list of pointers to // typeinfo objects at the end of the LSDA. However, unless we're in static // mode, this reference will require a relocation by the dynamic linker. // // Because of this, we have a couple of options: // // 1) If we are in -static mode, we can always use an absolute reference // from the LSDA, because the static linker will resolve it. // // 2) Otherwise, if the LSDA section is writable, we can output the direct // reference to the typeinfo and allow the dynamic linker to relocate // it. Since it is in a writable section, the dynamic linker won't // have a problem. // // 3) Finally, if we're in PIC mode and the LDSA section isn't writable, // we need to use some form of indirection. For example, on Darwin, // we can output a statically-relocatable reference to a dyld stub. The // offset to the stub is constant, but the contents are in a section // that is updated by the dynamic linker. This is easy enough, but we // need to tell the personality function of the unwinder to indirect // through the dyld stub. // // FIXME: When (3) is actually implemented, we'll have to emit the stubs // somewhere. This predicate should be moved to a shared location that is // in target-independent code. // TTypeEncoding = Asm->getObjFileLowering().getTTypeEncoding(); } // Begin the exception table. // Sometimes we want not to emit the data into separate section (e.g. ARM // EHABI). In this case LSDASection will be NULL. if (LSDASection) Asm->OutStreamer->SwitchSection(LSDASection); Asm->EmitAlignment(2); // Emit the LSDA. MCSymbol *GCCETSym = Asm->OutContext.getOrCreateSymbol(Twine("GCC_except_table")+ Twine(Asm->getFunctionNumber())); Asm->OutStreamer->EmitLabel(GCCETSym); Asm->OutStreamer->EmitLabel(Asm->getCurExceptionSym()); // Emit the LSDA header. Asm->EmitEncodingByte(dwarf::DW_EH_PE_omit, "@LPStart"); Asm->EmitEncodingByte(TTypeEncoding, "@TType"); MCSymbol *TTBaseLabel = nullptr; if (HaveTTData) { // N.B.: There is a dependency loop between the size of the TTBase uleb128 // here and the amount of padding before the aligned type table. The // assembler must sometimes pad this uleb128 or insert extra padding before // the type table. See PR35809 or GNU as bug 4029. MCSymbol *TTBaseRefLabel = Asm->createTempSymbol("ttbaseref"); TTBaseLabel = Asm->createTempSymbol("ttbase"); Asm->EmitLabelDifferenceAsULEB128(TTBaseLabel, TTBaseRefLabel); Asm->OutStreamer->EmitLabel(TTBaseRefLabel); } bool VerboseAsm = Asm->OutStreamer->isVerboseAsm(); // Emit the landing pad call site table. MCSymbol *CstBeginLabel = Asm->createTempSymbol("cst_begin"); MCSymbol *CstEndLabel = Asm->createTempSymbol("cst_end"); Asm->EmitEncodingByte(CallSiteEncoding, "Call site"); Asm->EmitLabelDifferenceAsULEB128(CstEndLabel, CstBeginLabel); Asm->OutStreamer->EmitLabel(CstBeginLabel); // SjLj / Wasm Exception handling if (IsSJLJ || IsWasm) { unsigned idx = 0; for (SmallVectorImpl::const_iterator I = CallSites.begin(), E = CallSites.end(); I != E; ++I, ++idx) { const CallSiteEntry &S = *I; // Index of the call site entry. if (VerboseAsm) { Asm->OutStreamer->AddComment(">> Call Site " + Twine(idx) + " <<"); Asm->OutStreamer->AddComment(" On exception at call site "+Twine(idx)); } Asm->EmitULEB128(idx); // Offset of the first associated action record, relative to the start of // the action table. This value is biased by 1 (1 indicates the start of // the action table), and 0 indicates that there are no actions. if (VerboseAsm) { if (S.Action == 0) Asm->OutStreamer->AddComment(" Action: cleanup"); else Asm->OutStreamer->AddComment(" Action: " + Twine((S.Action - 1) / 2 + 1)); } Asm->EmitULEB128(S.Action); } } else { // Itanium LSDA exception handling // The call-site table is a list of all call sites that may throw an // exception (including C++ 'throw' statements) in the procedure // fragment. It immediately follows the LSDA header. Each entry indicates, // for a given call, the first corresponding action record and corresponding // landing pad. // // The table begins with the number of bytes, stored as an LEB128 // compressed, unsigned integer. The records immediately follow the record // count. They are sorted in increasing call-site address. Each record // indicates: // // * The position of the call-site. // * The position of the landing pad. // * The first action record for that call site. // // A missing entry in the call-site table indicates that a call is not // supposed to throw. unsigned Entry = 0; for (SmallVectorImpl::const_iterator I = CallSites.begin(), E = CallSites.end(); I != E; ++I) { const CallSiteEntry &S = *I; MCSymbol *EHFuncBeginSym = Asm->getFunctionBegin(); MCSymbol *BeginLabel = S.BeginLabel; if (!BeginLabel) BeginLabel = EHFuncBeginSym; MCSymbol *EndLabel = S.EndLabel; if (!EndLabel) EndLabel = Asm->getFunctionEnd(); // Offset of the call site relative to the start of the procedure. if (VerboseAsm) Asm->OutStreamer->AddComment(">> Call Site " + Twine(++Entry) + " <<"); - Asm->EmitLabelDifferenceAsULEB128(BeginLabel, EHFuncBeginSym); + Asm->EmitCallSiteOffset(BeginLabel, EHFuncBeginSym, CallSiteEncoding); if (VerboseAsm) Asm->OutStreamer->AddComment(Twine(" Call between ") + BeginLabel->getName() + " and " + EndLabel->getName()); - Asm->EmitLabelDifferenceAsULEB128(EndLabel, BeginLabel); + Asm->EmitCallSiteOffset(EndLabel, BeginLabel, CallSiteEncoding); // Offset of the landing pad relative to the start of the procedure. if (!S.LPad) { if (VerboseAsm) Asm->OutStreamer->AddComment(" has no landing pad"); - Asm->EmitULEB128(0); + Asm->EmitCallSiteValue(0, CallSiteEncoding); } else { if (VerboseAsm) Asm->OutStreamer->AddComment(Twine(" jumps to ") + S.LPad->LandingPadLabel->getName()); - Asm->EmitLabelDifferenceAsULEB128(S.LPad->LandingPadLabel, - EHFuncBeginSym); + Asm->EmitCallSiteOffset(S.LPad->LandingPadLabel, EHFuncBeginSym, + CallSiteEncoding); } // Offset of the first associated action record, relative to the start of // the action table. This value is biased by 1 (1 indicates the start of // the action table), and 0 indicates that there are no actions. if (VerboseAsm) { if (S.Action == 0) Asm->OutStreamer->AddComment(" On action: cleanup"); else Asm->OutStreamer->AddComment(" On action: " + Twine((S.Action - 1) / 2 + 1)); } Asm->EmitULEB128(S.Action); } } Asm->OutStreamer->EmitLabel(CstEndLabel); // Emit the Action Table. int Entry = 0; for (SmallVectorImpl::const_iterator I = Actions.begin(), E = Actions.end(); I != E; ++I) { const ActionEntry &Action = *I; if (VerboseAsm) { // Emit comments that decode the action table. Asm->OutStreamer->AddComment(">> Action Record " + Twine(++Entry) + " <<"); } // Type Filter // // Used by the runtime to match the type of the thrown exception to the // type of the catch clauses or the types in the exception specification. if (VerboseAsm) { if (Action.ValueForTypeID > 0) Asm->OutStreamer->AddComment(" Catch TypeInfo " + Twine(Action.ValueForTypeID)); else if (Action.ValueForTypeID < 0) Asm->OutStreamer->AddComment(" Filter TypeInfo " + Twine(Action.ValueForTypeID)); else Asm->OutStreamer->AddComment(" Cleanup"); } Asm->EmitSLEB128(Action.ValueForTypeID); // Action Record // // Self-relative signed displacement in bytes of the next action record, // or 0 if there is no next action record. if (VerboseAsm) { if (Action.NextAction == 0) { Asm->OutStreamer->AddComment(" No further actions"); } else { unsigned NextAction = Entry + (Action.NextAction + 1) / 2; Asm->OutStreamer->AddComment(" Continue to action "+Twine(NextAction)); } } Asm->EmitSLEB128(Action.NextAction); } if (HaveTTData) { Asm->EmitAlignment(2); emitTypeInfos(TTypeEncoding, TTBaseLabel); } Asm->EmitAlignment(2); return GCCETSym; } void EHStreamer::emitTypeInfos(unsigned TTypeEncoding, MCSymbol *TTBaseLabel) { const MachineFunction *MF = Asm->MF; const std::vector &TypeInfos = MF->getTypeInfos(); const std::vector &FilterIds = MF->getFilterIds(); bool VerboseAsm = Asm->OutStreamer->isVerboseAsm(); int Entry = 0; // Emit the Catch TypeInfos. if (VerboseAsm && !TypeInfos.empty()) { Asm->OutStreamer->AddComment(">> Catch TypeInfos <<"); Asm->OutStreamer->AddBlankLine(); Entry = TypeInfos.size(); } for (const GlobalValue *GV : make_range(TypeInfos.rbegin(), TypeInfos.rend())) { if (VerboseAsm) Asm->OutStreamer->AddComment("TypeInfo " + Twine(Entry--)); Asm->EmitTTypeReference(GV, TTypeEncoding); } Asm->OutStreamer->EmitLabel(TTBaseLabel); // Emit the Exception Specifications. if (VerboseAsm && !FilterIds.empty()) { Asm->OutStreamer->AddComment(">> Filter TypeInfos <<"); Asm->OutStreamer->AddBlankLine(); Entry = 0; } for (std::vector::const_iterator I = FilterIds.begin(), E = FilterIds.end(); I < E; ++I) { unsigned TypeID = *I; if (VerboseAsm) { --Entry; if (isFilterEHSelector(TypeID)) Asm->OutStreamer->AddComment("FilterInfo " + Twine(Entry)); } Asm->EmitULEB128(TypeID); } } Index: llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp =================================================================== --- llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp (revision 366328) +++ llvm/trunk/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp (revision 366329) @@ -1,274 +1,293 @@ //===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the Dwarf emissions parts of AsmPrinter. // //===----------------------------------------------------------------------===// #include "ByteStreamer.h" #include "llvm/ADT/Twine.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/DIE.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/IR/DataLayout.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCDwarf.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MachineLocation.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; #define DEBUG_TYPE "asm-printer" //===----------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===----------------------------------------------------------------------===// /// EmitSLEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitSLEB128(int64_t Value, const char *Desc) const { if (isVerbose() && Desc) OutStreamer->AddComment(Desc); OutStreamer->EmitSLEB128IntValue(Value); } void AsmPrinter::EmitULEB128(uint64_t Value, const char *Desc, unsigned PadTo) const { if (isVerbose() && Desc) OutStreamer->AddComment(Desc); OutStreamer->EmitULEB128IntValue(Value, PadTo); } /// Emit something like ".uleb128 Hi-Lo". void AsmPrinter::EmitLabelDifferenceAsULEB128(const MCSymbol *Hi, const MCSymbol *Lo) const { OutStreamer->emitAbsoluteSymbolDiffAsULEB128(Hi, Lo); } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_uleb128: return "uleb128"; case dwarf::DW_EH_PE_sleb128: return "sleb128"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4 : return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 : return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8 : return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8 : return "indirect pcrel sdata8"; } return ""; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const { if (isVerbose()) { if (Desc) OutStreamer->AddComment(Twine(Desc) + " Encoding = " + Twine(DecodeDWARFEncoding(Val))); else OutStreamer->AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } OutStreamer->EmitIntValue(Val, 1); } /// GetSizeOfEncodedValue - Return the size of the encoding in bytes. unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { default: llvm_unreachable("Invalid encoded value."); case dwarf::DW_EH_PE_absptr: return MF->getDataLayout().getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } } void AsmPrinter::EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const { if (GV) { const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getTTypeGlobalReference(GV, Encoding, TM, MMI, *OutStreamer); OutStreamer->EmitValue(Exp, GetSizeOfEncodedValue(Encoding)); } else OutStreamer->EmitIntValue(0, GetSizeOfEncodedValue(Encoding)); } void AsmPrinter::emitDwarfSymbolReference(const MCSymbol *Label, bool ForceOffset) const { if (!ForceOffset) { // On COFF targets, we have to emit the special .secrel32 directive. if (MAI->needsDwarfSectionOffsetDirective()) { OutStreamer->EmitCOFFSecRel32(Label, /*Offset=*/0); return; } // If the format uses relocations with dwarf, refer to the symbol directly. if (MAI->doesDwarfUseRelocationsAcrossSections()) { OutStreamer->EmitSymbolValue(Label, 4); return; } } // Otherwise, emit it as a label difference from the start of the section. EmitLabelDifference(Label, Label->getSection().getBeginSymbol(), 4); } void AsmPrinter::emitDwarfStringOffset(DwarfStringPoolEntry S) const { if (MAI->doesDwarfUseRelocationsAcrossSections()) { assert(S.Symbol && "No symbol available"); emitDwarfSymbolReference(S.Symbol); return; } // Just emit the offset directly; no need for symbol math. emitInt32(S.Offset); } void AsmPrinter::EmitDwarfOffset(const MCSymbol *Label, uint64_t Offset) const { EmitLabelPlusOffset(Label, Offset, MAI->getCodePointerSize()); } +void AsmPrinter::EmitCallSiteOffset(const MCSymbol *Hi, + const MCSymbol *Lo, + unsigned Encoding) const { + // The least significant 3 bits specify the width of the encoding + if ((Encoding & 0x7) == dwarf::DW_EH_PE_uleb128) + EmitLabelDifferenceAsULEB128(Hi, Lo); + else + EmitLabelDifference(Hi, Lo, GetSizeOfEncodedValue(Encoding)); +} + +void AsmPrinter::EmitCallSiteValue(uint64_t Value, + unsigned Encoding) const { + // The least significant 3 bits specify the width of the encoding + if ((Encoding & 0x7) == dwarf::DW_EH_PE_uleb128) + EmitULEB128(Value); + else + OutStreamer->EmitIntValue(Value, GetSizeOfEncodedValue(Encoding)); +} + //===----------------------------------------------------------------------===// // Dwarf Lowering Routines //===----------------------------------------------------------------------===// void AsmPrinter::emitCFIInstruction(const MCCFIInstruction &Inst) const { switch (Inst.getOperation()) { default: llvm_unreachable("Unexpected instruction"); case MCCFIInstruction::OpDefCfaOffset: OutStreamer->EmitCFIDefCfaOffset(Inst.getOffset()); break; case MCCFIInstruction::OpAdjustCfaOffset: OutStreamer->EmitCFIAdjustCfaOffset(Inst.getOffset()); break; case MCCFIInstruction::OpDefCfa: OutStreamer->EmitCFIDefCfa(Inst.getRegister(), Inst.getOffset()); break; case MCCFIInstruction::OpDefCfaRegister: OutStreamer->EmitCFIDefCfaRegister(Inst.getRegister()); break; case MCCFIInstruction::OpOffset: OutStreamer->EmitCFIOffset(Inst.getRegister(), Inst.getOffset()); break; case MCCFIInstruction::OpRegister: OutStreamer->EmitCFIRegister(Inst.getRegister(), Inst.getRegister2()); break; case MCCFIInstruction::OpWindowSave: OutStreamer->EmitCFIWindowSave(); break; case MCCFIInstruction::OpNegateRAState: OutStreamer->EmitCFINegateRAState(); break; case MCCFIInstruction::OpSameValue: OutStreamer->EmitCFISameValue(Inst.getRegister()); break; case MCCFIInstruction::OpGnuArgsSize: OutStreamer->EmitCFIGnuArgsSize(Inst.getOffset()); break; case MCCFIInstruction::OpEscape: OutStreamer->EmitCFIEscape(Inst.getValues()); break; case MCCFIInstruction::OpRestore: OutStreamer->EmitCFIRestore(Inst.getRegister()); break; } } void AsmPrinter::emitDwarfDIE(const DIE &Die) const { // Emit the code (index) for the abbreviation. if (isVerbose()) OutStreamer->AddComment("Abbrev [" + Twine(Die.getAbbrevNumber()) + "] 0x" + Twine::utohexstr(Die.getOffset()) + ":0x" + Twine::utohexstr(Die.getSize()) + " " + dwarf::TagString(Die.getTag())); EmitULEB128(Die.getAbbrevNumber()); // Emit the DIE attribute values. for (const auto &V : Die.values()) { dwarf::Attribute Attr = V.getAttribute(); assert(V.getForm() && "Too many attributes for DIE (check abbreviation)"); if (isVerbose()) { OutStreamer->AddComment(dwarf::AttributeString(Attr)); if (Attr == dwarf::DW_AT_accessibility) OutStreamer->AddComment( dwarf::AccessibilityString(V.getDIEInteger().getValue())); } // Emit an attribute using the defined form. V.EmitValue(this); } // Emit the DIE children if any. if (Die.hasChildren()) { for (auto &Child : Die.children()) emitDwarfDIE(Child); OutStreamer->AddComment("End Of Children Mark"); emitInt8(0); } } void AsmPrinter::emitDwarfAbbrev(const DIEAbbrev &Abbrev) const { // Emit the abbreviations code (base 1 index.) EmitULEB128(Abbrev.getNumber(), "Abbreviation Code"); // Emit the abbreviations data. Abbrev.Emit(this); } Index: llvm/trunk/lib/Target/TargetLoweringObjectFile.cpp =================================================================== --- llvm/trunk/lib/Target/TargetLoweringObjectFile.cpp (revision 366328) +++ llvm/trunk/lib/Target/TargetLoweringObjectFile.cpp (revision 366329) @@ -1,345 +1,346 @@ //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements classes used to handle lowerings specific to common // object file formats. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Mangler.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; //===----------------------------------------------------------------------===// // Generic Code //===----------------------------------------------------------------------===// /// Initialize - this method must be called before any actual lowering is /// done. This specifies the current context for codegen, and gives the /// lowering implementations a chance to set up their default sections. void TargetLoweringObjectFile::Initialize(MCContext &ctx, const TargetMachine &TM) { Ctx = &ctx; // `Initialize` can be called more than once. delete Mang; Mang = new Mangler(); InitMCObjectFileInfo(TM.getTargetTriple(), TM.isPositionIndependent(), *Ctx, TM.getCodeModel() == CodeModel::Large); // Reset various EH DWARF encodings. PersonalityEncoding = LSDAEncoding = TTypeEncoding = dwarf::DW_EH_PE_absptr; + CallSiteEncoding = dwarf::DW_EH_PE_uleb128; } TargetLoweringObjectFile::~TargetLoweringObjectFile() { delete Mang; } static bool isNullOrUndef(const Constant *C) { // Check that the constant isn't all zeros or undefs. if (C->isNullValue() || isa(C)) return true; if (!isa(C)) return false; for (auto Operand : C->operand_values()) { if (!isNullOrUndef(cast(Operand))) return false; } return true; } static bool isSuitableForBSS(const GlobalVariable *GV) { const Constant *C = GV->getInitializer(); // Must have zero initializer. if (!isNullOrUndef(C)) return false; // Leave constant zeros in readonly constant sections, so they can be shared. if (GV->isConstant()) return false; // If the global has an explicit section specified, don't put it in BSS. if (GV->hasSection()) return false; // Otherwise, put it in BSS! return true; } /// IsNullTerminatedString - Return true if the specified constant (which is /// known to have a type that is an array of 1/2/4 byte elements) ends with a /// nul value and contains no other nuls in it. Note that this is more general /// than ConstantDataSequential::isString because we allow 2 & 4 byte strings. static bool IsNullTerminatedString(const Constant *C) { // First check: is we have constant array terminated with zero if (const ConstantDataSequential *CDS = dyn_cast(C)) { unsigned NumElts = CDS->getNumElements(); assert(NumElts != 0 && "Can't have an empty CDS"); if (CDS->getElementAsInteger(NumElts-1) != 0) return false; // Not null terminated. // Verify that the null doesn't occur anywhere else in the string. for (unsigned i = 0; i != NumElts-1; ++i) if (CDS->getElementAsInteger(i) == 0) return false; return true; } // Another possibility: [1 x i8] zeroinitializer if (isa(C)) return cast(C->getType())->getNumElements() == 1; return false; } MCSymbol *TargetLoweringObjectFile::getSymbolWithGlobalValueBase( const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const { assert(!Suffix.empty()); SmallString<60> NameStr; NameStr += GV->getParent()->getDataLayout().getPrivateGlobalPrefix(); TM.getNameWithPrefix(NameStr, GV, *Mang); NameStr.append(Suffix.begin(), Suffix.end()); return Ctx->getOrCreateSymbol(NameStr); } MCSymbol *TargetLoweringObjectFile::getCFIPersonalitySymbol( const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const { return TM.getSymbol(GV); } void TargetLoweringObjectFile::emitPersonalityValue(MCStreamer &Streamer, const DataLayout &, const MCSymbol *Sym) const { } /// getKindForGlobal - This is a top-level target-independent classifier for /// a global object. Given a global variable and information from the TM, this /// function classifies the global in a target independent manner. This function /// may be overridden by the target implementation. SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM){ assert(!GO->isDeclaration() && !GO->hasAvailableExternallyLinkage() && "Can only be used for global definitions"); // Functions are classified as text sections. if (isa(GO)) return SectionKind::getText(); // Global variables require more detailed analysis. const auto *GVar = cast(GO); // Handle thread-local data first. if (GVar->isThreadLocal()) { if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) return SectionKind::getThreadBSS(); return SectionKind::getThreadData(); } // Variables with common linkage always get classified as common. if (GVar->hasCommonLinkage()) return SectionKind::getCommon(); // Most non-mergeable zero data can be put in the BSS section unless otherwise // specified. if (isSuitableForBSS(GVar) && !TM.Options.NoZerosInBSS) { if (GVar->hasLocalLinkage()) return SectionKind::getBSSLocal(); else if (GVar->hasExternalLinkage()) return SectionKind::getBSSExtern(); return SectionKind::getBSS(); } // If the global is marked constant, we can put it into a mergable section, // a mergable string section, or general .data if it contains relocations. if (GVar->isConstant()) { // If the initializer for the global contains something that requires a // relocation, then we may have to drop this into a writable data section // even though it is marked const. const Constant *C = GVar->getInitializer(); if (!C->needsRelocation()) { // If the global is required to have a unique address, it can't be put // into a mergable section: just drop it into the general read-only // section instead. if (!GVar->hasGlobalUnnamedAddr()) return SectionKind::getReadOnly(); // If initializer is a null-terminated string, put it in a "cstring" // section of the right width. if (ArrayType *ATy = dyn_cast(C->getType())) { if (IntegerType *ITy = dyn_cast(ATy->getElementType())) { if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 || ITy->getBitWidth() == 32) && IsNullTerminatedString(C)) { if (ITy->getBitWidth() == 8) return SectionKind::getMergeable1ByteCString(); if (ITy->getBitWidth() == 16) return SectionKind::getMergeable2ByteCString(); assert(ITy->getBitWidth() == 32 && "Unknown width"); return SectionKind::getMergeable4ByteCString(); } } } // Otherwise, just drop it into a mergable constant section. If we have // a section for this size, use it, otherwise use the arbitrary sized // mergable section. switch ( GVar->getParent()->getDataLayout().getTypeAllocSize(C->getType())) { case 4: return SectionKind::getMergeableConst4(); case 8: return SectionKind::getMergeableConst8(); case 16: return SectionKind::getMergeableConst16(); case 32: return SectionKind::getMergeableConst32(); default: return SectionKind::getReadOnly(); } } else { // In static, ROPI and RWPI relocation models, the linker will resolve // all addresses, so the relocation entries will actually be constants by // the time the app starts up. However, we can't put this into a // mergable section, because the linker doesn't take relocations into // consideration when it tries to merge entries in the section. Reloc::Model ReloModel = TM.getRelocationModel(); if (ReloModel == Reloc::Static || ReloModel == Reloc::ROPI || ReloModel == Reloc::RWPI || ReloModel == Reloc::ROPI_RWPI) return SectionKind::getReadOnly(); // Otherwise, the dynamic linker needs to fix it up, put it in the // writable data.rel section. return SectionKind::getReadOnlyWithRel(); } } // Okay, this isn't a constant. return SectionKind::getData(); } /// This method computes the appropriate section to emit the specified global /// variable or function definition. This should not be passed external (or /// available externally) globals. MCSection *TargetLoweringObjectFile::SectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { // Select section name. if (GO->hasSection()) return getExplicitSectionGlobal(GO, Kind, TM); if (auto *GVar = dyn_cast(GO)) { auto Attrs = GVar->getAttributes(); if ((Attrs.hasAttribute("bss-section") && Kind.isBSS()) || (Attrs.hasAttribute("data-section") && Kind.isData()) || (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly())) { return getExplicitSectionGlobal(GO, Kind, TM); } } if (auto *F = dyn_cast(GO)) { if (F->hasFnAttribute("implicit-section-name")) return getExplicitSectionGlobal(GO, Kind, TM); } // Use default section depending on the 'type' of global return SelectSectionForGlobal(GO, Kind, TM); } MCSection *TargetLoweringObjectFile::getSectionForJumpTable( const Function &F, const TargetMachine &TM) const { unsigned Align = 0; return getSectionForConstant(F.getParent()->getDataLayout(), SectionKind::getReadOnly(), /*C=*/nullptr, Align); } bool TargetLoweringObjectFile::shouldPutJumpTableInFunctionSection( bool UsesLabelDifference, const Function &F) const { // In PIC mode, we need to emit the jump table to the same section as the // function body itself, otherwise the label differences won't make sense. // FIXME: Need a better predicate for this: what about custom entries? if (UsesLabelDifference) return true; // We should also do if the section name is NULL or function is declared // in discardable section // FIXME: this isn't the right predicate, should be based on the MCSection // for the function. return F.isWeakForLinker(); } /// Given a mergable constant with the specified size and relocation /// information, return a section that it should be placed in. MCSection *TargetLoweringObjectFile::getSectionForConstant( const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const { if (Kind.isReadOnly() && ReadOnlySection != nullptr) return ReadOnlySection; return DataSection; } /// getTTypeGlobalReference - Return an MCExpr to use for a /// reference to the specified global variable from exception /// handling information. const MCExpr *TargetLoweringObjectFile::getTTypeGlobalReference( const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const { const MCSymbolRefExpr *Ref = MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); return getTTypeReference(Ref, Encoding, Streamer); } const MCExpr *TargetLoweringObjectFile:: getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const { switch (Encoding & 0x70) { default: report_fatal_error("We do not support this DWARF encoding yet!"); case dwarf::DW_EH_PE_absptr: // Do nothing special return Sym; case dwarf::DW_EH_PE_pcrel: { // Emit a label to the streamer for the current position. This gives us // .-foo addressing. MCSymbol *PCSym = getContext().createTempSymbol(); Streamer.EmitLabel(PCSym); const MCExpr *PC = MCSymbolRefExpr::create(PCSym, getContext()); return MCBinaryExpr::createSub(Sym, PC, getContext()); } } } const MCExpr *TargetLoweringObjectFile::getDebugThreadLocalSymbol(const MCSymbol *Sym) const { // FIXME: It's not clear what, if any, default this should have - perhaps a // null return could mean 'no location' & we should just do that here. return MCSymbolRefExpr::create(Sym, *Ctx); } void TargetLoweringObjectFile::getNameWithPrefix( SmallVectorImpl &OutName, const GlobalValue *GV, const TargetMachine &TM) const { Mang->getNameWithPrefix(OutName, GV, /*CannotUsePrivateLabel=*/false); } Index: llvm/trunk/test/CodeGen/RISCV/dwarf-eh.ll =================================================================== --- llvm/trunk/test/CodeGen/RISCV/dwarf-eh.ll (revision 366328) +++ llvm/trunk/test/CodeGen/RISCV/dwarf-eh.ll (revision 366329) @@ -1,66 +1,66 @@ ; RUN: llc -march=riscv32 --code-model=small < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv32 --code-model=medium < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv32 --code-model=small -relocation-model=pic < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv32 --code-model=medium -relocation-model=pic < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv64 --code-model=small < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv64 --code-model=medium < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv64 --code-model=small -relocation-model=pic < %s \ ; RUN: | FileCheck %s ; RUN: llc -march=riscv64 --code-model=medium -relocation-model=pic < %s \ ; RUN: | FileCheck %s declare void @throw_exception() declare i32 @__gxx_personality_v0(...) declare i8* @__cxa_begin_catch(i8*) declare void @__cxa_end_catch() ; CHECK-LABEL: test1: ; CHECK: .cfi_startproc ; PersonalityEncoding = DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4 ; CHECK-NEXT: .cfi_personality 155, DW.ref.__gxx_personality_v0 ; LSDAEncoding = DW_EH_PE_pcrel | DW_EH_PE_sdata4 ; CHECK-NEXT: .cfi_lsda 27, .Lexception0 define void @test1() personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) { entry: invoke void @throw_exception() to label %try.cont unwind label %lpad lpad: %0 = landingpad { i8*, i32 } catch i8* null %1 = extractvalue { i8*, i32 } %0, 0 %2 = tail call i8* @__cxa_begin_catch(i8* %1) tail call void @__cxa_end_catch() br label %try.cont try.cont: ret void } ; CHECK-LABEL: GCC_except_table0: ; CHECK-NEXT: .Lexception0: ; CHECK-NEXT: .byte 255 # @LPStart Encoding = omit ; TTypeEncoding = DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4 ; CHECK-NEXT: .byte 155 # @TType Encoding = indirect pcrel sdata4 ; TODO: call site encoding should be DW_EH_PE_udata4 ; CHECK: .Lttbaseref0: -; CHECK-NEXT: .byte 1 # Call site Encoding = uleb128 +; CHECK-NEXT: .byte 3 # Call site Encoding = udata4 ; CHECK-NEXT: .uleb128 .Lcst_end0-.Lcst_begin0 ; CHECK-NEXT: cst_begin0: -; CHECK-NEXT: .uleb128 .Ltmp0-.Lfunc_begin0 # >> Call Site 1 << -; CHECK-NEXT: .uleb128 .Ltmp1-.Ltmp0 # Call between .Ltmp0 and .Ltmp1 -; CHECK-NEXT: .uleb128 .Ltmp2-.Lfunc_begin0 # jumps to .Ltmp2 +; CHECK-NEXT: .word .Ltmp0-.Lfunc_begin0 # >> Call Site 1 << +; CHECK-NEXT: .word .Ltmp1-.Ltmp0 # Call between .Ltmp0 and .Ltmp1 +; CHECK-NEXT: .word .Ltmp2-.Lfunc_begin0 # jumps to .Ltmp2 ; CHECK-NEXT: .byte 1 # On action: 1 -; CHECK-NEXT: .uleb128 .Ltmp1-.Lfunc_begin0 # >> Call Site 2 << -; CHECK-NEXT: .uleb128 .Lfunc_end0-.Ltmp1 # Call between .Ltmp1 and .Lfunc_end0 -; CHECK-NEXT: .byte 0 # has no landing pad +; CHECK-NEXT: .word .Ltmp1-.Lfunc_begin0 # >> Call Site 2 << +; CHECK-NEXT: .word .Lfunc_end0-.Ltmp1 # Call between .Ltmp1 and .Lfunc_end0 +; CHECK-NEXT: .word 0 # has no landing pad ; CHECK-NEXT: .byte 0 # On action: cleanup