Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/StackProtector.h
//===-- StackProtector.h - Stack Protector Insertion ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass inserts stack protectors into functions which need them. A variable // with a random value in it is stored onto the stack before the local variables // are allocated. Upon exiting the block, the stored value is checked. If it's // changed, then there was some sort of violation and the program aborts. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_STACKPROTECTOR_H #define LLVM_CODEGEN_STACKPROTECTOR_H #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Triple.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/ValueMap.h" #include "llvm/Pass.h" #include "llvm/Target/TargetLowering.h" namespace llvm { class Function; class Module; class PHINode; class StackProtector : public FunctionPass { public: /// SSPLayoutKind. Stack Smashing Protection (SSP) rules require that /// vulnerable stack allocations are located close the stack protector. enum SSPLayoutKind { SSPLK_None, ///< Did not trigger a stack protector. No effect on data ///< layout. SSPLK_LargeArray, ///< Array or nested array >= SSP-buffer-size. Closest ///< to the stack protector. SSPLK_SmallArray, ///< Array or nested array < SSP-buffer-size. 2nd closest ///< to the stack protector. SSPLK_AddrOf ///< The address of this allocation is exposed and ///< triggered protection. 3rd closest to the protector. }; /// A mapping of AllocaInsts to their required SSP layout. typedef ValueMap<const AllocaInst *, SSPLayoutKind> SSPLayoutMap; private: const TargetMachine *TM; /// TLI - Keep a pointer of a TargetLowering to consult for determining /// target type sizes. const TargetLoweringBase *TLI; const Triple Trip; Function *F; Module *M; DominatorTree *DT; /// Layout - Mapping of allocations to the required SSPLayoutKind. /// StackProtector analysis will update this map when determining if an /// AllocaInst triggers a stack protector. SSPLayoutMap Layout; /// \brief The minimum size of buffers that will receive stack smashing /// protection when -fstack-protection is used. unsigned SSPBufferSize; /// VisitedPHIs - The set of PHI nodes visited when determining /// if a variable's reference has been taken. This set /// is maintained to ensure we don't visit the same PHI node multiple /// times. SmallPtrSet<const PHINode *, 16> VisitedPHIs; /// InsertStackProtectors - Insert code into the prologue and epilogue of /// the function. /// /// - The prologue code loads and stores the stack guard onto the stack. /// - The epilogue checks the value stored in the prologue against the /// original value. It calls __stack_chk_fail if they differ. bool InsertStackProtectors(); /// CreateFailBB - Create a basic block to jump to when the stack protector /// check fails. BasicBlock *CreateFailBB(); /// ContainsProtectableArray - Check whether the type either is an array or /// contains an array of sufficient size so that we need stack protectors /// for it. /// \param [out] IsLarge is set to true if a protectable array is found and /// it is "large" ( >= ssp-buffer-size). In the case of a structure with /// multiple arrays, this gets set if any of them is large. bool ContainsProtectableArray(Type *Ty, bool &IsLarge, bool Strong = false, bool InStruct = false) const; /// \brief Check whether a stack allocation has its address taken. bool HasAddressTaken(const Instruction *AI); /// RequiresStackProtector - Check whether or not this function needs a /// stack protector based upon the stack protector level. bool RequiresStackProtector(); public: static char ID; // Pass identification, replacement for typeid. StackProtector() : FunctionPass(ID), TM(nullptr), TLI(nullptr), SSPBufferSize(0) { initializeStackProtectorPass(*PassRegistry::getPassRegistry()); } StackProtector(const TargetMachine *TM) : FunctionPass(ID), TM(TM), TLI(nullptr), Trip(TM->getTargetTriple()), SSPBufferSize(8) { initializeStackProtectorPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addPreserved<DominatorTreeWrapperPass>(); } SSPLayoutKind getSSPLayout(const AllocaInst *AI) const; void adjustForColoring(const AllocaInst *From, const AllocaInst *To); bool runOnFunction(Function &Fn) override; }; } // end namespace llvm #endif // LLVM_CODEGEN_STACKPROTECTOR_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/ScheduleDAGInstrs.h
//==- ScheduleDAGInstrs.h - MachineInstr Scheduling --------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ScheduleDAGInstrs class, which implements // scheduling for a MachineInstr-based dependency graph. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_SCHEDULEDAGINSTRS_H #define LLVM_CODEGEN_SCHEDULEDAGINSTRS_H #include "llvm/ADT/SparseMultiSet.h" #include "llvm/ADT/SparseSet.h" #include "llvm/CodeGen/ScheduleDAG.h" #include "llvm/CodeGen/TargetSchedule.h" #include "llvm/Support/Compiler.h" #include "llvm/Target/TargetRegisterInfo.h" namespace llvm { class MachineFrameInfo; class MachineLoopInfo; class MachineDominatorTree; class LiveIntervals; class RegPressureTracker; class PressureDiffs; /// An individual mapping from virtual register number to SUnit. struct VReg2SUnit { unsigned VirtReg; SUnit *SU; VReg2SUnit(unsigned reg, SUnit *su): VirtReg(reg), SU(su) {} unsigned getSparseSetIndex() const { return TargetRegisterInfo::virtReg2Index(VirtReg); } }; /// Record a physical register access. /// For non-data-dependent uses, OpIdx == -1. struct PhysRegSUOper { SUnit *SU; int OpIdx; unsigned Reg; PhysRegSUOper(SUnit *su, int op, unsigned R): SU(su), OpIdx(op), Reg(R) {} unsigned getSparseSetIndex() const { return Reg; } }; /// Use a SparseMultiSet to track physical registers. Storage is only /// allocated once for the pass. It can be cleared in constant time and reused /// without any frees. typedef SparseMultiSet<PhysRegSUOper, llvm::identity<unsigned>, uint16_t> Reg2SUnitsMap; /// Use SparseSet as a SparseMap by relying on the fact that it never /// compares ValueT's, only unsigned keys. This allows the set to be cleared /// between scheduling regions in constant time as long as ValueT does not /// require a destructor. typedef SparseSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2SUnitMap; /// Track local uses of virtual registers. These uses are gathered by the DAG /// builder and may be consulted by the scheduler to avoid iterating an entire /// vreg use list. typedef SparseMultiSet<VReg2SUnit, VirtReg2IndexFunctor> VReg2UseMap; /// ScheduleDAGInstrs - A ScheduleDAG subclass for scheduling lists of /// MachineInstrs. class ScheduleDAGInstrs : public ScheduleDAG { protected: const MachineLoopInfo *MLI; const MachineFrameInfo *MFI; /// Live Intervals provides reaching defs in preRA scheduling. LiveIntervals *LIS; /// TargetSchedModel provides an interface to the machine model. TargetSchedModel SchedModel; /// isPostRA flag indicates vregs cannot be present. bool IsPostRA; /// True if the DAG builder should remove kill flags (in preparation for /// rescheduling). bool RemoveKillFlags; /// The standard DAG builder does not normally include terminators as DAG /// nodes because it does not create the necessary dependencies to prevent /// reordering. A specialized scheduler can override /// TargetInstrInfo::isSchedulingBoundary then enable this flag to indicate /// it has taken responsibility for scheduling the terminator correctly. bool CanHandleTerminators; /// State specific to the current scheduling region. /// ------------------------------------------------ /// The block in which to insert instructions MachineBasicBlock *BB; /// The beginning of the range to be scheduled. MachineBasicBlock::iterator RegionBegin; /// The end of the range to be scheduled. MachineBasicBlock::iterator RegionEnd; /// Instructions in this region (distance(RegionBegin, RegionEnd)). unsigned NumRegionInstrs; /// After calling BuildSchedGraph, each machine instruction in the current /// scheduling region is mapped to an SUnit. DenseMap<MachineInstr*, SUnit*> MISUnitMap; /// After calling BuildSchedGraph, each vreg used in the scheduling region /// is mapped to a set of SUnits. These include all local vreg uses, not /// just the uses for a singly defined vreg. VReg2UseMap VRegUses; /// State internal to DAG building. /// ------------------------------- /// Defs, Uses - Remember where defs and uses of each register are as we /// iterate upward through the instructions. This is allocated here instead /// of inside BuildSchedGraph to avoid the need for it to be initialized and /// destructed for each block. Reg2SUnitsMap Defs; Reg2SUnitsMap Uses; /// Track the last instruction in this region defining each virtual register. VReg2SUnitMap VRegDefs; /// PendingLoads - Remember where unknown loads are after the most recent /// unknown store, as we iterate. As with Defs and Uses, this is here /// to minimize construction/destruction. std::vector<SUnit *> PendingLoads; /// DbgValues - Remember instruction that precedes DBG_VALUE. /// These are generated by buildSchedGraph but persist so they can be /// referenced when emitting the final schedule. typedef std::vector<std::pair<MachineInstr *, MachineInstr *> > DbgValueVector; DbgValueVector DbgValues; MachineInstr *FirstDbgValue; /// Set of live physical registers for updating kill flags. BitVector LiveRegs; public: explicit ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool IsPostRAFlag, bool RemoveKillFlags = false, LiveIntervals *LIS = nullptr); ~ScheduleDAGInstrs() override {} bool isPostRA() const { return IsPostRA; } /// \brief Expose LiveIntervals for use in DAG mutators and such. LiveIntervals *getLIS() const { return LIS; } /// \brief Get the machine model for instruction scheduling. const TargetSchedModel *getSchedModel() const { return &SchedModel; } /// \brief Resolve and cache a resolved scheduling class for an SUnit. const MCSchedClassDesc *getSchedClass(SUnit *SU) const { if (!SU->SchedClass && SchedModel.hasInstrSchedModel()) SU->SchedClass = SchedModel.resolveSchedClass(SU->getInstr()); return SU->SchedClass; } /// begin - Return an iterator to the top of the current scheduling region. MachineBasicBlock::iterator begin() const { return RegionBegin; } /// end - Return an iterator to the bottom of the current scheduling region. MachineBasicBlock::iterator end() const { return RegionEnd; } /// newSUnit - Creates a new SUnit and return a ptr to it. SUnit *newSUnit(MachineInstr *MI); /// getSUnit - Return an existing SUnit for this MI, or NULL. SUnit *getSUnit(MachineInstr *MI) const; /// startBlock - Prepare to perform scheduling in the given block. virtual void startBlock(MachineBasicBlock *BB); /// finishBlock - Clean up after scheduling in the given block. virtual void finishBlock(); /// Initialize the scheduler state for the next scheduling region. virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs); /// Notify that the scheduler has finished scheduling the current region. virtual void exitRegion(); /// buildSchedGraph - Build SUnits from the MachineBasicBlock that we are /// input. void buildSchedGraph(AliasAnalysis *AA, RegPressureTracker *RPTracker = nullptr, PressureDiffs *PDiffs = nullptr); /// addSchedBarrierDeps - Add dependencies from instructions in the current /// list of instructions being scheduled to scheduling barrier. We want to /// make sure instructions which define registers that are either used by /// the terminator or are live-out are properly scheduled. This is /// especially important when the definition latency of the return value(s) /// are too high to be hidden by the branch or when the liveout registers /// used by instructions in the fallthrough block. void addSchedBarrierDeps(); /// schedule - Order nodes according to selected style, filling /// in the Sequence member. /// /// Typically, a scheduling algorithm will implement schedule() without /// overriding enterRegion() or exitRegion(). virtual void schedule() = 0; /// finalizeSchedule - Allow targets to perform final scheduling actions at /// the level of the whole MachineFunction. By default does nothing. virtual void finalizeSchedule() {} void dumpNode(const SUnit *SU) const override; /// Return a label for a DAG node that points to an instruction. std::string getGraphNodeLabel(const SUnit *SU) const override; /// Return a label for the region of code covered by the DAG. std::string getDAGName() const override; /// \brief Fix register kill flags that scheduling has made invalid. void fixupKills(MachineBasicBlock *MBB); protected: void initSUnits(); void addPhysRegDataDeps(SUnit *SU, unsigned OperIdx); void addPhysRegDeps(SUnit *SU, unsigned OperIdx); void addVRegDefDeps(SUnit *SU, unsigned OperIdx); void addVRegUseDeps(SUnit *SU, unsigned OperIdx); /// \brief PostRA helper for rewriting kill flags. void startBlockForKills(MachineBasicBlock *BB); /// \brief Toggle a register operand kill flag. /// /// Other adjustments may be made to the instruction if necessary. Return /// true if the operand has been deleted, false if not. bool toggleKillFlag(MachineInstr *MI, MachineOperand &MO); }; /// newSUnit - Creates a new SUnit and return a ptr to it. inline SUnit *ScheduleDAGInstrs::newSUnit(MachineInstr *MI) { #ifndef NDEBUG const SUnit *Addr = SUnits.empty() ? nullptr : &SUnits[0]; #endif SUnits.emplace_back(MI, (unsigned)SUnits.size()); assert((Addr == nullptr || Addr == &SUnits[0]) && "SUnits std::vector reallocated on the fly!"); SUnits.back().OrigNode = &SUnits.back(); return &SUnits.back(); } /// getSUnit - Return an existing SUnit for this MI, or NULL. inline SUnit *ScheduleDAGInstrs::getSUnit(MachineInstr *MI) const { DenseMap<MachineInstr*, SUnit*>::const_iterator I = MISUnitMap.find(MI); if (I == MISUnitMap.end()) return nullptr; return I->second; } } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/ScheduleDAG.h
//===------- llvm/CodeGen/ScheduleDAG.h - Common Base Class------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ScheduleDAG class, which is used as the common // base class for instruction schedulers. This encapsulates the scheduling DAG, // which is shared between SelectionDAG and MachineInstr scheduling. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_SCHEDULEDAG_H #define LLVM_CODEGEN_SCHEDULEDAG_H #include "llvm/ADT/BitVector.h" #include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetLowering.h" namespace llvm { class AliasAnalysis; class SUnit; class MachineConstantPool; class MachineFunction; class MachineRegisterInfo; class MachineInstr; struct MCSchedClassDesc; class TargetRegisterInfo; class ScheduleDAG; class SDNode; class TargetInstrInfo; class MCInstrDesc; class TargetMachine; class TargetRegisterClass; template<class Graph> class GraphWriter; /// SDep - Scheduling dependency. This represents one direction of an /// edge in the scheduling DAG. class SDep { public: /// Kind - These are the different kinds of scheduling dependencies. enum Kind { Data, ///< Regular data dependence (aka true-dependence). Anti, ///< A register anti-dependedence (aka WAR). Output, ///< A register output-dependence (aka WAW). Order ///< Any other ordering dependency. }; // Strong dependencies must be respected by the scheduler. Artificial // dependencies may be removed only if they are redundant with another // strong depedence. // // Weak dependencies may be violated by the scheduling strategy, but only if // the strategy can prove it is correct to do so. // // Strong OrderKinds must occur before "Weak". // Weak OrderKinds must occur after "Weak". enum OrderKind { Barrier, ///< An unknown scheduling barrier. MayAliasMem, ///< Nonvolatile load/Store instructions that may alias. MustAliasMem, ///< Nonvolatile load/Store instructions that must alias. Artificial, ///< Arbitrary strong DAG edge (no real dependence). Weak, ///< Arbitrary weak DAG edge. Cluster ///< Weak DAG edge linking a chain of clustered instrs. }; private: /// Dep - A pointer to the depending/depended-on SUnit, and an enum /// indicating the kind of the dependency. PointerIntPair<SUnit *, 2, Kind> Dep; /// Contents - A union discriminated by the dependence kind. union { /// Reg - For Data, Anti, and Output dependencies, the associated /// register. For Data dependencies that don't currently have a register /// assigned, this is set to zero. unsigned Reg; /// Order - Additional information about Order dependencies. unsigned OrdKind; // enum OrderKind } Contents; /// Latency - The time associated with this edge. Often this is just /// the value of the Latency field of the predecessor, however advanced /// models may provide additional information about specific edges. unsigned Latency; public: /// SDep - Construct a null SDep. This is only for use by container /// classes which require default constructors. SUnits may not /// have null SDep edges. SDep() : Dep(nullptr, Data) {} /// SDep - Construct an SDep with the specified values. SDep(SUnit *S, Kind kind, unsigned Reg) : Dep(S, kind), Contents() { switch (kind) { default: llvm_unreachable("Reg given for non-register dependence!"); case Anti: case Output: assert(Reg != 0 && "SDep::Anti and SDep::Output must use a non-zero Reg!"); Contents.Reg = Reg; Latency = 0; break; case Data: Contents.Reg = Reg; Latency = 1; break; } } SDep(SUnit *S, OrderKind kind) : Dep(S, Order), Contents(), Latency(0) { Contents.OrdKind = kind; } /// Return true if the specified SDep is equivalent except for latency. bool overlaps(const SDep &Other) const { if (Dep != Other.Dep) return false; switch (Dep.getInt()) { case Data: case Anti: case Output: return Contents.Reg == Other.Contents.Reg; case Order: return Contents.OrdKind == Other.Contents.OrdKind; } llvm_unreachable("Invalid dependency kind!"); } bool operator==(const SDep &Other) const { return overlaps(Other) && Latency == Other.Latency; } bool operator!=(const SDep &Other) const { return !operator==(Other); } /// getLatency - Return the latency value for this edge, which roughly /// means the minimum number of cycles that must elapse between the /// predecessor and the successor, given that they have this edge /// between them. unsigned getLatency() const { return Latency; } /// setLatency - Set the latency for this edge. void setLatency(unsigned Lat) { Latency = Lat; } //// getSUnit - Return the SUnit to which this edge points. SUnit *getSUnit() const { return Dep.getPointer(); } //// setSUnit - Assign the SUnit to which this edge points. void setSUnit(SUnit *SU) { Dep.setPointer(SU); } /// getKind - Return an enum value representing the kind of the dependence. Kind getKind() const { return Dep.getInt(); } /// isCtrl - Shorthand for getKind() != SDep::Data. bool isCtrl() const { return getKind() != Data; } /// isNormalMemory - Test if this is an Order dependence between two /// memory accesses where both sides of the dependence access memory /// in non-volatile and fully modeled ways. bool isNormalMemory() const { return getKind() == Order && (Contents.OrdKind == MayAliasMem || Contents.OrdKind == MustAliasMem); } /// isBarrier - Test if this is an Order dependence that is marked /// as a barrier. bool isBarrier() const { return getKind() == Order && Contents.OrdKind == Barrier; } /// isNormalMemoryOrBarrier - Test if this is could be any kind of memory /// dependence. bool isNormalMemoryOrBarrier() const { return (isNormalMemory() || isBarrier()); } /// isMustAlias - Test if this is an Order dependence that is marked /// as "must alias", meaning that the SUnits at either end of the edge /// have a memory dependence on a known memory location. bool isMustAlias() const { return getKind() == Order && Contents.OrdKind == MustAliasMem; } /// isWeak - Test if this a weak dependence. Weak dependencies are /// considered DAG edges for height computation and other heuristics, but do /// not force ordering. Breaking a weak edge may require the scheduler to /// compensate, for example by inserting a copy. bool isWeak() const { return getKind() == Order && Contents.OrdKind >= Weak; } /// isArtificial - Test if this is an Order dependence that is marked /// as "artificial", meaning it isn't necessary for correctness. bool isArtificial() const { return getKind() == Order && Contents.OrdKind == Artificial; } /// isCluster - Test if this is an Order dependence that is marked /// as "cluster", meaning it is artificial and wants to be adjacent. bool isCluster() const { return getKind() == Order && Contents.OrdKind == Cluster; } /// isAssignedRegDep - Test if this is a Data dependence that is /// associated with a register. bool isAssignedRegDep() const { return getKind() == Data && Contents.Reg != 0; } /// getReg - Return the register associated with this edge. This is /// only valid on Data, Anti, and Output edges. On Data edges, this /// value may be zero, meaning there is no associated register. unsigned getReg() const { assert((getKind() == Data || getKind() == Anti || getKind() == Output) && "getReg called on non-register dependence edge!"); return Contents.Reg; } /// setReg - Assign the associated register for this edge. This is /// only valid on Data, Anti, and Output edges. On Anti and Output /// edges, this value must not be zero. On Data edges, the value may /// be zero, which would mean that no specific register is associated /// with this edge. void setReg(unsigned Reg) { assert((getKind() == Data || getKind() == Anti || getKind() == Output) && "setReg called on non-register dependence edge!"); assert((getKind() != Anti || Reg != 0) && "SDep::Anti edge cannot use the zero register!"); assert((getKind() != Output || Reg != 0) && "SDep::Output edge cannot use the zero register!"); Contents.Reg = Reg; } }; template <> struct isPodLike<SDep> { static const bool value = true; }; /// SUnit - Scheduling unit. This is a node in the scheduling DAG. class SUnit { private: enum : unsigned { BoundaryID = ~0u }; SDNode *Node; // Representative node. MachineInstr *Instr; // Alternatively, a MachineInstr. public: SUnit *OrigNode; // If not this, the node from which // this node was cloned. // (SD scheduling only) const MCSchedClassDesc *SchedClass; // NULL or resolved SchedClass. // Preds/Succs - The SUnits before/after us in the graph. SmallVector<SDep, 4> Preds; // All sunit predecessors. SmallVector<SDep, 4> Succs; // All sunit successors. typedef SmallVectorImpl<SDep>::iterator pred_iterator; typedef SmallVectorImpl<SDep>::iterator succ_iterator; typedef SmallVectorImpl<SDep>::const_iterator const_pred_iterator; typedef SmallVectorImpl<SDep>::const_iterator const_succ_iterator; unsigned NodeNum; // Entry # of node in the node vector. unsigned NodeQueueId; // Queue id of node. unsigned NumPreds; // # of SDep::Data preds. unsigned NumSuccs; // # of SDep::Data sucss. unsigned NumPredsLeft; // # of preds not scheduled. unsigned NumSuccsLeft; // # of succs not scheduled. unsigned WeakPredsLeft; // # of weak preds not scheduled. unsigned WeakSuccsLeft; // # of weak succs not scheduled. unsigned short NumRegDefsLeft; // # of reg defs with no scheduled use. unsigned short Latency; // Node latency. bool isVRegCycle : 1; // May use and def the same vreg. bool isCall : 1; // Is a function call. bool isCallOp : 1; // Is a function call operand. bool isTwoAddress : 1; // Is a two-address instruction. bool isCommutable : 1; // Is a commutable instruction. bool hasPhysRegUses : 1; // Has physreg uses. bool hasPhysRegDefs : 1; // Has physreg defs that are being used. bool hasPhysRegClobbers : 1; // Has any physreg defs, used or not. bool isPending : 1; // True once pending. bool isAvailable : 1; // True once available. bool isScheduled : 1; // True once scheduled. bool isScheduleHigh : 1; // True if preferable to schedule high. bool isScheduleLow : 1; // True if preferable to schedule low. bool isCloned : 1; // True if this node has been cloned. bool isUnbuffered : 1; // Uses an unbuffered resource. bool hasReservedResource : 1; // Uses a reserved resource. Sched::Preference SchedulingPref; // Scheduling preference. private: bool isDepthCurrent : 1; // True if Depth is current. bool isHeightCurrent : 1; // True if Height is current. unsigned Depth; // Node depth. unsigned Height; // Node height. public: unsigned TopReadyCycle; // Cycle relative to start when node is ready. unsigned BotReadyCycle; // Cycle relative to end when node is ready. const TargetRegisterClass *CopyDstRC; // Is a special copy node if not null. const TargetRegisterClass *CopySrcRC; /// SUnit - Construct an SUnit for pre-regalloc scheduling to represent /// an SDNode and any nodes flagged to it. SUnit(SDNode *node, unsigned nodenum) : Node(node), Instr(nullptr), OrigNode(nullptr), SchedClass(nullptr), NodeNum(nodenum), NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false), isCommutable(false), hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false), isAvailable(false), isScheduled(false), isScheduleHigh(false), isScheduleLow(false), isCloned(false), isUnbuffered(false), hasReservedResource(false), SchedulingPref(Sched::None), isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {} /// SUnit - Construct an SUnit for post-regalloc scheduling to represent /// a MachineInstr. SUnit(MachineInstr *instr, unsigned nodenum) : Node(nullptr), Instr(instr), OrigNode(nullptr), SchedClass(nullptr), NodeNum(nodenum), NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false), isCommutable(false), hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false), isAvailable(false), isScheduled(false), isScheduleHigh(false), isScheduleLow(false), isCloned(false), isUnbuffered(false), hasReservedResource(false), SchedulingPref(Sched::None), isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {} /// SUnit - Construct a placeholder SUnit. SUnit() : Node(nullptr), Instr(nullptr), OrigNode(nullptr), SchedClass(nullptr), NodeNum(BoundaryID), NodeQueueId(0), NumPreds(0), NumSuccs(0), NumPredsLeft(0), NumSuccsLeft(0), WeakPredsLeft(0), WeakSuccsLeft(0), NumRegDefsLeft(0), Latency(0), isVRegCycle(false), isCall(false), isCallOp(false), isTwoAddress(false), isCommutable(false), hasPhysRegUses(false), hasPhysRegDefs(false), hasPhysRegClobbers(false), isPending(false), isAvailable(false), isScheduled(false), isScheduleHigh(false), isScheduleLow(false), isCloned(false), isUnbuffered(false), hasReservedResource(false), SchedulingPref(Sched::None), isDepthCurrent(false), isHeightCurrent(false), Depth(0), Height(0), TopReadyCycle(0), BotReadyCycle(0), CopyDstRC(nullptr), CopySrcRC(nullptr) {} /// \brief Boundary nodes are placeholders for the boundary of the /// scheduling region. /// /// BoundaryNodes can have DAG edges, including Data edges, but they do not /// correspond to schedulable entities (e.g. instructions) and do not have a /// valid ID. Consequently, always check for boundary nodes before accessing /// an assoicative data structure keyed on node ID. bool isBoundaryNode() const { return NodeNum == BoundaryID; }; /// setNode - Assign the representative SDNode for this SUnit. /// This may be used during pre-regalloc scheduling. void setNode(SDNode *N) { assert(!Instr && "Setting SDNode of SUnit with MachineInstr!"); Node = N; } /// getNode - Return the representative SDNode for this SUnit. /// This may be used during pre-regalloc scheduling. SDNode *getNode() const { assert(!Instr && "Reading SDNode of SUnit with MachineInstr!"); return Node; } /// isInstr - Return true if this SUnit refers to a machine instruction as /// opposed to an SDNode. bool isInstr() const { return Instr; } /// setInstr - Assign the instruction for the SUnit. /// This may be used during post-regalloc scheduling. void setInstr(MachineInstr *MI) { assert(!Node && "Setting MachineInstr of SUnit with SDNode!"); Instr = MI; } /// getInstr - Return the representative MachineInstr for this SUnit. /// This may be used during post-regalloc scheduling. MachineInstr *getInstr() const { assert(!Node && "Reading MachineInstr of SUnit with SDNode!"); return Instr; } /// addPred - This adds the specified edge as a pred of the current node if /// not already. It also adds the current node as a successor of the /// specified node. bool addPred(const SDep &D, bool Required = true); /// removePred - This removes the specified edge as a pred of the current /// node if it exists. It also removes the current node as a successor of /// the specified node. void removePred(const SDep &D); /// getDepth - Return the depth of this node, which is the length of the /// maximum path up to any node which has no predecessors. unsigned getDepth() const { if (!isDepthCurrent) const_cast<SUnit *>(this)->ComputeDepth(); return Depth; } /// getHeight - Return the height of this node, which is the length of the /// maximum path down to any node which has no successors. unsigned getHeight() const { if (!isHeightCurrent) const_cast<SUnit *>(this)->ComputeHeight(); return Height; } /// setDepthToAtLeast - If NewDepth is greater than this node's /// depth value, set it to be the new depth value. This also /// recursively marks successor nodes dirty. void setDepthToAtLeast(unsigned NewDepth); /// setDepthToAtLeast - If NewDepth is greater than this node's /// depth value, set it to be the new height value. This also /// recursively marks predecessor nodes dirty. void setHeightToAtLeast(unsigned NewHeight); /// setDepthDirty - Set a flag in this node to indicate that its /// stored Depth value will require recomputation the next time /// getDepth() is called. void setDepthDirty(); /// setHeightDirty - Set a flag in this node to indicate that its /// stored Height value will require recomputation the next time /// getHeight() is called. void setHeightDirty(); /// isPred - Test if node N is a predecessor of this node. bool isPred(SUnit *N) { for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i) if (Preds[i].getSUnit() == N) return true; return false; } /// isSucc - Test if node N is a successor of this node. bool isSucc(SUnit *N) { for (unsigned i = 0, e = (unsigned)Succs.size(); i != e; ++i) if (Succs[i].getSUnit() == N) return true; return false; } bool isTopReady() const { return NumPredsLeft == 0; } bool isBottomReady() const { return NumSuccsLeft == 0; } /// \brief Order this node's predecessor edges such that the critical path /// edge occurs first. void biasCriticalPath(); void dump(const ScheduleDAG *G) const; void dumpAll(const ScheduleDAG *G) const; void print(raw_ostream &O, const ScheduleDAG *G) const; private: void ComputeDepth(); void ComputeHeight(); }; //===--------------------------------------------------------------------===// /// SchedulingPriorityQueue - This interface is used to plug different /// priorities computation algorithms into the list scheduler. It implements /// the interface of a standard priority queue, where nodes are inserted in /// arbitrary order and returned in priority order. The computation of the /// priority and the representation of the queue are totally up to the /// implementation to decide. /// class SchedulingPriorityQueue { virtual void anchor(); unsigned CurCycle; bool HasReadyFilter; public: SchedulingPriorityQueue(bool rf = false): CurCycle(0), HasReadyFilter(rf) {} virtual ~SchedulingPriorityQueue() {} virtual bool isBottomUp() const = 0; virtual void initNodes(std::vector<SUnit> &SUnits) = 0; virtual void addNode(const SUnit *SU) = 0; virtual void updateNode(const SUnit *SU) = 0; virtual void releaseState() = 0; virtual bool empty() const = 0; bool hasReadyFilter() const { return HasReadyFilter; } virtual bool tracksRegPressure() const { return false; } virtual bool isReady(SUnit *) const { assert(!HasReadyFilter && "The ready filter must override isReady()"); return true; } virtual void push(SUnit *U) = 0; void push_all(const std::vector<SUnit *> &Nodes) { for (std::vector<SUnit *>::const_iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) push(*I); } virtual SUnit *pop() = 0; virtual void remove(SUnit *SU) = 0; virtual void dump(ScheduleDAG *) const {} /// scheduledNode - As each node is scheduled, this method is invoked. This /// allows the priority function to adjust the priority of related /// unscheduled nodes, for example. /// virtual void scheduledNode(SUnit *) {} virtual void unscheduledNode(SUnit *) {} void setCurCycle(unsigned Cycle) { CurCycle = Cycle; } unsigned getCurCycle() const { return CurCycle; } }; class ScheduleDAG { public: const TargetMachine &TM; // Target processor const TargetInstrInfo *TII; // Target instruction information const TargetRegisterInfo *TRI; // Target processor register info MachineFunction &MF; // Machine function MachineRegisterInfo &MRI; // Virtual/real register map std::vector<SUnit> SUnits; // The scheduling units. SUnit EntrySU; // Special node for the region entry. SUnit ExitSU; // Special node for the region exit. #ifdef NDEBUG static const bool StressSched = false; #else bool StressSched; #endif explicit ScheduleDAG(MachineFunction &mf); virtual ~ScheduleDAG(); /// clearDAG - clear the DAG state (between regions). void clearDAG(); /// getInstrDesc - Return the MCInstrDesc of this SUnit. /// Return NULL for SDNodes without a machine opcode. const MCInstrDesc *getInstrDesc(const SUnit *SU) const { if (SU->isInstr()) return &SU->getInstr()->getDesc(); return getNodeDesc(SU->getNode()); } /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rendered /// using 'dot'. /// virtual void viewGraph(const Twine &Name, const Twine &Title); virtual void viewGraph(); virtual void dumpNode(const SUnit *SU) const = 0; /// getGraphNodeLabel - Return a label for an SUnit node in a visualization /// of the ScheduleDAG. virtual std::string getGraphNodeLabel(const SUnit *SU) const = 0; /// getDAGLabel - Return a label for the region of code covered by the DAG. virtual std::string getDAGName() const = 0; /// addCustomGraphFeatures - Add custom features for a visualization of /// the ScheduleDAG. virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const {} #ifndef NDEBUG /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that /// their state is consistent. Return the number of scheduled SUnits. unsigned VerifyScheduledDAG(bool isBottomUp); #endif private: // Return the MCInstrDesc of this SDNode or NULL. const MCInstrDesc *getNodeDesc(const SDNode *Node) const; }; class SUnitIterator { SUnit *Node; unsigned Operand; SUnitIterator(SUnit *N, unsigned Op) : Node(N), Operand(Op) {} public: using iterator_category = std::forward_iterator_tag; using value_type = SUnit; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; bool operator==(const SUnitIterator& x) const { return Operand == x.Operand; } bool operator!=(const SUnitIterator& x) const { return !operator==(x); } pointer operator*() const { return Node->Preds[Operand].getSUnit(); } pointer operator->() const { return operator*(); } SUnitIterator& operator++() { // Preincrement ++Operand; return *this; } SUnitIterator operator++(int) { // Postincrement SUnitIterator tmp = *this; ++*this; return tmp; } static SUnitIterator begin(SUnit *N) { return SUnitIterator(N, 0); } static SUnitIterator end (SUnit *N) { return SUnitIterator(N, (unsigned)N->Preds.size()); } unsigned getOperand() const { return Operand; } const SUnit *getNode() const { return Node; } /// isCtrlDep - Test if this is not an SDep::Data dependence. bool isCtrlDep() const { return getSDep().isCtrl(); } bool isArtificialDep() const { return getSDep().isArtificial(); } const SDep &getSDep() const { return Node->Preds[Operand]; } }; template <> struct GraphTraits<SUnit*> { typedef SUnit NodeType; typedef SUnitIterator ChildIteratorType; static inline NodeType *getEntryNode(SUnit *N) { return N; } static inline ChildIteratorType child_begin(NodeType *N) { return SUnitIterator::begin(N); } static inline ChildIteratorType child_end(NodeType *N) { return SUnitIterator::end(N); } }; template <> struct GraphTraits<ScheduleDAG*> : public GraphTraits<SUnit*> { typedef std::vector<SUnit>::iterator nodes_iterator; static nodes_iterator nodes_begin(ScheduleDAG *G) { return G->SUnits.begin(); } static nodes_iterator nodes_end(ScheduleDAG *G) { return G->SUnits.end(); } }; /// ScheduleDAGTopologicalSort is a class that computes a topological /// ordering for SUnits and provides methods for dynamically updating /// the ordering as new edges are added. /// /// This allows a very fast implementation of IsReachable, for example. /// class ScheduleDAGTopologicalSort { /// SUnits - A reference to the ScheduleDAG's SUnits. std::vector<SUnit> &SUnits; SUnit *ExitSU; /// Index2Node - Maps topological index to the node number. std::vector<int> Index2Node; /// Node2Index - Maps the node number to its topological index. std::vector<int> Node2Index; /// Visited - a set of nodes visited during a DFS traversal. BitVector Visited; /// DFS - make a DFS traversal and mark all nodes affected by the /// edge insertion. These nodes will later get new topological indexes /// by means of the Shift method. void DFS(const SUnit *SU, int UpperBound, bool& HasLoop); /// Shift - reassign topological indexes for the nodes in the DAG /// to preserve the topological ordering. void Shift(BitVector& Visited, int LowerBound, int UpperBound); /// Allocate - assign the topological index to the node n. void Allocate(int n, int index); public: ScheduleDAGTopologicalSort(std::vector<SUnit> &SUnits, SUnit *ExitSU); /// InitDAGTopologicalSorting - create the initial topological /// ordering from the DAG to be scheduled. void InitDAGTopologicalSorting(); /// IsReachable - Checks if SU is reachable from TargetSU. bool IsReachable(const SUnit *SU, const SUnit *TargetSU); /// WillCreateCycle - Return true if addPred(TargetSU, SU) creates a cycle. bool WillCreateCycle(SUnit *TargetSU, SUnit *SU); /// AddPred - Updates the topological ordering to accommodate an edge /// to be added from SUnit X to SUnit Y. void AddPred(SUnit *Y, SUnit *X); /// RemovePred - Updates the topological ordering to accommodate an /// an edge to be removed from the specified node N from the predecessors /// of the current node M. void RemovePred(SUnit *M, SUnit *N); typedef std::vector<int>::iterator iterator; typedef std::vector<int>::const_iterator const_iterator; iterator begin() { return Index2Node.begin(); } const_iterator begin() const { return Index2Node.begin(); } iterator end() { return Index2Node.end(); } const_iterator end() const { return Index2Node.end(); } typedef std::vector<int>::reverse_iterator reverse_iterator; typedef std::vector<int>::const_reverse_iterator const_reverse_iterator; reverse_iterator rbegin() { return Index2Node.rbegin(); } const_reverse_iterator rbegin() const { return Index2Node.rbegin(); } reverse_iterator rend() { return Index2Node.rend(); } const_reverse_iterator rend() const { return Index2Node.rend(); } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/ScoreboardHazardRecognizer.h
//=- llvm/CodeGen/ScoreboardHazardRecognizer.h - Schedule Support -*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ScoreboardHazardRecognizer class, which // encapsulates hazard-avoidance heuristics for scheduling, based on the // scheduling itineraries specified for the target. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H #define LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H #include "llvm/CodeGen/ScheduleHazardRecognizer.h" #include "llvm/Support/DataTypes.h" #include <cassert> #include <cstring> namespace llvm { class InstrItineraryData; class ScheduleDAG; class SUnit; class ScoreboardHazardRecognizer : public ScheduleHazardRecognizer { // Scoreboard to track function unit usage. Scoreboard[0] is a // mask of the FUs in use in the cycle currently being // schedule. Scoreboard[1] is a mask for the next cycle. The // Scoreboard is used as a circular buffer with the current cycle // indicated by Head. // // Scoreboard always counts cycles in forward execution order. If used by a // bottom-up scheduler, then the scoreboard cycles are the inverse of the // scheduler's cycles. class Scoreboard { unsigned *Data; // The maximum number of cycles monitored by the Scoreboard. This // value is determined based on the target itineraries to ensure // that all hazards can be tracked. size_t Depth; // Indices into the Scoreboard that represent the current cycle. size_t Head; public: Scoreboard():Data(nullptr), Depth(0), Head(0) { } ~Scoreboard() { delete[] Data; } size_t getDepth() const { return Depth; } unsigned& operator[](size_t idx) const { // Depth is expected to be a power-of-2. assert(Depth && !(Depth & (Depth - 1)) && "Scoreboard was not initialized properly!"); return Data[(Head + idx) & (Depth-1)]; } void reset(size_t d = 1) { if (!Data) { Depth = d; Data = new unsigned[Depth]; } memset(Data, 0, Depth * sizeof(Data[0])); Head = 0; } void advance() { Head = (Head + 1) & (Depth-1); } void recede() { Head = (Head - 1) & (Depth-1); } // Print the scoreboard. void dump() const; }; #ifndef NDEBUG // Support for tracing ScoreboardHazardRecognizer as a component within // another module. Follows the current thread-unsafe model of tracing. static const char *DebugType; #endif // Itinerary data for the target. const InstrItineraryData *ItinData; const ScheduleDAG *DAG; /// IssueWidth - Max issue per cycle. 0=Unknown. unsigned IssueWidth; /// IssueCount - Count instructions issued in this cycle. unsigned IssueCount; Scoreboard ReservedScoreboard; Scoreboard RequiredScoreboard; public: ScoreboardHazardRecognizer(const InstrItineraryData *ItinData, const ScheduleDAG *DAG, const char *ParentDebugType = ""); /// atIssueLimit - Return true if no more instructions may be issued in this /// cycle. bool atIssueLimit() const override; // Stalls provides an cycle offset at which SU will be scheduled. It will be // negative for bottom-up scheduling. HazardType getHazardType(SUnit *SU, int Stalls) override; void Reset() override; void EmitInstruction(SUnit *SU) override; void AdvanceCycle() override; void RecedeCycle() override; }; } #endif //!LLVM_CODEGEN_SCOREBOARDHAZARDRECOGNIZER_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/LiveStackAnalysis.h
//===-- LiveStackAnalysis.h - Live Stack Slot Analysis ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the live stack slot analysis pass. It is analogous to // live interval analysis except it's analyzing liveness of stack slots rather // than registers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_LIVESTACKANALYSIS_H #define LLVM_CODEGEN_LIVESTACKANALYSIS_H #include "llvm/CodeGen/LiveInterval.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/Support/Allocator.h" #include "llvm/Target/TargetRegisterInfo.h" #include <map> #include <unordered_map> namespace llvm { class LiveStacks : public MachineFunctionPass { const TargetRegisterInfo *TRI; /// Special pool allocator for VNInfo's (LiveInterval val#). /// VNInfo::Allocator VNInfoAllocator; /// S2IMap - Stack slot indices to live interval mapping. /// typedef std::unordered_map<int, LiveInterval> SS2IntervalMap; SS2IntervalMap S2IMap; /// S2RCMap - Stack slot indices to register class mapping. std::map<int, const TargetRegisterClass*> S2RCMap; public: static char ID; // Pass identification, replacement for typeid LiveStacks() : MachineFunctionPass(ID) { initializeLiveStacksPass(*PassRegistry::getPassRegistry()); } typedef SS2IntervalMap::iterator iterator; typedef SS2IntervalMap::const_iterator const_iterator; const_iterator begin() const { return S2IMap.begin(); } const_iterator end() const { return S2IMap.end(); } iterator begin() { return S2IMap.begin(); } iterator end() { return S2IMap.end(); } unsigned getNumIntervals() const { return (unsigned)S2IMap.size(); } LiveInterval &getOrCreateInterval(int Slot, const TargetRegisterClass *RC); LiveInterval &getInterval(int Slot) { assert(Slot >= 0 && "Spill slot indice must be >= 0"); SS2IntervalMap::iterator I = S2IMap.find(Slot); assert(I != S2IMap.end() && "Interval does not exist for stack slot"); return I->second; } const LiveInterval &getInterval(int Slot) const { assert(Slot >= 0 && "Spill slot indice must be >= 0"); SS2IntervalMap::const_iterator I = S2IMap.find(Slot); assert(I != S2IMap.end() && "Interval does not exist for stack slot"); return I->second; } bool hasInterval(int Slot) const { return S2IMap.count(Slot); } const TargetRegisterClass *getIntervalRegClass(int Slot) const { assert(Slot >= 0 && "Spill slot indice must be >= 0"); std::map<int, const TargetRegisterClass*>::const_iterator I = S2RCMap.find(Slot); assert(I != S2RCMap.end() && "Register class info does not exist for stack slot"); return I->second; } VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; } void getAnalysisUsage(AnalysisUsage &AU) const override; void releaseMemory() override; /// runOnMachineFunction - pass entry point bool runOnMachineFunction(MachineFunction&) override; /// print - Implement the dump method. void print(raw_ostream &O, const Module* = nullptr) const override; }; } #endif /* LLVM_CODEGEN_LIVESTACK_ANALYSIS_H */
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/CodeGen/CommandFlags.h
//===-- CommandFlags.h - Command Line Flags Interface -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains codegen-specific flags that are shared between different // command line tools. The tools "llc" and "opt" both use this file to prevent // flag duplication. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_COMMANDFLAGS_H #define LLVM_CODEGEN_COMMANDFLAGS_H #include "llvm/ADT/StringExtras.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCTargetOptionsCommandFlags.h" #include "llvm//MC/SubtargetFeature.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Host.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRecip.h" #include <string> using namespace llvm; cl::opt<std::string> MArch("march", cl::desc("Architecture to generate code for (see --version)")); cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<Reloc::Model> RelocModel("relocation-model", cl::desc("Choose relocation model"), cl::init(Reloc::Default), cl::values( clEnumValN(Reloc::Default, "default", "Target default relocation model"), clEnumValN(Reloc::Static, "static", "Non-relocatable code"), clEnumValN(Reloc::PIC_, "pic", "Fully relocatable, position independent code"), clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", "Relocatable external references, non-relocatable code"), clEnumValEnd)); cl::opt<ThreadModel::Model> TMModel("thread-model", cl::desc("Choose threading model"), cl::init(ThreadModel::POSIX), cl::values(clEnumValN(ThreadModel::POSIX, "posix", "POSIX thread model"), clEnumValN(ThreadModel::Single, "single", "Single thread model"), clEnumValEnd)); cl::opt<llvm::CodeModel::Model> CMModel("code-model", cl::desc("Choose code model"), cl::init(CodeModel::Default), cl::values(clEnumValN(CodeModel::Default, "default", "Target default code model"), clEnumValN(CodeModel::Small, "small", "Small code model"), clEnumValN(CodeModel::Kernel, "kernel", "Kernel code model"), clEnumValN(CodeModel::Medium, "medium", "Medium code model"), clEnumValN(CodeModel::Large, "large", "Large code model"), clEnumValEnd)); cl::opt<TargetMachine::CodeGenFileType> FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values( clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"), clEnumValN(TargetMachine::CGFT_ObjectFile, "obj", "Emit a native object ('.o') file"), clEnumValN(TargetMachine::CGFT_Null, "null", "Emit nothing, for performance testing"), clEnumValEnd)); cl::opt<bool> EnableFPMAD("enable-fp-mad", cl::desc("Enable less precise MAD instructions to be generated"), cl::init(false)); cl::opt<bool> DisableFPElim("disable-fp-elim", cl::desc("Disable frame pointer elimination optimization"), cl::init(false)); cl::opt<bool> EnableUnsafeFPMath("enable-unsafe-fp-math", cl::desc("Enable optimizations that may decrease FP precision"), cl::init(false)); cl::opt<bool> EnableNoInfsFPMath("enable-no-infs-fp-math", cl::desc("Enable FP math optimizations that assume no +-Infs"), cl::init(false)); cl::opt<bool> EnableNoNaNsFPMath("enable-no-nans-fp-math", cl::desc("Enable FP math optimizations that assume no NaNs"), cl::init(false)); cl::opt<bool> EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math", cl::Hidden, cl::desc("Force codegen to assume rounding mode can change dynamically"), cl::init(false)); cl::opt<llvm::FloatABI::ABIType> FloatABIForCalls("float-abi", cl::desc("Choose float ABI type"), cl::init(FloatABI::Default), cl::values( clEnumValN(FloatABI::Default, "default", "Target default float ABI type"), clEnumValN(FloatABI::Soft, "soft", "Soft float ABI (implied by -soft-float)"), clEnumValN(FloatABI::Hard, "hard", "Hard float ABI (uses FP registers)"), clEnumValEnd)); cl::opt<llvm::FPOpFusion::FPOpFusionMode> FuseFPOps("fp-contract", cl::desc("Enable aggressive formation of fused FP ops"), cl::init(FPOpFusion::Standard), cl::values( clEnumValN(FPOpFusion::Fast, "fast", "Fuse FP ops whenever profitable"), clEnumValN(FPOpFusion::Standard, "on", "Only fuse 'blessed' FP ops."), clEnumValN(FPOpFusion::Strict, "off", "Only fuse FP ops when the result won't be affected."), clEnumValEnd)); cl::list<std::string> ReciprocalOps("recip", cl::CommaSeparated, cl::desc("Choose reciprocal operation types and parameters."), cl::value_desc("all,none,default,divf,!vec-sqrtd,vec-divd:0,sqrt:9...")); cl::opt<bool> DontPlaceZerosInBSS("nozero-initialized-in-bss", cl::desc("Don't place zero-initialized symbols into bss section"), cl::init(false)); cl::opt<bool> EnableGuaranteedTailCallOpt("tailcallopt", cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."), cl::init(false)); cl::opt<bool> DisableTailCalls("disable-tail-calls", cl::desc("Never emit tail calls"), cl::init(false)); cl::opt<unsigned> OverrideStackAlignment("stack-alignment", cl::desc("Override default stack alignment"), cl::init(0)); cl::opt<std::string> TrapFuncName("trap-func", cl::Hidden, cl::desc("Emit a call to trap function rather than a trap instruction"), cl::init("")); cl::opt<bool> EnablePIE("enable-pie", cl::desc("Assume the creation of a position independent executable."), cl::init(false)); cl::opt<bool> UseCtors("use-ctors", cl::desc("Use .ctors instead of .init_array."), cl::init(false)); cl::opt<std::string> StopAfter("stop-after", cl::desc("Stop compilation after a specific pass"), cl::value_desc("pass-name"), cl::init("")); cl::opt<std::string> StartAfter("start-after", cl::desc("Resume compilation after a specific pass"), cl::value_desc("pass-name"), cl::init("")); cl::opt<std::string> RunPass("run-pass", cl::desc("Run compiler only for one specific pass"), cl::value_desc("pass-name"), cl::init("")); cl::opt<bool> DataSections("data-sections", cl::desc("Emit data into separate sections"), cl::init(false)); cl::opt<bool> FunctionSections("function-sections", cl::desc("Emit functions into separate sections"), cl::init(false)); cl::opt<bool> UniqueSectionNames("unique-section-names", cl::desc("Give unique names to every section"), cl::init(true)); cl::opt<llvm::JumpTable::JumpTableType> JTableType("jump-table-type", cl::desc("Choose the type of Jump-Instruction Table for jumptable."), cl::init(JumpTable::Single), cl::values( clEnumValN(JumpTable::Single, "single", "Create a single table for all jumptable functions"), clEnumValN(JumpTable::Arity, "arity", "Create one table per number of parameters."), clEnumValN(JumpTable::Simplified, "simplified", "Create one table per simplified function type."), clEnumValN(JumpTable::Full, "full", "Create one table per unique function type."), clEnumValEnd)); // Common utility function tightly tied to the options listed here. Initializes // a TargetOptions object with CodeGen flags and returns it. static inline TargetOptions InitTargetOptionsFromCodeGenFlags() { TargetOptions Options; Options.LessPreciseFPMADOption = EnableFPMAD; Options.AllowFPOpFusion = FuseFPOps; Options.Reciprocals = TargetRecip(ReciprocalOps); Options.UnsafeFPMath = EnableUnsafeFPMath; Options.NoInfsFPMath = EnableNoInfsFPMath; Options.NoNaNsFPMath = EnableNoNaNsFPMath; Options.HonorSignDependentRoundingFPMathOption = EnableHonorSignDependentRoundingFPMath; if (FloatABIForCalls != FloatABI::Default) Options.FloatABIType = FloatABIForCalls; Options.NoZerosInBSS = DontPlaceZerosInBSS; Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt; Options.StackAlignmentOverride = OverrideStackAlignment; Options.PositionIndependentExecutable = EnablePIE; Options.UseInitArray = !UseCtors; Options.DataSections = DataSections; Options.FunctionSections = FunctionSections; Options.UniqueSectionNames = UniqueSectionNames; Options.MCOptions = InitMCTargetOptionsFromFlags(); Options.JTType = JTableType; Options.ThreadModel = TMModel; return Options; } static inline std::string getCPUStr() { // If user asked for the 'native' CPU, autodetect here. If autodection fails, // this will set the CPU to an empty string which tells the target to // pick a basic default. if (MCPU == "native") return sys::getHostCPUName(); return MCPU; } static inline std::string getFeaturesStr() { #if 1 // HLSL Change Starts return std::string(); #else // HLSL Change Ends SubtargetFeatures Features; // If user asked for the 'native' CPU, we need to autodetect features. // This is necessary for x86 where the CPU might not support all the // features the autodetected CPU name lists in the target. For example, // not all Sandybridge processors support AVX. if (MCPU == "native") { StringMap<bool> HostFeatures; if (sys::getHostCPUFeatures(HostFeatures)) for (auto &F : HostFeatures) Features.AddFeature(F.first(), F.second); } for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); return Features.getString(); #endif // HLSL Change - no target/subtarget features } /// \brief Set function attributes of functions in Module M based on CPU, /// Features, and command line flags. static inline void setFunctionAttributes(StringRef CPU, StringRef Features, Module &M) { for (auto &F : M) { auto &Ctx = F.getContext(); AttributeSet Attrs = F.getAttributes(), NewAttrs; if (!CPU.empty()) NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, "target-cpu", CPU); if (!Features.empty()) NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, "target-features", Features); if (DisableFPElim.getNumOccurrences() > 0) NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, "no-frame-pointer-elim", DisableFPElim ? "true" : "false"); if (DisableTailCalls.getNumOccurrences() > 0) NewAttrs = NewAttrs.addAttribute(Ctx, AttributeSet::FunctionIndex, "disable-tail-calls", toStringRef(DisableTailCalls)); if (TrapFuncName.getNumOccurrences() > 0) for (auto &B : F) for (auto &I : B) if (auto *Call = dyn_cast<CallInst>(&I)) if (const auto *F = Call->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::debugtrap || F->getIntrinsicID() == Intrinsic::trap) Call->addAttribute(llvm::AttributeSet::FunctionIndex, "trap-func-name", TrapFuncName); // Let NewAttrs override Attrs. NewAttrs = Attrs.addAttributes(Ctx, AttributeSet::FunctionIndex, NewAttrs); F.setAttributes(NewAttrs); } } #endif
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/PBQP/Solution.h
//===-- Solution.h ------- PBQP Solution ------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // PBQP Solution class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PBQP_SOLUTION_H #define LLVM_CODEGEN_PBQP_SOLUTION_H #include "Graph.h" #include "Math.h" #include <map> namespace llvm { namespace PBQP { /// \brief Represents a solution to a PBQP problem. /// /// To get the selection for each node in the problem use the getSelection method. class Solution { private: typedef std::map<GraphBase::NodeId, unsigned> SelectionsMap; SelectionsMap selections; unsigned r0Reductions, r1Reductions, r2Reductions, rNReductions; public: /// \brief Initialise an empty solution. Solution() : r0Reductions(0), r1Reductions(0), r2Reductions(0), rNReductions(0) {} /// \brief Number of nodes for which selections have been made. /// @return Number of nodes for which selections have been made. unsigned numNodes() const { return selections.size(); } /// \brief Records a reduction via the R0 rule. Should be called from the /// solver only. void recordR0() { ++r0Reductions; } /// \brief Returns the number of R0 reductions applied to solve the problem. unsigned numR0Reductions() const { return r0Reductions; } /// \brief Records a reduction via the R1 rule. Should be called from the /// solver only. void recordR1() { ++r1Reductions; } /// \brief Returns the number of R1 reductions applied to solve the problem. unsigned numR1Reductions() const { return r1Reductions; } /// \brief Records a reduction via the R2 rule. Should be called from the /// solver only. void recordR2() { ++r2Reductions; } /// \brief Returns the number of R2 reductions applied to solve the problem. unsigned numR2Reductions() const { return r2Reductions; } /// \brief Records a reduction via the RN rule. Should be called from the /// solver only. void recordRN() { ++ rNReductions; } /// \brief Returns the number of RN reductions applied to solve the problem. unsigned numRNReductions() const { return rNReductions; } /// \brief Set the selection for a given node. /// @param nodeId Node id. /// @param selection Selection for nodeId. void setSelection(GraphBase::NodeId nodeId, unsigned selection) { selections[nodeId] = selection; } /// \brief Get a node's selection. /// @param nodeId Node id. /// @return The selection for nodeId; unsigned getSelection(GraphBase::NodeId nodeId) const { SelectionsMap::const_iterator sItr = selections.find(nodeId); assert(sItr != selections.end() && "No selection for node."); return sItr->second; } }; } // namespace PBQP } // namespace llvm #endif // LLVM_CODEGEN_PBQP_SOLUTION_H
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/PBQP/ReductionRules.h
//===----------- ReductionRules.h - Reduction Rules -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Reduction Rules. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PBQP_REDUCTIONRULES_H #define LLVM_CODEGEN_PBQP_REDUCTIONRULES_H #include "Graph.h" #include "Math.h" #include "Solution.h" namespace llvm { namespace PBQP { /// \brief Reduce a node of degree one. /// /// Propagate costs from the given node, which must be of degree one, to its /// neighbor. Notify the problem domain. template <typename GraphT> void applyR1(GraphT &G, typename GraphT::NodeId NId) { typedef typename GraphT::NodeId NodeId; typedef typename GraphT::EdgeId EdgeId; typedef typename GraphT::Vector Vector; typedef typename GraphT::Matrix Matrix; typedef typename GraphT::RawVector RawVector; assert(G.getNodeDegree(NId) == 1 && "R1 applied to node with degree != 1."); EdgeId EId = *G.adjEdgeIds(NId).begin(); NodeId MId = G.getEdgeOtherNodeId(EId, NId); const Matrix &ECosts = G.getEdgeCosts(EId); const Vector &XCosts = G.getNodeCosts(NId); RawVector YCosts = G.getNodeCosts(MId); // Duplicate a little to avoid transposing matrices. if (NId == G.getEdgeNode1Id(EId)) { for (unsigned j = 0; j < YCosts.getLength(); ++j) { PBQPNum Min = ECosts[0][j] + XCosts[0]; for (unsigned i = 1; i < XCosts.getLength(); ++i) { PBQPNum C = ECosts[i][j] + XCosts[i]; if (C < Min) Min = C; } YCosts[j] += Min; } } else { for (unsigned i = 0; i < YCosts.getLength(); ++i) { PBQPNum Min = ECosts[i][0] + XCosts[0]; for (unsigned j = 1; j < XCosts.getLength(); ++j) { PBQPNum C = ECosts[i][j] + XCosts[j]; if (C < Min) Min = C; } YCosts[i] += Min; } } G.setNodeCosts(MId, YCosts); G.disconnectEdge(EId, MId); } template <typename GraphT> void applyR2(GraphT &G, typename GraphT::NodeId NId) { typedef typename GraphT::NodeId NodeId; typedef typename GraphT::EdgeId EdgeId; typedef typename GraphT::Vector Vector; typedef typename GraphT::Matrix Matrix; typedef typename GraphT::RawMatrix RawMatrix; assert(G.getNodeDegree(NId) == 2 && "R2 applied to node with degree != 2."); const Vector &XCosts = G.getNodeCosts(NId); typename GraphT::AdjEdgeItr AEItr = G.adjEdgeIds(NId).begin(); EdgeId YXEId = *AEItr, ZXEId = *(++AEItr); NodeId YNId = G.getEdgeOtherNodeId(YXEId, NId), ZNId = G.getEdgeOtherNodeId(ZXEId, NId); bool FlipEdge1 = (G.getEdgeNode1Id(YXEId) == NId), FlipEdge2 = (G.getEdgeNode1Id(ZXEId) == NId); const Matrix *YXECosts = FlipEdge1 ? new Matrix(G.getEdgeCosts(YXEId).transpose()) : &G.getEdgeCosts(YXEId); const Matrix *ZXECosts = FlipEdge2 ? new Matrix(G.getEdgeCosts(ZXEId).transpose()) : &G.getEdgeCosts(ZXEId); unsigned XLen = XCosts.getLength(), YLen = YXECosts->getRows(), ZLen = ZXECosts->getRows(); RawMatrix Delta(YLen, ZLen); for (unsigned i = 0; i < YLen; ++i) { for (unsigned j = 0; j < ZLen; ++j) { PBQPNum Min = (*YXECosts)[i][0] + (*ZXECosts)[j][0] + XCosts[0]; for (unsigned k = 1; k < XLen; ++k) { PBQPNum C = (*YXECosts)[i][k] + (*ZXECosts)[j][k] + XCosts[k]; if (C < Min) { Min = C; } } Delta[i][j] = Min; } } if (FlipEdge1) delete YXECosts; if (FlipEdge2) delete ZXECosts; EdgeId YZEId = G.findEdge(YNId, ZNId); if (YZEId == G.invalidEdgeId()) { YZEId = G.addEdge(YNId, ZNId, Delta); } else { const Matrix &YZECosts = G.getEdgeCosts(YZEId); if (YNId == G.getEdgeNode1Id(YZEId)) { G.updateEdgeCosts(YZEId, Delta + YZECosts); } else { G.updateEdgeCosts(YZEId, Delta.transpose() + YZECosts); } } G.disconnectEdge(YXEId, YNId); G.disconnectEdge(ZXEId, ZNId); // TODO: Try to normalize newly added/modified edge. } #ifndef NDEBUG // Does this Cost vector have any register options ? template <typename VectorT> bool hasRegisterOptions(const VectorT &V) { unsigned VL = V.getLength(); // An empty or spill only cost vector does not provide any register option. if (VL <= 1) return false; // If there are registers in the cost vector, but all of them have infinite // costs, then ... there is no available register. for (unsigned i = 1; i < VL; ++i) if (V[i] != std::numeric_limits<PBQP::PBQPNum>::infinity()) return true; return false; } #endif // \brief Find a solution to a fully reduced graph by backpropagation. // // Given a graph and a reduction order, pop each node from the reduction // order and greedily compute a minimum solution based on the node costs, and // the dependent costs due to previously solved nodes. // // Note - This does not return the graph to its original (pre-reduction) // state: the existing solvers destructively alter the node and edge // costs. Given that, the backpropagate function doesn't attempt to // replace the edges either, but leaves the graph in its reduced // state. template <typename GraphT, typename StackT> Solution backpropagate(GraphT& G, StackT stack) { typedef GraphBase::NodeId NodeId; typedef typename GraphT::Matrix Matrix; typedef typename GraphT::RawVector RawVector; Solution s; while (!stack.empty()) { NodeId NId = stack.back(); stack.pop_back(); RawVector v = G.getNodeCosts(NId); #ifndef NDEBUG // Although a conservatively allocatable node can be allocated to a register, // spilling it may provide a lower cost solution. Assert here that spilling // is done by choice, not because there were no register available. if (G.getNodeMetadata(NId).wasConservativelyAllocatable()) assert(hasRegisterOptions(v) && "A conservatively allocatable node " "must have available register options"); #endif for (auto EId : G.adjEdgeIds(NId)) { const Matrix& edgeCosts = G.getEdgeCosts(EId); if (NId == G.getEdgeNode1Id(EId)) { NodeId mId = G.getEdgeNode2Id(EId); v += edgeCosts.getColAsVector(s.getSelection(mId)); } else { NodeId mId = G.getEdgeNode1Id(EId); v += edgeCosts.getRowAsVector(s.getSelection(mId)); } } s.setSelection(NId, v.minIndex()); } return s; } } // namespace PBQP } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/PBQP/Math.h
//===------ Math.h - PBQP Vector and Matrix classes -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PBQP_MATH_H #define LLVM_CODEGEN_PBQP_MATH_H #include "llvm/ADT/Hashing.h" #include <algorithm> #include <cassert> #include <functional> namespace llvm { namespace PBQP { typedef float PBQPNum; /// \brief PBQP Vector class. class Vector { friend hash_code hash_value(const Vector &); public: /// \brief Construct a PBQP vector of the given size. explicit Vector(unsigned Length) : Length(Length), Data(new PBQPNum[Length]) { // llvm::dbgs() << "Constructing PBQP::Vector " // << this << " (length " << Length << ")\n"; } /// \brief Construct a PBQP vector with initializer. Vector(unsigned Length, PBQPNum InitVal) : Length(Length), Data(new PBQPNum[Length]) { // llvm::dbgs() << "Constructing PBQP::Vector " // << this << " (length " << Length << ", fill " // << InitVal << ")\n"; std::fill(Data, Data + Length, InitVal); } /// \brief Copy construct a PBQP vector. Vector(const Vector &V) : Length(V.Length), Data(new PBQPNum[Length]) { // llvm::dbgs() << "Copy-constructing PBQP::Vector " << this // << " from PBQP::Vector " << &V << "\n"; std::copy(V.Data, V.Data + Length, Data); } /// \brief Move construct a PBQP vector. Vector(Vector &&V) : Length(V.Length), Data(V.Data) { V.Length = 0; V.Data = nullptr; } /// \brief Destroy this vector, return its memory. ~Vector() { // llvm::dbgs() << "Deleting PBQP::Vector " << this << "\n"; delete[] Data; } /// \brief Copy-assignment operator. Vector& operator=(const Vector &V) { // llvm::dbgs() << "Assigning to PBQP::Vector " << this // << " from PBQP::Vector " << &V << "\n"; delete[] Data; Length = V.Length; Data = new PBQPNum[Length]; std::copy(V.Data, V.Data + Length, Data); return *this; } /// \brief Move-assignment operator. Vector& operator=(Vector &&V) { delete[] Data; Length = V.Length; Data = V.Data; V.Length = 0; V.Data = nullptr; return *this; } /// \brief Comparison operator. bool operator==(const Vector &V) const { assert(Length != 0 && Data != nullptr && "Invalid vector"); if (Length != V.Length) return false; return std::equal(Data, Data + Length, V.Data); } /// \brief Return the length of the vector unsigned getLength() const { assert(Length != 0 && Data != nullptr && "Invalid vector"); return Length; } /// \brief Element access. PBQPNum& operator[](unsigned Index) { assert(Length != 0 && Data != nullptr && "Invalid vector"); assert(Index < Length && "Vector element access out of bounds."); return Data[Index]; } /// \brief Const element access. const PBQPNum& operator[](unsigned Index) const { assert(Length != 0 && Data != nullptr && "Invalid vector"); assert(Index < Length && "Vector element access out of bounds."); return Data[Index]; } /// \brief Add another vector to this one. Vector& operator+=(const Vector &V) { assert(Length != 0 && Data != nullptr && "Invalid vector"); assert(Length == V.Length && "Vector length mismatch."); std::transform(Data, Data + Length, V.Data, Data, std::plus<PBQPNum>()); return *this; } /// \brief Subtract another vector from this one. Vector& operator-=(const Vector &V) { assert(Length != 0 && Data != nullptr && "Invalid vector"); assert(Length == V.Length && "Vector length mismatch."); std::transform(Data, Data + Length, V.Data, Data, std::minus<PBQPNum>()); return *this; } /// \brief Returns the index of the minimum value in this vector unsigned minIndex() const { assert(Length != 0 && Data != nullptr && "Invalid vector"); return std::min_element(Data, Data + Length) - Data; } private: unsigned Length; PBQPNum *Data; }; /// \brief Return a hash_value for the given vector. inline hash_code hash_value(const Vector &V) { unsigned *VBegin = reinterpret_cast<unsigned*>(V.Data); unsigned *VEnd = reinterpret_cast<unsigned*>(V.Data + V.Length); return hash_combine(V.Length, hash_combine_range(VBegin, VEnd)); } /// \brief Output a textual representation of the given vector on the given /// output stream. template <typename OStream> OStream& operator<<(OStream &OS, const Vector &V) { assert((V.getLength() != 0) && "Zero-length vector badness."); OS << "[ " << V[0]; for (unsigned i = 1; i < V.getLength(); ++i) OS << ", " << V[i]; OS << " ]"; return OS; } /// \brief PBQP Matrix class class Matrix { private: friend hash_code hash_value(const Matrix &); public: /// \brief Construct a PBQP Matrix with the given dimensions. Matrix(unsigned Rows, unsigned Cols) : Rows(Rows), Cols(Cols), Data(new PBQPNum[Rows * Cols]) { } /// \brief Construct a PBQP Matrix with the given dimensions and initial /// value. Matrix(unsigned Rows, unsigned Cols, PBQPNum InitVal) : Rows(Rows), Cols(Cols), Data(new PBQPNum[Rows * Cols]) { std::fill(Data, Data + (Rows * Cols), InitVal); } /// \brief Copy construct a PBQP matrix. Matrix(const Matrix &M) : Rows(M.Rows), Cols(M.Cols), Data(new PBQPNum[Rows * Cols]) { std::copy(M.Data, M.Data + (Rows * Cols), Data); } /// \brief Move construct a PBQP matrix. Matrix(Matrix &&M) : Rows(M.Rows), Cols(M.Cols), Data(M.Data) { M.Rows = M.Cols = 0; M.Data = nullptr; } /// \brief Destroy this matrix, return its memory. ~Matrix() { delete[] Data; } /// \brief Copy-assignment operator. Matrix& operator=(const Matrix &M) { delete[] Data; Rows = M.Rows; Cols = M.Cols; Data = new PBQPNum[Rows * Cols]; std::copy(M.Data, M.Data + (Rows * Cols), Data); return *this; } /// \brief Move-assignment operator. Matrix& operator=(Matrix &&M) { delete[] Data; Rows = M.Rows; Cols = M.Cols; Data = M.Data; M.Rows = M.Cols = 0; M.Data = nullptr; return *this; } /// \brief Comparison operator. bool operator==(const Matrix &M) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); if (Rows != M.Rows || Cols != M.Cols) return false; return std::equal(Data, Data + (Rows * Cols), M.Data); } /// \brief Return the number of rows in this matrix. unsigned getRows() const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); return Rows; } /// \brief Return the number of cols in this matrix. unsigned getCols() const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); return Cols; } /// \brief Matrix element access. PBQPNum* operator[](unsigned R) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(R < Rows && "Row out of bounds."); return Data + (R * Cols); } /// \brief Matrix element access. const PBQPNum* operator[](unsigned R) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(R < Rows && "Row out of bounds."); return Data + (R * Cols); } /// \brief Returns the given row as a vector. Vector getRowAsVector(unsigned R) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); Vector V(Cols); for (unsigned C = 0; C < Cols; ++C) V[C] = (*this)[R][C]; return V; } /// \brief Returns the given column as a vector. Vector getColAsVector(unsigned C) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); Vector V(Rows); for (unsigned R = 0; R < Rows; ++R) V[R] = (*this)[R][C]; return V; } /// \brief Reset the matrix to the given value. Matrix& reset(PBQPNum Val = 0) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); std::fill(Data, Data + (Rows * Cols), Val); return *this; } /// \brief Set a single row of this matrix to the given value. Matrix& setRow(unsigned R, PBQPNum Val) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(R < Rows && "Row out of bounds."); std::fill(Data + (R * Cols), Data + ((R + 1) * Cols), Val); return *this; } /// \brief Set a single column of this matrix to the given value. Matrix& setCol(unsigned C, PBQPNum Val) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(C < Cols && "Column out of bounds."); for (unsigned R = 0; R < Rows; ++R) (*this)[R][C] = Val; return *this; } /// \brief Matrix transpose. Matrix transpose() const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); Matrix M(Cols, Rows); for (unsigned r = 0; r < Rows; ++r) for (unsigned c = 0; c < Cols; ++c) M[c][r] = (*this)[r][c]; return M; } /// \brief Returns the diagonal of the matrix as a vector. /// /// Matrix must be square. Vector diagonalize() const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(Rows == Cols && "Attempt to diagonalize non-square matrix."); Vector V(Rows); for (unsigned r = 0; r < Rows; ++r) V[r] = (*this)[r][r]; return V; } /// \brief Add the given matrix to this one. Matrix& operator+=(const Matrix &M) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(Rows == M.Rows && Cols == M.Cols && "Matrix dimensions mismatch."); std::transform(Data, Data + (Rows * Cols), M.Data, Data, std::plus<PBQPNum>()); return *this; } Matrix operator+(const Matrix &M) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); Matrix Tmp(*this); Tmp += M; return Tmp; } /// \brief Returns the minimum of the given row PBQPNum getRowMin(unsigned R) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(R < Rows && "Row out of bounds"); return *std::min_element(Data + (R * Cols), Data + ((R + 1) * Cols)); } /// \brief Returns the minimum of the given column PBQPNum getColMin(unsigned C) const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); PBQPNum MinElem = (*this)[0][C]; for (unsigned R = 1; R < Rows; ++R) if ((*this)[R][C] < MinElem) MinElem = (*this)[R][C]; return MinElem; } /// \brief Subtracts the given scalar from the elements of the given row. Matrix& subFromRow(unsigned R, PBQPNum Val) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); assert(R < Rows && "Row out of bounds"); std::transform(Data + (R * Cols), Data + ((R + 1) * Cols), Data + (R * Cols), std::bind2nd(std::minus<PBQPNum>(), Val)); return *this; } /// \brief Subtracts the given scalar from the elements of the given column. Matrix& subFromCol(unsigned C, PBQPNum Val) { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); for (unsigned R = 0; R < Rows; ++R) (*this)[R][C] -= Val; return *this; } /// \brief Returns true if this is a zero matrix. bool isZero() const { assert(Rows != 0 && Cols != 0 && Data != nullptr && "Invalid matrix"); return find_if(Data, Data + (Rows * Cols), std::bind2nd(std::not_equal_to<PBQPNum>(), 0)) == Data + (Rows * Cols); } private: unsigned Rows, Cols; PBQPNum *Data; }; /// \brief Return a hash_code for the given matrix. inline hash_code hash_value(const Matrix &M) { unsigned *MBegin = reinterpret_cast<unsigned*>(M.Data); unsigned *MEnd = reinterpret_cast<unsigned*>(M.Data + (M.Rows * M.Cols)); return hash_combine(M.Rows, M.Cols, hash_combine_range(MBegin, MEnd)); } /// \brief Output a textual representation of the given matrix on the given /// output stream. template <typename OStream> OStream& operator<<(OStream &OS, const Matrix &M) { assert((M.getRows() != 0) && "Zero-row matrix badness."); for (unsigned i = 0; i < M.getRows(); ++i) OS << M.getRowAsVector(i) << "\n"; return OS; } template <typename Metadata> class MDVector : public Vector { public: MDVector(const Vector &v) : Vector(v), md(*this) { } MDVector(Vector &&v) : Vector(std::move(v)), md(*this) { } const Metadata& getMetadata() const { return md; } private: Metadata md; }; template <typename Metadata> inline hash_code hash_value(const MDVector<Metadata> &V) { return hash_value(static_cast<const Vector&>(V)); } template <typename Metadata> class MDMatrix : public Matrix { public: MDMatrix(const Matrix &m) : Matrix(m), md(*this) { } MDMatrix(Matrix &&m) : Matrix(std::move(m)), md(*this) { } const Metadata& getMetadata() const { return md; } private: Metadata md; }; template <typename Metadata> inline hash_code hash_value(const MDMatrix<Metadata> &M) { return hash_value(static_cast<const Matrix&>(M)); } } // namespace PBQP } // namespace llvm #endif // LLVM_CODEGEN_PBQP_MATH_H
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/PBQP/Graph.h
//===-------------------- Graph.h - PBQP Graph ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // PBQP Graph class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PBQP_GRAPH_H #define LLVM_CODEGEN_PBQP_GRAPH_H #include "llvm/ADT/ilist.h" #include "llvm/ADT/ilist_node.h" #include "llvm/Support/Debug.h" #include <list> #include <map> #include <set> #include <vector> namespace llvm { namespace PBQP { class GraphBase { public: typedef unsigned NodeId; typedef unsigned EdgeId; /// @brief Returns a value representing an invalid (non-existent) node. static NodeId invalidNodeId() { return std::numeric_limits<NodeId>::max(); } /// @brief Returns a value representing an invalid (non-existent) edge. static EdgeId invalidEdgeId() { return std::numeric_limits<EdgeId>::max(); } }; /// PBQP Graph class. /// Instances of this class describe PBQP problems. /// template <typename SolverT> class Graph : public GraphBase { private: typedef typename SolverT::CostAllocator CostAllocator; public: typedef typename SolverT::RawVector RawVector; typedef typename SolverT::RawMatrix RawMatrix; typedef typename SolverT::Vector Vector; typedef typename SolverT::Matrix Matrix; typedef typename CostAllocator::VectorPtr VectorPtr; typedef typename CostAllocator::MatrixPtr MatrixPtr; typedef typename SolverT::NodeMetadata NodeMetadata; typedef typename SolverT::EdgeMetadata EdgeMetadata; typedef typename SolverT::GraphMetadata GraphMetadata; private: class NodeEntry { public: typedef std::vector<EdgeId> AdjEdgeList; typedef AdjEdgeList::size_type AdjEdgeIdx; typedef AdjEdgeList::const_iterator AdjEdgeItr; static AdjEdgeIdx getInvalidAdjEdgeIdx() { return std::numeric_limits<AdjEdgeIdx>::max(); } NodeEntry(VectorPtr Costs) : Costs(Costs) {} AdjEdgeIdx addAdjEdgeId(EdgeId EId) { AdjEdgeIdx Idx = AdjEdgeIds.size(); AdjEdgeIds.push_back(EId); return Idx; } void removeAdjEdgeId(Graph &G, NodeId ThisNId, AdjEdgeIdx Idx) { // Swap-and-pop for fast removal. // 1) Update the adj index of the edge currently at back(). // 2) Move last Edge down to Idx. // 3) pop_back() // If Idx == size() - 1 then the setAdjEdgeIdx and swap are // redundant, but both operations are cheap. G.getEdge(AdjEdgeIds.back()).setAdjEdgeIdx(ThisNId, Idx); AdjEdgeIds[Idx] = AdjEdgeIds.back(); AdjEdgeIds.pop_back(); } const AdjEdgeList& getAdjEdgeIds() const { return AdjEdgeIds; } VectorPtr Costs; NodeMetadata Metadata; private: AdjEdgeList AdjEdgeIds; }; class EdgeEntry { public: EdgeEntry(NodeId N1Id, NodeId N2Id, MatrixPtr Costs) : Costs(Costs) { NIds[0] = N1Id; NIds[1] = N2Id; ThisEdgeAdjIdxs[0] = NodeEntry::getInvalidAdjEdgeIdx(); ThisEdgeAdjIdxs[1] = NodeEntry::getInvalidAdjEdgeIdx(); } void invalidate() { NIds[0] = NIds[1] = Graph::invalidNodeId(); ThisEdgeAdjIdxs[0] = ThisEdgeAdjIdxs[1] = NodeEntry::getInvalidAdjEdgeIdx(); Costs = nullptr; } void connectToN(Graph &G, EdgeId ThisEdgeId, unsigned NIdx) { assert(ThisEdgeAdjIdxs[NIdx] == NodeEntry::getInvalidAdjEdgeIdx() && "Edge already connected to NIds[NIdx]."); NodeEntry &N = G.getNode(NIds[NIdx]); ThisEdgeAdjIdxs[NIdx] = N.addAdjEdgeId(ThisEdgeId); } void connectTo(Graph &G, EdgeId ThisEdgeId, NodeId NId) { if (NId == NIds[0]) connectToN(G, ThisEdgeId, 0); else { assert(NId == NIds[1] && "Edge does not connect NId."); connectToN(G, ThisEdgeId, 1); } } void connect(Graph &G, EdgeId ThisEdgeId) { connectToN(G, ThisEdgeId, 0); connectToN(G, ThisEdgeId, 1); } void setAdjEdgeIdx(NodeId NId, typename NodeEntry::AdjEdgeIdx NewIdx) { if (NId == NIds[0]) ThisEdgeAdjIdxs[0] = NewIdx; else { assert(NId == NIds[1] && "Edge not connected to NId"); ThisEdgeAdjIdxs[1] = NewIdx; } } void disconnectFromN(Graph &G, unsigned NIdx) { assert(ThisEdgeAdjIdxs[NIdx] != NodeEntry::getInvalidAdjEdgeIdx() && "Edge not connected to NIds[NIdx]."); NodeEntry &N = G.getNode(NIds[NIdx]); N.removeAdjEdgeId(G, NIds[NIdx], ThisEdgeAdjIdxs[NIdx]); ThisEdgeAdjIdxs[NIdx] = NodeEntry::getInvalidAdjEdgeIdx(); } void disconnectFrom(Graph &G, NodeId NId) { if (NId == NIds[0]) disconnectFromN(G, 0); else { assert(NId == NIds[1] && "Edge does not connect NId"); disconnectFromN(G, 1); } } NodeId getN1Id() const { return NIds[0]; } NodeId getN2Id() const { return NIds[1]; } MatrixPtr Costs; EdgeMetadata Metadata; private: NodeId NIds[2]; typename NodeEntry::AdjEdgeIdx ThisEdgeAdjIdxs[2]; }; // ----- MEMBERS ----- GraphMetadata Metadata; CostAllocator CostAlloc; SolverT *Solver; typedef std::vector<NodeEntry> NodeVector; typedef std::vector<NodeId> FreeNodeVector; NodeVector Nodes; FreeNodeVector FreeNodeIds; typedef std::vector<EdgeEntry> EdgeVector; typedef std::vector<EdgeId> FreeEdgeVector; EdgeVector Edges; FreeEdgeVector FreeEdgeIds; // ----- INTERNAL METHODS ----- NodeEntry &getNode(NodeId NId) { assert(NId < Nodes.size() && "Out of bound NodeId"); return Nodes[NId]; } const NodeEntry &getNode(NodeId NId) const { assert(NId < Nodes.size() && "Out of bound NodeId"); return Nodes[NId]; } EdgeEntry& getEdge(EdgeId EId) { return Edges[EId]; } const EdgeEntry& getEdge(EdgeId EId) const { return Edges[EId]; } NodeId addConstructedNode(NodeEntry N) { NodeId NId = 0; if (!FreeNodeIds.empty()) { NId = FreeNodeIds.back(); FreeNodeIds.pop_back(); Nodes[NId] = std::move(N); } else { NId = Nodes.size(); Nodes.push_back(std::move(N)); } return NId; } EdgeId addConstructedEdge(EdgeEntry E) { assert(findEdge(E.getN1Id(), E.getN2Id()) == invalidEdgeId() && "Attempt to add duplicate edge."); EdgeId EId = 0; if (!FreeEdgeIds.empty()) { EId = FreeEdgeIds.back(); FreeEdgeIds.pop_back(); Edges[EId] = std::move(E); } else { EId = Edges.size(); Edges.push_back(std::move(E)); } EdgeEntry &NE = getEdge(EId); // Add the edge to the adjacency sets of its nodes. NE.connect(*this, EId); return EId; } Graph(const Graph &Other) {} void operator=(const Graph &Other) {} public: typedef typename NodeEntry::AdjEdgeItr AdjEdgeItr; class NodeItr { public: typedef std::forward_iterator_tag iterator_category; typedef NodeId value_type; typedef int difference_type; typedef NodeId* pointer; typedef NodeId& reference; NodeItr(NodeId CurNId, const Graph &G) : CurNId(CurNId), EndNId(G.Nodes.size()), FreeNodeIds(G.FreeNodeIds) { this->CurNId = findNextInUse(CurNId); // Move to first in-use node id } bool operator==(const NodeItr &O) const { return CurNId == O.CurNId; } bool operator!=(const NodeItr &O) const { return !(*this == O); } NodeItr& operator++() { CurNId = findNextInUse(++CurNId); return *this; } NodeId operator*() const { return CurNId; } private: NodeId findNextInUse(NodeId NId) const { while (NId < EndNId && std::find(FreeNodeIds.begin(), FreeNodeIds.end(), NId) != FreeNodeIds.end()) { ++NId; } return NId; } NodeId CurNId, EndNId; const FreeNodeVector &FreeNodeIds; }; class EdgeItr { public: EdgeItr(EdgeId CurEId, const Graph &G) : CurEId(CurEId), EndEId(G.Edges.size()), FreeEdgeIds(G.FreeEdgeIds) { this->CurEId = findNextInUse(CurEId); // Move to first in-use edge id } bool operator==(const EdgeItr &O) const { return CurEId == O.CurEId; } bool operator!=(const EdgeItr &O) const { return !(*this == O); } EdgeItr& operator++() { CurEId = findNextInUse(++CurEId); return *this; } EdgeId operator*() const { return CurEId; } private: EdgeId findNextInUse(EdgeId EId) const { while (EId < EndEId && std::find(FreeEdgeIds.begin(), FreeEdgeIds.end(), EId) != FreeEdgeIds.end()) { ++EId; } return EId; } EdgeId CurEId, EndEId; const FreeEdgeVector &FreeEdgeIds; }; class NodeIdSet { public: NodeIdSet(const Graph &G) : G(G) { } NodeItr begin() const { return NodeItr(0, G); } NodeItr end() const { return NodeItr(G.Nodes.size(), G); } bool empty() const { return G.Nodes.empty(); } typename NodeVector::size_type size() const { return G.Nodes.size() - G.FreeNodeIds.size(); } private: const Graph& G; }; class EdgeIdSet { public: EdgeIdSet(const Graph &G) : G(G) { } EdgeItr begin() const { return EdgeItr(0, G); } EdgeItr end() const { return EdgeItr(G.Edges.size(), G); } bool empty() const { return G.Edges.empty(); } typename NodeVector::size_type size() const { return G.Edges.size() - G.FreeEdgeIds.size(); } private: const Graph& G; }; class AdjEdgeIdSet { public: AdjEdgeIdSet(const NodeEntry &NE) : NE(NE) { } typename NodeEntry::AdjEdgeItr begin() const { return NE.getAdjEdgeIds().begin(); } typename NodeEntry::AdjEdgeItr end() const { return NE.getAdjEdgeIds().end(); } bool empty() const { return NE.getAdjEdgeIds().empty(); } typename NodeEntry::AdjEdgeList::size_type size() const { return NE.getAdjEdgeIds().size(); } private: const NodeEntry &NE; }; /// @brief Construct an empty PBQP graph. Graph() : Solver(nullptr) {} /// @brief Construct an empty PBQP graph with the given graph metadata. Graph(GraphMetadata Metadata) : Metadata(Metadata), Solver(nullptr) {} /// @brief Get a reference to the graph metadata. GraphMetadata& getMetadata() { return Metadata; } /// @brief Get a const-reference to the graph metadata. const GraphMetadata& getMetadata() const { return Metadata; } /// @brief Lock this graph to the given solver instance in preparation /// for running the solver. This method will call solver.handleAddNode for /// each node in the graph, and handleAddEdge for each edge, to give the /// solver an opportunity to set up any requried metadata. void setSolver(SolverT &S) { assert(!Solver && "Solver already set. Call unsetSolver()."); Solver = &S; for (auto NId : nodeIds()) Solver->handleAddNode(NId); for (auto EId : edgeIds()) Solver->handleAddEdge(EId); } /// @brief Release from solver instance. void unsetSolver() { assert(Solver && "Solver not set."); Solver = nullptr; } /// @brief Add a node with the given costs. /// @param Costs Cost vector for the new node. /// @return Node iterator for the added node. template <typename OtherVectorT> NodeId addNode(OtherVectorT Costs) { // Get cost vector from the problem domain VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs)); NodeId NId = addConstructedNode(NodeEntry(AllocatedCosts)); if (Solver) Solver->handleAddNode(NId); return NId; } /// @brief Add a node bypassing the cost allocator. /// @param Costs Cost vector ptr for the new node (must be convertible to /// VectorPtr). /// @return Node iterator for the added node. /// /// This method allows for fast addition of a node whose costs don't need /// to be passed through the cost allocator. The most common use case for /// this is when duplicating costs from an existing node (when using a /// pooling allocator). These have already been uniqued, so we can avoid /// re-constructing and re-uniquing them by attaching them directly to the /// new node. template <typename OtherVectorPtrT> NodeId addNodeBypassingCostAllocator(OtherVectorPtrT Costs) { NodeId NId = addConstructedNode(NodeEntry(Costs)); if (Solver) Solver->handleAddNode(NId); return NId; } /// @brief Add an edge between the given nodes with the given costs. /// @param N1Id First node. /// @param N2Id Second node. /// @param Costs Cost matrix for new edge. /// @return Edge iterator for the added edge. template <typename OtherVectorT> EdgeId addEdge(NodeId N1Id, NodeId N2Id, OtherVectorT Costs) { assert(getNodeCosts(N1Id).getLength() == Costs.getRows() && getNodeCosts(N2Id).getLength() == Costs.getCols() && "Matrix dimensions mismatch."); // Get cost matrix from the problem domain. MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs)); EdgeId EId = addConstructedEdge(EdgeEntry(N1Id, N2Id, AllocatedCosts)); if (Solver) Solver->handleAddEdge(EId); return EId; } /// @brief Add an edge bypassing the cost allocator. /// @param N1Id First node. /// @param N2Id Second node. /// @param Costs Cost matrix for new edge. /// @return Edge iterator for the added edge. /// /// This method allows for fast addition of an edge whose costs don't need /// to be passed through the cost allocator. The most common use case for /// this is when duplicating costs from an existing edge (when using a /// pooling allocator). These have already been uniqued, so we can avoid /// re-constructing and re-uniquing them by attaching them directly to the /// new edge. template <typename OtherMatrixPtrT> NodeId addEdgeBypassingCostAllocator(NodeId N1Id, NodeId N2Id, OtherMatrixPtrT Costs) { assert(getNodeCosts(N1Id).getLength() == Costs->getRows() && getNodeCosts(N2Id).getLength() == Costs->getCols() && "Matrix dimensions mismatch."); // Get cost matrix from the problem domain. EdgeId EId = addConstructedEdge(EdgeEntry(N1Id, N2Id, Costs)); if (Solver) Solver->handleAddEdge(EId); return EId; } /// @brief Returns true if the graph is empty. bool empty() const { return NodeIdSet(*this).empty(); } NodeIdSet nodeIds() const { return NodeIdSet(*this); } EdgeIdSet edgeIds() const { return EdgeIdSet(*this); } AdjEdgeIdSet adjEdgeIds(NodeId NId) { return AdjEdgeIdSet(getNode(NId)); } /// @brief Get the number of nodes in the graph. /// @return Number of nodes in the graph. unsigned getNumNodes() const { return NodeIdSet(*this).size(); } /// @brief Get the number of edges in the graph. /// @return Number of edges in the graph. unsigned getNumEdges() const { return EdgeIdSet(*this).size(); } /// @brief Set a node's cost vector. /// @param NId Node to update. /// @param Costs New costs to set. template <typename OtherVectorT> void setNodeCosts(NodeId NId, OtherVectorT Costs) { VectorPtr AllocatedCosts = CostAlloc.getVector(std::move(Costs)); if (Solver) Solver->handleSetNodeCosts(NId, *AllocatedCosts); getNode(NId).Costs = AllocatedCosts; } /// @brief Get a VectorPtr to a node's cost vector. Rarely useful - use /// getNodeCosts where possible. /// @param NId Node id. /// @return VectorPtr to node cost vector. /// /// This method is primarily useful for duplicating costs quickly by /// bypassing the cost allocator. See addNodeBypassingCostAllocator. Prefer /// getNodeCosts when dealing with node cost values. const VectorPtr& getNodeCostsPtr(NodeId NId) const { return getNode(NId).Costs; } /// @brief Get a node's cost vector. /// @param NId Node id. /// @return Node cost vector. const Vector& getNodeCosts(NodeId NId) const { return *getNodeCostsPtr(NId); } NodeMetadata& getNodeMetadata(NodeId NId) { return getNode(NId).Metadata; } const NodeMetadata& getNodeMetadata(NodeId NId) const { return getNode(NId).Metadata; } typename NodeEntry::AdjEdgeList::size_type getNodeDegree(NodeId NId) const { return getNode(NId).getAdjEdgeIds().size(); } /// @brief Update an edge's cost matrix. /// @param EId Edge id. /// @param Costs New cost matrix. template <typename OtherMatrixT> void updateEdgeCosts(EdgeId EId, OtherMatrixT Costs) { MatrixPtr AllocatedCosts = CostAlloc.getMatrix(std::move(Costs)); if (Solver) Solver->handleUpdateCosts(EId, *AllocatedCosts); getEdge(EId).Costs = AllocatedCosts; } /// @brief Get a MatrixPtr to a node's cost matrix. Rarely useful - use /// getEdgeCosts where possible. /// @param EId Edge id. /// @return MatrixPtr to edge cost matrix. /// /// This method is primarily useful for duplicating costs quickly by /// bypassing the cost allocator. See addNodeBypassingCostAllocator. Prefer /// getEdgeCosts when dealing with edge cost values. const MatrixPtr& getEdgeCostsPtr(EdgeId EId) const { return getEdge(EId).Costs; } /// @brief Get an edge's cost matrix. /// @param EId Edge id. /// @return Edge cost matrix. const Matrix& getEdgeCosts(EdgeId EId) const { return *getEdge(EId).Costs; } EdgeMetadata& getEdgeMetadata(EdgeId EId) { return getEdge(EId).Metadata; } const EdgeMetadata& getEdgeMetadata(EdgeId EId) const { return getEdge(EId).Metadata; } /// @brief Get the first node connected to this edge. /// @param EId Edge id. /// @return The first node connected to the given edge. NodeId getEdgeNode1Id(EdgeId EId) const { return getEdge(EId).getN1Id(); } /// @brief Get the second node connected to this edge. /// @param EId Edge id. /// @return The second node connected to the given edge. NodeId getEdgeNode2Id(EdgeId EId) const { return getEdge(EId).getN2Id(); } /// @brief Get the "other" node connected to this edge. /// @param EId Edge id. /// @param NId Node id for the "given" node. /// @return The iterator for the "other" node connected to this edge. NodeId getEdgeOtherNodeId(EdgeId EId, NodeId NId) { EdgeEntry &E = getEdge(EId); if (E.getN1Id() == NId) { return E.getN2Id(); } // else return E.getN1Id(); } /// @brief Get the edge connecting two nodes. /// @param N1Id First node id. /// @param N2Id Second node id. /// @return An id for edge (N1Id, N2Id) if such an edge exists, /// otherwise returns an invalid edge id. EdgeId findEdge(NodeId N1Id, NodeId N2Id) { for (auto AEId : adjEdgeIds(N1Id)) { if ((getEdgeNode1Id(AEId) == N2Id) || (getEdgeNode2Id(AEId) == N2Id)) { return AEId; } } return invalidEdgeId(); } /// @brief Remove a node from the graph. /// @param NId Node id. void removeNode(NodeId NId) { if (Solver) Solver->handleRemoveNode(NId); NodeEntry &N = getNode(NId); // TODO: Can this be for-each'd? for (AdjEdgeItr AEItr = N.adjEdgesBegin(), AEEnd = N.adjEdgesEnd(); AEItr != AEEnd;) { EdgeId EId = *AEItr; ++AEItr; removeEdge(EId); } FreeNodeIds.push_back(NId); } /// @brief Disconnect an edge from the given node. /// /// Removes the given edge from the adjacency list of the given node. /// This operation leaves the edge in an 'asymmetric' state: It will no /// longer appear in an iteration over the given node's (NId's) edges, but /// will appear in an iteration over the 'other', unnamed node's edges. /// /// This does not correspond to any normal graph operation, but exists to /// support efficient PBQP graph-reduction based solvers. It is used to /// 'effectively' remove the unnamed node from the graph while the solver /// is performing the reduction. The solver will later call reconnectNode /// to restore the edge in the named node's adjacency list. /// /// Since the degree of a node is the number of connected edges, /// disconnecting an edge from a node 'u' will cause the degree of 'u' to /// drop by 1. /// /// A disconnected edge WILL still appear in an iteration over the graph /// edges. /// /// A disconnected edge should not be removed from the graph, it should be /// reconnected first. /// /// A disconnected edge can be reconnected by calling the reconnectEdge /// method. void disconnectEdge(EdgeId EId, NodeId NId) { if (Solver) Solver->handleDisconnectEdge(EId, NId); EdgeEntry &E = getEdge(EId); E.disconnectFrom(*this, NId); } /// @brief Convenience method to disconnect all neighbours from the given /// node. void disconnectAllNeighborsFromNode(NodeId NId) { for (auto AEId : adjEdgeIds(NId)) disconnectEdge(AEId, getEdgeOtherNodeId(AEId, NId)); } /// @brief Re-attach an edge to its nodes. /// /// Adds an edge that had been previously disconnected back into the /// adjacency set of the nodes that the edge connects. void reconnectEdge(EdgeId EId, NodeId NId) { EdgeEntry &E = getEdge(EId); E.connectTo(*this, EId, NId); if (Solver) Solver->handleReconnectEdge(EId, NId); } /// @brief Remove an edge from the graph. /// @param EId Edge id. void removeEdge(EdgeId EId) { if (Solver) Solver->handleRemoveEdge(EId); EdgeEntry &E = getEdge(EId); E.disconnect(); FreeEdgeIds.push_back(EId); Edges[EId].invalidate(); } /// @brief Remove all nodes and edges from the graph. void clear() { Nodes.clear(); FreeNodeIds.clear(); Edges.clear(); FreeEdgeIds.clear(); } }; } // namespace PBQP } // namespace llvm #endif // LLVM_CODEGEN_PBQP_GRAPH_HPP
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/PBQP/CostAllocator.h
//===---------- CostAllocator.h - PBQP Cost Allocator -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines classes conforming to the PBQP cost value manager concept. // // Cost value managers are memory managers for PBQP cost values (vectors and // matrices). Since PBQP graphs can grow very large (E.g. hundreds of thousands // of edges on the largest function in SPEC2006). // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PBQP_COSTALLOCATOR_H #define LLVM_CODEGEN_PBQP_COSTALLOCATOR_H #include "llvm/ADT/DenseSet.h" #include <memory> #include <type_traits> namespace llvm { namespace PBQP { template <typename ValueT> class ValuePool { public: typedef std::shared_ptr<const ValueT> PoolRef; private: class PoolEntry : public std::enable_shared_from_this<PoolEntry> { public: template <typename ValueKeyT> PoolEntry(ValuePool &Pool, ValueKeyT Value) : Pool(Pool), Value(std::move(Value)) {} ~PoolEntry() { Pool.removeEntry(this); } const ValueT& getValue() const { return Value; } private: ValuePool &Pool; ValueT Value; }; class PoolEntryDSInfo { public: static inline PoolEntry* getEmptyKey() { return nullptr; } static inline PoolEntry* getTombstoneKey() { return reinterpret_cast<PoolEntry*>(static_cast<uintptr_t>(1)); } template <typename ValueKeyT> static unsigned getHashValue(const ValueKeyT &C) { return hash_value(C); } static unsigned getHashValue(PoolEntry *P) { return getHashValue(P->getValue()); } static unsigned getHashValue(const PoolEntry *P) { return getHashValue(P->getValue()); } template <typename ValueKeyT1, typename ValueKeyT2> static bool isEqual(const ValueKeyT1 &C1, const ValueKeyT2 &C2) { return C1 == C2; } template <typename ValueKeyT> static bool isEqual(const ValueKeyT &C, PoolEntry *P) { if (P == getEmptyKey() || P == getTombstoneKey()) return false; return isEqual(C, P->getValue()); } static bool isEqual(PoolEntry *P1, PoolEntry *P2) { if (P1 == getEmptyKey() || P1 == getTombstoneKey()) return P1 == P2; return isEqual(P1->getValue(), P2); } }; typedef DenseSet<PoolEntry*, PoolEntryDSInfo> EntrySetT; EntrySetT EntrySet; void removeEntry(PoolEntry *P) { EntrySet.erase(P); } public: template <typename ValueKeyT> PoolRef getValue(ValueKeyT ValueKey) { typename EntrySetT::iterator I = EntrySet.find_as(ValueKey); if (I != EntrySet.end()) return PoolRef((*I)->shared_from_this(), &(*I)->getValue()); auto P = std::make_shared<PoolEntry>(*this, std::move(ValueKey)); EntrySet.insert(P.get()); return PoolRef(std::move(P), &P->getValue()); } }; template <typename VectorT, typename MatrixT> class PoolCostAllocator { private: typedef ValuePool<VectorT> VectorCostPool; typedef ValuePool<MatrixT> MatrixCostPool; public: typedef VectorT Vector; typedef MatrixT Matrix; typedef typename VectorCostPool::PoolRef VectorPtr; typedef typename MatrixCostPool::PoolRef MatrixPtr; template <typename VectorKeyT> VectorPtr getVector(VectorKeyT v) { return VectorPool.getValue(std::move(v)); } template <typename MatrixKeyT> MatrixPtr getMatrix(MatrixKeyT m) { return MatrixPool.getValue(std::move(m)); } private: VectorCostPool VectorPool; MatrixCostPool MatrixPool; }; } // namespace PBQP } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm/CodeGen
repos/DirectXShaderCompiler/include/llvm/CodeGen/MIRParser/MIRParser.h
//===- MIRParser.h - MIR serialization format parser ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This MIR serialization library is currently a work in progress. It can't // serialize machine functions at this time. // // This file declares the functions that parse the MIR serialization format // files. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_MIRPARSER_MIRPARSER_H #define LLVM_CODEGEN_MIRPARSER_MIRPARSER_H #include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/MachineFunctionInitializer.h" #include "llvm/IR/Module.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> namespace llvm { class MIRParserImpl; class SMDiagnostic; /// This class initializes machine functions by applying the state loaded from /// a MIR file. class MIRParser : public MachineFunctionInitializer { std::unique_ptr<MIRParserImpl> Impl; public: MIRParser(std::unique_ptr<MIRParserImpl> Impl); MIRParser(const MIRParser &) = delete; ~MIRParser(); /// Parse the optional LLVM IR module that's embedded in the MIR file. /// /// A new, empty module is created if the LLVM IR isn't present. /// Returns null if a parsing error occurred. std::unique_ptr<Module> parseLLVMModule(); /// Initialize the machine function to the state that's described in the MIR /// file. /// /// Return true if error occurred. bool initializeMachineFunction(MachineFunction &MF) override; }; /// This function is the main interface to the MIR serialization format parser. /// /// It reads in a MIR file and returns a MIR parser that can parse the embedded /// LLVM IR module and initialize the machine functions by parsing the machine /// function's state. /// /// \param Filename - The name of the file to parse. /// \param Error - Error result info. /// \param Context - Context which will be used for the parsed LLVM IR module. std::unique_ptr<MIRParser> createMIRParserFromFile(StringRef Filename, SMDiagnostic &Error, LLVMContext &Context); /// This function is another interface to the MIR serialization format parser. /// /// It returns a MIR parser that works with the given memory buffer and that can /// parse the embedded LLVM IR module and initialize the machine functions by /// parsing the machine function's state. /// /// \param Contents - The MemoryBuffer containing the machine level IR. /// \param Context - Context which will be used for the parsed LLVM IR module. std::unique_ptr<MIRParser> createMIRParser(std::unique_ptr<MemoryBuffer> Contents, LLVMContext &Context); } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/BitcodeWriterPass.h
//===-- BitcodeWriterPass.h - Bitcode writing pass --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// This file provides a bitcode writing pass. /// //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_BITCODEWRITERPASS_H #define LLVM_BITCODE_BITCODEWRITERPASS_H #include "llvm/ADT/StringRef.h" namespace llvm { class Module; class ModulePass; class raw_ostream; class PreservedAnalyses; /// \brief Create and return a pass that writes the module to the specified /// ostream. Note that this pass is designed for use with the legacy pass /// manager. /// /// If \c ShouldPreserveUseListOrder, encode use-list order so it can be /// reproduced when deserialized. ModulePass *createBitcodeWriterPass(raw_ostream &Str, bool ShouldPreserveUseListOrder = false); /// \brief Pass for writing a module of IR out to a bitcode file. /// /// Note that this is intended for use with the new pass manager. To construct /// a pass for the legacy pass manager, use the function above. class BitcodeWriterPass { raw_ostream &OS; bool ShouldPreserveUseListOrder; public: /// \brief Construct a bitcode writer pass around a particular output stream. /// /// If \c ShouldPreserveUseListOrder, encode use-list order so it can be /// reproduced when deserialized. explicit BitcodeWriterPass(raw_ostream &OS, bool ShouldPreserveUseListOrder = false) : OS(OS), ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {} /// \brief Run the bitcode writer pass, and output the module to the selected /// output stream. PreservedAnalyses run(Module &M); static StringRef name() { return "BitcodeWriterPass"; } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/BitstreamReader.h
//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines the BitstreamReader class. This class can be used to // read an arbitrary bitstream, regardless of its contents. // //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_BITSTREAMREADER_H #define LLVM_BITCODE_BITSTREAMREADER_H #include "llvm/Bitcode/BitCodes.h" #include "llvm/Support/Endian.h" #include "llvm/Support/StreamingMemoryObject.h" #include <climits> #include <string> #include <vector> namespace llvm { // HLSL Change Starts class BitstreamCursor; class BitstreamUseTracker { private: typedef std::pair<uint64_t, uint64_t> UseRange; SmallVector<UseRange, 8> Ranges; enum ExtendResult { Exclusive, ExtendedBegin, ExtendedEnd, ExtendedBoth, Included }; static ExtendResult extendRange(UseRange &R, UseRange &NewRange); static bool contains(const UseRange &UR); bool considerMergeRight(size_t idx); public: struct AutoTrack { BitstreamUseTracker *BT; uint64_t begin; void end(uint64_t end) { BitstreamUseTracker::track(BT, begin, end); } }; static AutoTrack start(BitstreamUseTracker *BT, uint64_t begin) { AutoTrack AT; AT.BT = BT; AT.begin = begin; return AT; } struct ScopeTrack { BitstreamCursor *BC; uint64_t begin; inline ~ScopeTrack(); }; static ScopeTrack scope_track(BitstreamCursor *BC); static void track(BitstreamUseTracker *BT, uint64_t begin, uint64_t end); void insert(uint64_t begin, uint64_t end); bool isDense(uint64_t endBitoffset) const; }; // HLSL Change Ends /// This class is used to read from an LLVM bitcode stream, maintaining /// information that is global to decoding the entire file. While a file is /// being read, multiple cursors can be independently advanced or skipped around /// within the file. These are represented by the BitstreamCursor class. class BitstreamReader { public: /// This contains information emitted to BLOCKINFO_BLOCK blocks. These /// describe abbreviations that all blocks of the specified ID inherit. struct BlockInfo { unsigned BlockID; std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs; std::string Name; std::vector<std::pair<unsigned, std::string> > RecordNames; }; private: std::unique_ptr<MemoryObject> BitcodeBytes; std::vector<BlockInfo> BlockInfoRecords; /// This is set to true if we don't care about the block/record name /// information in the BlockInfo block. Only llvm-bcanalyzer uses this. bool IgnoreBlockInfoNames; BitstreamReader(const BitstreamReader&) = delete; void operator=(const BitstreamReader&) = delete; public: BitstreamReader() : IgnoreBlockInfoNames(true) { } BitstreamReader(const unsigned char *Start, const unsigned char *End) : IgnoreBlockInfoNames(true) { init(Start, End); } BitstreamUseTracker *Tracker = nullptr; // HLSL Change BitstreamReader(std::unique_ptr<MemoryObject> BitcodeBytes) : BitcodeBytes(std::move(BitcodeBytes)), IgnoreBlockInfoNames(true) {} BitstreamReader(BitstreamReader &&Other) { *this = std::move(Other); } BitstreamReader &operator=(BitstreamReader &&Other) { BitcodeBytes = std::move(Other.BitcodeBytes); // Explicitly swap block info, so that nothing gets destroyed twice. std::swap(BlockInfoRecords, Other.BlockInfoRecords); IgnoreBlockInfoNames = Other.IgnoreBlockInfoNames; return *this; } void init(const unsigned char *Start, const unsigned char *End) { assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes"); BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End)); } MemoryObject &getBitcodeBytes() { return *BitcodeBytes; } /// This is called by clients that want block/record name information. void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; } bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; } //===--------------------------------------------------------------------===// // Block Manipulation //===--------------------------------------------------------------------===// /// Return true if we've already read and processed the block info block for /// this Bitstream. We only process it for the first cursor that walks over /// it. bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); } /// If there is block info for the specified ID, return it, otherwise return /// null. const BlockInfo *getBlockInfo(unsigned BlockID) const { // Common case, the most recent entry matches BlockID. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID) return &BlockInfoRecords.back(); for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size()); i != e; ++i) if (BlockInfoRecords[i].BlockID == BlockID) return &BlockInfoRecords[i]; return nullptr; } BlockInfo &getOrCreateBlockInfo(unsigned BlockID) { if (const BlockInfo *BI = getBlockInfo(BlockID)) return *const_cast<BlockInfo*>(BI); // Otherwise, add a new record. BlockInfoRecords.emplace_back(); BlockInfoRecords.back().BlockID = BlockID; return BlockInfoRecords.back(); } /// Takes block info from the other bitstream reader. /// /// This is a "take" operation because BlockInfo records are non-trivial, and /// indeed rather expensive. void takeBlockInfo(BitstreamReader &&Other) { assert(!hasBlockInfoRecords()); BlockInfoRecords = std::move(Other.BlockInfoRecords); } }; /// When advancing through a bitstream cursor, each advance can discover a few /// different kinds of entries: struct BitstreamEntry { enum { Error, // Malformed bitcode was found. EndBlock, // We've reached the end of the current block, (or the end of the // file, which is treated like a series of EndBlock records. SubBlock, // This is the start of a new subblock of a specific ID. Record // This is a record with a specific AbbrevID. } Kind; unsigned ID; static BitstreamEntry getError() { BitstreamEntry E; E.Kind = Error; return E; } static BitstreamEntry getEndBlock() { BitstreamEntry E; E.Kind = EndBlock; return E; } static BitstreamEntry getSubBlock(unsigned ID) { BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E; } static BitstreamEntry getRecord(unsigned AbbrevID) { BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E; } }; /// This represents a position within a bitcode file. There may be multiple /// independent cursors reading within one bitstream, each maintaining their own /// local state. /// /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not /// be passed by value. class BitstreamCursor { BitstreamReader *BitStream; size_t NextChar; // The size of the bicode. 0 if we don't know it yet. size_t Size; /// This is the current data we have pulled from the stream but have not /// returned to the client. This is specifically and intentionally defined to /// follow the word size of the host machine for efficiency. We use word_t in /// places that are aware of this to make it perfectly explicit what is going /// on. typedef size_t word_t; word_t CurWord; /// This is the number of bits in CurWord that are valid. This is always from /// [0...bits_of(size_t)-1] inclusive. unsigned BitsInCurWord; // This is the declared size of code values used for the current block, in // bits. unsigned CurCodeSize; /// Abbrevs installed at in this block. std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs; struct Block { unsigned PrevCodeSize; std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs; explicit Block(unsigned PCS) : PrevCodeSize(PCS) {} }; /// This tracks the codesize of parent blocks. SmallVector<Block, 8> BlockScope; template<typename T> inline void AddRecordElements(BitCodeAbbrevOp::Encoding enc, uint64_t encData, unsigned NumElts, SmallVectorImpl<T> &Vals); // HLSL Change public: static const size_t MaxChunkSize = sizeof(word_t) * 8; BitstreamCursor() { init(nullptr); } explicit BitstreamCursor(BitstreamReader &R) { init(&R); } void init(BitstreamReader *R) { freeState(); BitStream = R; NextChar = 0; Size = 0; BitsInCurWord = 0; CurCodeSize = 2; } void freeState(); bool canSkipToPos(size_t pos) const { // pos can be skipped to if it is a valid address or one byte past the end. return pos == 0 || BitStream->getBitcodeBytes().isValidAddress( static_cast<uint64_t>(pos - 1)); } bool AtEndOfStream() { if (BitsInCurWord != 0) return false; if (Size != 0) return Size == NextChar; fillCurWord(); return BitsInCurWord == 0; } /// Return the number of bits used to encode an abbrev #. unsigned getAbbrevIDWidth() const { return CurCodeSize; } /// Return the bit # of the bit we are reading. uint64_t GetCurrentBitNo() const { return NextChar*CHAR_BIT - BitsInCurWord; } BitstreamReader *getBitStreamReader() { return BitStream; } const BitstreamReader *getBitStreamReader() const { return BitStream; } /// Flags that modify the behavior of advance(). enum { /// If this flag is used, the advance() method does not automatically pop /// the block scope when the end of a block is reached. AF_DontPopBlockAtEnd = 1, /// If this flag is used, abbrev entries are returned just like normal /// records. AF_DontAutoprocessAbbrevs = 2 }; /// Advance the current bitstream, returning the next entry in the stream. BitstreamEntry advance(unsigned Flags = 0) { while (1) { unsigned Code = ReadCode(); if (Code == bitc::END_BLOCK) { // Pop the end of the block unless Flags tells us not to. if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd()) return BitstreamEntry::getError(); return BitstreamEntry::getEndBlock(); } if (Code == bitc::ENTER_SUBBLOCK) return BitstreamEntry::getSubBlock(ReadSubBlockID()); if (Code == bitc::DEFINE_ABBREV && !(Flags & AF_DontAutoprocessAbbrevs)) { // We read and accumulate abbrev's, the client can't do anything with // them anyway. ReadAbbrevRecord(); continue; } return BitstreamEntry::getRecord(Code); } } /// This is a convenience function for clients that don't expect any /// subblocks. This just skips over them automatically. BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0, unsigned *pCount = nullptr) { while (1) { // If we found a normal entry, return it. BitstreamEntry Entry = advance(Flags); if (Entry.Kind != BitstreamEntry::SubBlock) return Entry; // If we found a sub-block, just skip over it and check the next entry. if (pCount) *pCount += 1; // HLSL Change - count skipped blocks if (SkipBlock()) return BitstreamEntry::getError(); } } /// Reset the stream to the specified bit number. void JumpToBit(uint64_t BitNo) { size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1); unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1)); assert(canSkipToPos(ByteNo) && "Invalid location"); // Move the cursor to the right word. NextChar = ByteNo; BitsInCurWord = 0; // Skip over any bits that are already consumed. if (WordBitNo) Read(WordBitNo); } void fillCurWord() { if (Size != 0 && NextChar >= Size) report_fatal_error("Unexpected end of file"); // Read the next word from the stream. uint8_t Array[sizeof(word_t)] = {0}; uint64_t BytesRead = BitStream->getBitcodeBytes().readBytes(Array, sizeof(Array), NextChar); // If we run out of data, stop at the end of the stream. if (BytesRead == 0) { Size = NextChar; return; } CurWord = support::endian::read<word_t, support::little, support::unaligned>( Array); NextChar += BytesRead; BitsInCurWord = BytesRead * 8; } word_t Read(unsigned NumBits) { static const unsigned BitsInWord = MaxChunkSize; assert(NumBits && NumBits <= BitsInWord && "Cannot return zero or more than BitsInWord bits!"); static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f; // If the field is fully contained by CurWord, return it quickly. auto T = BitstreamUseTracker::scope_track(this); // HLSL Change if (BitsInCurWord >= NumBits) { word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits)); // Use a mask to avoid undefined behavior. CurWord >>= (NumBits & Mask); BitsInCurWord -= NumBits; return R; } word_t R = BitsInCurWord ? CurWord : 0; unsigned BitsLeft = NumBits - BitsInCurWord; fillCurWord(); // If we run out of data, stop at the end of the stream. if (BitsLeft > BitsInCurWord) return 0; word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft)); // Use a mask to avoid undefined behavior. CurWord >>= (BitsLeft & Mask); BitsInCurWord -= BitsLeft; R |= R2 << (NumBits - BitsLeft); return R; } uint32_t ReadVBR(unsigned NumBits) { uint32_t Piece = Read(NumBits); if ((Piece & (1U << (NumBits-1))) == 0) return Piece; uint32_t Result = 0; unsigned NextBit = 0; while (1) { Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit; if ((Piece & (1U << (NumBits-1))) == 0) return Result; NextBit += NumBits-1; Piece = Read(NumBits); } } // Read a VBR that may have a value up to 64-bits in size. The chunk size of // the VBR must still be <= 32 bits though. uint64_t ReadVBR64(unsigned NumBits) { uint32_t Piece = Read(NumBits); if ((Piece & (1U << (NumBits-1))) == 0) return uint64_t(Piece); uint64_t Result = 0; unsigned NextBit = 0; while (1) { Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit; if ((Piece & (1U << (NumBits-1))) == 0) return Result; NextBit += NumBits-1; Piece = Read(NumBits); } } private: void SkipToFourByteBoundary() { // If word_t is 64-bits and if we've read less than 32 bits, just dump // the bits we have up to the next 32-bit boundary. auto T = BitstreamUseTracker::scope_track(this); // HLSL Change if (sizeof(word_t) > 4 && BitsInCurWord >= 32) { CurWord >>= BitsInCurWord-32; BitsInCurWord = 32; return; } BitsInCurWord = 0; } public: unsigned ReadCode() { return Read(CurCodeSize); } // HLSL Change - begin inline unsigned PeekCode() { auto BitPos = GetCurrentBitNo(); unsigned result = Read(CurCodeSize); JumpToBit(BitPos); return result; } // HLSL Change - end // Block header: // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen] /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block. unsigned ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); } /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body /// of this block. If the block record is malformed, return true. bool SkipBlock() { // Read and ignore the codelen value. Since we are skipping this block, we // don't care what code widths are used inside of it. ReadVBR(bitc::CodeLenWidth); SkipToFourByteBoundary(); unsigned NumFourBytes = Read(bitc::BlockSizeWidth); // Check that the block wasn't partially defined, and that the offset isn't // bogus. size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8; if (AtEndOfStream() || !canSkipToPos(SkipTo/8)) return true; JumpToBit(SkipTo); return false; } /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true /// if the block has an error. bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr); bool ReadBlockEnd() { if (BlockScope.empty()) return true; // Block tail: // [END_BLOCK, <align4bytes>] SkipToFourByteBoundary(); popBlockScope(); return false; } private: void popBlockScope() { CurCodeSize = BlockScope.back().PrevCodeSize; CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs); BlockScope.pop_back(); } //===--------------------------------------------------------------------===// // Record Processing //===--------------------------------------------------------------------===// public: /// Return the abbreviation for the specified AbbrevId. const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) { unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV; if (AbbrevNo >= CurAbbrevs.size()) report_fatal_error("Invalid abbrev number"); return CurAbbrevs[AbbrevNo].get(); } /// Read the current record and discard it. void skipRecord(unsigned AbbrevID); unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals, StringRef *Blob = nullptr, SmallVectorImpl<uint8_t> *Uint8Vals = nullptr); // HLSL Change unsigned peekRecord(unsigned AbbrevID); // HLSL Change //===--------------------------------------------------------------------===// // Abbrev Processing //===--------------------------------------------------------------------===// void ReadAbbrevRecord(); bool ReadBlockInfoBlock(unsigned *pCount = nullptr); }; // HLSL Change - Begin BitstreamUseTracker::ScopeTrack::~ScopeTrack() { if (auto *Tracker = BC->getBitStreamReader()->Tracker) Tracker->insert(begin, BC->GetCurrentBitNo()); } // HLSL Change - End } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/LLVMBitCodes.h
//===- LLVMBitCodes.h - Enum values for the LLVM bitcode format -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines Bitcode enum values for LLVM IR bitcode files. // // The enum values defined in this file should be considered permanent. If // new features are added, they should have values added at the end of the // respective lists. // //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_LLVMBITCODES_H #define LLVM_BITCODE_LLVMBITCODES_H #include "llvm/Bitcode/BitCodes.h" namespace llvm { namespace bitc { // The only top-level block type defined is for a module. enum BlockIDs { // Blocks MODULE_BLOCK_ID = FIRST_APPLICATION_BLOCKID, // Module sub-block id's. PARAMATTR_BLOCK_ID, PARAMATTR_GROUP_BLOCK_ID, CONSTANTS_BLOCK_ID, FUNCTION_BLOCK_ID, UNUSED_ID1, VALUE_SYMTAB_BLOCK_ID, METADATA_BLOCK_ID, METADATA_ATTACHMENT_ID, TYPE_BLOCK_ID_NEW, USELIST_BLOCK_ID }; /// MODULE blocks have a number of optional fields and subblocks. enum ModuleCodes { MODULE_CODE_VERSION = 1, // VERSION: [version#] MODULE_CODE_TRIPLE = 2, // TRIPLE: [strchr x N] MODULE_CODE_DATALAYOUT = 3, // DATALAYOUT: [strchr x N] MODULE_CODE_ASM = 4, // ASM: [strchr x N] MODULE_CODE_SECTIONNAME = 5, // SECTIONNAME: [strchr x N] // FIXME: Remove DEPLIB in 4.0. MODULE_CODE_DEPLIB = 6, // DEPLIB: [strchr x N] // GLOBALVAR: [pointer type, isconst, initid, // linkage, alignment, section, visibility, threadlocal] MODULE_CODE_GLOBALVAR = 7, // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, // section, visibility, gc, unnamed_addr] MODULE_CODE_FUNCTION = 8, // ALIAS: [alias type, aliasee val#, linkage, visibility] MODULE_CODE_ALIAS = 9, // MODULE_CODE_PURGEVALS: [numvals] MODULE_CODE_PURGEVALS = 10, MODULE_CODE_GCNAME = 11, // GCNAME: [strchr x N] MODULE_CODE_COMDAT = 12, // COMDAT: [selection_kind, name] }; /// PARAMATTR blocks have code for defining a parameter attribute set. enum AttributeCodes { // FIXME: Remove `PARAMATTR_CODE_ENTRY_OLD' in 4.0 PARAMATTR_CODE_ENTRY_OLD = 1, // ENTRY: [paramidx0, attr0, // paramidx1, attr1...] PARAMATTR_CODE_ENTRY = 2, // ENTRY: [paramidx0, attrgrp0, // paramidx1, attrgrp1, ...] PARAMATTR_GRP_CODE_ENTRY = 3 // ENTRY: [id, attr0, att1, ...] }; /// TYPE blocks have codes for each type primitive they use. enum TypeCodes { TYPE_CODE_NUMENTRY = 1, // NUMENTRY: [numentries] // Type Codes TYPE_CODE_VOID = 2, // VOID TYPE_CODE_FLOAT = 3, // FLOAT TYPE_CODE_DOUBLE = 4, // DOUBLE TYPE_CODE_LABEL = 5, // LABEL TYPE_CODE_OPAQUE = 6, // OPAQUE TYPE_CODE_INTEGER = 7, // INTEGER: [width] TYPE_CODE_POINTER = 8, // POINTER: [pointee type] TYPE_CODE_FUNCTION_OLD = 9, // FUNCTION: [vararg, attrid, retty, // paramty x N] TYPE_CODE_HALF = 10, // HALF TYPE_CODE_ARRAY = 11, // ARRAY: [numelts, eltty] TYPE_CODE_VECTOR = 12, // VECTOR: [numelts, eltty] // These are not with the other floating point types because they're // a late addition, and putting them in the right place breaks // binary compatibility. TYPE_CODE_X86_FP80 = 13, // X86 LONG DOUBLE TYPE_CODE_FP128 = 14, // LONG DOUBLE (112 bit mantissa) TYPE_CODE_PPC_FP128= 15, // PPC LONG DOUBLE (2 doubles) TYPE_CODE_METADATA = 16, // METADATA TYPE_CODE_X86_MMX = 17, // X86 MMX TYPE_CODE_STRUCT_ANON = 18, // STRUCT_ANON: [ispacked, eltty x N] TYPE_CODE_STRUCT_NAME = 19, // STRUCT_NAME: [strchr x N] TYPE_CODE_STRUCT_NAMED = 20,// STRUCT_NAMED: [ispacked, eltty x N] TYPE_CODE_FUNCTION = 21 // FUNCTION: [vararg, retty, paramty x N] }; // The type symbol table only has one code (TST_ENTRY_CODE). enum TypeSymtabCodes { TST_CODE_ENTRY = 1 // TST_ENTRY: [typeid, namechar x N] }; // The value symbol table only has one code (VST_ENTRY_CODE). enum ValueSymtabCodes { VST_CODE_ENTRY = 1, // VST_ENTRY: [valid, namechar x N] VST_CODE_BBENTRY = 2 // VST_BBENTRY: [bbid, namechar x N] }; enum MetadataCodes { METADATA_STRING = 1, // MDSTRING: [values] METADATA_VALUE = 2, // VALUE: [type num, value num] METADATA_NODE = 3, // NODE: [n x md num] METADATA_NAME = 4, // STRING: [values] METADATA_DISTINCT_NODE = 5, // DISTINCT_NODE: [n x md num] METADATA_KIND = 6, // [n x [id, name]] METADATA_LOCATION = 7, // [distinct, line, col, scope, inlined-at?] METADATA_OLD_NODE = 8, // OLD_NODE: [n x (type num, value num)] METADATA_OLD_FN_NODE = 9, // OLD_FN_NODE: [n x (type num, value num)] METADATA_NAMED_NODE = 10, // NAMED_NODE: [n x mdnodes] METADATA_ATTACHMENT = 11, // [m x [value, [n x [id, mdnode]]] METADATA_GENERIC_DEBUG = 12, // [distinct, tag, vers, header, n x md num] METADATA_SUBRANGE = 13, // [distinct, count, lo] METADATA_ENUMERATOR = 14, // [distinct, value, name] METADATA_BASIC_TYPE = 15, // [distinct, tag, name, size, align, enc] METADATA_FILE = 16, // [distinct, filename, directory] METADATA_DERIVED_TYPE = 17, // [distinct, ...] METADATA_COMPOSITE_TYPE= 18, // [distinct, ...] METADATA_SUBROUTINE_TYPE=19, // [distinct, flags, types] METADATA_COMPILE_UNIT = 20, // [distinct, ...] METADATA_SUBPROGRAM = 21, // [distinct, ...] METADATA_LEXICAL_BLOCK = 22, // [distinct, scope, file, line, column] METADATA_LEXICAL_BLOCK_FILE=23,//[distinct, scope, file, discriminator] METADATA_NAMESPACE = 24, // [distinct, scope, file, name, line] METADATA_TEMPLATE_TYPE = 25, // [distinct, scope, name, type, ...] METADATA_TEMPLATE_VALUE= 26, // [distinct, scope, name, type, value, ...] METADATA_GLOBAL_VAR = 27, // [distinct, ...] METADATA_LOCAL_VAR = 28, // [distinct, ...] METADATA_EXPRESSION = 29, // [distinct, n x element] METADATA_OBJC_PROPERTY = 30, // [distinct, name, file, line, ...] METADATA_IMPORTED_ENTITY=31, // [distinct, tag, scope, entity, line, name] METADATA_MODULE=32, // [distinct, scope, name, ...] }; // The constants block (CONSTANTS_BLOCK_ID) describes emission for each // constant and maintains an implicit current type value. enum ConstantsCodes { CST_CODE_SETTYPE = 1, // SETTYPE: [typeid] CST_CODE_NULL = 2, // NULL CST_CODE_UNDEF = 3, // UNDEF CST_CODE_INTEGER = 4, // INTEGER: [intval] CST_CODE_WIDE_INTEGER = 5, // WIDE_INTEGER: [n x intval] CST_CODE_FLOAT = 6, // FLOAT: [fpval] CST_CODE_AGGREGATE = 7, // AGGREGATE: [n x value number] CST_CODE_STRING = 8, // STRING: [values] CST_CODE_CSTRING = 9, // CSTRING: [values] CST_CODE_CE_BINOP = 10, // CE_BINOP: [opcode, opval, opval] CST_CODE_CE_CAST = 11, // CE_CAST: [opcode, opty, opval] CST_CODE_CE_GEP = 12, // CE_GEP: [n x operands] CST_CODE_CE_SELECT = 13, // CE_SELECT: [opval, opval, opval] CST_CODE_CE_EXTRACTELT = 14, // CE_EXTRACTELT: [opty, opval, opval] CST_CODE_CE_INSERTELT = 15, // CE_INSERTELT: [opval, opval, opval] CST_CODE_CE_SHUFFLEVEC = 16, // CE_SHUFFLEVEC: [opval, opval, opval] CST_CODE_CE_CMP = 17, // CE_CMP: [opty, opval, opval, pred] CST_CODE_INLINEASM_OLD = 18, // INLINEASM: [sideeffect|alignstack, // asmstr,conststr] CST_CODE_CE_SHUFVEC_EX = 19, // SHUFVEC_EX: [opty, opval, opval, opval] CST_CODE_CE_INBOUNDS_GEP = 20,// INBOUNDS_GEP: [n x operands] CST_CODE_BLOCKADDRESS = 21, // CST_CODE_BLOCKADDRESS [fnty, fnval, bb#] CST_CODE_DATA = 22, // DATA: [n x elements] CST_CODE_INLINEASM = 23 // INLINEASM: [sideeffect|alignstack| // asmdialect,asmstr,conststr] }; /// CastOpcodes - These are values used in the bitcode files to encode which /// cast a CST_CODE_CE_CAST or a XXX refers to. The values of these enums /// have no fixed relation to the LLVM IR enum values. Changing these will /// break compatibility with old files. enum CastOpcodes { CAST_TRUNC = 0, CAST_ZEXT = 1, CAST_SEXT = 2, CAST_FPTOUI = 3, CAST_FPTOSI = 4, CAST_UITOFP = 5, CAST_SITOFP = 6, CAST_FPTRUNC = 7, CAST_FPEXT = 8, CAST_PTRTOINT = 9, CAST_INTTOPTR = 10, CAST_BITCAST = 11, CAST_ADDRSPACECAST = 12 }; /// BinaryOpcodes - These are values used in the bitcode files to encode which /// binop a CST_CODE_CE_BINOP or a XXX refers to. The values of these enums /// have no fixed relation to the LLVM IR enum values. Changing these will /// break compatibility with old files. enum BinaryOpcodes { BINOP_ADD = 0, BINOP_SUB = 1, BINOP_MUL = 2, BINOP_UDIV = 3, BINOP_SDIV = 4, // overloaded for FP BINOP_UREM = 5, BINOP_SREM = 6, // overloaded for FP BINOP_SHL = 7, BINOP_LSHR = 8, BINOP_ASHR = 9, BINOP_AND = 10, BINOP_OR = 11, BINOP_XOR = 12 }; /// These are values used in the bitcode files to encode AtomicRMW operations. /// The values of these enums have no fixed relation to the LLVM IR enum /// values. Changing these will break compatibility with old files. enum RMWOperations { RMW_XCHG = 0, RMW_ADD = 1, RMW_SUB = 2, RMW_AND = 3, RMW_NAND = 4, RMW_OR = 5, RMW_XOR = 6, RMW_MAX = 7, RMW_MIN = 8, RMW_UMAX = 9, RMW_UMIN = 10 }; /// OverflowingBinaryOperatorOptionalFlags - Flags for serializing /// OverflowingBinaryOperator's SubclassOptionalData contents. enum OverflowingBinaryOperatorOptionalFlags { OBO_NO_UNSIGNED_WRAP = 0, OBO_NO_SIGNED_WRAP = 1 }; /// PossiblyExactOperatorOptionalFlags - Flags for serializing /// PossiblyExactOperator's SubclassOptionalData contents. enum PossiblyExactOperatorOptionalFlags { PEO_EXACT = 0 }; /// Encoded AtomicOrdering values. enum AtomicOrderingCodes { ORDERING_NOTATOMIC = 0, ORDERING_UNORDERED = 1, ORDERING_MONOTONIC = 2, ORDERING_ACQUIRE = 3, ORDERING_RELEASE = 4, ORDERING_ACQREL = 5, ORDERING_SEQCST = 6 }; /// Encoded SynchronizationScope values. enum AtomicSynchScopeCodes { SYNCHSCOPE_SINGLETHREAD = 0, SYNCHSCOPE_CROSSTHREAD = 1 }; // The function body block (FUNCTION_BLOCK_ID) describes function bodies. It // can contain a constant block (CONSTANTS_BLOCK_ID). enum FunctionCodes { FUNC_CODE_DECLAREBLOCKS = 1, // DECLAREBLOCKS: [n] FUNC_CODE_INST_BINOP = 2, // BINOP: [opcode, ty, opval, opval] FUNC_CODE_INST_CAST = 3, // CAST: [opcode, ty, opty, opval] FUNC_CODE_INST_GEP_OLD = 4, // GEP: [n x operands] FUNC_CODE_INST_SELECT = 5, // SELECT: [ty, opval, opval, opval] FUNC_CODE_INST_EXTRACTELT = 6, // EXTRACTELT: [opty, opval, opval] FUNC_CODE_INST_INSERTELT = 7, // INSERTELT: [ty, opval, opval, opval] FUNC_CODE_INST_SHUFFLEVEC = 8, // SHUFFLEVEC: [ty, opval, opval, opval] FUNC_CODE_INST_CMP = 9, // CMP: [opty, opval, opval, pred] FUNC_CODE_INST_RET = 10, // RET: [opty,opval<both optional>] FUNC_CODE_INST_BR = 11, // BR: [bb#, bb#, cond] or [bb#] FUNC_CODE_INST_SWITCH = 12, // SWITCH: [opty, op0, op1, ...] FUNC_CODE_INST_INVOKE = 13, // INVOKE: [attr, fnty, op0,op1, ...] // 14 is unused. FUNC_CODE_INST_UNREACHABLE = 15, // UNREACHABLE FUNC_CODE_INST_PHI = 16, // PHI: [ty, val0,bb0, ...] // 17 is unused. // 18 is unused. FUNC_CODE_INST_ALLOCA = 19, // ALLOCA: [instty, opty, op, align] FUNC_CODE_INST_LOAD = 20, // LOAD: [opty, op, align, vol] // 21 is unused. // 22 is unused. FUNC_CODE_INST_VAARG = 23, // VAARG: [valistty, valist, instty] // This store code encodes the pointer type, rather than the value type // this is so information only available in the pointer type (e.g. address // spaces) is retained. FUNC_CODE_INST_STORE_OLD = 24, // STORE: [ptrty,ptr,val, align, vol] // 25 is unused. FUNC_CODE_INST_EXTRACTVAL = 26, // EXTRACTVAL: [n x operands] FUNC_CODE_INST_INSERTVAL = 27, // INSERTVAL: [n x operands] // fcmp/icmp returning Int1TY or vector of Int1Ty. Same as CMP, exists to // support legacy vicmp/vfcmp instructions. FUNC_CODE_INST_CMP2 = 28, // CMP2: [opty, opval, opval, pred] // new select on i1 or [N x i1] FUNC_CODE_INST_VSELECT = 29, // VSELECT: [ty,opval,opval,predty,pred] FUNC_CODE_INST_INBOUNDS_GEP_OLD = 30, // INBOUNDS_GEP: [n x operands] FUNC_CODE_INST_INDIRECTBR = 31, // INDIRECTBR: [opty, op0, op1, ...] // 32 is unused. FUNC_CODE_DEBUG_LOC_AGAIN = 33, // DEBUG_LOC_AGAIN FUNC_CODE_INST_CALL = 34, // CALL: [attr, cc, fnty, fnid, args...] FUNC_CODE_DEBUG_LOC = 35, // DEBUG_LOC: [Line,Col,ScopeVal, IAVal] FUNC_CODE_INST_FENCE = 36, // FENCE: [ordering, synchscope] FUNC_CODE_INST_CMPXCHG_OLD = 37, // CMPXCHG: [ptrty,ptr,cmp,new, align, vol, // ordering, synchscope] FUNC_CODE_INST_ATOMICRMW = 38, // ATOMICRMW: [ptrty,ptr,val, operation, // align, vol, // ordering, synchscope] FUNC_CODE_INST_RESUME = 39, // RESUME: [opval] FUNC_CODE_INST_LANDINGPAD_OLD = 40, // LANDINGPAD: [ty,val,val,num,id0,val0...] FUNC_CODE_INST_LOADATOMIC = 41, // LOAD: [opty, op, align, vol, // ordering, synchscope] FUNC_CODE_INST_STOREATOMIC_OLD = 42, // STORE: [ptrty,ptr,val, align, vol // ordering, synchscope] FUNC_CODE_INST_GEP = 43, // GEP: [inbounds, n x operands] FUNC_CODE_INST_STORE = 44, // STORE: [ptrty,ptr,valty,val, align, vol] FUNC_CODE_INST_STOREATOMIC = 45, // STORE: [ptrty,ptr,val, align, vol FUNC_CODE_INST_CMPXCHG = 46, // CMPXCHG: [ptrty,ptr,valty,cmp,new, align, // vol,ordering,synchscope] FUNC_CODE_INST_LANDINGPAD = 47, // LANDINGPAD: [ty,val,num,id0,val0...] }; enum UseListCodes { USELIST_CODE_DEFAULT = 1, // DEFAULT: [index..., value-id] USELIST_CODE_BB = 2 // BB: [index..., bb-id] }; enum AttributeKindCodes { // = 0 is unused ATTR_KIND_ALIGNMENT = 1, ATTR_KIND_ALWAYS_INLINE = 2, ATTR_KIND_BY_VAL = 3, ATTR_KIND_INLINE_HINT = 4, ATTR_KIND_IN_REG = 5, ATTR_KIND_MIN_SIZE = 6, ATTR_KIND_NAKED = 7, ATTR_KIND_NEST = 8, ATTR_KIND_NO_ALIAS = 9, ATTR_KIND_NO_BUILTIN = 10, ATTR_KIND_NO_CAPTURE = 11, ATTR_KIND_NO_DUPLICATE = 12, ATTR_KIND_NO_IMPLICIT_FLOAT = 13, ATTR_KIND_NO_INLINE = 14, ATTR_KIND_NON_LAZY_BIND = 15, ATTR_KIND_NO_RED_ZONE = 16, ATTR_KIND_NO_RETURN = 17, ATTR_KIND_NO_UNWIND = 18, ATTR_KIND_OPTIMIZE_FOR_SIZE = 19, ATTR_KIND_READ_NONE = 20, ATTR_KIND_READ_ONLY = 21, ATTR_KIND_RETURNED = 22, ATTR_KIND_RETURNS_TWICE = 23, ATTR_KIND_S_EXT = 24, ATTR_KIND_STACK_ALIGNMENT = 25, ATTR_KIND_STACK_PROTECT = 26, ATTR_KIND_STACK_PROTECT_REQ = 27, ATTR_KIND_STACK_PROTECT_STRONG = 28, ATTR_KIND_STRUCT_RET = 29, ATTR_KIND_SANITIZE_ADDRESS = 30, ATTR_KIND_SANITIZE_THREAD = 31, ATTR_KIND_SANITIZE_MEMORY = 32, ATTR_KIND_UW_TABLE = 33, ATTR_KIND_Z_EXT = 34, ATTR_KIND_BUILTIN = 35, ATTR_KIND_COLD = 36, ATTR_KIND_OPTIMIZE_NONE = 37, ATTR_KIND_IN_ALLOCA = 38, ATTR_KIND_NON_NULL = 39, ATTR_KIND_JUMP_TABLE = 40, ATTR_KIND_DEREFERENCEABLE = 41, ATTR_KIND_DEREFERENCEABLE_OR_NULL = 42, ATTR_KIND_CONVERGENT = 43, ATTR_KIND_SAFESTACK = 44, ATTR_KIND_ARGMEMONLY = 45 }; enum ComdatSelectionKindCodes { COMDAT_SELECTION_KIND_ANY = 1, COMDAT_SELECTION_KIND_EXACT_MATCH = 2, COMDAT_SELECTION_KIND_LARGEST = 3, COMDAT_SELECTION_KIND_NO_DUPLICATES = 4, COMDAT_SELECTION_KIND_SAME_SIZE = 5, }; } // End bitc namespace } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/BitCodes.h
//===- BitCodes.h - Enum values for the bitcode format ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header Bitcode enum values. // // The enum values defined in this file should be considered permanent. If // new features are added, they should have values added at the end of the // respective lists. // //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_BITCODES_H #define LLVM_BITCODE_BITCODES_H #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> namespace llvm { namespace bitc { enum StandardWidths { BlockIDWidth = 8, // We use VBR-8 for block IDs. CodeLenWidth = 4, // Codelen are VBR-4. BlockSizeWidth = 32 // BlockSize up to 2^32 32-bit words = 16GB per block. }; // The standard abbrev namespace always has a way to exit a block, enter a // nested block, define abbrevs, and define an unabbreviated record. enum FixedAbbrevIDs { END_BLOCK = 0, // Must be zero to guarantee termination for broken bitcode. ENTER_SUBBLOCK = 1, /// DEFINE_ABBREV - Defines an abbrev for the current block. It consists /// of a vbr5 for # operand infos. Each operand info is emitted with a /// single bit to indicate if it is a literal encoding. If so, the value is /// emitted with a vbr8. If not, the encoding is emitted as 3 bits followed /// by the info value as a vbr5 if needed. DEFINE_ABBREV = 2, // UNABBREV_RECORDs are emitted with a vbr6 for the record code, followed by // a vbr6 for the # operands, followed by vbr6's for each operand. UNABBREV_RECORD = 3, // This is not a code, this is a marker for the first abbrev assignment. FIRST_APPLICATION_ABBREV = 4 }; /// StandardBlockIDs - All bitcode files can optionally include a BLOCKINFO /// block, which contains metadata about other blocks in the file. enum StandardBlockIDs { /// BLOCKINFO_BLOCK is used to define metadata about blocks, for example, /// standard abbrevs that should be available to all blocks of a specified /// ID. BLOCKINFO_BLOCK_ID = 0, // Block IDs 1-7 are reserved for future expansion. FIRST_APPLICATION_BLOCKID = 8 }; /// BlockInfoCodes - The blockinfo block contains metadata about user-defined /// blocks. enum BlockInfoCodes { // DEFINE_ABBREV has magic semantics here, applying to the current SETBID'd // block, instead of the BlockInfo block. BLOCKINFO_CODE_SETBID = 1, // SETBID: [blockid#] BLOCKINFO_CODE_BLOCKNAME = 2, // BLOCKNAME: [name] BLOCKINFO_CODE_SETRECORDNAME = 3 // BLOCKINFO_CODE_SETRECORDNAME: // [id, name] }; } // End bitc namespace /// BitCodeAbbrevOp - This describes one or more operands in an abbreviation. /// This is actually a union of two different things: /// 1. It could be a literal integer value ("the operand is always 17"). /// 2. It could be an encoding specification ("this operand encoded like so"). /// class BitCodeAbbrevOp { uint64_t Val; // A literal value or data for an encoding. bool IsLiteral : 1; // Indicate whether this is a literal value or not. unsigned Enc : 3; // The encoding to use. public: enum Encoding { Fixed = 1, // A fixed width field, Val specifies number of bits. VBR = 2, // A VBR field where Val specifies the width of each chunk. Array = 3, // A sequence of fields, next field species elt encoding. Char6 = 4, // A 6-bit fixed field which maps to [a-zA-Z0-9._]. Blob = 5 // 32-bit aligned array of 8-bit characters. }; explicit BitCodeAbbrevOp(uint64_t V) : Val(V), IsLiteral(true) {} explicit BitCodeAbbrevOp(Encoding E, uint64_t Data = 0) : Val(Data), IsLiteral(false), Enc(E) {} bool isLiteral() const { return IsLiteral; } bool isEncoding() const { return !IsLiteral; } // Accessors for literals. uint64_t getLiteralValue() const { assert(isLiteral()); return Val; } // Accessors for encoding info. Encoding getEncoding() const { assert(isEncoding()); return (Encoding)Enc; } uint64_t getEncodingData() const { assert(isEncoding() && hasEncodingData()); return Val; } bool hasEncodingData() const { return hasEncodingData(getEncoding()); } static bool hasEncodingData(Encoding E) { switch (E) { case Fixed: case VBR: return true; case Array: case Char6: case Blob: return false; } report_fatal_error("Invalid encoding"); } /// isChar6 - Return true if this character is legal in the Char6 encoding. static bool isChar6(char C) { if (C >= 'a' && C <= 'z') return true; if (C >= 'A' && C <= 'Z') return true; if (C >= '0' && C <= '9') return true; if (C == '.' || C == '_') return true; return false; } static unsigned EncodeChar6(char C) { if (C >= 'a' && C <= 'z') return C-'a'; if (C >= 'A' && C <= 'Z') return C-'A'+26; if (C >= '0' && C <= '9') return C-'0'+26+26; if (C == '.') return 62; if (C == '_') return 63; llvm_unreachable("Not a value Char6 character!"); } static char DecodeChar6(unsigned V) { assert((V & ~63) == 0 && "Not a Char6 encoded character!"); if (V < 26) return V+'a'; if (V < 26+26) return V-26+'A'; if (V < 26+26+10) return V-26-26+'0'; if (V == 62) return '.'; if (V == 63) return '_'; llvm_unreachable("Not a value Char6 character!"); } }; template <> struct isPodLike<BitCodeAbbrevOp> { static const bool value=true; }; /// BitCodeAbbrev - This class represents an abbreviation record. An /// abbreviation allows a complex record that has redundancy to be stored in a /// specialized format instead of the fully-general, fully-vbr, format. class BitCodeAbbrev : public RefCountedBase<BitCodeAbbrev> { SmallVector<BitCodeAbbrevOp, 32> OperandList; // Only RefCountedBase is allowed to delete. ~BitCodeAbbrev() = default; friend class RefCountedBase<BitCodeAbbrev>; public: unsigned getNumOperandInfos() const { return static_cast<unsigned>(OperandList.size()); } const BitCodeAbbrevOp &getOperandInfo(unsigned N) const { return OperandList[N]; } void Add(const BitCodeAbbrevOp &OpInfo) { OperandList.push_back(OpInfo); } }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/ReaderWriter.h
//===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines interfaces to read and write LLVM bitcode files/streams. // //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_READERWRITER_H #define LLVM_BITCODE_READERWRITER_H #include "llvm/IR/DiagnosticInfo.h" #include "llvm/Support/Endian.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <string> namespace llvm { class BitstreamWriter; class DataStreamer; class LLVMContext; class Module; class ModulePass; class raw_ostream; /// Read the header of the specified bitcode buffer and prepare for lazy /// deserialization of function bodies. If ShouldLazyLoadMetadata is true, /// lazily load metadata as well. If successful, this moves Buffer. On /// error, this *does not* move Buffer. ErrorOr<std::unique_ptr<Module>> getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler = nullptr, bool ShouldLazyLoadMetadata = false, bool ShouldTrackBitstreamUsage = false); /// Read the header of the specified stream and prepare for lazy /// deserialization and streaming of function bodies. ErrorOr<std::unique_ptr<Module>> getStreamedBitcodeModule( StringRef Name, std::unique_ptr<DataStreamer> Streamer, LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler = nullptr); /// Read the header of the specified bitcode buffer and extract just the /// triple information. If successful, this returns a string. On error, this /// returns "". std::string getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler = nullptr); /// Read the specified bitcode file, returning the module. ErrorOr<std::unique_ptr<Module>> parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler = nullptr, bool ShouldTrackBitstreamUsage = false); // HLSL Change /// \brief Write the specified module to the specified raw output stream. /// /// For streams where it matters, the given stream should be in "binary" /// mode. /// /// If \c ShouldPreserveUseListOrder, encode the use-list order for each \a /// Value in \c M. These will be reconstructed exactly when \a M is /// deserialized. void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder = false); /// isBitcodeWrapper - Return true if the given bytes are the magic bytes /// for an LLVM IR bitcode wrapper. /// inline bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd) { // See if you can find the hidden message in the magic bytes :-). // (Hint: it's a little-endian encoding.) return BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 && BufPtr[2] == 0x17 && BufPtr[3] == 0x0B; } /// isRawBitcode - Return true if the given bytes are the magic bytes for /// raw LLVM IR bitcode (without a wrapper). /// inline bool isRawBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd) { // These bytes sort of have a hidden message, but it's not in // little-endian this time, and it's a little redundant. return BufPtr != BufEnd && BufPtr[0] == 'B' && BufPtr[1] == 'C' && BufPtr[2] == 0xc0 && BufPtr[3] == 0xde; } /// isBitcode - Return true if the given bytes are the magic bytes for /// LLVM IR bitcode, either with or without a wrapper. /// inline bool isBitcode(const unsigned char *BufPtr, const unsigned char *BufEnd) { return isBitcodeWrapper(BufPtr, BufEnd) || isRawBitcode(BufPtr, BufEnd); } /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special /// header for padding or other reasons. The format of this header is: /// /// struct bc_header { /// uint32_t Magic; // 0x0B17C0DE /// uint32_t Version; // Version, currently always 0. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. /// uint32_t BitcodeSize; // Size of traditional bitcode file. /// ... potentially other gunk ... /// }; /// /// This function is called when we find a file with a matching magic number. /// In this case, skip down to the subsection of the file that is actually a /// BC file. /// If 'VerifyBufferSize' is true, check that the buffer is large enough to /// contain the whole bitcode file. inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize) { enum { KnownHeaderSize = 4*4, // Size of header we read. OffsetField = 2*4, // Offset in bytes to Offset field. SizeField = 3*4 // Offset in bytes to Size field. }; // Must contain the header! if (BufEnd-BufPtr < KnownHeaderSize) return true; unsigned Offset = support::endian::read32le(&BufPtr[OffsetField]); unsigned Size = support::endian::read32le(&BufPtr[SizeField]); // Verify that Offset+Size fits in the file. if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr)) return true; BufPtr += Offset; BufEnd = BufPtr+Size; return false; } const std::error_category &BitcodeErrorCategory(); enum class BitcodeError { InvalidBitcodeSignature = 1, CorruptedBitcode }; inline std::error_code make_error_code(BitcodeError E) { return std::error_code(static_cast<int>(E), BitcodeErrorCategory()); } class BitcodeDiagnosticInfo : public DiagnosticInfo { const Twine &Msg; std::error_code EC; public: BitcodeDiagnosticInfo(std::error_code EC, DiagnosticSeverity Severity, const Twine &Msg); void print(DiagnosticPrinter &DP) const override; std::error_code getError() const { return EC; }; static bool classof(const DiagnosticInfo *DI) { return DI->getKind() == DK_Bitcode; } }; } // End llvm namespace namespace std { template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {}; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Bitcode/BitstreamWriter.h
//===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines the BitstreamWriter class. This class can be used to // write an arbitrary bitstream, regardless of its contents. // //===----------------------------------------------------------------------===// #ifndef LLVM_BITCODE_BITSTREAMWRITER_H #define LLVM_BITCODE_BITSTREAMWRITER_H #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Bitcode/BitCodes.h" #include "llvm/Support/Endian.h" #include <vector> namespace llvm { class BitstreamWriter { SmallVectorImpl<char> &Out; /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use. unsigned CurBit; /// CurValue - The current value. Only bits < CurBit are valid. uint32_t CurValue; /// CurCodeSize - This is the declared size of code values used for the /// current block, in bits. unsigned CurCodeSize; /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently /// selected BLOCK ID. unsigned BlockInfoCurBID; /// CurAbbrevs - Abbrevs installed at in this block. std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs; struct Block { unsigned PrevCodeSize; unsigned StartSizeWord; std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs; Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {} }; /// BlockScope - This tracks the current blocks that we have entered. std::vector<Block> BlockScope; /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks. /// These describe abbreviations that all blocks of the specified ID inherit. struct BlockInfo { unsigned BlockID; std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs; }; std::vector<BlockInfo> BlockInfoRecords; // BackpatchWord - Backpatch a 32-bit word in the output with the specified // value. void BackpatchWord(unsigned ByteNo, unsigned NewWord) { support::endian::write32le(&Out[ByteNo], NewWord); } void WriteByte(unsigned char Value) { Out.push_back(Value); } void WriteWord(unsigned Value) { Value = support::endian::byte_swap<uint32_t, support::little>(Value); Out.append(reinterpret_cast<const char *>(&Value), reinterpret_cast<const char *>(&Value + 1)); } unsigned GetBufferOffset() const { return Out.size(); } unsigned GetWordIndex() const { unsigned Offset = GetBufferOffset(); assert((Offset & 3) == 0 && "Not 32-bit aligned"); return Offset / 4; } public: explicit BitstreamWriter(SmallVectorImpl<char> &O) : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {} ~BitstreamWriter() { #if 0 // HLSL Change - these are not true when recovering from OOM assert(CurBit == 0 && "Unflushed data remaining"); assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance"); #endif } /// \brief Retrieve the current position in the stream, in bits. uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; } //===--------------------------------------------------------------------===// // Basic Primitives for emitting bits to the stream. //===--------------------------------------------------------------------===// void Emit(uint32_t Val, unsigned NumBits) { assert(NumBits && NumBits <= 32 && "Invalid value size!"); assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!"); CurValue |= Val << CurBit; if (CurBit + NumBits < 32) { CurBit += NumBits; return; } // Add the current word. WriteWord(CurValue); if (CurBit) CurValue = Val >> (32-CurBit); else CurValue = 0; CurBit = (CurBit+NumBits) & 31; } void Emit64(uint64_t Val, unsigned NumBits) { if (NumBits <= 32) Emit((uint32_t)Val, NumBits); else { Emit((uint32_t)Val, 32); Emit((uint32_t)(Val >> 32), NumBits-32); } } void FlushToWord() { if (CurBit) { WriteWord(CurValue); CurBit = 0; CurValue = 0; } } void EmitVBR(uint32_t Val, unsigned NumBits) { assert(NumBits <= 32 && "Too many bits to emit!"); uint32_t Threshold = 1U << (NumBits-1); // Emit the bits with VBR encoding, NumBits-1 bits at a time. while (Val >= Threshold) { Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits); Val >>= NumBits-1; } Emit(Val, NumBits); } void EmitVBR64(uint64_t Val, unsigned NumBits) { assert(NumBits <= 32 && "Too many bits to emit!"); if ((uint32_t)Val == Val) return EmitVBR((uint32_t)Val, NumBits); uint32_t Threshold = 1U << (NumBits-1); // Emit the bits with VBR encoding, NumBits-1 bits at a time. while (Val >= Threshold) { Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits); Val >>= NumBits-1; } Emit((uint32_t)Val, NumBits); } /// EmitCode - Emit the specified code. void EmitCode(unsigned Val) { Emit(Val, CurCodeSize); } //===--------------------------------------------------------------------===// // Block Manipulation //===--------------------------------------------------------------------===// /// getBlockInfo - If there is block info for the specified ID, return it, /// otherwise return null. BlockInfo *getBlockInfo(unsigned BlockID) { // Common case, the most recent entry matches BlockID. if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID) return &BlockInfoRecords.back(); for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size()); i != e; ++i) if (BlockInfoRecords[i].BlockID == BlockID) return &BlockInfoRecords[i]; return nullptr; } void EnterSubblock(unsigned BlockID, unsigned CodeLen) { // Block header: // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen] EmitCode(bitc::ENTER_SUBBLOCK); EmitVBR(BlockID, bitc::BlockIDWidth); EmitVBR(CodeLen, bitc::CodeLenWidth); FlushToWord(); unsigned BlockSizeWordIndex = GetWordIndex(); unsigned OldCodeSize = CurCodeSize; // Emit a placeholder, which will be replaced when the block is popped. Emit(0, bitc::BlockSizeWidth); CurCodeSize = CodeLen; // Push the outer block's abbrev set onto the stack, start out with an // empty abbrev set. BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex); BlockScope.back().PrevAbbrevs.swap(CurAbbrevs); // If there is a blockinfo for this BlockID, add all the predefined abbrevs // to the abbrev list. if (BlockInfo *Info = getBlockInfo(BlockID)) { CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(), Info->Abbrevs.end()); } } void ExitBlock() { assert(!BlockScope.empty() && "Block scope imbalance!"); const Block &B = BlockScope.back(); // Block tail: // [END_BLOCK, <align4bytes>] EmitCode(bitc::END_BLOCK); FlushToWord(); // Compute the size of the block, in words, not counting the size field. unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1; unsigned ByteNo = B.StartSizeWord*4; // Update the block size field in the header of this sub-block. BackpatchWord(ByteNo, SizeInWords); // Restore the inner block's code size and abbrev table. CurCodeSize = B.PrevCodeSize; CurAbbrevs = std::move(B.PrevAbbrevs); BlockScope.pop_back(); } //===--------------------------------------------------------------------===// // Record Emission //===--------------------------------------------------------------------===// private: /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev /// record. This is a no-op, since the abbrev specifies the literal to use. template<typename uintty> void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) { assert(Op.isLiteral() && "Not a literal"); // If the abbrev specifies the literal value to use, don't emit // anything. assert(V == Op.getLiteralValue() && "Invalid abbrev for record!"); } /// EmitAbbreviatedField - Emit a single scalar field value with the specified /// encoding. template<typename uintty> void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) { assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!"); // Encode the value as we are commanded. switch (Op.getEncoding()) { default: llvm_unreachable("Unknown encoding!"); case BitCodeAbbrevOp::Fixed: if (Op.getEncodingData()) Emit((unsigned)V, (unsigned)Op.getEncodingData()); break; case BitCodeAbbrevOp::VBR: if (Op.getEncodingData()) EmitVBR64(V, (unsigned)Op.getEncodingData()); break; case BitCodeAbbrevOp::Char6: Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6); break; } } /// EmitRecordWithAbbrevImpl - This is the core implementation of the record /// emission code. If BlobData is non-null, then it specifies an array of /// data that should be emitted as part of the Blob or Array operand that is /// known to exist at the end of the record. template<typename uintty> void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals, StringRef Blob) { const char *BlobData = Blob.data(); unsigned BlobLen = (unsigned) Blob.size(); unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV; assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!"); const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get(); EmitCode(Abbrev); unsigned RecordIdx = 0; for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos()); i != e; ++i) { const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i); if (Op.isLiteral()) { assert(RecordIdx < Vals.size() && "Invalid abbrev/record"); EmitAbbreviatedLiteral(Op, Vals[RecordIdx]); ++RecordIdx; } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) { // Array case. assert(i+2 == e && "array op not second to last?"); const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i); // If this record has blob data, emit it, otherwise we must have record // entries to encode this way. if (BlobData) { assert(RecordIdx == Vals.size() && "Blob data and record entries specified for array!"); // Emit a vbr6 to indicate the number of elements present. EmitVBR(static_cast<uint32_t>(BlobLen), 6); // Emit each field. for (unsigned i = 0; i != BlobLen; ++i) EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]); // Know that blob data is consumed for assertion below. BlobData = nullptr; } else { // Emit a vbr6 to indicate the number of elements present. EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6); // Emit each field. for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) EmitAbbreviatedField(EltEnc, Vals[RecordIdx]); } } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) { // If this record has blob data, emit it, otherwise we must have record // entries to encode this way. // Emit a vbr6 to indicate the number of elements present. if (BlobData) { EmitVBR(static_cast<uint32_t>(BlobLen), 6); assert(RecordIdx == Vals.size() && "Blob data and record entries specified for blob operand!"); } else { EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6); } // Flush to a 32-bit alignment boundary. FlushToWord(); // Emit each field as a literal byte. if (BlobData) { for (unsigned i = 0; i != BlobLen; ++i) WriteByte((unsigned char)BlobData[i]); // Know that blob data is consumed for assertion below. BlobData = nullptr; } else { for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) { assert(isUInt<8>(Vals[RecordIdx]) && "Value too large to emit as blob"); WriteByte((unsigned char)Vals[RecordIdx]); } } // Align end to 32-bits. while (GetBufferOffset() & 3) WriteByte(0); } else { // Single scalar field. assert(RecordIdx < Vals.size() && "Invalid abbrev/record"); EmitAbbreviatedField(Op, Vals[RecordIdx]); ++RecordIdx; } } assert(RecordIdx == Vals.size() && "Not all record operands emitted!"); assert(BlobData == nullptr && "Blob data specified for record that doesn't use it!"); } public: /// EmitRecord - Emit the specified record to the stream, using an abbrev if /// we have one to compress the output. template<typename uintty> void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals, unsigned Abbrev = 0) { if (!Abbrev) { // If we don't have an abbrev to use, emit this in its fully unabbreviated // form. EmitCode(bitc::UNABBREV_RECORD); EmitVBR(Code, 6); EmitVBR(static_cast<uint32_t>(Vals.size()), 6); for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i) EmitVBR64(Vals[i], 6); return; } // Insert the code into Vals to treat it uniformly. Vals.insert(Vals.begin(), Code); EmitRecordWithAbbrev(Abbrev, Vals); } /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation. /// Unlike EmitRecord, the code for the record should be included in Vals as /// the first entry. template<typename uintty> void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) { EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef()); } /// EmitRecordWithBlob - Emit the specified record to the stream, using an /// abbrev that includes a blob at the end. The blob data to emit is /// specified by the pointer and length specified at the end. In contrast to /// EmitRecord, this routine expects that the first entry in Vals is the code /// of the record. template<typename uintty> void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals, StringRef Blob) { EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob); } template<typename uintty> void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals, const char *BlobData, unsigned BlobLen) { return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen)); } /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records /// that end with an array. template<typename uintty> void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals, StringRef Array) { EmitRecordWithAbbrevImpl(Abbrev, Vals, Array); } template<typename uintty> void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals, const char *ArrayData, unsigned ArrayLen) { return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData, ArrayLen)); } //===--------------------------------------------------------------------===// // Abbrev Emission //===--------------------------------------------------------------------===// private: // Emit the abbreviation as a DEFINE_ABBREV record. void EncodeAbbrev(BitCodeAbbrev *Abbv) { EmitCode(bitc::DEFINE_ABBREV); EmitVBR(Abbv->getNumOperandInfos(), 5); for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos()); i != e; ++i) { const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i); Emit(Op.isLiteral(), 1); if (Op.isLiteral()) { EmitVBR64(Op.getLiteralValue(), 8); } else { Emit(Op.getEncoding(), 3); if (Op.hasEncodingData()) EmitVBR64(Op.getEncodingData(), 5); } } } public: /// EmitAbbrev - This emits an abbreviation to the stream. Note that this /// method takes ownership of the specified abbrev. unsigned EmitAbbrev(BitCodeAbbrev *Abbv) { // Emit the abbreviation as a record. EncodeAbbrev(Abbv); CurAbbrevs.push_back(Abbv); return static_cast<unsigned>(CurAbbrevs.size())-1 + bitc::FIRST_APPLICATION_ABBREV; } //===--------------------------------------------------------------------===// // BlockInfo Block Emission //===--------------------------------------------------------------------===// /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK. void EnterBlockInfoBlock(unsigned CodeWidth) { EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth); BlockInfoCurBID = ~0U; } private: /// SwitchToBlockID - If we aren't already talking about the specified block /// ID, emit a BLOCKINFO_CODE_SETBID record. void SwitchToBlockID(unsigned BlockID) { if (BlockInfoCurBID == BlockID) return; SmallVector<unsigned, 2> V; V.push_back(BlockID); EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V); BlockInfoCurBID = BlockID; } BlockInfo &getOrCreateBlockInfo(unsigned BlockID) { if (BlockInfo *BI = getBlockInfo(BlockID)) return *BI; // Otherwise, add a new record. BlockInfoRecords.emplace_back(); BlockInfoRecords.back().BlockID = BlockID; return BlockInfoRecords.back(); } public: /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified /// BlockID. unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) { SwitchToBlockID(BlockID); EncodeAbbrev(Abbv); // Add the abbrev to the specified block record. BlockInfo &Info = getOrCreateBlockInfo(BlockID); Info.Abbrevs.push_back(Abbv); return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV; } }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/IRReader/IRReader.h
//===---- llvm/IRReader/IRReader.h - Reader for LLVM IR files ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines functions for reading LLVM IR. They support both // Bitcode and Assembly, automatically detecting the input format. // //===----------------------------------------------------------------------===// #ifndef LLVM_IRREADER_IRREADER_H #define LLVM_IRREADER_IRREADER_H #include "llvm/Support/MemoryBuffer.h" #include <string> namespace llvm { class Module; class SMDiagnostic; class LLVMContext; /// If the given file holds a bitcode image, return a Module /// for it which does lazy deserialization of function bodies. Otherwise, /// attempt to parse it as LLVM Assembly and return a fully populated /// Module. std::unique_ptr<Module> getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context); /// If the given MemoryBuffer holds a bitcode image, return a Module /// for it. Otherwise, attempt to parse it as LLVM Assembly and return /// a Module for it. std::unique_ptr<Module> parseIR(MemoryBufferRef Buffer, SMDiagnostic &Err, LLVMContext &Context); /// If the given file holds a bitcode image, return a Module for it. /// Otherwise, attempt to parse it as LLVM Assembly and return a Module /// for it. std::unique_ptr<Module> parseIRFile(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context); } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/LTO/LTOModule.h
//===-LTOModule.h - LLVM Link Time Optimizer ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the LTOModule class. // //===----------------------------------------------------------------------===// #ifndef LLVM_LTO_LTOMODULE_H #define LLVM_LTO_LTOMODULE_H #include "llvm-c/lto.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/Object/IRObjectFile.h" #include "llvm/Target/TargetMachine.h" #include <string> #include <vector> // Forward references to llvm classes. namespace llvm { class Function; class GlobalValue; class MemoryBuffer; class TargetOptions; class Value; // // /////////////////////////////////////////////////////////////////////////////// /// C++ class which implements the opaque lto_module_t type. /// struct LTOModule { private: struct NameAndAttributes { const char *name; uint32_t attributes; bool isFunction; const GlobalValue *symbol; }; std::unique_ptr<LLVMContext> OwnedContext; std::string LinkerOpts; std::unique_ptr<object::IRObjectFile> IRFile; std::unique_ptr<TargetMachine> _target; std::vector<NameAndAttributes> _symbols; // _defines and _undefines only needed to disambiguate tentative definitions StringSet<> _defines; StringMap<NameAndAttributes> _undefines; std::vector<const char*> _asm_undefines; LTOModule(std::unique_ptr<object::IRObjectFile> Obj, TargetMachine *TM); LTOModule(std::unique_ptr<object::IRObjectFile> Obj, TargetMachine *TM, std::unique_ptr<LLVMContext> Context); public: ~LTOModule(); /// Returns 'true' if the file or memory contents is LLVM bitcode. static bool isBitcodeFile(const void *mem, size_t length); static bool isBitcodeFile(const char *path); /// Returns 'true' if the memory buffer is LLVM bitcode for the specified /// triple. static bool isBitcodeForTarget(MemoryBuffer *memBuffer, StringRef triplePrefix); /// Create a MemoryBuffer from a memory range with an optional name. static std::unique_ptr<MemoryBuffer> makeBuffer(const void *mem, size_t length, StringRef name = ""); /// Create an LTOModule. N.B. These methods take ownership of the buffer. The /// caller must have initialized the Targets, the TargetMCs, the AsmPrinters, /// and the AsmParsers by calling: /// /// InitializeAllTargets(); /// InitializeAllTargetMCs(); /// InitializeAllAsmPrinters(); /// InitializeAllAsmParsers(); static LTOModule *createFromFile(const char *path, TargetOptions options, std::string &errMsg); static LTOModule *createFromOpenFile(int fd, const char *path, size_t size, TargetOptions options, std::string &errMsg); static LTOModule *createFromOpenFileSlice(int fd, const char *path, size_t map_size, off_t offset, TargetOptions options, std::string &errMsg); static LTOModule *createFromBuffer(const void *mem, size_t length, TargetOptions options, std::string &errMsg, StringRef path = ""); static LTOModule *createInLocalContext(const void *mem, size_t length, TargetOptions options, std::string &errMsg, StringRef path); static LTOModule *createInContext(const void *mem, size_t length, TargetOptions options, std::string &errMsg, StringRef path, LLVMContext *Context); const Module &getModule() const { return const_cast<LTOModule*>(this)->getModule(); } Module &getModule() { return IRFile->getModule(); } /// Return the Module's target triple. const std::string &getTargetTriple() { return getModule().getTargetTriple(); } /// Set the Module's target triple. void setTargetTriple(StringRef Triple) { getModule().setTargetTriple(Triple); } /// Get the number of symbols uint32_t getSymbolCount() { return _symbols.size(); } /// Get the attributes for a symbol at the specified index. lto_symbol_attributes getSymbolAttributes(uint32_t index) { if (index < _symbols.size()) return lto_symbol_attributes(_symbols[index].attributes); return lto_symbol_attributes(0); } /// Get the name of the symbol at the specified index. const char *getSymbolName(uint32_t index) { if (index < _symbols.size()) return _symbols[index].name; return nullptr; } const GlobalValue *getSymbolGV(uint32_t index) { if (index < _symbols.size()) return _symbols[index].symbol; return nullptr; } const char *getLinkerOpts() { return LinkerOpts.c_str(); } const std::vector<const char*> &getAsmUndefinedRefs() { return _asm_undefines; } private: /// Parse metadata from the module // FIXME: it only parses "Linker Options" metadata at the moment void parseMetadata(); /// Parse the symbols from the module and model-level ASM and add them to /// either the defined or undefined lists. bool parseSymbols(std::string &errMsg); /// Add a symbol which isn't defined just yet to a list to be resolved later. void addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym, bool isFunc); /// Add a defined symbol to the list. void addDefinedSymbol(const char *Name, const GlobalValue *def, bool isFunction); /// Add a data symbol as defined to the list. void addDefinedDataSymbol(const object::BasicSymbolRef &Sym); void addDefinedDataSymbol(const char*Name, const GlobalValue *v); /// Add a function symbol as defined to the list. void addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym); void addDefinedFunctionSymbol(const char *Name, const Function *F); /// Add a global symbol from module-level ASM to the defined list. void addAsmGlobalSymbol(const char *, lto_symbol_attributes scope); /// Add a global symbol from module-level ASM to the undefined list. void addAsmGlobalSymbolUndef(const char *); /// Parse i386/ppc ObjC class data structure. void addObjCClass(const GlobalVariable *clgv); /// Parse i386/ppc ObjC category data structure. void addObjCCategory(const GlobalVariable *clgv); /// Parse i386/ppc ObjC class list data structure. void addObjCClassRef(const GlobalVariable *clgv); /// Get string that the data pointer points to. bool objcClassNameFromExpression(const Constant *c, std::string &name); /// Create an LTOModule (private version). static LTOModule *makeLTOModule(MemoryBufferRef Buffer, TargetOptions options, std::string &errMsg, LLVMContext *Context); }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/LTO/LTOCodeGenerator.h
//===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the LTOCodeGenerator class. // // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO. // // The Pre-IPO phase compiles source code into bitcode file. The resulting // bitcode files, along with object files and libraries, will be fed to the // linker to through the IPO and Post-IPO phases. By using obj-file extension, // the resulting bitcode file disguises itself as an object file, and therefore // obviates the need of writing a special set of the make-rules only for LTO // compilation. // // The IPO phase perform inter-procedural analyses and optimizations, and // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations // (SOPT), and intra-procedural target-dependent code generator (CG). // // As of this writing, we don't separate IPO and the Post-IPO SOPT. They // are intermingled together, and are driven by a single pass manager (see // PassManagerBuilder::populateLTOPassManager()). // // The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages. // The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator" // with the machine specific code generator. // //===----------------------------------------------------------------------===// #ifndef LLVM_LTO_LTOCODEGENERATOR_H #define LLVM_LTO_LTOCODEGENERATOR_H #include "llvm-c/lto.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringMap.h" #include "llvm/Linker/Linker.h" #include "llvm/Target/TargetOptions.h" #include <string> #include <vector> namespace llvm { class LLVMContext; class DiagnosticInfo; class GlobalValue; class Mangler; class MemoryBuffer; class TargetLibraryInfo; class TargetMachine; class raw_ostream; class raw_pwrite_stream; // // /////////////////////////////////////////////////////////////////////////////// /// C++ class which implements the opaque lto_code_gen_t type. /// struct LTOCodeGenerator { static const char *getVersionString(); LTOCodeGenerator(); LTOCodeGenerator(std::unique_ptr<LLVMContext> Context); ~LTOCodeGenerator(); // Merge given module, return true on success. bool addModule(struct LTOModule *); // Set the destination module. void setModule(struct LTOModule *); void setTargetOptions(TargetOptions options); void setDebugInfo(lto_debug_model); void setCodePICModel(lto_codegen_model); void setCpu(const char *mCpu) { MCpu = mCpu; } void setAttr(const char *mAttr) { MAttr = mAttr; } void setOptLevel(unsigned optLevel) { OptLevel = optLevel; } void setShouldInternalize(bool Value) { ShouldInternalize = Value; } void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; } void addMustPreserveSymbol(StringRef sym) { MustPreserveSymbols[sym] = 1; } // To pass options to the driver and optimization passes. These options are // not necessarily for debugging purpose (The function name is misleading). // This function should be called before LTOCodeGenerator::compilexxx(), // and LTOCodeGenerator::writeMergedModules(). void setCodeGenDebugOptions(const char *opts); // Parse the options set in setCodeGenDebugOptions. Like // setCodeGenDebugOptions, this must be called before // LTOCodeGenerator::compilexxx() and LTOCodeGenerator::writeMergedModules() void parseCodeGenDebugOptions(); // Write the merged module to the file specified by the given path. // Return true on success. bool writeMergedModules(const char *path, std::string &errMsg); // Compile the merged module into a *single* object file; the path to object // file is returned to the caller via argument "name". Return true on // success. // // NOTE that it is up to the linker to remove the intermediate object file. // Do not try to remove the object file in LTOCodeGenerator's destructor // as we don't who (LTOCodeGenerator or the obj file) will last longer. bool compile_to_file(const char **name, bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg); // As with compile_to_file(), this function compiles the merged module into // single object file. Instead of returning the object-file-path to the caller // (linker), it brings the object to a buffer, and return the buffer to the // caller. This function should delete intermediate object file once its content // is brought to memory. Return NULL if the compilation was not successful. std::unique_ptr<MemoryBuffer> compile(bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg); // Optimizes the merged module. Returns true on success. bool optimize(bool disableInline, bool disableGVNLoadPRE, bool disableVectorization, std::string &errMsg); // Compiles the merged optimized module into a single object file. It brings // the object to a buffer, and returns the buffer to the caller. Return NULL // if the compilation was not successful. std::unique_ptr<MemoryBuffer> compileOptimized(std::string &errMsg); void setDiagnosticHandler(lto_diagnostic_handler_t, void *); LLVMContext &getContext() { return Context; } private: void initializeLTOPasses(); bool compileOptimized(raw_pwrite_stream &out, std::string &errMsg); bool compileOptimizedToFile(const char **name, std::string &errMsg); void applyScopeRestrictions(); void applyRestriction(GlobalValue &GV, ArrayRef<StringRef> Libcalls, std::vector<const char *> &MustPreserveList, SmallPtrSetImpl<GlobalValue *> &AsmUsed, Mangler &Mangler); bool determineTarget(std::string &errMsg); static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context); void DiagnosticHandler2(const DiagnosticInfo &DI); typedef StringMap<uint8_t> StringSet; void destroyMergedModule(); std::unique_ptr<LLVMContext> OwnedContext; LLVMContext &Context; Linker IRLinker; TargetMachine *TargetMach = nullptr; bool EmitDwarfDebugInfo = false; bool ScopeRestrictionsDone = false; lto_codegen_model CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT; StringSet MustPreserveSymbols; StringSet AsmUndefinedRefs; std::vector<char *> CodegenOptions; std::string MCpu; std::string MAttr; std::string NativeObjectPath; TargetOptions Options; unsigned OptLevel = 2; lto_diagnostic_handler_t DiagHandler = nullptr; void *DiagContext = nullptr; LTOModule *OwnedModule = nullptr; bool ShouldInternalize = true; bool ShouldEmbedUselists = false; }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Passes/PassBuilder.h
//===- Parsing, selection, and construction of pass pipelines --*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// Interfaces for registering analysis passes, producing common pass manager /// configurations, and parsing of pass pipelines. /// //===----------------------------------------------------------------------===// #ifndef LLVM_PASSES_PASSBUILDER_H #define LLVM_PASSES_PASSBUILDER_H #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/CGSCCPassManager.h" #include "llvm/IR/PassManager.h" namespace llvm { class TargetMachine; /// \brief This class provides access to building LLVM's passes. /// /// It's members provide the baseline state available to passes during their /// construction. The \c PassRegistry.def file specifies how to construct all /// of the built-in passes, and those may reference these members during /// construction. class PassBuilder { TargetMachine *TM; public: explicit PassBuilder(TargetMachine *TM = nullptr) : TM(TM) {} /// \brief Registers all available module analysis passes. /// /// This is an interface that can be used to populate a \c /// ModuleAnalysisManager with all registered module analyses. Callers can /// still manually register any additional analyses. void registerModuleAnalyses(ModuleAnalysisManager &MAM); /// \brief Registers all available CGSCC analysis passes. /// /// This is an interface that can be used to populate a \c CGSCCAnalysisManager /// with all registered CGSCC analyses. Callers can still manually register any /// additional analyses. void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM); /// \brief Registers all available function analysis passes. /// /// This is an interface that can be used to populate a \c /// FunctionAnalysisManager with all registered function analyses. Callers can /// still manually register any additional analyses. void registerFunctionAnalyses(FunctionAnalysisManager &FAM); /// \brief Parse a textual pass pipeline description into a \c ModulePassManager. /// /// The format of the textual pass pipeline description looks something like: /// /// module(function(instcombine,sroa),dce,cgscc(inliner,function(...)),...) /// /// Pass managers have ()s describing the nest structure of passes. All passes /// are comma separated. As a special shortcut, if the very first pass is not /// a module pass (as a module pass manager is), this will automatically form /// the shortest stack of pass managers that allow inserting that first pass. /// So, assuming function passes 'fpassN', CGSCC passes 'cgpassN', and loop passes /// 'lpassN', all of these are valid: /// /// fpass1,fpass2,fpass3 /// cgpass1,cgpass2,cgpass3 /// lpass1,lpass2,lpass3 /// /// And they are equivalent to the following (resp.): /// /// module(function(fpass1,fpass2,fpass3)) /// module(cgscc(cgpass1,cgpass2,cgpass3)) /// module(function(loop(lpass1,lpass2,lpass3))) /// /// This shortcut is especially useful for debugging and testing small pass /// combinations. Note that these shortcuts don't introduce any other magic. If /// the sequence of passes aren't all the exact same kind of pass, it will be /// an error. You cannot mix different levels implicitly, you must explicitly /// form a pass manager in which to nest passes. bool parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass = true, bool DebugLogging = false); private: bool parseModulePassName(ModulePassManager &MPM, StringRef Name); bool parseCGSCCPassName(CGSCCPassManager &CGPM, StringRef Name); bool parseFunctionPassName(FunctionPassManager &FPM, StringRef Name); bool parseFunctionPassPipeline(FunctionPassManager &FPM, StringRef &PipelineText, bool VerifyEachPass, bool DebugLogging); bool parseCGSCCPassPipeline(CGSCCPassManager &CGPM, StringRef &PipelineText, bool VerifyEachPass, bool DebugLogging); bool parseModulePassPipeline(ModulePassManager &MPM, StringRef &PipelineText, bool VerifyEachPass, bool DebugLogging); }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/CoverageMappingWriter.h
//=-- CoverageMappingWriter.h - Code coverage mapping writer ------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing coverage mapping data for // instrumentation based coverage. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_COVERAGEMAPPINGWRITER_H #define LLVM_PROFILEDATA_COVERAGEMAPPINGWRITER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringMap.h" #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace coverage { /// \brief Writer of the filenames section for the instrumentation /// based code coverage. class CoverageFilenamesSectionWriter { ArrayRef<StringRef> Filenames; public: CoverageFilenamesSectionWriter(ArrayRef<StringRef> Filenames) : Filenames(Filenames) {} /// \brief Write encoded filenames to the given output stream. void write(raw_ostream &OS); }; /// \brief Writer for instrumentation based coverage mapping data. class CoverageMappingWriter { ArrayRef<unsigned> VirtualFileMapping; ArrayRef<CounterExpression> Expressions; MutableArrayRef<CounterMappingRegion> MappingRegions; public: CoverageMappingWriter(ArrayRef<unsigned> VirtualFileMapping, ArrayRef<CounterExpression> Expressions, MutableArrayRef<CounterMappingRegion> MappingRegions) : VirtualFileMapping(VirtualFileMapping), Expressions(Expressions), MappingRegions(MappingRegions) {} CoverageMappingWriter(ArrayRef<CounterExpression> Expressions, MutableArrayRef<CounterMappingRegion> MappingRegions) : Expressions(Expressions), MappingRegions(MappingRegions) {} /// \brief Write encoded coverage mapping data to the given output stream. void write(raw_ostream &OS); }; } // end namespace coverage } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/InstrProfReader.h
//=-- InstrProfReader.h - Instrumented profiling readers ----------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for reading profiling data for instrumentation // based PGO and coverage. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_INSTRPROFREADER_H #define LLVM_PROFILEDATA_INSTRPROFREADER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/LineIterator.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/OnDiskHashTable.h" #include <iterator> namespace llvm { class InstrProfReader; /// A file format agnostic iterator over profiling data. class InstrProfIterator { InstrProfReader *Reader; InstrProfRecord Record; void Increment(); public: using iterator_category = std::input_iterator_tag; using value_type = InstrProfRecord; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; InstrProfIterator() : Reader(nullptr) {} InstrProfIterator(InstrProfReader *Reader) : Reader(Reader) { Increment(); } InstrProfIterator &operator++() { Increment(); return *this; } bool operator==(const InstrProfIterator &RHS) { return Reader == RHS.Reader; } bool operator!=(const InstrProfIterator &RHS) { return Reader != RHS.Reader; } InstrProfRecord &operator*() { return Record; } InstrProfRecord *operator->() { return &Record; } }; /// Base class and interface for reading profiling data of any known instrprof /// format. Provides an iterator over InstrProfRecords. class InstrProfReader { std::error_code LastError; public: InstrProfReader() : LastError(instrprof_error::success) {} virtual ~InstrProfReader() {} /// Read the header. Required before reading first record. virtual std::error_code readHeader() = 0; /// Read a single record. virtual std::error_code readNextRecord(InstrProfRecord &Record) = 0; /// Iterator over profile data. InstrProfIterator begin() { return InstrProfIterator(this); } InstrProfIterator end() { return InstrProfIterator(); } protected: /// Set the current std::error_code and return same. std::error_code error(std::error_code EC) { LastError = EC; return EC; } /// Clear the current error code and return a successful one. std::error_code success() { return error(instrprof_error::success); } public: /// Return true if the reader has finished reading the profile data. bool isEOF() { return LastError == instrprof_error::eof; } /// Return true if the reader encountered an error reading profiling data. bool hasError() { return LastError && !isEOF(); } /// Get the current error code. std::error_code getError() { return LastError; } /// Factory method to create an appropriately typed reader for the given /// instrprof file. static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::string Path); static ErrorOr<std::unique_ptr<InstrProfReader>> create(std::unique_ptr<MemoryBuffer> Buffer); }; /// Reader for the simple text based instrprof format. /// /// This format is a simple text format that's suitable for test data. Records /// are separated by one or more blank lines, and record fields are separated by /// new lines. /// /// Each record consists of a function name, a function hash, a number of /// counters, and then each counter value, in that order. class TextInstrProfReader : public InstrProfReader { private: /// The profile data file contents. std::unique_ptr<MemoryBuffer> DataBuffer; /// Iterator over the profile data. line_iterator Line; TextInstrProfReader(const TextInstrProfReader &) = delete; TextInstrProfReader &operator=(const TextInstrProfReader &) = delete; public: TextInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer_) : DataBuffer(std::move(DataBuffer_)), Line(*DataBuffer, true, '#') {} /// Read the header. std::error_code readHeader() override { return success(); } /// Read a single record. std::error_code readNextRecord(InstrProfRecord &Record) override; }; /// Reader for the raw instrprof binary format from runtime. /// /// This format is a raw memory dump of the instrumentation-baed profiling data /// from the runtime. It has no index. /// /// Templated on the unsigned type whose size matches pointers on the platform /// that wrote the profile. template <class IntPtrT> class RawInstrProfReader : public InstrProfReader { private: /// The profile data file contents. std::unique_ptr<MemoryBuffer> DataBuffer; struct ProfileData { const uint32_t NameSize; const uint32_t NumCounters; const uint64_t FuncHash; const IntPtrT NamePtr; const IntPtrT CounterPtr; }; struct RawHeader { const uint64_t Magic; const uint64_t Version; const uint64_t DataSize; const uint64_t CountersSize; const uint64_t NamesSize; const uint64_t CountersDelta; const uint64_t NamesDelta; }; bool ShouldSwapBytes; uint64_t CountersDelta; uint64_t NamesDelta; const ProfileData *Data; const ProfileData *DataEnd; const uint64_t *CountersStart; const char *NamesStart; const char *ProfileEnd; RawInstrProfReader(const RawInstrProfReader &) = delete; RawInstrProfReader &operator=(const RawInstrProfReader &) = delete; public: RawInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer) : DataBuffer(std::move(DataBuffer)) { } static bool hasFormat(const MemoryBuffer &DataBuffer); std::error_code readHeader() override; std::error_code readNextRecord(InstrProfRecord &Record) override; private: std::error_code readNextHeader(const char *CurrentPos); std::error_code readHeader(const RawHeader &Header); template <class IntT> IntT swap(IntT Int) const { return ShouldSwapBytes ? sys::getSwappedBytes(Int) : Int; } const uint64_t *getCounter(IntPtrT CounterPtr) const { ptrdiff_t Offset = (swap(CounterPtr) - CountersDelta) / sizeof(uint64_t); return CountersStart + Offset; } const char *getName(IntPtrT NamePtr) const { ptrdiff_t Offset = (swap(NamePtr) - NamesDelta) / sizeof(char); return NamesStart + Offset; } }; typedef RawInstrProfReader<uint32_t> RawInstrProfReader32; typedef RawInstrProfReader<uint64_t> RawInstrProfReader64; namespace IndexedInstrProf { enum class HashT : uint32_t; } /// Trait for lookups into the on-disk hash table for the binary instrprof /// format. class InstrProfLookupTrait { std::vector<InstrProfRecord> DataBuffer; IndexedInstrProf::HashT HashType; unsigned FormatVersion; public: InstrProfLookupTrait(IndexedInstrProf::HashT HashType, unsigned FormatVersion) : HashType(HashType), FormatVersion(FormatVersion) {} typedef ArrayRef<InstrProfRecord> data_type; typedef StringRef internal_key_type; typedef StringRef external_key_type; typedef uint64_t hash_value_type; typedef uint64_t offset_type; static bool EqualKey(StringRef A, StringRef B) { return A == B; } static StringRef GetInternalKey(StringRef K) { return K; } hash_value_type ComputeHash(StringRef K); static std::pair<offset_type, offset_type> ReadKeyDataLength(const unsigned char *&D) { using namespace support; offset_type KeyLen = endian::readNext<offset_type, little, unaligned>(D); offset_type DataLen = endian::readNext<offset_type, little, unaligned>(D); return std::make_pair(KeyLen, DataLen); } StringRef ReadKey(const unsigned char *D, offset_type N) { return StringRef((const char *)D, N); } data_type ReadData(StringRef K, const unsigned char *D, offset_type N); }; typedef OnDiskIterableChainedHashTable<InstrProfLookupTrait> InstrProfReaderIndex; /// Reader for the indexed binary instrprof format. class IndexedInstrProfReader : public InstrProfReader { private: /// The profile data file contents. std::unique_ptr<MemoryBuffer> DataBuffer; /// The index into the profile data. std::unique_ptr<InstrProfReaderIndex> Index; /// Iterator over the profile data. InstrProfReaderIndex::data_iterator RecordIterator; /// The file format version of the profile data. uint64_t FormatVersion; /// The maximal execution count among all functions. uint64_t MaxFunctionCount; IndexedInstrProfReader(const IndexedInstrProfReader &) = delete; IndexedInstrProfReader &operator=(const IndexedInstrProfReader &) = delete; public: IndexedInstrProfReader(std::unique_ptr<MemoryBuffer> DataBuffer) : DataBuffer(std::move(DataBuffer)), Index(nullptr) {} /// Return true if the given buffer is in an indexed instrprof format. static bool hasFormat(const MemoryBuffer &DataBuffer); /// Read the file header. std::error_code readHeader() override; /// Read a single record. std::error_code readNextRecord(InstrProfRecord &Record) override; /// Fill Counts with the profile data for the given function name. std::error_code getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector<uint64_t> &Counts); /// Return the maximum of all known function counts. uint64_t getMaximumFunctionCount() { return MaxFunctionCount; } /// Factory method to create an indexed reader. static ErrorOr<std::unique_ptr<IndexedInstrProfReader>> create(std::string Path); static ErrorOr<std::unique_ptr<IndexedInstrProfReader>> create(std::unique_ptr<MemoryBuffer> Buffer); }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/CoverageMapping.h
//=-- CoverageMapping.h - Code coverage mapping support ---------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Code coverage mapping data is generated by clang and read by // llvm-cov to show code coverage statistics for a file. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_COVERAGEMAPPING_H_ #define LLVM_PROFILEDATA_COVERAGEMAPPING_H_ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/iterator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/raw_ostream.h" #include <system_error> #include <tuple> namespace llvm { class IndexedInstrProfReader; namespace coverage { class CoverageMappingReader; class CoverageMapping; struct CounterExpressions; enum CoverageMappingVersion { CoverageMappingVersion1 }; /// \brief A Counter is an abstract value that describes how to compute the /// execution count for a region of code using the collected profile count data. struct Counter { enum CounterKind { Zero, CounterValueReference, Expression }; static const unsigned EncodingTagBits = 2; static const unsigned EncodingTagMask = 0x3; static const unsigned EncodingCounterTagAndExpansionRegionTagBits = EncodingTagBits + 1; private: CounterKind Kind; unsigned ID; Counter(CounterKind Kind, unsigned ID) : Kind(Kind), ID(ID) {} public: Counter() : Kind(Zero), ID(0) {} CounterKind getKind() const { return Kind; } bool isZero() const { return Kind == Zero; } bool isExpression() const { return Kind == Expression; } unsigned getCounterID() const { return ID; } unsigned getExpressionID() const { return ID; } friend bool operator==(const Counter &LHS, const Counter &RHS) { return LHS.Kind == RHS.Kind && LHS.ID == RHS.ID; } friend bool operator!=(const Counter &LHS, const Counter &RHS) { return !(LHS == RHS); } friend bool operator<(const Counter &LHS, const Counter &RHS) { return std::tie(LHS.Kind, LHS.ID) < std::tie(RHS.Kind, RHS.ID); } /// \brief Return the counter that represents the number zero. static Counter getZero() { return Counter(); } /// \brief Return the counter that corresponds to a specific profile counter. static Counter getCounter(unsigned CounterId) { return Counter(CounterValueReference, CounterId); } /// \brief Return the counter that corresponds to a specific /// addition counter expression. static Counter getExpression(unsigned ExpressionId) { return Counter(Expression, ExpressionId); } }; /// \brief A Counter expression is a value that represents an arithmetic /// operation with two counters. struct CounterExpression { enum ExprKind { Subtract, Add }; ExprKind Kind; Counter LHS, RHS; CounterExpression(ExprKind Kind, Counter LHS, Counter RHS) : Kind(Kind), LHS(LHS), RHS(RHS) {} }; /// \brief A Counter expression builder is used to construct the /// counter expressions. It avoids unecessary duplication /// and simplifies algebraic expressions. class CounterExpressionBuilder { /// \brief A list of all the counter expressions std::vector<CounterExpression> Expressions; /// \brief A lookup table for the index of a given expression. llvm::DenseMap<CounterExpression, unsigned> ExpressionIndices; /// \brief Return the counter which corresponds to the given expression. /// /// If the given expression is already stored in the builder, a counter /// that references that expression is returned. Otherwise, the given /// expression is added to the builder's collection of expressions. Counter get(const CounterExpression &E); /// \brief Gather the terms of the expression tree for processing. /// /// This collects each addition and subtraction referenced by the counter into /// a sequence that can be sorted and combined to build a simplified counter /// expression. void extractTerms(Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms); /// \brief Simplifies the given expression tree /// by getting rid of algebraically redundant operations. Counter simplify(Counter ExpressionTree); public: ArrayRef<CounterExpression> getExpressions() const { return Expressions; } /// \brief Return a counter that represents the expression /// that adds LHS and RHS. Counter add(Counter LHS, Counter RHS); /// \brief Return a counter that represents the expression /// that subtracts RHS from LHS. Counter subtract(Counter LHS, Counter RHS); }; /// \brief A Counter mapping region associates a source range with /// a specific counter. struct CounterMappingRegion { enum RegionKind { /// \brief A CodeRegion associates some code with a counter CodeRegion, /// \brief An ExpansionRegion represents a file expansion region that /// associates a source range with the expansion of a virtual source file, /// such as for a macro instantiation or #include file. ExpansionRegion, /// \brief A SkippedRegion represents a source range with code that /// was skipped by a preprocessor or similar means. SkippedRegion }; Counter Count; unsigned FileID, ExpandedFileID; unsigned LineStart, ColumnStart, LineEnd, ColumnEnd; RegionKind Kind; CounterMappingRegion(Counter Count, unsigned FileID, unsigned ExpandedFileID, unsigned LineStart, unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd, RegionKind Kind) : Count(Count), FileID(FileID), ExpandedFileID(ExpandedFileID), LineStart(LineStart), ColumnStart(ColumnStart), LineEnd(LineEnd), ColumnEnd(ColumnEnd), Kind(Kind) {} static CounterMappingRegion makeRegion(Counter Count, unsigned FileID, unsigned LineStart, unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) { return CounterMappingRegion(Count, FileID, 0, LineStart, ColumnStart, LineEnd, ColumnEnd, CodeRegion); } static CounterMappingRegion makeExpansion(unsigned FileID, unsigned ExpandedFileID, unsigned LineStart, unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) { return CounterMappingRegion(Counter(), FileID, ExpandedFileID, LineStart, ColumnStart, LineEnd, ColumnEnd, ExpansionRegion); } static CounterMappingRegion makeSkipped(unsigned FileID, unsigned LineStart, unsigned ColumnStart, unsigned LineEnd, unsigned ColumnEnd) { return CounterMappingRegion(Counter(), FileID, 0, LineStart, ColumnStart, LineEnd, ColumnEnd, SkippedRegion); } inline std::pair<unsigned, unsigned> startLoc() const { return std::pair<unsigned, unsigned>(LineStart, ColumnStart); } inline std::pair<unsigned, unsigned> endLoc() const { return std::pair<unsigned, unsigned>(LineEnd, ColumnEnd); } bool operator<(const CounterMappingRegion &Other) const { if (FileID != Other.FileID) return FileID < Other.FileID; return startLoc() < Other.startLoc(); } bool contains(const CounterMappingRegion &Other) const { if (FileID != Other.FileID) return false; if (startLoc() > Other.startLoc()) return false; if (endLoc() < Other.endLoc()) return false; return true; } }; /// \brief Associates a source range with an execution count. struct CountedRegion : public CounterMappingRegion { uint64_t ExecutionCount; CountedRegion(const CounterMappingRegion &R, uint64_t ExecutionCount) : CounterMappingRegion(R), ExecutionCount(ExecutionCount) {} }; /// \brief A Counter mapping context is used to connect the counters, /// expressions and the obtained counter values. class CounterMappingContext { ArrayRef<CounterExpression> Expressions; ArrayRef<uint64_t> CounterValues; public: CounterMappingContext(ArrayRef<CounterExpression> Expressions, ArrayRef<uint64_t> CounterValues = ArrayRef<uint64_t>()) : Expressions(Expressions), CounterValues(CounterValues) {} void setCounts(ArrayRef<uint64_t> Counts) { CounterValues = Counts; } void dump(const Counter &C, llvm::raw_ostream &OS) const; void dump(const Counter &C) const { dump(C, dbgs()); } /// \brief Return the number of times that a region of code associated with /// this counter was executed. ErrorOr<int64_t> evaluate(const Counter &C) const; }; /// \brief Code coverage information for a single function. struct FunctionRecord { /// \brief Raw function name. std::string Name; /// \brief Associated files. std::vector<std::string> Filenames; /// \brief Regions in the function along with their counts. std::vector<CountedRegion> CountedRegions; /// \brief The number of times this function was executed. uint64_t ExecutionCount; FunctionRecord(StringRef Name, ArrayRef<StringRef> Filenames) : Name(Name), Filenames(Filenames.begin(), Filenames.end()) {} void pushRegion(CounterMappingRegion Region, uint64_t Count) { if (CountedRegions.empty()) ExecutionCount = Count; CountedRegions.emplace_back(Region, Count); } }; /// \brief Iterator over Functions, optionally filtered to a single file. class FunctionRecordIterator : public iterator_facade_base<FunctionRecordIterator, std::forward_iterator_tag, FunctionRecord> { ArrayRef<FunctionRecord> Records; ArrayRef<FunctionRecord>::iterator Current; StringRef Filename; /// \brief Skip records whose primary file is not \c Filename. void skipOtherFiles(); public: FunctionRecordIterator(ArrayRef<FunctionRecord> Records_, StringRef Filename = "") : Records(Records_), Current(Records.begin()), Filename(Filename) { skipOtherFiles(); } FunctionRecordIterator() : Current(Records.begin()) {} bool operator==(const FunctionRecordIterator &RHS) const { return Current == RHS.Current && Filename == RHS.Filename; } const FunctionRecord &operator*() const { return *Current; } FunctionRecordIterator &operator++() { assert(Current != Records.end() && "incremented past end"); ++Current; skipOtherFiles(); return *this; } }; /// \brief Coverage information for a macro expansion or #included file. /// /// When covered code has pieces that can be expanded for more detail, such as a /// preprocessor macro use and its definition, these are represented as /// expansions whose coverage can be looked up independently. struct ExpansionRecord { /// \brief The abstract file this expansion covers. unsigned FileID; /// \brief The region that expands to this record. const CountedRegion &Region; /// \brief Coverage for the expansion. const FunctionRecord &Function; ExpansionRecord(const CountedRegion &Region, const FunctionRecord &Function) : FileID(Region.ExpandedFileID), Region(Region), Function(Function) {} }; /// \brief The execution count information starting at a point in a file. /// /// A sequence of CoverageSegments gives execution counts for a file in format /// that's simple to iterate through for processing. struct CoverageSegment { /// \brief The line where this segment begins. unsigned Line; /// \brief The column where this segment begins. unsigned Col; /// \brief The execution count, or zero if no count was recorded. uint64_t Count; /// \brief When false, the segment was uninstrumented or skipped. bool HasCount; /// \brief Whether this enters a new region or returns to a previous count. bool IsRegionEntry; CoverageSegment(unsigned Line, unsigned Col, bool IsRegionEntry) : Line(Line), Col(Col), Count(0), HasCount(false), IsRegionEntry(IsRegionEntry) {} CoverageSegment(unsigned Line, unsigned Col, uint64_t Count, bool IsRegionEntry) : Line(Line), Col(Col), Count(Count), HasCount(true), IsRegionEntry(IsRegionEntry) {} friend bool operator==(const CoverageSegment &L, const CoverageSegment &R) { return std::tie(L.Line, L.Col, L.Count, L.HasCount, L.IsRegionEntry) == std::tie(R.Line, R.Col, R.Count, R.HasCount, R.IsRegionEntry); } void setCount(uint64_t NewCount) { Count = NewCount; HasCount = true; } void addCount(uint64_t NewCount) { setCount(Count + NewCount); } }; /// \brief Coverage information to be processed or displayed. /// /// This represents the coverage of an entire file, expansion, or function. It /// provides a sequence of CoverageSegments to iterate through, as well as the /// list of expansions that can be further processed. class CoverageData { std::string Filename; std::vector<CoverageSegment> Segments; std::vector<ExpansionRecord> Expansions; friend class CoverageMapping; public: CoverageData() {} CoverageData(StringRef Filename) : Filename(Filename) {} CoverageData(CoverageData &&RHS) : Filename(std::move(RHS.Filename)), Segments(std::move(RHS.Segments)), Expansions(std::move(RHS.Expansions)) {} /// \brief Get the name of the file this data covers. StringRef getFilename() { return Filename; } std::vector<CoverageSegment>::iterator begin() { return Segments.begin(); } std::vector<CoverageSegment>::iterator end() { return Segments.end(); } bool empty() { return Segments.empty(); } /// \brief Expansions that can be further processed. std::vector<ExpansionRecord> getExpansions() { return Expansions; } }; /// \brief The mapping of profile information to coverage data. /// /// This is the main interface to get coverage information, using a profile to /// fill out execution counts. class CoverageMapping { std::vector<FunctionRecord> Functions; unsigned MismatchedFunctionCount; CoverageMapping() : MismatchedFunctionCount(0) {} public: /// \brief Load the coverage mapping using the given readers. static ErrorOr<std::unique_ptr<CoverageMapping>> load(CoverageMappingReader &CoverageReader, IndexedInstrProfReader &ProfileReader); /// \brief Load the coverage mapping from the given files. static ErrorOr<std::unique_ptr<CoverageMapping>> load(StringRef ObjectFilename, StringRef ProfileFilename, StringRef Arch = StringRef()); /// \brief The number of functions that couldn't have their profiles mapped. /// /// This is a count of functions whose profile is out of date or otherwise /// can't be associated with any coverage information. unsigned getMismatchedCount() { return MismatchedFunctionCount; } /// \brief Returns the list of files that are covered. std::vector<StringRef> getUniqueSourceFiles() const; /// \brief Get the coverage for a particular file. /// /// The given filename must be the name as recorded in the coverage /// information. That is, only names returned from getUniqueSourceFiles will /// yield a result. CoverageData getCoverageForFile(StringRef Filename); /// \brief Gets all of the functions covered by this profile. iterator_range<FunctionRecordIterator> getCoveredFunctions() const { return make_range(FunctionRecordIterator(Functions), FunctionRecordIterator()); } /// \brief Gets all of the functions in a particular file. iterator_range<FunctionRecordIterator> getCoveredFunctions(StringRef Filename) const { return make_range(FunctionRecordIterator(Functions, Filename), FunctionRecordIterator()); } /// \brief Get the list of function instantiations in the file. /// /// Fucntions that are instantiated more than once, such as C++ template /// specializations, have distinct coverage records for each instantiation. std::vector<const FunctionRecord *> getInstantiations(StringRef Filename); /// \brief Get the coverage for a particular function. CoverageData getCoverageForFunction(const FunctionRecord &Function); /// \brief Get the coverage for an expansion within a coverage set. CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion); }; } // end namespace coverage /// \brief Provide DenseMapInfo for CounterExpression template<> struct DenseMapInfo<coverage::CounterExpression> { static inline coverage::CounterExpression getEmptyKey() { using namespace coverage; return CounterExpression(CounterExpression::ExprKind::Subtract, Counter::getCounter(~0U), Counter::getCounter(~0U)); } static inline coverage::CounterExpression getTombstoneKey() { using namespace coverage; return CounterExpression(CounterExpression::ExprKind::Add, Counter::getCounter(~0U), Counter::getCounter(~0U)); } static unsigned getHashValue(const coverage::CounterExpression &V) { return static_cast<unsigned>( hash_combine(V.Kind, V.LHS.getKind(), V.LHS.getCounterID(), V.RHS.getKind(), V.RHS.getCounterID())); } static bool isEqual(const coverage::CounterExpression &LHS, const coverage::CounterExpression &RHS) { return LHS.Kind == RHS.Kind && LHS.LHS == RHS.LHS && LHS.RHS == RHS.RHS; } }; const std::error_category &coveragemap_category(); enum class coveragemap_error { success = 0, eof, no_data_found, unsupported_version, truncated, malformed }; inline std::error_code make_error_code(coveragemap_error E) { return std::error_code(static_cast<int>(E), coveragemap_category()); } } // end namespace llvm namespace std { template <> struct is_error_code_enum<llvm::coveragemap_error> : std::true_type {}; } #endif // LLVM_PROFILEDATA_COVERAGEMAPPING_H_
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/CoverageMappingReader.h
//=-- CoverageMappingReader.h - Code coverage mapping reader ------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for reading coverage mapping data for // instrumentation based coverage. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_COVERAGEMAPPINGREADER_H #define LLVM_PROFILEDATA_COVERAGEMAPPINGREADER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Triple.h" #include "llvm/Object/ObjectFile.h" #include "llvm/ProfileData/CoverageMapping.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include <iterator> namespace llvm { namespace coverage { class CoverageMappingReader; /// \brief Coverage mapping information for a single function. struct CoverageMappingRecord { StringRef FunctionName; uint64_t FunctionHash; ArrayRef<StringRef> Filenames; ArrayRef<CounterExpression> Expressions; ArrayRef<CounterMappingRegion> MappingRegions; }; /// \brief A file format agnostic iterator over coverage mapping data. class CoverageMappingIterator { CoverageMappingReader *Reader; CoverageMappingRecord Record; void increment(); public: using iterator_category = std::input_iterator_tag; using value_type = CoverageMappingRecord; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; CoverageMappingIterator() : Reader(nullptr) {} CoverageMappingIterator(CoverageMappingReader *Reader) : Reader(Reader) { increment(); } CoverageMappingIterator &operator++() { increment(); return *this; } bool operator==(const CoverageMappingIterator &RHS) { return Reader == RHS.Reader; } bool operator!=(const CoverageMappingIterator &RHS) { return Reader != RHS.Reader; } CoverageMappingRecord &operator*() { return Record; } CoverageMappingRecord *operator->() { return &Record; } }; class CoverageMappingReader { public: virtual std::error_code readNextRecord(CoverageMappingRecord &Record) = 0; CoverageMappingIterator begin() { return CoverageMappingIterator(this); } CoverageMappingIterator end() { return CoverageMappingIterator(); } virtual ~CoverageMappingReader() {} }; /// \brief Base class for the raw coverage mapping and filenames data readers. class RawCoverageReader { protected: StringRef Data; RawCoverageReader(StringRef Data) : Data(Data) {} std::error_code readULEB128(uint64_t &Result); std::error_code readIntMax(uint64_t &Result, uint64_t MaxPlus1); std::error_code readSize(uint64_t &Result); std::error_code readString(StringRef &Result); }; /// \brief Reader for the raw coverage filenames. class RawCoverageFilenamesReader : public RawCoverageReader { std::vector<StringRef> &Filenames; RawCoverageFilenamesReader(const RawCoverageFilenamesReader &) = delete; RawCoverageFilenamesReader & operator=(const RawCoverageFilenamesReader &) = delete; public: RawCoverageFilenamesReader(StringRef Data, std::vector<StringRef> &Filenames) : RawCoverageReader(Data), Filenames(Filenames) {} std::error_code read(); }; /// \brief Reader for the raw coverage mapping data. class RawCoverageMappingReader : public RawCoverageReader { ArrayRef<StringRef> TranslationUnitFilenames; std::vector<StringRef> &Filenames; std::vector<CounterExpression> &Expressions; std::vector<CounterMappingRegion> &MappingRegions; RawCoverageMappingReader(const RawCoverageMappingReader &) = delete; RawCoverageMappingReader & operator=(const RawCoverageMappingReader &) = delete; public: RawCoverageMappingReader(StringRef MappingData, ArrayRef<StringRef> TranslationUnitFilenames, std::vector<StringRef> &Filenames, std::vector<CounterExpression> &Expressions, std::vector<CounterMappingRegion> &MappingRegions) : RawCoverageReader(MappingData), TranslationUnitFilenames(TranslationUnitFilenames), Filenames(Filenames), Expressions(Expressions), MappingRegions(MappingRegions) {} std::error_code read(); private: std::error_code decodeCounter(unsigned Value, Counter &C); std::error_code readCounter(Counter &C); std::error_code readMappingRegionsSubArray(std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID, size_t NumFileIDs); }; /// \brief Reader for the coverage mapping data that is emitted by the /// frontend and stored in an object file. class BinaryCoverageReader : public CoverageMappingReader { public: struct ProfileMappingRecord { CoverageMappingVersion Version; StringRef FunctionName; uint64_t FunctionHash; StringRef CoverageMapping; size_t FilenamesBegin; size_t FilenamesSize; ProfileMappingRecord(CoverageMappingVersion Version, StringRef FunctionName, uint64_t FunctionHash, StringRef CoverageMapping, size_t FilenamesBegin, size_t FilenamesSize) : Version(Version), FunctionName(FunctionName), FunctionHash(FunctionHash), CoverageMapping(CoverageMapping), FilenamesBegin(FilenamesBegin), FilenamesSize(FilenamesSize) {} }; private: std::vector<StringRef> Filenames; std::vector<ProfileMappingRecord> MappingRecords; size_t CurrentRecord; std::vector<StringRef> FunctionsFilenames; std::vector<CounterExpression> Expressions; std::vector<CounterMappingRegion> MappingRegions; BinaryCoverageReader(const BinaryCoverageReader &) = delete; BinaryCoverageReader &operator=(const BinaryCoverageReader &) = delete; BinaryCoverageReader() : CurrentRecord(0) {} public: static ErrorOr<std::unique_ptr<BinaryCoverageReader>> create(std::unique_ptr<MemoryBuffer> &ObjectBuffer, StringRef Arch); std::error_code readNextRecord(CoverageMappingRecord &Record) override; }; } // end namespace coverage } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/InstrProf.h
//=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Instrumentation-based profiling data is generated by instrumented // binaries through library functions in compiler-rt, and read by the clang // frontend to feed PGO. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_INSTRPROF_H_ #define LLVM_PROFILEDATA_INSTRPROF_H_ #include "llvm/ADT/StringRef.h" #include <cstdint> #include <system_error> #include <vector> namespace llvm { const std::error_category &instrprof_category(); enum class instrprof_error { success = 0, eof, bad_magic, bad_header, unsupported_version, unsupported_hash_type, too_large, truncated, malformed, unknown_function, hash_mismatch, count_mismatch, counter_overflow }; inline std::error_code make_error_code(instrprof_error E) { return std::error_code(static_cast<int>(E), instrprof_category()); } /// Profiling information for a single function. struct InstrProfRecord { InstrProfRecord() {} InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts) : Name(Name), Hash(Hash), Counts(std::move(Counts)) {} StringRef Name; uint64_t Hash; std::vector<uint64_t> Counts; }; } // end namespace llvm namespace std { template <> struct is_error_code_enum<llvm::instrprof_error> : std::true_type {}; } #endif // LLVM_PROFILEDATA_INSTRPROF_H_
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/SampleProf.h
//=-- SampleProf.h - Sampling profiling format support --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains common definitions used in the reading and writing of // sample profile data. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H_ #define LLVM_PROFILEDATA_SAMPLEPROF_H_ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <system_error> namespace llvm { const std::error_category &sampleprof_category(); enum class sampleprof_error { success = 0, bad_magic, unsupported_version, too_large, truncated, malformed, unrecognized_format }; inline std::error_code make_error_code(sampleprof_error E) { return std::error_code(static_cast<int>(E), sampleprof_category()); } } // end namespace llvm namespace std { template <> struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {}; } namespace llvm { namespace sampleprof { static inline uint64_t SPMagic() { return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) | uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) | uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) | uint64_t('2') << (64 - 56) | uint64_t(0xff); } static inline uint64_t SPVersion() { return 100; } /// Represents the relative location of an instruction. /// /// Instruction locations are specified by the line offset from the /// beginning of the function (marked by the line where the function /// header is) and the discriminator value within that line. /// /// The discriminator value is useful to distinguish instructions /// that are on the same line but belong to different basic blocks /// (e.g., the two post-increment instructions in "if (p) x++; else y++;"). struct LineLocation { LineLocation(int L, unsigned D) : LineOffset(L), Discriminator(D) {} int LineOffset; unsigned Discriminator; }; } // End namespace sampleprof template <> struct DenseMapInfo<sampleprof::LineLocation> { typedef DenseMapInfo<int> OffsetInfo; typedef DenseMapInfo<unsigned> DiscriminatorInfo; static inline sampleprof::LineLocation getEmptyKey() { return sampleprof::LineLocation(OffsetInfo::getEmptyKey(), DiscriminatorInfo::getEmptyKey()); } static inline sampleprof::LineLocation getTombstoneKey() { return sampleprof::LineLocation(OffsetInfo::getTombstoneKey(), DiscriminatorInfo::getTombstoneKey()); } static inline unsigned getHashValue(sampleprof::LineLocation Val) { return DenseMapInfo<std::pair<int, unsigned>>::getHashValue( std::pair<int, unsigned>(Val.LineOffset, Val.Discriminator)); } static inline bool isEqual(sampleprof::LineLocation LHS, sampleprof::LineLocation RHS) { return LHS.LineOffset == RHS.LineOffset && LHS.Discriminator == RHS.Discriminator; } }; namespace sampleprof { /// Representation of a single sample record. /// /// A sample record is represented by a positive integer value, which /// indicates how frequently was the associated line location executed. /// /// Additionally, if the associated location contains a function call, /// the record will hold a list of all the possible called targets. For /// direct calls, this will be the exact function being invoked. For /// indirect calls (function pointers, virtual table dispatch), this /// will be a list of one or more functions. class SampleRecord { public: typedef StringMap<unsigned> CallTargetMap; SampleRecord() : NumSamples(0), CallTargets() {} /// Increment the number of samples for this record by \p S. /// /// Sample counts accumulate using saturating arithmetic, to avoid wrapping /// around unsigned integers. void addSamples(unsigned S) { if (NumSamples <= std::numeric_limits<unsigned>::max() - S) NumSamples += S; else NumSamples = std::numeric_limits<unsigned>::max(); } /// Add called function \p F with samples \p S. /// /// Sample counts accumulate using saturating arithmetic, to avoid wrapping /// around unsigned integers. void addCalledTarget(StringRef F, unsigned S) { unsigned &TargetSamples = CallTargets[F]; if (TargetSamples <= std::numeric_limits<unsigned>::max() - S) TargetSamples += S; else TargetSamples = std::numeric_limits<unsigned>::max(); } /// Return true if this sample record contains function calls. bool hasCalls() const { return CallTargets.size() > 0; } unsigned getSamples() const { return NumSamples; } const CallTargetMap &getCallTargets() const { return CallTargets; } /// Merge the samples in \p Other into this record. void merge(const SampleRecord &Other) { addSamples(Other.getSamples()); for (const auto &I : Other.getCallTargets()) addCalledTarget(I.first(), I.second); } private: unsigned NumSamples; CallTargetMap CallTargets; }; typedef DenseMap<LineLocation, SampleRecord> BodySampleMap; /// Representation of the samples collected for a function. /// /// This data structure contains all the collected samples for the body /// of a function. Each sample corresponds to a LineLocation instance /// within the body of the function. class FunctionSamples { public: FunctionSamples() : TotalSamples(0), TotalHeadSamples(0) {} void print(raw_ostream &OS = dbgs()); void addTotalSamples(unsigned Num) { TotalSamples += Num; } void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; } void addBodySamples(int LineOffset, unsigned Discriminator, unsigned Num) { assert(LineOffset >= 0); // When dealing with instruction weights, we use the value // zero to indicate the absence of a sample. If we read an // actual zero from the profile file, use the value 1 to // avoid the confusion later on. if (Num == 0) Num = 1; BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(Num); } void addCalledTargetSamples(int LineOffset, unsigned Discriminator, std::string FName, unsigned Num) { assert(LineOffset >= 0); BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(FName, Num); } /// Return the sample record at the given location. /// Each location is specified by \p LineOffset and \p Discriminator. SampleRecord &sampleRecordAt(const LineLocation &Loc) { return BodySamples[Loc]; } /// Return the number of samples collected at the given location. /// Each location is specified by \p LineOffset and \p Discriminator. unsigned samplesAt(int LineOffset, unsigned Discriminator) { return sampleRecordAt(LineLocation(LineOffset, Discriminator)).getSamples(); } bool empty() const { return BodySamples.empty(); } /// Return the total number of samples collected inside the function. unsigned getTotalSamples() const { return TotalSamples; } /// Return the total number of samples collected at the head of the /// function. unsigned getHeadSamples() const { return TotalHeadSamples; } /// Return all the samples collected in the body of the function. const BodySampleMap &getBodySamples() const { return BodySamples; } /// Merge the samples in \p Other into this one. void merge(const FunctionSamples &Other) { addTotalSamples(Other.getTotalSamples()); addHeadSamples(Other.getHeadSamples()); for (const auto &I : Other.getBodySamples()) { const LineLocation &Loc = I.first; const SampleRecord &Rec = I.second; sampleRecordAt(Loc).merge(Rec); } } private: /// Total number of samples collected inside this function. /// /// Samples are cumulative, they include all the samples collected /// inside this function and all its inlined callees. unsigned TotalSamples; /// Total number of samples collected at the head of the function. /// This is an approximation of the number of calls made to this function /// at runtime. unsigned TotalHeadSamples; /// Map instruction locations to collected samples. /// /// Each entry in this map contains the number of samples /// collected at the corresponding line offset. All line locations /// are an offset from the start of the function. BodySampleMap BodySamples; }; } // End namespace sampleprof } // End namespace llvm #endif // LLVM_PROFILEDATA_SAMPLEPROF_H_
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/InstrProfWriter.h
//=-- InstrProfWriter.h - Instrumented profiling writer -----------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing profiling data for instrumentation // based PGO and coverage. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_INSTRPROFWRITER_H #define LLVM_PROFILEDATA_INSTRPROFWRITER_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <vector> namespace llvm { /// Writer for instrumentation based profile data. class InstrProfWriter { public: typedef SmallDenseMap<uint64_t, std::vector<uint64_t>, 1> CounterData; private: StringMap<CounterData> FunctionData; uint64_t MaxFunctionCount; public: InstrProfWriter() : MaxFunctionCount(0) {} /// Add function counts for the given function. If there are already counts /// for this function and the hash and number of counts match, each counter is /// summed. std::error_code addFunctionCounts(StringRef FunctionName, uint64_t FunctionHash, ArrayRef<uint64_t> Counters); /// Write the profile to \c OS void write(raw_fd_ostream &OS); /// Write the profile, returning the raw data. For testing. std::unique_ptr<MemoryBuffer> writeBuffer(); private: std::pair<uint64_t, uint64_t> writeImpl(raw_ostream &OS); }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/SampleProfReader.h
//===- SampleProfReader.h - Read LLVM sample profile data -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains definitions needed for reading sample profiles. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_SAMPLEPROFREADER_H #define LLVM_PROFILEDATA_SAMPLEPROFREADER_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/ProfileData/SampleProf.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace sampleprof { /// \brief Sample-based profile reader. /// /// Each profile contains sample counts for all the functions /// executed. Inside each function, statements are annotated with the /// collected samples on all the instructions associated with that /// statement. /// /// For this to produce meaningful data, the program needs to be /// compiled with some debug information (at minimum, line numbers: /// -gline-tables-only). Otherwise, it will be impossible to match IR /// instructions to the line numbers collected by the profiler. /// /// From the profile file, we are interested in collecting the /// following information: /// /// * A list of functions included in the profile (mangled names). /// /// * For each function F: /// 1. The total number of samples collected in F. /// /// 2. The samples collected at each line in F. To provide some /// protection against source code shuffling, line numbers should /// be relative to the start of the function. /// /// The reader supports two file formats: text and binary. The text format /// is useful for debugging and testing, while the binary format is more /// compact. They can both be used interchangeably. class SampleProfileReader { public: SampleProfileReader(std::unique_ptr<MemoryBuffer> B, LLVMContext &C) : Profiles(0), Ctx(C), Buffer(std::move(B)) {} virtual ~SampleProfileReader() {} /// \brief Read and validate the file header. virtual std::error_code readHeader() = 0; /// \brief Read sample profiles from the associated file. virtual std::error_code read() = 0; /// \brief Print the profile for \p FName on stream \p OS. void dumpFunctionProfile(StringRef FName, raw_ostream &OS = dbgs()); /// \brief Print all the profiles on stream \p OS. void dump(raw_ostream &OS = dbgs()); /// \brief Return the samples collected for function \p F. FunctionSamples *getSamplesFor(const Function &F) { return &Profiles[F.getName()]; } /// \brief Return all the profiles. StringMap<FunctionSamples> &getProfiles() { return Profiles; } /// \brief Report a parse error message. void reportParseError(int64_t LineNumber, Twine Msg) const { Ctx.diagnose(DiagnosticInfoSampleProfile(Buffer->getBufferIdentifier(), LineNumber, Msg)); } /// \brief Create a sample profile reader appropriate to the file format. static ErrorOr<std::unique_ptr<SampleProfileReader>> create(StringRef Filename, LLVMContext &C); protected: /// \brief Map every function to its associated profile. /// /// The profile of every function executed at runtime is collected /// in the structure FunctionSamples. This maps function objects /// to their corresponding profiles. StringMap<FunctionSamples> Profiles; /// \brief LLVM context used to emit diagnostics. LLVMContext &Ctx; /// \brief Memory buffer holding the profile file. std::unique_ptr<MemoryBuffer> Buffer; }; class SampleProfileReaderText : public SampleProfileReader { public: SampleProfileReaderText(std::unique_ptr<MemoryBuffer> B, LLVMContext &C) : SampleProfileReader(std::move(B), C) {} /// \brief Read and validate the file header. std::error_code readHeader() override { return sampleprof_error::success; } /// \brief Read sample profiles from the associated file. std::error_code read() override; }; class SampleProfileReaderBinary : public SampleProfileReader { public: SampleProfileReaderBinary(std::unique_ptr<MemoryBuffer> B, LLVMContext &C) : SampleProfileReader(std::move(B), C), Data(nullptr), End(nullptr) {} /// \brief Read and validate the file header. std::error_code readHeader() override; /// \brief Read sample profiles from the associated file. std::error_code read() override; /// \brief Return true if \p Buffer is in the format supported by this class. static bool hasFormat(const MemoryBuffer &Buffer); protected: /// \brief Read a numeric value of type T from the profile. /// /// If an error occurs during decoding, a diagnostic message is emitted and /// EC is set. /// /// \returns the read value. template <typename T> ErrorOr<T> readNumber(); /// \brief Read a string from the profile. /// /// If an error occurs during decoding, a diagnostic message is emitted and /// EC is set. /// /// \returns the read value. ErrorOr<StringRef> readString(); /// \brief Return true if we've reached the end of file. bool at_eof() const { return Data >= End; } /// \brief Points to the current location in the buffer. const uint8_t *Data; /// \brief Points to the end of the buffer. const uint8_t *End; }; } // End namespace sampleprof } // End namespace llvm #endif // LLVM_PROFILEDATA_SAMPLEPROFREADER_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/ProfileData/SampleProfWriter.h
//===- SampleProfWriter.h - Write LLVM sample profile data ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains definitions needed for writing sample profiles. // //===----------------------------------------------------------------------===// #ifndef LLVM_PROFILEDATA_SAMPLEPROFWRITER_H #define LLVM_PROFILEDATA_SAMPLEPROFWRITER_H #include "llvm/ADT/StringRef.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/ProfileData/SampleProf.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace sampleprof { enum SampleProfileFormat { SPF_None = 0, SPF_Text, SPF_Binary, SPF_GCC }; /// \brief Sample-based profile writer. Base class. class SampleProfileWriter { public: SampleProfileWriter(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags) : OS(Filename, EC, Flags) {} virtual ~SampleProfileWriter() {} /// \brief Write sample profiles in \p S for function \p FName. /// /// \returns true if the file was updated successfully. False, otherwise. virtual bool write(StringRef FName, const FunctionSamples &S) = 0; /// \brief Write sample profiles in \p S for function \p F. bool write(const Function &F, const FunctionSamples &S) { return write(F.getName(), S); } /// \brief Write all the sample profiles for all the functions in \p M. /// /// \returns true if the file was updated successfully. False, otherwise. bool write(const Module &M, StringMap<FunctionSamples> &P) { for (const auto &F : M) { StringRef Name = F.getName(); if (!write(Name, P[Name])) return false; } return true; } /// \brief Write all the sample profiles in the given map of samples. /// /// \returns true if the file was updated successfully. False, otherwise. bool write(StringMap<FunctionSamples> &ProfileMap) { for (auto &I : ProfileMap) { StringRef FName = I.first(); FunctionSamples &Profile = I.second; if (!write(FName, Profile)) return false; } return true; } /// \brief Profile writer factory. Create a new writer based on the value of /// \p Format. static ErrorOr<std::unique_ptr<SampleProfileWriter>> create(StringRef Filename, SampleProfileFormat Format); protected: /// \brief Output stream where to emit the profile to. raw_fd_ostream OS; }; /// \brief Sample-based profile writer (text format). class SampleProfileWriterText : public SampleProfileWriter { public: SampleProfileWriterText(StringRef F, std::error_code &EC) : SampleProfileWriter(F, EC, sys::fs::F_Text) {} bool write(StringRef FName, const FunctionSamples &S) override; bool write(const Module &M, StringMap<FunctionSamples> &P) { return SampleProfileWriter::write(M, P); } }; /// \brief Sample-based profile writer (binary format). class SampleProfileWriterBinary : public SampleProfileWriter { public: SampleProfileWriterBinary(StringRef F, std::error_code &EC); bool write(StringRef F, const FunctionSamples &S) override; bool write(const Module &M, StringMap<FunctionSamples> &P) { return SampleProfileWriter::write(M, P); } }; } // End namespace sampleprof } // End namespace llvm #endif // LLVM_PROFILEDATA_SAMPLEPROFWRITER_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/OacrIgnoreCond.h
//===--- OacrIgnoreCond.h - OACR directives ---------------------*- C++ -*-===// /////////////////////////////////////////////////////////////////////////////// // // // OacrIgnoreCond.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once // // In free builds, configuration options relating to compiler switches, // most importantly languages, become constants, thereby removing // codepaths and reducing disk footprint. // // OACR has a number of warnings however for these degenerate conditionals, // which this file suppresses. // OACR error 6235 #pragma prefast( \ disable \ : __WARNING_NONZEROLOGICALOR, \ "external project has dead branches for unsupported configuration combinations, by design") // OACR error 6236 #pragma prefast( \ disable \ : __WARNING_LOGICALORNONZERO, \ "external project has dead branches for unsupported configuration combinations, by design") // OACR error 6236 #pragma prefast( \ disable \ : __WARNING_ZEROLOGICALANDLOSINGSIDEEFFECTS, \ "external project has dead branches for unsupported configuration combinations, by design") // OACR error 6285 #pragma prefast( \ disable \ : __WARNING_LOGICALOROFCONSTANTS, \ "external project has dead branches for unsupported configuration combinations, by design") // OACR error 6286 #pragma prefast( \ disable \ : __WARNING_NONZEROLOGICALORLOSINGSIDEEFFECTS, \ "external project has dead branches for unsupported configuration combinations, by design") // OACR error 6287 #pragma prefast( \ disable \ : __WARNING_REDUNDANTTEST, \ "external project has dead branches for unsupported configuration combinations, by design") // local variable is initialized but not referenced - every LangOpts use on // stack triggers this #pragma warning(disable : 4189)
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/AlignOf.h
//===--- AlignOf.h - Portable calculation of type alignment -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the AlignOf function that computes alignments for // arbitrary types. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ALIGNOF_H #define LLVM_SUPPORT_ALIGNOF_H #include "llvm/Support/Compiler.h" #include <cstddef> namespace llvm { template <typename T> struct AlignmentCalcImpl { char x; #if defined(_MSC_VER) // Disables "structure was padded due to __declspec(align())" warnings that are // generated by any class using AlignOf<T> with a manually specified alignment. // Although the warning is disabled in the LLVM project we need this pragma // as AlignOf.h is a published support header that's available for use // out-of-tree, and we would like that to compile cleanly at /W4. #pragma warning(suppress : 4324) #endif T t; private: AlignmentCalcImpl() {} // Never instantiate. }; /// AlignOf - A templated class that contains an enum value representing /// the alignment of the template argument. For example, /// AlignOf<int>::Alignment represents the alignment of type "int". The /// alignment calculated is the minimum alignment, and not necessarily /// the "desired" alignment returned by GCC's __alignof__ (for example). Note /// that because the alignment is an enum value, it can be used as a /// compile-time constant (e.g., for template instantiation). template <typename T> struct AlignOf { #ifndef _MSC_VER // Avoid warnings from GCC like: // comparison between 'enum llvm::AlignOf<X>::<anonymous>' and 'enum // llvm::AlignOf<Y>::<anonymous>' [-Wenum-compare] // by using constexpr instead of enum. // (except on MSVC, since it doesn't support constexpr yet). static constexpr unsigned Alignment = static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)); #else enum { Alignment = static_cast<unsigned int>(sizeof(AlignmentCalcImpl<T>) - sizeof(T)) }; #endif enum { Alignment_GreaterEqual_2Bytes = Alignment >= 2 ? 1 : 0 }; enum { Alignment_GreaterEqual_4Bytes = Alignment >= 4 ? 1 : 0 }; enum { Alignment_GreaterEqual_8Bytes = Alignment >= 8 ? 1 : 0 }; enum { Alignment_GreaterEqual_16Bytes = Alignment >= 16 ? 1 : 0 }; enum { Alignment_LessEqual_2Bytes = Alignment <= 2 ? 1 : 0 }; enum { Alignment_LessEqual_4Bytes = Alignment <= 4 ? 1 : 0 }; enum { Alignment_LessEqual_8Bytes = Alignment <= 8 ? 1 : 0 }; enum { Alignment_LessEqual_16Bytes = Alignment <= 16 ? 1 : 0 }; }; #ifndef _MSC_VER template <typename T> constexpr unsigned AlignOf<T>::Alignment; #endif /// alignOf - A templated function that returns the minimum alignment of /// of a type. This provides no extra functionality beyond the AlignOf /// class besides some cosmetic cleanliness. Example usage: /// alignOf<int>() returns the alignment of an int. template <typename T> inline unsigned alignOf() { return AlignOf<T>::Alignment; } /// \struct AlignedCharArray /// \brief Helper for building an aligned character array type. /// /// This template is used to explicitly build up a collection of aligned /// character array types. We have to build these up using a macro and explicit /// specialization to cope with old versions of MSVC and GCC where only an /// integer literal can be used to specify an alignment constraint. Once built /// up here, we can then begin to indirect between these using normal C++ /// template parameters. // MSVC requires special handling here. #ifndef _MSC_VER #if __has_feature(cxx_alignas) template<std::size_t Alignment, std::size_t Size> struct AlignedCharArray { alignas(Alignment) char buffer[Size]; }; #elif defined(__GNUC__) || defined(__IBM_ATTRIBUTES) /// \brief Create a type with an aligned char buffer. template<std::size_t Alignment, std::size_t Size> struct AlignedCharArray; #define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ template<std::size_t Size> \ struct AlignedCharArray<x, Size> { \ __attribute__((aligned(x))) char buffer[Size]; \ }; LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(1) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(2) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(4) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(8) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128) #undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT #else # error No supported align as directive. #endif #else // _MSC_VER /// \brief Create a type with an aligned char buffer. template<std::size_t Alignment, std::size_t Size> struct AlignedCharArray; // We provide special variations of this template for the most common // alignments because __declspec(align(...)) doesn't actually work when it is // a member of a by-value function argument in MSVC, even if the alignment // request is something reasonably like 8-byte or 16-byte. Note that we can't // even include the declspec with the union that forces the alignment because // MSVC warns on the existence of the declspec despite the union member forcing // proper alignment. template<std::size_t Size> struct AlignedCharArray<1, Size> { union { char aligned; char buffer[Size]; }; }; template<std::size_t Size> struct AlignedCharArray<2, Size> { union { short aligned; char buffer[Size]; }; }; template<std::size_t Size> struct AlignedCharArray<4, Size> { union { int aligned; char buffer[Size]; }; }; template<std::size_t Size> struct AlignedCharArray<8, Size> { union { double aligned; char buffer[Size]; }; }; // The rest of these are provided with a __declspec(align(...)) and we simply // can't pass them by-value as function arguments on MSVC. #define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \ template<std::size_t Size> \ struct AlignedCharArray<x, Size> { \ __declspec(align(x)) char buffer[Size]; \ }; LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64) LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128) #undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT #endif // _MSC_VER namespace detail { template <typename T1, typename T2 = char, typename T3 = char, typename T4 = char, typename T5 = char, typename T6 = char, typename T7 = char, typename T8 = char, typename T9 = char, typename T10 = char> class AlignerImpl { T1 t1; T2 t2; T3 t3; T4 t4; T5 t5; T6 t6; T7 t7; T8 t8; T9 t9; T10 t10; AlignerImpl(); // Never defined or instantiated. }; template <typename T1, typename T2 = char, typename T3 = char, typename T4 = char, typename T5 = char, typename T6 = char, typename T7 = char, typename T8 = char, typename T9 = char, typename T10 = char> union SizerImpl { char arr1[sizeof(T1)], arr2[sizeof(T2)], arr3[sizeof(T3)], arr4[sizeof(T4)], arr5[sizeof(T5)], arr6[sizeof(T6)], arr7[sizeof(T7)], arr8[sizeof(T8)], arr9[sizeof(T9)], arr10[sizeof(T10)]; }; } // end namespace detail /// \brief This union template exposes a suitably aligned and sized character /// array member which can hold elements of any of up to ten types. /// /// These types may be arrays, structs, or any other types. The goal is to /// expose a char array buffer member which can be used as suitable storage for /// a placement new of any of these types. Support for more than ten types can /// be added at the cost of more boilerplate. template <typename T1, typename T2 = char, typename T3 = char, typename T4 = char, typename T5 = char, typename T6 = char, typename T7 = char, typename T8 = char, typename T9 = char, typename T10 = char> struct AlignedCharArrayUnion : llvm::AlignedCharArray< AlignOf<detail::AlignerImpl<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> >::Alignment, sizeof(detail::SizerImpl<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>)> { }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/BranchProbability.h
//===- BranchProbability.h - Branch Probability Wrapper ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Definition of BranchProbability shared by IR and Machine Instructions. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_BRANCHPROBABILITY_H #define LLVM_SUPPORT_BRANCHPROBABILITY_H #include "llvm/Support/DataTypes.h" #include <cassert> namespace llvm { class raw_ostream; // This class represents Branch Probability as a non-negative fraction. class BranchProbability { // Numerator uint32_t N; // Denominator uint32_t D; public: BranchProbability(uint32_t n, uint32_t d) : N(n), D(d) { assert(d > 0 && "Denominator cannot be 0!"); assert(n <= d && "Probability cannot be bigger than 1!"); } static BranchProbability getZero() { return BranchProbability(0, 1); } static BranchProbability getOne() { return BranchProbability(1, 1); } uint32_t getNumerator() const { return N; } uint32_t getDenominator() const { return D; } // Return (1 - Probability). BranchProbability getCompl() const { return BranchProbability(D - N, D); } raw_ostream &print(raw_ostream &OS) const; void dump() const; /// \brief Scale a large integer. /// /// Scales \c Num. Guarantees full precision. Returns the floor of the /// result. /// /// \return \c Num times \c this. uint64_t scale(uint64_t Num) const; /// \brief Scale a large integer by the inverse. /// /// Scales \c Num by the inverse of \c this. Guarantees full precision. /// Returns the floor of the result. /// /// \return \c Num divided by \c this. uint64_t scaleByInverse(uint64_t Num) const; bool operator==(BranchProbability RHS) const { return (uint64_t)N * RHS.D == (uint64_t)D * RHS.N; } bool operator!=(BranchProbability RHS) const { return !(*this == RHS); } bool operator<(BranchProbability RHS) const { return (uint64_t)N * RHS.D < (uint64_t)D * RHS.N; } bool operator>(BranchProbability RHS) const { return RHS < *this; } bool operator<=(BranchProbability RHS) const { return !(RHS < *this); } bool operator>=(BranchProbability RHS) const { return !(*this < RHS); } }; inline raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob) { return Prob.print(OS); } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/TargetRegistry.h
//===-- Support/TargetRegistry.h - Target Registration ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file exposes the TargetRegistry interface, which tools can use to access // the appropriate target specific classes (TargetMachine, AsmPrinter, etc.) // which have been registered. // // Target specific class implementations should register themselves using the // appropriate TargetRegistry interfaces. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TARGETREGISTRY_H #define LLVM_SUPPORT_TARGETREGISTRY_H #include "llvm-c/Disassembler.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/FormattedStream.h" #include <cassert> #include <memory> #include <string> namespace llvm { class AsmPrinter; class MCAsmBackend; class MCAsmInfo; class MCAsmParser; class MCCodeEmitter; class MCCodeGenInfo; class MCContext; class MCDisassembler; class MCInstrAnalysis; class MCInstPrinter; class MCInstrInfo; class MCRegisterInfo; class MCStreamer; class MCSubtargetInfo; class MCSymbolizer; class MCRelocationInfo; class MCTargetAsmParser; class MCTargetOptions; class MCTargetStreamer; class TargetMachine; class TargetOptions; class raw_ostream; class raw_pwrite_stream; class formatted_raw_ostream; MCStreamer *createNullStreamer(MCContext &Ctx); MCStreamer *createAsmStreamer(MCContext &Ctx, std::unique_ptr<formatted_raw_ostream> OS, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst); /// Takes ownership of \p TAB and \p CE. MCStreamer *createELFStreamer(MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *CE, bool RelaxAll); MCStreamer *createMachOStreamer(MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *CE, bool RelaxAll, bool DWARFMustBeAtTheEnd, bool LabelSections = false); MCRelocationInfo *createMCRelocationInfo(const Triple &TT, MCContext &Ctx); MCSymbolizer *createMCSymbolizer(const Triple &TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr<MCRelocationInfo> &&RelInfo); /// Target - Wrapper for Target specific information. /// /// For registration purposes, this is a POD type so that targets can be /// registered without the use of static constructors. /// /// Targets should implement a single global instance of this class (which /// will be zero initialized), and pass that instance to the TargetRegistry as /// part of their initialization. class Target { public: friend struct TargetRegistry; typedef bool (*ArchMatchFnTy)(Triple::ArchType Arch); typedef MCAsmInfo *(*MCAsmInfoCtorFnTy)(const MCRegisterInfo &MRI, const Triple &TT); typedef MCCodeGenInfo *(*MCCodeGenInfoCtorFnTy)(const Triple &TT, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL); typedef MCInstrInfo *(*MCInstrInfoCtorFnTy)(void); typedef MCInstrAnalysis *(*MCInstrAnalysisCtorFnTy)(const MCInstrInfo *Info); typedef MCRegisterInfo *(*MCRegInfoCtorFnTy)(const Triple &TT); typedef MCSubtargetInfo *(*MCSubtargetInfoCtorFnTy)(const Triple &TT, StringRef CPU, StringRef Features); typedef TargetMachine *(*TargetMachineCtorTy)( const Target &T, const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL); // If it weren't for layering issues (this header is in llvm/Support, but // depends on MC?) this should take the Streamer by value rather than rvalue // reference. typedef AsmPrinter *(*AsmPrinterCtorTy)( TargetMachine &TM, std::unique_ptr<MCStreamer> &&Streamer); typedef MCAsmBackend *(*MCAsmBackendCtorTy)(const Target &T, const MCRegisterInfo &MRI, const Triple &TT, StringRef CPU); typedef MCTargetAsmParser *(*MCAsmParserCtorTy)( MCSubtargetInfo &STI, MCAsmParser &P, const MCInstrInfo &MII, const MCTargetOptions &Options); typedef MCDisassembler *(*MCDisassemblerCtorTy)(const Target &T, const MCSubtargetInfo &STI, MCContext &Ctx); typedef MCInstPrinter *(*MCInstPrinterCtorTy)(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI); typedef MCCodeEmitter *(*MCCodeEmitterCtorTy)(const MCInstrInfo &II, const MCRegisterInfo &MRI, MCContext &Ctx); typedef MCStreamer *(*ELFStreamerCtorTy)(const Triple &T, MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll); typedef MCStreamer *(*MachOStreamerCtorTy)(MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll, bool DWARFMustBeAtTheEnd); typedef MCStreamer *(*COFFStreamerCtorTy)(MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll); typedef MCTargetStreamer *(*NullTargetStreamerCtorTy)(MCStreamer &S); typedef MCTargetStreamer *(*AsmTargetStreamerCtorTy)( MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint, bool IsVerboseAsm); typedef MCTargetStreamer *(*ObjectTargetStreamerCtorTy)( MCStreamer &S, const MCSubtargetInfo &STI); typedef MCRelocationInfo *(*MCRelocationInfoCtorTy)(const Triple &TT, MCContext &Ctx); typedef MCSymbolizer *(*MCSymbolizerCtorTy)( const Triple &TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr<MCRelocationInfo> &&RelInfo); private: /// Next - The next registered target in the linked list, maintained by the /// TargetRegistry. Target *Next; /// The target function for checking if an architecture is supported. ArchMatchFnTy ArchMatchFn; /// Name - The target name. const char *Name; /// ShortDesc - A short description of the target. const char *ShortDesc; /// HasJIT - Whether this target supports the JIT. bool HasJIT; /// MCAsmInfoCtorFn - Constructor function for this target's MCAsmInfo, if /// registered. MCAsmInfoCtorFnTy MCAsmInfoCtorFn; /// MCCodeGenInfoCtorFn - Constructor function for this target's /// MCCodeGenInfo, if registered. MCCodeGenInfoCtorFnTy MCCodeGenInfoCtorFn; /// MCInstrInfoCtorFn - Constructor function for this target's MCInstrInfo, /// if registered. MCInstrInfoCtorFnTy MCInstrInfoCtorFn; /// MCInstrAnalysisCtorFn - Constructor function for this target's /// MCInstrAnalysis, if registered. MCInstrAnalysisCtorFnTy MCInstrAnalysisCtorFn; /// MCRegInfoCtorFn - Constructor function for this target's MCRegisterInfo, /// if registered. MCRegInfoCtorFnTy MCRegInfoCtorFn; /// MCSubtargetInfoCtorFn - Constructor function for this target's /// MCSubtargetInfo, if registered. MCSubtargetInfoCtorFnTy MCSubtargetInfoCtorFn; /// TargetMachineCtorFn - Construction function for this target's /// TargetMachine, if registered. TargetMachineCtorTy TargetMachineCtorFn; /// MCAsmBackendCtorFn - Construction function for this target's /// MCAsmBackend, if registered. MCAsmBackendCtorTy MCAsmBackendCtorFn; /// MCAsmParserCtorFn - Construction function for this target's /// MCTargetAsmParser, if registered. MCAsmParserCtorTy MCAsmParserCtorFn; /// AsmPrinterCtorFn - Construction function for this target's AsmPrinter, /// if registered. AsmPrinterCtorTy AsmPrinterCtorFn; /// MCDisassemblerCtorFn - Construction function for this target's /// MCDisassembler, if registered. MCDisassemblerCtorTy MCDisassemblerCtorFn; /// MCInstPrinterCtorFn - Construction function for this target's /// MCInstPrinter, if registered. MCInstPrinterCtorTy MCInstPrinterCtorFn; /// MCCodeEmitterCtorFn - Construction function for this target's /// CodeEmitter, if registered. MCCodeEmitterCtorTy MCCodeEmitterCtorFn; // Construction functions for the various object formats, if registered. COFFStreamerCtorTy COFFStreamerCtorFn; MachOStreamerCtorTy MachOStreamerCtorFn; ELFStreamerCtorTy ELFStreamerCtorFn; /// Construction function for this target's null TargetStreamer, if /// registered (default = nullptr). NullTargetStreamerCtorTy NullTargetStreamerCtorFn; /// Construction function for this target's asm TargetStreamer, if /// registered (default = nullptr). AsmTargetStreamerCtorTy AsmTargetStreamerCtorFn; /// Construction function for this target's obj TargetStreamer, if /// registered (default = nullptr). ObjectTargetStreamerCtorTy ObjectTargetStreamerCtorFn; /// MCRelocationInfoCtorFn - Construction function for this target's /// MCRelocationInfo, if registered (default = llvm::createMCRelocationInfo) MCRelocationInfoCtorTy MCRelocationInfoCtorFn; /// MCSymbolizerCtorFn - Construction function for this target's /// MCSymbolizer, if registered (default = llvm::createMCSymbolizer) MCSymbolizerCtorTy MCSymbolizerCtorFn; public: Target() : COFFStreamerCtorFn(nullptr), MachOStreamerCtorFn(nullptr), ELFStreamerCtorFn(nullptr), NullTargetStreamerCtorFn(nullptr), AsmTargetStreamerCtorFn(nullptr), ObjectTargetStreamerCtorFn(nullptr), MCRelocationInfoCtorFn(nullptr), MCSymbolizerCtorFn(nullptr) {} /// @name Target Information /// @{ // getNext - Return the next registered target. const Target *getNext() const { return Next; } /// getName - Get the target name. const char *getName() const { return Name; } /// getShortDescription - Get a short description of the target. const char *getShortDescription() const { return ShortDesc; } /// @} /// @name Feature Predicates /// @{ /// hasJIT - Check if this targets supports the just-in-time compilation. bool hasJIT() const { return HasJIT; } /// hasTargetMachine - Check if this target supports code generation. bool hasTargetMachine() const { return TargetMachineCtorFn != nullptr; } /// hasMCAsmBackend - Check if this target supports .o generation. bool hasMCAsmBackend() const { return MCAsmBackendCtorFn != nullptr; } /// @} /// @name Feature Constructors /// @{ /// createMCAsmInfo - Create a MCAsmInfo implementation for the specified /// target triple. /// /// \param TheTriple This argument is used to determine the target machine /// feature set; it should always be provided. Generally this should be /// either the target triple from the module, or the target triple of the /// host if that does not exist. MCAsmInfo *createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple) const { if (!MCAsmInfoCtorFn) return nullptr; return MCAsmInfoCtorFn(MRI, Triple(TheTriple)); } /// createMCCodeGenInfo - Create a MCCodeGenInfo implementation. /// MCCodeGenInfo *createMCCodeGenInfo(StringRef TT, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) const { if (!MCCodeGenInfoCtorFn) return nullptr; return MCCodeGenInfoCtorFn(Triple(TT), RM, CM, OL); } /// createMCInstrInfo - Create a MCInstrInfo implementation. /// MCInstrInfo *createMCInstrInfo() const { if (!MCInstrInfoCtorFn) return nullptr; return MCInstrInfoCtorFn(); } /// createMCInstrAnalysis - Create a MCInstrAnalysis implementation. /// MCInstrAnalysis *createMCInstrAnalysis(const MCInstrInfo *Info) const { if (!MCInstrAnalysisCtorFn) return nullptr; return MCInstrAnalysisCtorFn(Info); } /// createMCRegInfo - Create a MCRegisterInfo implementation. /// MCRegisterInfo *createMCRegInfo(StringRef TT) const { if (!MCRegInfoCtorFn) return nullptr; return MCRegInfoCtorFn(Triple(TT)); } /// createMCSubtargetInfo - Create a MCSubtargetInfo implementation. /// /// \param TheTriple This argument is used to determine the target machine /// feature set; it should always be provided. Generally this should be /// either the target triple from the module, or the target triple of the /// host if that does not exist. /// \param CPU This specifies the name of the target CPU. /// \param Features This specifies the string representation of the /// additional target features. MCSubtargetInfo *createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const { if (!MCSubtargetInfoCtorFn) return nullptr; return MCSubtargetInfoCtorFn(Triple(TheTriple), CPU, Features); } /// createTargetMachine - Create a target specific machine implementation /// for the specified \p Triple. /// /// \param TT This argument is used to determine the target machine /// feature set; it should always be provided. Generally this should be /// either the target triple from the module, or the target triple of the /// host if that does not exist. TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Reloc::Model RM = Reloc::Default, CodeModel::Model CM = CodeModel::Default, CodeGenOpt::Level OL = CodeGenOpt::Default) const { if (!TargetMachineCtorFn) return nullptr; return TargetMachineCtorFn(*this, Triple(TT), CPU, Features, Options, RM, CM, OL); } /// createMCAsmBackend - Create a target specific assembly parser. /// /// \param TheTriple The target triple string. MCAsmBackend *createMCAsmBackend(const MCRegisterInfo &MRI, StringRef TheTriple, StringRef CPU) const { if (!MCAsmBackendCtorFn) return nullptr; return MCAsmBackendCtorFn(*this, MRI, Triple(TheTriple), CPU); } /// createMCAsmParser - Create a target specific assembly parser. /// /// \param Parser The target independent parser implementation to use for /// parsing and lexing. MCTargetAsmParser *createMCAsmParser(MCSubtargetInfo &STI, MCAsmParser &Parser, const MCInstrInfo &MII, const MCTargetOptions &Options) const { if (!MCAsmParserCtorFn) return nullptr; return MCAsmParserCtorFn(STI, Parser, MII, Options); } /// createAsmPrinter - Create a target specific assembly printer pass. This /// takes ownership of the MCStreamer object. AsmPrinter *createAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> &&Streamer) const { if (!AsmPrinterCtorFn) return nullptr; return AsmPrinterCtorFn(TM, std::move(Streamer)); } MCDisassembler *createMCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx) const { if (!MCDisassemblerCtorFn) return nullptr; return MCDisassemblerCtorFn(*this, STI, Ctx); } MCInstPrinter *createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const { if (!MCInstPrinterCtorFn) return nullptr; return MCInstPrinterCtorFn(T, SyntaxVariant, MAI, MII, MRI); } /// createMCCodeEmitter - Create a target specific code emitter. MCCodeEmitter *createMCCodeEmitter(const MCInstrInfo &II, const MCRegisterInfo &MRI, MCContext &Ctx) const { if (!MCCodeEmitterCtorFn) return nullptr; return MCCodeEmitterCtorFn(II, MRI, Ctx); } /// Create a target specific MCStreamer. /// /// \param T The target triple. /// \param Ctx The target context. /// \param TAB The target assembler backend object. Takes ownership. /// \param OS The stream object. /// \param Emitter The target independent assembler object.Takes ownership. /// \param RelaxAll Relax all fixups? MCStreamer *createMCObjectStreamer(const Triple &T, MCContext &Ctx, MCAsmBackend &TAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, const MCSubtargetInfo &STI, bool RelaxAll, bool DWARFMustBeAtTheEnd) const { MCStreamer *S; switch (T.getObjectFormat()) { default: llvm_unreachable("Unknown object format"); case Triple::COFF: assert(T.isOSWindows() && "only Windows COFF is supported"); S = COFFStreamerCtorFn(Ctx, TAB, OS, Emitter, RelaxAll); break; case Triple::MachO: if (MachOStreamerCtorFn) S = MachOStreamerCtorFn(Ctx, TAB, OS, Emitter, RelaxAll, DWARFMustBeAtTheEnd); else S = createMachOStreamer(Ctx, TAB, OS, Emitter, RelaxAll, DWARFMustBeAtTheEnd); break; case Triple::ELF: if (ELFStreamerCtorFn) S = ELFStreamerCtorFn(T, Ctx, TAB, OS, Emitter, RelaxAll); else S = createELFStreamer(Ctx, TAB, OS, Emitter, RelaxAll); break; } if (ObjectTargetStreamerCtorFn) ObjectTargetStreamerCtorFn(*S, STI); return S; } MCStreamer *createAsmStreamer(MCContext &Ctx, std::unique_ptr<formatted_raw_ostream> OS, bool IsVerboseAsm, bool UseDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst) const { formatted_raw_ostream &OSRef = *OS; MCStreamer *S = llvm::createAsmStreamer(Ctx, std::move(OS), IsVerboseAsm, UseDwarfDirectory, InstPrint, CE, TAB, ShowInst); createAsmTargetStreamer(*S, OSRef, InstPrint, IsVerboseAsm); return S; } MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint, bool IsVerboseAsm) const { if (AsmTargetStreamerCtorFn) return AsmTargetStreamerCtorFn(S, OS, InstPrint, IsVerboseAsm); return nullptr; } MCStreamer *createNullStreamer(MCContext &Ctx) const { MCStreamer *S = llvm::createNullStreamer(Ctx); createNullTargetStreamer(*S); return S; } MCTargetStreamer *createNullTargetStreamer(MCStreamer &S) const { if (NullTargetStreamerCtorFn) return NullTargetStreamerCtorFn(S); return nullptr; } /// createMCRelocationInfo - Create a target specific MCRelocationInfo. /// /// \param TT The target triple. /// \param Ctx The target context. MCRelocationInfo *createMCRelocationInfo(StringRef TT, MCContext &Ctx) const { MCRelocationInfoCtorTy Fn = MCRelocationInfoCtorFn ? MCRelocationInfoCtorFn : llvm::createMCRelocationInfo; return Fn(Triple(TT), Ctx); } /// createMCSymbolizer - Create a target specific MCSymbolizer. /// /// \param TT The target triple. /// \param GetOpInfo The function to get the symbolic information for /// operands. /// \param SymbolLookUp The function to lookup a symbol name. /// \param DisInfo The pointer to the block of symbolic information for above /// call /// back. /// \param Ctx The target context. /// \param RelInfo The relocation information for this target. Takes /// ownership. MCSymbolizer * createMCSymbolizer(StringRef TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr<MCRelocationInfo> &&RelInfo) const { MCSymbolizerCtorTy Fn = MCSymbolizerCtorFn ? MCSymbolizerCtorFn : llvm::createMCSymbolizer; return Fn(Triple(TT), GetOpInfo, SymbolLookUp, DisInfo, Ctx, std::move(RelInfo)); } /// @} }; /// TargetRegistry - Generic interface to target specific features. struct TargetRegistry { // FIXME: Make this a namespace, probably just move all the Register* // functions into Target (currently they all just set members on the Target // anyway, and Target friends this class so those functions can... // function). TargetRegistry() = delete; class iterator { const Target *Current; explicit iterator(Target *T) : Current(T) {} friend struct TargetRegistry; public: using iterator_category = std::forward_iterator_tag; using value_type = Target; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; iterator() : Current(nullptr) {} bool operator==(const iterator &x) const { return Current == x.Current; } bool operator!=(const iterator &x) const { return !operator==(x); } // Iterator traversal: forward iteration only iterator &operator++() { // Preincrement assert(Current && "Cannot increment end iterator!"); Current = Current->getNext(); return *this; } iterator operator++(int) { // Postincrement iterator tmp = *this; ++*this; return tmp; } const Target &operator*() const { assert(Current && "Cannot dereference end iterator!"); return *Current; } const Target *operator->() const { return &operator*(); } }; /// printRegisteredTargetsForVersion - Print the registered targets /// appropriately for inclusion in a tool's version output. static void printRegisteredTargetsForVersion(); /// @name Registry Access /// @{ static iterator_range<iterator> targets(); /// lookupTarget - Lookup a target based on a target triple. /// /// \param Triple - The triple to use for finding a target. /// \param Error - On failure, an error string describing why no target was /// found. static const Target *lookupTarget(const std::string &Triple, std::string &Error); /// lookupTarget - Lookup a target based on an architecture name /// and a target triple. If the architecture name is non-empty, /// then the lookup is done by architecture. Otherwise, the target /// triple is used. /// /// \param ArchName - The architecture to use for finding a target. /// \param TheTriple - The triple to use for finding a target. The /// triple is updated with canonical architecture name if a lookup /// by architecture is done. /// \param Error - On failure, an error string describing why no target was /// found. static const Target *lookupTarget(const std::string &ArchName, Triple &TheTriple, std::string &Error); /// @} /// @name Target Registration /// @{ /// RegisterTarget - Register the given target. Attempts to register a /// target which has already been registered will be ignored. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Name - The target name. This should be a static string. /// @param ShortDesc - A short target description. This should be a static /// string. /// @param ArchMatchFn - The arch match checking function for this target. /// @param HasJIT - Whether the target supports JIT code /// generation. static void RegisterTarget(Target &T, const char *Name, const char *ShortDesc, Target::ArchMatchFnTy ArchMatchFn, bool HasJIT = false); /// RegisterMCAsmInfo - Register a MCAsmInfo implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a MCAsmInfo for the target. static void RegisterMCAsmInfo(Target &T, Target::MCAsmInfoCtorFnTy Fn) { T.MCAsmInfoCtorFn = Fn; } /// RegisterMCCodeGenInfo - Register a MCCodeGenInfo implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a MCCodeGenInfo for the target. static void RegisterMCCodeGenInfo(Target &T, Target::MCCodeGenInfoCtorFnTy Fn) { T.MCCodeGenInfoCtorFn = Fn; } /// RegisterMCInstrInfo - Register a MCInstrInfo implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a MCInstrInfo for the target. static void RegisterMCInstrInfo(Target &T, Target::MCInstrInfoCtorFnTy Fn) { T.MCInstrInfoCtorFn = Fn; } /// RegisterMCInstrAnalysis - Register a MCInstrAnalysis implementation for /// the given target. static void RegisterMCInstrAnalysis(Target &T, Target::MCInstrAnalysisCtorFnTy Fn) { T.MCInstrAnalysisCtorFn = Fn; } /// RegisterMCRegInfo - Register a MCRegisterInfo implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a MCRegisterInfo for the target. static void RegisterMCRegInfo(Target &T, Target::MCRegInfoCtorFnTy Fn) { T.MCRegInfoCtorFn = Fn; } /// RegisterMCSubtargetInfo - Register a MCSubtargetInfo implementation for /// the given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a MCSubtargetInfo for the target. static void RegisterMCSubtargetInfo(Target &T, Target::MCSubtargetInfoCtorFnTy Fn) { T.MCSubtargetInfoCtorFn = Fn; } /// RegisterTargetMachine - Register a TargetMachine implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct a TargetMachine for the target. static void RegisterTargetMachine(Target &T, Target::TargetMachineCtorTy Fn) { T.TargetMachineCtorFn = Fn; } /// RegisterMCAsmBackend - Register a MCAsmBackend implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an AsmBackend for the target. static void RegisterMCAsmBackend(Target &T, Target::MCAsmBackendCtorTy Fn) { T.MCAsmBackendCtorFn = Fn; } /// RegisterMCAsmParser - Register a MCTargetAsmParser implementation for /// the given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCTargetAsmParser for the target. static void RegisterMCAsmParser(Target &T, Target::MCAsmParserCtorTy Fn) { T.MCAsmParserCtorFn = Fn; } /// RegisterAsmPrinter - Register an AsmPrinter implementation for the given /// target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an AsmPrinter for the target. static void RegisterAsmPrinter(Target &T, Target::AsmPrinterCtorTy Fn) { T.AsmPrinterCtorFn = Fn; } /// RegisterMCDisassembler - Register a MCDisassembler implementation for /// the given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCDisassembler for the target. static void RegisterMCDisassembler(Target &T, Target::MCDisassemblerCtorTy Fn) { T.MCDisassemblerCtorFn = Fn; } /// RegisterMCInstPrinter - Register a MCInstPrinter implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCInstPrinter for the target. static void RegisterMCInstPrinter(Target &T, Target::MCInstPrinterCtorTy Fn) { T.MCInstPrinterCtorFn = Fn; } /// RegisterMCCodeEmitter - Register a MCCodeEmitter implementation for the /// given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCCodeEmitter for the target. static void RegisterMCCodeEmitter(Target &T, Target::MCCodeEmitterCtorTy Fn) { T.MCCodeEmitterCtorFn = Fn; } static void RegisterCOFFStreamer(Target &T, Target::COFFStreamerCtorTy Fn) { T.COFFStreamerCtorFn = Fn; } static void RegisterMachOStreamer(Target &T, Target::MachOStreamerCtorTy Fn) { T.MachOStreamerCtorFn = Fn; } static void RegisterELFStreamer(Target &T, Target::ELFStreamerCtorTy Fn) { T.ELFStreamerCtorFn = Fn; } static void RegisterNullTargetStreamer(Target &T, Target::NullTargetStreamerCtorTy Fn) { T.NullTargetStreamerCtorFn = Fn; } static void RegisterAsmTargetStreamer(Target &T, Target::AsmTargetStreamerCtorTy Fn) { T.AsmTargetStreamerCtorFn = Fn; } static void RegisterObjectTargetStreamer(Target &T, Target::ObjectTargetStreamerCtorTy Fn) { T.ObjectTargetStreamerCtorFn = Fn; } /// RegisterMCRelocationInfo - Register an MCRelocationInfo /// implementation for the given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCRelocationInfo for the target. static void RegisterMCRelocationInfo(Target &T, Target::MCRelocationInfoCtorTy Fn) { T.MCRelocationInfoCtorFn = Fn; } /// RegisterMCSymbolizer - Register an MCSymbolizer /// implementation for the given target. /// /// Clients are responsible for ensuring that registration doesn't occur /// while another thread is attempting to access the registry. Typically /// this is done by initializing all targets at program startup. /// /// @param T - The target being registered. /// @param Fn - A function to construct an MCSymbolizer for the target. static void RegisterMCSymbolizer(Target &T, Target::MCSymbolizerCtorTy Fn) { T.MCSymbolizerCtorFn = Fn; } /// @} }; //===--------------------------------------------------------------------===// /// RegisterTarget - Helper template for registering a target, for use in the /// target's initialization function. Usage: /// /// /// Target TheFooTarget; // The global target instance. /// /// extern "C" void LLVMInitializeFooTargetInfo() { /// RegisterTarget<Triple::foo> X(TheFooTarget, "foo", "Foo description"); /// } template <Triple::ArchType TargetArchType = Triple::UnknownArch, bool HasJIT = false> struct RegisterTarget { RegisterTarget(Target &T, const char *Name, const char *Desc) { TargetRegistry::RegisterTarget(T, Name, Desc, &getArchMatch, HasJIT); } static bool getArchMatch(Triple::ArchType Arch) { return Arch == TargetArchType; } }; /// RegisterMCAsmInfo - Helper template for registering a target assembly info /// implementation. This invokes the static "Create" method on the class to /// actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCAsmInfo<FooMCAsmInfo> X(TheFooTarget); /// } template <class MCAsmInfoImpl> struct RegisterMCAsmInfo { RegisterMCAsmInfo(Target &T) { TargetRegistry::RegisterMCAsmInfo(T, &Allocator); } private: static MCAsmInfo *Allocator(const MCRegisterInfo & /*MRI*/, const Triple &TT) { return new MCAsmInfoImpl(TT); } }; /// RegisterMCAsmInfoFn - Helper template for registering a target assembly info /// implementation. This invokes the specified function to do the /// construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCAsmInfoFn X(TheFooTarget, TheFunction); /// } struct RegisterMCAsmInfoFn { RegisterMCAsmInfoFn(Target &T, Target::MCAsmInfoCtorFnTy Fn) { TargetRegistry::RegisterMCAsmInfo(T, Fn); } }; /// RegisterMCCodeGenInfo - Helper template for registering a target codegen /// info /// implementation. This invokes the static "Create" method on the class /// to actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCCodeGenInfo<FooMCCodeGenInfo> X(TheFooTarget); /// } template <class MCCodeGenInfoImpl> struct RegisterMCCodeGenInfo { RegisterMCCodeGenInfo(Target &T) { TargetRegistry::RegisterMCCodeGenInfo(T, &Allocator); } private: static MCCodeGenInfo *Allocator(const Triple & /*TT*/, Reloc::Model /*RM*/, CodeModel::Model /*CM*/, CodeGenOpt::Level /*OL*/) { return new MCCodeGenInfoImpl(); } }; /// RegisterMCCodeGenInfoFn - Helper template for registering a target codegen /// info implementation. This invokes the specified function to do the /// construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCCodeGenInfoFn X(TheFooTarget, TheFunction); /// } struct RegisterMCCodeGenInfoFn { RegisterMCCodeGenInfoFn(Target &T, Target::MCCodeGenInfoCtorFnTy Fn) { TargetRegistry::RegisterMCCodeGenInfo(T, Fn); } }; /// RegisterMCInstrInfo - Helper template for registering a target instruction /// info implementation. This invokes the static "Create" method on the class /// to actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCInstrInfo<FooMCInstrInfo> X(TheFooTarget); /// } template <class MCInstrInfoImpl> struct RegisterMCInstrInfo { RegisterMCInstrInfo(Target &T) { TargetRegistry::RegisterMCInstrInfo(T, &Allocator); } private: static MCInstrInfo *Allocator() { return new MCInstrInfoImpl(); } }; /// RegisterMCInstrInfoFn - Helper template for registering a target /// instruction info implementation. This invokes the specified function to /// do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCInstrInfoFn X(TheFooTarget, TheFunction); /// } struct RegisterMCInstrInfoFn { RegisterMCInstrInfoFn(Target &T, Target::MCInstrInfoCtorFnTy Fn) { TargetRegistry::RegisterMCInstrInfo(T, Fn); } }; /// RegisterMCInstrAnalysis - Helper template for registering a target /// instruction analyzer implementation. This invokes the static "Create" /// method on the class to actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCInstrAnalysis<FooMCInstrAnalysis> X(TheFooTarget); /// } template <class MCInstrAnalysisImpl> struct RegisterMCInstrAnalysis { RegisterMCInstrAnalysis(Target &T) { TargetRegistry::RegisterMCInstrAnalysis(T, &Allocator); } private: static MCInstrAnalysis *Allocator(const MCInstrInfo *Info) { return new MCInstrAnalysisImpl(Info); } }; /// RegisterMCInstrAnalysisFn - Helper template for registering a target /// instruction analyzer implementation. This invokes the specified function /// to do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCInstrAnalysisFn X(TheFooTarget, TheFunction); /// } struct RegisterMCInstrAnalysisFn { RegisterMCInstrAnalysisFn(Target &T, Target::MCInstrAnalysisCtorFnTy Fn) { TargetRegistry::RegisterMCInstrAnalysis(T, Fn); } }; /// RegisterMCRegInfo - Helper template for registering a target register info /// implementation. This invokes the static "Create" method on the class to /// actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCRegInfo<FooMCRegInfo> X(TheFooTarget); /// } template <class MCRegisterInfoImpl> struct RegisterMCRegInfo { RegisterMCRegInfo(Target &T) { TargetRegistry::RegisterMCRegInfo(T, &Allocator); } private: static MCRegisterInfo *Allocator(const Triple & /*TT*/) { return new MCRegisterInfoImpl(); } }; /// RegisterMCRegInfoFn - Helper template for registering a target register /// info implementation. This invokes the specified function to do the /// construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCRegInfoFn X(TheFooTarget, TheFunction); /// } struct RegisterMCRegInfoFn { RegisterMCRegInfoFn(Target &T, Target::MCRegInfoCtorFnTy Fn) { TargetRegistry::RegisterMCRegInfo(T, Fn); } }; /// RegisterMCSubtargetInfo - Helper template for registering a target /// subtarget info implementation. This invokes the static "Create" method /// on the class to actually do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCSubtargetInfo<FooMCSubtargetInfo> X(TheFooTarget); /// } template <class MCSubtargetInfoImpl> struct RegisterMCSubtargetInfo { RegisterMCSubtargetInfo(Target &T) { TargetRegistry::RegisterMCSubtargetInfo(T, &Allocator); } private: static MCSubtargetInfo *Allocator(const Triple & /*TT*/, StringRef /*CPU*/, StringRef /*FS*/) { return new MCSubtargetInfoImpl(); } }; /// RegisterMCSubtargetInfoFn - Helper template for registering a target /// subtarget info implementation. This invokes the specified function to /// do the construction. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterMCSubtargetInfoFn X(TheFooTarget, TheFunction); /// } struct RegisterMCSubtargetInfoFn { RegisterMCSubtargetInfoFn(Target &T, Target::MCSubtargetInfoCtorFnTy Fn) { TargetRegistry::RegisterMCSubtargetInfo(T, Fn); } }; /// RegisterTargetMachine - Helper template for registering a target machine /// implementation, for use in the target machine initialization /// function. Usage: /// /// extern "C" void LLVMInitializeFooTarget() { /// extern Target TheFooTarget; /// RegisterTargetMachine<FooTargetMachine> X(TheFooTarget); /// } template <class TargetMachineImpl> struct RegisterTargetMachine { RegisterTargetMachine(Target &T) { TargetRegistry::RegisterTargetMachine(T, &Allocator); } private: static TargetMachine *Allocator(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) { return new TargetMachineImpl(T, TT, CPU, FS, Options, RM, CM, OL); } }; /// RegisterMCAsmBackend - Helper template for registering a target specific /// assembler backend. Usage: /// /// extern "C" void LLVMInitializeFooMCAsmBackend() { /// extern Target TheFooTarget; /// RegisterMCAsmBackend<FooAsmLexer> X(TheFooTarget); /// } template <class MCAsmBackendImpl> struct RegisterMCAsmBackend { RegisterMCAsmBackend(Target &T) { TargetRegistry::RegisterMCAsmBackend(T, &Allocator); } private: static MCAsmBackend *Allocator(const Target &T, const MCRegisterInfo &MRI, const Triple &TheTriple, StringRef CPU) { return new MCAsmBackendImpl(T, MRI, TheTriple, CPU); } }; /// RegisterMCAsmParser - Helper template for registering a target specific /// assembly parser, for use in the target machine initialization /// function. Usage: /// /// extern "C" void LLVMInitializeFooMCAsmParser() { /// extern Target TheFooTarget; /// RegisterMCAsmParser<FooAsmParser> X(TheFooTarget); /// } template <class MCAsmParserImpl> struct RegisterMCAsmParser { RegisterMCAsmParser(Target &T) { TargetRegistry::RegisterMCAsmParser(T, &Allocator); } private: static MCTargetAsmParser *Allocator(MCSubtargetInfo &STI, MCAsmParser &P, const MCInstrInfo &MII, const MCTargetOptions &Options) { return new MCAsmParserImpl(STI, P, MII, Options); } }; /// RegisterAsmPrinter - Helper template for registering a target specific /// assembly printer, for use in the target machine initialization /// function. Usage: /// /// extern "C" void LLVMInitializeFooAsmPrinter() { /// extern Target TheFooTarget; /// RegisterAsmPrinter<FooAsmPrinter> X(TheFooTarget); /// } template <class AsmPrinterImpl> struct RegisterAsmPrinter { RegisterAsmPrinter(Target &T) { TargetRegistry::RegisterAsmPrinter(T, &Allocator); } private: static AsmPrinter *Allocator(TargetMachine &TM, std::unique_ptr<MCStreamer> &&Streamer) { return new AsmPrinterImpl(TM, std::move(Streamer)); } }; /// RegisterMCCodeEmitter - Helper template for registering a target specific /// machine code emitter, for use in the target initialization /// function. Usage: /// /// extern "C" void LLVMInitializeFooMCCodeEmitter() { /// extern Target TheFooTarget; /// RegisterMCCodeEmitter<FooCodeEmitter> X(TheFooTarget); /// } template <class MCCodeEmitterImpl> struct RegisterMCCodeEmitter { RegisterMCCodeEmitter(Target &T) { TargetRegistry::RegisterMCCodeEmitter(T, &Allocator); } private: static MCCodeEmitter *Allocator(const MCInstrInfo & /*II*/, const MCRegisterInfo & /*MRI*/, MCContext & /*Ctx*/) { return new MCCodeEmitterImpl(); } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/FileOutputBuffer.h
//=== FileOutputBuffer.h - File Output Buffer -------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Utility for creating a in-memory buffer that will be written to a file. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_FILEOUTPUTBUFFER_H #define LLVM_SUPPORT_FILEOUTPUTBUFFER_H #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/FileSystem.h" namespace llvm { /// FileOutputBuffer - This interface provides simple way to create an in-memory /// buffer which will be written to a file. During the lifetime of these /// objects, the content or existence of the specified file is undefined. That /// is, creating an OutputBuffer for a file may immediately remove the file. /// If the FileOutputBuffer is committed, the target file's content will become /// the buffer content at the time of the commit. If the FileOutputBuffer is /// not committed, the file will be deleted in the FileOutputBuffer destructor. class FileOutputBuffer { public: enum { F_executable = 1 /// set the 'x' bit on the resulting file }; /// Factory method to create an OutputBuffer object which manages a read/write /// buffer of the specified size. When committed, the buffer will be written /// to the file at the specified path. static std::error_code create(StringRef FilePath, size_t Size, std::unique_ptr<FileOutputBuffer> &Result, unsigned Flags = 0); /// Returns a pointer to the start of the buffer. uint8_t *getBufferStart() { return (uint8_t*)Region->data(); } /// Returns a pointer to the end of the buffer. uint8_t *getBufferEnd() { return (uint8_t*)Region->data() + Region->size(); } /// Returns size of the buffer. size_t getBufferSize() const { return Region->size(); } /// Returns path where file will show up if buffer is committed. StringRef getPath() const { return FinalPath; } /// Flushes the content of the buffer to its file and deallocates the /// buffer. If commit() is not called before this object's destructor /// is called, the file is deleted in the destructor. The optional parameter /// is used if it turns out you want the file size to be smaller than /// initially requested. std::error_code commit(); /// If this object was previously committed, the destructor just deletes /// this object. If this object was not committed, the destructor /// deallocates the buffer and the target file is never written. ~FileOutputBuffer(); private: FileOutputBuffer(const FileOutputBuffer &) = delete; FileOutputBuffer &operator=(const FileOutputBuffer &) = delete; FileOutputBuffer(std::unique_ptr<llvm::sys::fs::mapped_file_region> R, StringRef Path, StringRef TempPath); std::unique_ptr<llvm::sys::fs::mapped_file_region> Region; SmallString<128> FinalPath; SmallString<128> TempPath; }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/LEB128.h
//===- llvm/Support/LEB128.h - [SU]LEB128 utility functions -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares some utility functions for encoding SLEB128 and // ULEB128 values. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_LEB128_H #define LLVM_SUPPORT_LEB128_H #include "llvm/Support/raw_ostream.h" namespace llvm { /// Utility function to encode a SLEB128 value to an output stream. inline void encodeSLEB128(int64_t Value, raw_ostream &OS) { bool More; do { uint8_t Byte = Value & 0x7f; // NOTE: this assumes that this signed shift is an arithmetic right shift. Value >>= 7; More = !((((Value == 0 ) && ((Byte & 0x40) == 0)) || ((Value == -1) && ((Byte & 0x40) != 0)))); if (More) Byte |= 0x80; // Mark this byte to show that more bytes will follow. OS << char(Byte); } while (More); } /// Utility function to encode a ULEB128 value to an output stream. inline void encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned Padding = 0) { do { uint8_t Byte = Value & 0x7f; Value >>= 7; if (Value != 0 || Padding != 0) Byte |= 0x80; // Mark this byte to show that more bytes will follow. OS << char(Byte); } while (Value != 0); // Pad with 0x80 and emit a null byte at the end. if (Padding != 0) { for (; Padding != 1; --Padding) OS << '\x80'; OS << '\x00'; } } /// Utility function to encode a ULEB128 value to a buffer. Returns /// the length in bytes of the encoded value. inline unsigned encodeULEB128(uint64_t Value, uint8_t *p, unsigned Padding = 0) { uint8_t *orig_p = p; do { uint8_t Byte = Value & 0x7f; Value >>= 7; if (Value != 0 || Padding != 0) Byte |= 0x80; // Mark this byte to show that more bytes will follow. *p++ = Byte; } while (Value != 0); // Pad with 0x80 and emit a null byte at the end. if (Padding != 0) { for (; Padding != 1; --Padding) *p++ = '\x80'; *p++ = '\x00'; } return (unsigned)(p - orig_p); } /// Utility function to decode a ULEB128 value. inline uint64_t decodeULEB128(const uint8_t *p, unsigned *n = nullptr) { const uint8_t *orig_p = p; uint64_t Value = 0; unsigned Shift = 0; do { Value += uint64_t(*p & 0x7f) << Shift; Shift += 7; } while (*p++ >= 128); if (n) *n = (unsigned)(p - orig_p); return Value; } /// Utility function to decode a SLEB128 value. inline int64_t decodeSLEB128(const uint8_t *p, unsigned *n = nullptr) { const uint8_t *orig_p = p; int64_t Value = 0; unsigned Shift = 0; uint8_t Byte; do { Byte = *p++; Value |= (((uint64_t)(Byte & 0x7f)) << Shift); // HLSL Change - use 64 bits before casting, not after Shift += 7; } while (Byte >= 128); // Sign extend negative numbers. if (Byte & 0x40) Value |= (-1ULL) << Shift; if (n) *n = (unsigned)(p - orig_p); return Value; } /// Utility function to get the size of the ULEB128-encoded value. extern unsigned getULEB128Size(uint64_t Value); /// Utility function to get the size of the SLEB128-encoded value. extern unsigned getSLEB128Size(int64_t Value); } // namespace llvm #endif // LLVM_SYSTEM_LEB128_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/StringPool.h
//===-- StringPool.h - Interned string pool ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares an interned string pool, which helps reduce the cost of // strings by using the same storage for identical strings. // // To intern a string: // // StringPool Pool; // PooledStringPtr Str = Pool.intern("wakka wakka"); // // To use the value of an interned string, use operator bool and operator*: // // if (Str) // cerr << "the string is" << *Str << "\n"; // // Pooled strings are immutable, but you can change a PooledStringPtr to point // to another instance. So that interned strings can eventually be freed, // strings in the string pool are reference-counted (automatically). // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_STRINGPOOL_H #define LLVM_SUPPORT_STRINGPOOL_H #include "llvm/ADT/StringMap.h" #include <cassert> namespace llvm { class PooledStringPtr; /// StringPool - An interned string pool. Use the intern method to add a /// string. Strings are removed automatically as PooledStringPtrs are /// destroyed. class StringPool { /// PooledString - This is the value of an entry in the pool's interning /// table. struct PooledString { StringPool *Pool; ///< So the string can remove itself. unsigned Refcount; ///< Number of referencing PooledStringPtrs. public: PooledString() : Pool(nullptr), Refcount(0) { } }; friend class PooledStringPtr; typedef StringMap<PooledString> table_t; typedef StringMapEntry<PooledString> entry_t; table_t InternTable; public: StringPool(); ~StringPool(); /// intern - Adds a string to the pool and returns a reference-counted /// pointer to it. No additional memory is allocated if the string already /// exists in the pool. PooledStringPtr intern(StringRef Str); /// empty - Checks whether the pool is empty. Returns true if so. /// inline bool empty() const { return InternTable.empty(); } }; /// PooledStringPtr - A pointer to an interned string. Use operator bool to /// test whether the pointer is valid, and operator * to get the string if so. /// This is a lightweight value class with storage requirements equivalent to /// a single pointer, but it does have reference-counting overhead when /// copied. class PooledStringPtr { typedef StringPool::entry_t entry_t; entry_t *S; public: PooledStringPtr() : S(nullptr) {} explicit PooledStringPtr(entry_t *E) : S(E) { if (S) ++S->getValue().Refcount; } PooledStringPtr(const PooledStringPtr &That) : S(That.S) { if (S) ++S->getValue().Refcount; } PooledStringPtr &operator=(const PooledStringPtr &That) { if (S != That.S) { clear(); S = That.S; if (S) ++S->getValue().Refcount; } return *this; } void clear() { if (!S) return; if (--S->getValue().Refcount == 0) { S->getValue().Pool->InternTable.remove(S); S->Destroy(); } S = nullptr; } ~PooledStringPtr() { clear(); } inline const char *begin() const { assert(*this && "Attempt to dereference empty PooledStringPtr!"); return S->getKeyData(); } inline const char *end() const { assert(*this && "Attempt to dereference empty PooledStringPtr!"); return S->getKeyData() + S->getKeyLength(); } inline unsigned size() const { assert(*this && "Attempt to dereference empty PooledStringPtr!"); return S->getKeyLength(); } inline const char *operator*() const { return begin(); } inline explicit operator bool() const { return S != nullptr; } inline bool operator==(const PooledStringPtr &That) const { return S == That.S; } inline bool operator!=(const PooledStringPtr &That) const { return S != That.S; } }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/MachO.h
//===-- llvm/Support/MachO.h - The MachO file format ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines manifest constants for the MachO object file format. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_MACHO_H #define LLVM_SUPPORT_MACHO_H #include "llvm/Support/Compiler.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Host.h" namespace llvm { namespace MachO { // Enums from <mach-o/loader.h> enum : uint32_t { // Constants for the "magic" field in llvm::MachO::mach_header and // llvm::MachO::mach_header_64 MH_MAGIC = 0xFEEDFACEu, MH_CIGAM = 0xCEFAEDFEu, MH_MAGIC_64 = 0xFEEDFACFu, MH_CIGAM_64 = 0xCFFAEDFEu, FAT_MAGIC = 0xCAFEBABEu, FAT_CIGAM = 0xBEBAFECAu }; enum HeaderFileType { // Constants for the "filetype" field in llvm::MachO::mach_header and // llvm::MachO::mach_header_64 MH_OBJECT = 0x1u, MH_EXECUTE = 0x2u, MH_FVMLIB = 0x3u, MH_CORE = 0x4u, MH_PRELOAD = 0x5u, MH_DYLIB = 0x6u, MH_DYLINKER = 0x7u, MH_BUNDLE = 0x8u, MH_DYLIB_STUB = 0x9u, MH_DSYM = 0xAu, MH_KEXT_BUNDLE = 0xBu }; enum { // Constant bits for the "flags" field in llvm::MachO::mach_header and // llvm::MachO::mach_header_64 MH_NOUNDEFS = 0x00000001u, MH_INCRLINK = 0x00000002u, MH_DYLDLINK = 0x00000004u, MH_BINDATLOAD = 0x00000008u, MH_PREBOUND = 0x00000010u, MH_SPLIT_SEGS = 0x00000020u, MH_LAZY_INIT = 0x00000040u, MH_TWOLEVEL = 0x00000080u, MH_FORCE_FLAT = 0x00000100u, MH_NOMULTIDEFS = 0x00000200u, MH_NOFIXPREBINDING = 0x00000400u, MH_PREBINDABLE = 0x00000800u, MH_ALLMODSBOUND = 0x00001000u, MH_SUBSECTIONS_VIA_SYMBOLS = 0x00002000u, MH_CANONICAL = 0x00004000u, MH_WEAK_DEFINES = 0x00008000u, MH_BINDS_TO_WEAK = 0x00010000u, MH_ALLOW_STACK_EXECUTION = 0x00020000u, MH_ROOT_SAFE = 0x00040000u, MH_SETUID_SAFE = 0x00080000u, MH_NO_REEXPORTED_DYLIBS = 0x00100000u, MH_PIE = 0x00200000u, MH_DEAD_STRIPPABLE_DYLIB = 0x00400000u, MH_HAS_TLV_DESCRIPTORS = 0x00800000u, MH_NO_HEAP_EXECUTION = 0x01000000u, MH_APP_EXTENSION_SAFE = 0x02000000u }; enum : uint32_t { // Flags for the "cmd" field in llvm::MachO::load_command LC_REQ_DYLD = 0x80000000u }; enum LoadCommandType : uint32_t { // Constants for the "cmd" field in llvm::MachO::load_command LC_SEGMENT = 0x00000001u, LC_SYMTAB = 0x00000002u, LC_SYMSEG = 0x00000003u, LC_THREAD = 0x00000004u, LC_UNIXTHREAD = 0x00000005u, LC_LOADFVMLIB = 0x00000006u, LC_IDFVMLIB = 0x00000007u, LC_IDENT = 0x00000008u, LC_FVMFILE = 0x00000009u, LC_PREPAGE = 0x0000000Au, LC_DYSYMTAB = 0x0000000Bu, LC_LOAD_DYLIB = 0x0000000Cu, LC_ID_DYLIB = 0x0000000Du, LC_LOAD_DYLINKER = 0x0000000Eu, LC_ID_DYLINKER = 0x0000000Fu, LC_PREBOUND_DYLIB = 0x00000010u, LC_ROUTINES = 0x00000011u, LC_SUB_FRAMEWORK = 0x00000012u, LC_SUB_UMBRELLA = 0x00000013u, LC_SUB_CLIENT = 0x00000014u, LC_SUB_LIBRARY = 0x00000015u, LC_TWOLEVEL_HINTS = 0x00000016u, LC_PREBIND_CKSUM = 0x00000017u, LC_LOAD_WEAK_DYLIB = 0x80000018u, LC_SEGMENT_64 = 0x00000019u, LC_ROUTINES_64 = 0x0000001Au, LC_UUID = 0x0000001Bu, LC_RPATH = 0x8000001Cu, LC_CODE_SIGNATURE = 0x0000001Du, LC_SEGMENT_SPLIT_INFO = 0x0000001Eu, LC_REEXPORT_DYLIB = 0x8000001Fu, LC_LAZY_LOAD_DYLIB = 0x00000020u, LC_ENCRYPTION_INFO = 0x00000021u, LC_DYLD_INFO = 0x00000022u, LC_DYLD_INFO_ONLY = 0x80000022u, LC_LOAD_UPWARD_DYLIB = 0x80000023u, LC_VERSION_MIN_MACOSX = 0x00000024u, LC_VERSION_MIN_IPHONEOS = 0x00000025u, LC_FUNCTION_STARTS = 0x00000026u, LC_DYLD_ENVIRONMENT = 0x00000027u, LC_MAIN = 0x80000028u, LC_DATA_IN_CODE = 0x00000029u, LC_SOURCE_VERSION = 0x0000002Au, LC_DYLIB_CODE_SIGN_DRS = 0x0000002Bu, LC_ENCRYPTION_INFO_64 = 0x0000002Cu, LC_LINKER_OPTION = 0x0000002Du, LC_LINKER_OPTIMIZATION_HINT = 0x0000002Eu }; enum : uint32_t { // Constant bits for the "flags" field in llvm::MachO::segment_command SG_HIGHVM = 0x1u, SG_FVMLIB = 0x2u, SG_NORELOC = 0x4u, SG_PROTECTED_VERSION_1 = 0x8u, // Constant masks for the "flags" field in llvm::MachO::section and // llvm::MachO::section_64 SECTION_TYPE = 0x000000ffu, // SECTION_TYPE SECTION_ATTRIBUTES = 0xffffff00u, // SECTION_ATTRIBUTES SECTION_ATTRIBUTES_USR = 0xff000000u, // SECTION_ATTRIBUTES_USR SECTION_ATTRIBUTES_SYS = 0x00ffff00u // SECTION_ATTRIBUTES_SYS }; /// These are the section type and attributes fields. A MachO section can /// have only one Type, but can have any of the attributes specified. enum SectionType : uint32_t { // Constant masks for the "flags[7:0]" field in llvm::MachO::section and // llvm::MachO::section_64 (mask "flags" with SECTION_TYPE) /// S_REGULAR - Regular section. S_REGULAR = 0x00u, /// S_ZEROFILL - Zero fill on demand section. S_ZEROFILL = 0x01u, /// S_CSTRING_LITERALS - Section with literal C strings. S_CSTRING_LITERALS = 0x02u, /// S_4BYTE_LITERALS - Section with 4 byte literals. S_4BYTE_LITERALS = 0x03u, /// S_8BYTE_LITERALS - Section with 8 byte literals. S_8BYTE_LITERALS = 0x04u, /// S_LITERAL_POINTERS - Section with pointers to literals. S_LITERAL_POINTERS = 0x05u, /// S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers. S_NON_LAZY_SYMBOL_POINTERS = 0x06u, /// S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers. S_LAZY_SYMBOL_POINTERS = 0x07u, /// S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in /// the Reserved2 field. S_SYMBOL_STUBS = 0x08u, /// S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for /// initialization. S_MOD_INIT_FUNC_POINTERS = 0x09u, /// S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for /// termination. S_MOD_TERM_FUNC_POINTERS = 0x0au, /// S_COALESCED - Section contains symbols that are to be coalesced. S_COALESCED = 0x0bu, /// S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4 /// gigabytes). S_GB_ZEROFILL = 0x0cu, /// S_INTERPOSING - Section with only pairs of function pointers for /// interposing. S_INTERPOSING = 0x0du, /// S_16BYTE_LITERALS - Section with only 16 byte literals. S_16BYTE_LITERALS = 0x0eu, /// S_DTRACE_DOF - Section contains DTrace Object Format. S_DTRACE_DOF = 0x0fu, /// S_LAZY_DYLIB_SYMBOL_POINTERS - Section with lazy symbol pointers to /// lazy loaded dylibs. S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10u, /// S_THREAD_LOCAL_REGULAR - Thread local data section. S_THREAD_LOCAL_REGULAR = 0x11u, /// S_THREAD_LOCAL_ZEROFILL - Thread local zerofill section. S_THREAD_LOCAL_ZEROFILL = 0x12u, /// S_THREAD_LOCAL_VARIABLES - Section with thread local variable /// structure data. S_THREAD_LOCAL_VARIABLES = 0x13u, /// S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread /// local structures. S_THREAD_LOCAL_VARIABLE_POINTERS = 0x14u, /// S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - Section with thread local /// variable initialization pointers to functions. S_THREAD_LOCAL_INIT_FUNCTION_POINTERS = 0x15u, LAST_KNOWN_SECTION_TYPE = S_THREAD_LOCAL_INIT_FUNCTION_POINTERS }; enum : uint32_t { // Constant masks for the "flags[31:24]" field in llvm::MachO::section and // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_USR) /// S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine /// instructions. S_ATTR_PURE_INSTRUCTIONS = 0x80000000u, /// S_ATTR_NO_TOC - Section contains coalesced symbols that are not to be /// in a ranlib table of contents. S_ATTR_NO_TOC = 0x40000000u, /// S_ATTR_STRIP_STATIC_SYMS - Ok to strip static symbols in this section /// in files with the MY_DYLDLINK flag. S_ATTR_STRIP_STATIC_SYMS = 0x20000000u, /// S_ATTR_NO_DEAD_STRIP - No dead stripping. S_ATTR_NO_DEAD_STRIP = 0x10000000u, /// S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks. S_ATTR_LIVE_SUPPORT = 0x08000000u, /// S_ATTR_SELF_MODIFYING_CODE - Used with i386 code stubs written on by /// dyld. S_ATTR_SELF_MODIFYING_CODE = 0x04000000u, /// S_ATTR_DEBUG - A debug section. S_ATTR_DEBUG = 0x02000000u, // Constant masks for the "flags[23:8]" field in llvm::MachO::section and // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_SYS) /// S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions. S_ATTR_SOME_INSTRUCTIONS = 0x00000400u, /// S_ATTR_EXT_RELOC - Section has external relocation entries. S_ATTR_EXT_RELOC = 0x00000200u, /// S_ATTR_LOC_RELOC - Section has local relocation entries. S_ATTR_LOC_RELOC = 0x00000100u, // Constant masks for the value of an indirect symbol in an indirect // symbol table INDIRECT_SYMBOL_LOCAL = 0x80000000u, INDIRECT_SYMBOL_ABS = 0x40000000u }; enum DataRegionType { // Constants for the "kind" field in a data_in_code_entry structure DICE_KIND_DATA = 1u, DICE_KIND_JUMP_TABLE8 = 2u, DICE_KIND_JUMP_TABLE16 = 3u, DICE_KIND_JUMP_TABLE32 = 4u, DICE_KIND_ABS_JUMP_TABLE32 = 5u }; enum RebaseType { REBASE_TYPE_POINTER = 1u, REBASE_TYPE_TEXT_ABSOLUTE32 = 2u, REBASE_TYPE_TEXT_PCREL32 = 3u }; enum { REBASE_OPCODE_MASK = 0xF0u, REBASE_IMMEDIATE_MASK = 0x0Fu }; enum RebaseOpcode { REBASE_OPCODE_DONE = 0x00u, REBASE_OPCODE_SET_TYPE_IMM = 0x10u, REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x20u, REBASE_OPCODE_ADD_ADDR_ULEB = 0x30u, REBASE_OPCODE_ADD_ADDR_IMM_SCALED = 0x40u, REBASE_OPCODE_DO_REBASE_IMM_TIMES = 0x50u, REBASE_OPCODE_DO_REBASE_ULEB_TIMES = 0x60u, REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB = 0x70u, REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB = 0x80u }; enum BindType { BIND_TYPE_POINTER = 1u, BIND_TYPE_TEXT_ABSOLUTE32 = 2u, BIND_TYPE_TEXT_PCREL32 = 3u }; enum BindSpecialDylib { BIND_SPECIAL_DYLIB_SELF = 0, BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE = -1, BIND_SPECIAL_DYLIB_FLAT_LOOKUP = -2 }; enum { BIND_SYMBOL_FLAGS_WEAK_IMPORT = 0x1u, BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION = 0x8u, BIND_OPCODE_MASK = 0xF0u, BIND_IMMEDIATE_MASK = 0x0Fu }; enum BindOpcode { BIND_OPCODE_DONE = 0x00u, BIND_OPCODE_SET_DYLIB_ORDINAL_IMM = 0x10u, BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB = 0x20u, BIND_OPCODE_SET_DYLIB_SPECIAL_IMM = 0x30u, BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM = 0x40u, BIND_OPCODE_SET_TYPE_IMM = 0x50u, BIND_OPCODE_SET_ADDEND_SLEB = 0x60u, BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x70u, BIND_OPCODE_ADD_ADDR_ULEB = 0x80u, BIND_OPCODE_DO_BIND = 0x90u, BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB = 0xA0u, BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED = 0xB0u, BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB = 0xC0u }; enum { EXPORT_SYMBOL_FLAGS_KIND_MASK = 0x03u, EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION = 0x04u, EXPORT_SYMBOL_FLAGS_REEXPORT = 0x08u, EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER = 0x10u }; enum ExportSymbolKind { EXPORT_SYMBOL_FLAGS_KIND_REGULAR = 0x00u, EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL = 0x01u, EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE = 0x02u }; enum { // Constant masks for the "n_type" field in llvm::MachO::nlist and // llvm::MachO::nlist_64 N_STAB = 0xe0, N_PEXT = 0x10, N_TYPE = 0x0e, N_EXT = 0x01 }; enum NListType { // Constants for the "n_type & N_TYPE" llvm::MachO::nlist and // llvm::MachO::nlist_64 N_UNDF = 0x0u, N_ABS = 0x2u, N_SECT = 0xeu, N_PBUD = 0xcu, N_INDR = 0xau }; enum SectionOrdinal { // Constants for the "n_sect" field in llvm::MachO::nlist and // llvm::MachO::nlist_64 NO_SECT = 0u, MAX_SECT = 0xffu }; enum { // Constant masks for the "n_desc" field in llvm::MachO::nlist and // llvm::MachO::nlist_64 // The low 3 bits are the for the REFERENCE_TYPE. REFERENCE_TYPE = 0x7, REFERENCE_FLAG_UNDEFINED_NON_LAZY = 0, REFERENCE_FLAG_UNDEFINED_LAZY = 1, REFERENCE_FLAG_DEFINED = 2, REFERENCE_FLAG_PRIVATE_DEFINED = 3, REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY = 4, REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY = 5, // Flag bits (some overlap with the library ordinal bits). N_ARM_THUMB_DEF = 0x0008u, REFERENCED_DYNAMICALLY = 0x0010u, N_NO_DEAD_STRIP = 0x0020u, N_WEAK_REF = 0x0040u, N_WEAK_DEF = 0x0080u, N_SYMBOL_RESOLVER = 0x0100u, N_ALT_ENTRY = 0x0200u, // For undefined symbols coming from libraries, see GET_LIBRARY_ORDINAL() // as these are in the top 8 bits. SELF_LIBRARY_ORDINAL = 0x0, MAX_LIBRARY_ORDINAL = 0xfd, DYNAMIC_LOOKUP_ORDINAL = 0xfe, EXECUTABLE_ORDINAL = 0xff }; enum StabType { // Constant values for the "n_type" field in llvm::MachO::nlist and // llvm::MachO::nlist_64 when "(n_type & N_STAB) != 0" N_GSYM = 0x20u, N_FNAME = 0x22u, N_FUN = 0x24u, N_STSYM = 0x26u, N_LCSYM = 0x28u, N_BNSYM = 0x2Eu, N_PC = 0x30u, N_AST = 0x32u, N_OPT = 0x3Cu, N_RSYM = 0x40u, N_SLINE = 0x44u, N_ENSYM = 0x4Eu, N_SSYM = 0x60u, N_SO = 0x64u, N_OSO = 0x66u, N_LSYM = 0x80u, N_BINCL = 0x82u, N_SOL = 0x84u, N_PARAMS = 0x86u, N_VERSION = 0x88u, N_OLEVEL = 0x8Au, N_PSYM = 0xA0u, N_EINCL = 0xA2u, N_ENTRY = 0xA4u, N_LBRAC = 0xC0u, N_EXCL = 0xC2u, N_RBRAC = 0xE0u, N_BCOMM = 0xE2u, N_ECOMM = 0xE4u, N_ECOML = 0xE8u, N_LENG = 0xFEu }; enum : uint32_t { // Constant values for the r_symbolnum field in an // llvm::MachO::relocation_info structure when r_extern is 0. R_ABS = 0, // Constant bits for the r_address field in an // llvm::MachO::relocation_info structure. R_SCATTERED = 0x80000000 }; enum RelocationInfoType { // Constant values for the r_type field in an // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info // structure. GENERIC_RELOC_VANILLA = 0, GENERIC_RELOC_PAIR = 1, GENERIC_RELOC_SECTDIFF = 2, GENERIC_RELOC_PB_LA_PTR = 3, GENERIC_RELOC_LOCAL_SECTDIFF = 4, GENERIC_RELOC_TLV = 5, // Constant values for the r_type field in a PowerPC architecture // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info // structure. PPC_RELOC_VANILLA = GENERIC_RELOC_VANILLA, PPC_RELOC_PAIR = GENERIC_RELOC_PAIR, PPC_RELOC_BR14 = 2, PPC_RELOC_BR24 = 3, PPC_RELOC_HI16 = 4, PPC_RELOC_LO16 = 5, PPC_RELOC_HA16 = 6, PPC_RELOC_LO14 = 7, PPC_RELOC_SECTDIFF = 8, PPC_RELOC_PB_LA_PTR = 9, PPC_RELOC_HI16_SECTDIFF = 10, PPC_RELOC_LO16_SECTDIFF = 11, PPC_RELOC_HA16_SECTDIFF = 12, PPC_RELOC_JBSR = 13, PPC_RELOC_LO14_SECTDIFF = 14, PPC_RELOC_LOCAL_SECTDIFF = 15, // Constant values for the r_type field in an ARM architecture // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info // structure. ARM_RELOC_VANILLA = GENERIC_RELOC_VANILLA, ARM_RELOC_PAIR = GENERIC_RELOC_PAIR, ARM_RELOC_SECTDIFF = GENERIC_RELOC_SECTDIFF, ARM_RELOC_LOCAL_SECTDIFF = 3, ARM_RELOC_PB_LA_PTR = 4, ARM_RELOC_BR24 = 5, ARM_THUMB_RELOC_BR22 = 6, ARM_THUMB_32BIT_BRANCH = 7, // obsolete ARM_RELOC_HALF = 8, ARM_RELOC_HALF_SECTDIFF = 9, // Constant values for the r_type field in an ARM64 architecture // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info // structure. // For pointers. ARM64_RELOC_UNSIGNED = 0, // Must be followed by an ARM64_RELOC_UNSIGNED ARM64_RELOC_SUBTRACTOR = 1, // A B/BL instruction with 26-bit displacement. ARM64_RELOC_BRANCH26 = 2, // PC-rel distance to page of target. ARM64_RELOC_PAGE21 = 3, // Offset within page, scaled by r_length. ARM64_RELOC_PAGEOFF12 = 4, // PC-rel distance to page of GOT slot. ARM64_RELOC_GOT_LOAD_PAGE21 = 5, // Offset within page of GOT slot, scaled by r_length. ARM64_RELOC_GOT_LOAD_PAGEOFF12 = 6, // For pointers to GOT slots. ARM64_RELOC_POINTER_TO_GOT = 7, // PC-rel distance to page of TLVP slot. ARM64_RELOC_TLVP_LOAD_PAGE21 = 8, // Offset within page of TLVP slot, scaled by r_length. ARM64_RELOC_TLVP_LOAD_PAGEOFF12 = 9, // Must be followed by ARM64_RELOC_PAGE21 or ARM64_RELOC_PAGEOFF12. ARM64_RELOC_ADDEND = 10, // Constant values for the r_type field in an x86_64 architecture // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info // structure X86_64_RELOC_UNSIGNED = 0, X86_64_RELOC_SIGNED = 1, X86_64_RELOC_BRANCH = 2, X86_64_RELOC_GOT_LOAD = 3, X86_64_RELOC_GOT = 4, X86_64_RELOC_SUBTRACTOR = 5, X86_64_RELOC_SIGNED_1 = 6, X86_64_RELOC_SIGNED_2 = 7, X86_64_RELOC_SIGNED_4 = 8, X86_64_RELOC_TLV = 9 }; // Values for segment_command.initprot. // From <mach/vm_prot.h> enum { VM_PROT_READ = 0x1, VM_PROT_WRITE = 0x2, VM_PROT_EXECUTE = 0x4 }; // Structs from <mach-o/loader.h> struct mach_header { uint32_t magic; uint32_t cputype; uint32_t cpusubtype; uint32_t filetype; uint32_t ncmds; uint32_t sizeofcmds; uint32_t flags; }; struct mach_header_64 { uint32_t magic; uint32_t cputype; uint32_t cpusubtype; uint32_t filetype; uint32_t ncmds; uint32_t sizeofcmds; uint32_t flags; uint32_t reserved; }; struct load_command { uint32_t cmd; uint32_t cmdsize; }; struct segment_command { uint32_t cmd; uint32_t cmdsize; char segname[16]; uint32_t vmaddr; uint32_t vmsize; uint32_t fileoff; uint32_t filesize; uint32_t maxprot; uint32_t initprot; uint32_t nsects; uint32_t flags; }; struct segment_command_64 { uint32_t cmd; uint32_t cmdsize; char segname[16]; uint64_t vmaddr; uint64_t vmsize; uint64_t fileoff; uint64_t filesize; uint32_t maxprot; uint32_t initprot; uint32_t nsects; uint32_t flags; }; struct section { char sectname[16]; char segname[16]; uint32_t addr; uint32_t size; uint32_t offset; uint32_t align; uint32_t reloff; uint32_t nreloc; uint32_t flags; uint32_t reserved1; uint32_t reserved2; }; struct section_64 { char sectname[16]; char segname[16]; uint64_t addr; uint64_t size; uint32_t offset; uint32_t align; uint32_t reloff; uint32_t nreloc; uint32_t flags; uint32_t reserved1; uint32_t reserved2; uint32_t reserved3; }; struct fvmlib { uint32_t name; uint32_t minor_version; uint32_t header_addr; }; struct fvmlib_command { uint32_t cmd; uint32_t cmdsize; struct fvmlib fvmlib; }; struct dylib { uint32_t name; uint32_t timestamp; uint32_t current_version; uint32_t compatibility_version; }; struct dylib_command { uint32_t cmd; uint32_t cmdsize; struct dylib dylib; }; struct sub_framework_command { uint32_t cmd; uint32_t cmdsize; uint32_t umbrella; }; struct sub_client_command { uint32_t cmd; uint32_t cmdsize; uint32_t client; }; struct sub_umbrella_command { uint32_t cmd; uint32_t cmdsize; uint32_t sub_umbrella; }; struct sub_library_command { uint32_t cmd; uint32_t cmdsize; uint32_t sub_library; }; struct prebound_dylib_command { uint32_t cmd; uint32_t cmdsize; uint32_t name; uint32_t nmodules; uint32_t linked_modules; }; struct dylinker_command { uint32_t cmd; uint32_t cmdsize; uint32_t name; }; struct thread_command { uint32_t cmd; uint32_t cmdsize; }; struct routines_command { uint32_t cmd; uint32_t cmdsize; uint32_t init_address; uint32_t init_module; uint32_t reserved1; uint32_t reserved2; uint32_t reserved3; uint32_t reserved4; uint32_t reserved5; uint32_t reserved6; }; struct routines_command_64 { uint32_t cmd; uint32_t cmdsize; uint64_t init_address; uint64_t init_module; uint64_t reserved1; uint64_t reserved2; uint64_t reserved3; uint64_t reserved4; uint64_t reserved5; uint64_t reserved6; }; struct symtab_command { uint32_t cmd; uint32_t cmdsize; uint32_t symoff; uint32_t nsyms; uint32_t stroff; uint32_t strsize; }; struct dysymtab_command { uint32_t cmd; uint32_t cmdsize; uint32_t ilocalsym; uint32_t nlocalsym; uint32_t iextdefsym; uint32_t nextdefsym; uint32_t iundefsym; uint32_t nundefsym; uint32_t tocoff; uint32_t ntoc; uint32_t modtaboff; uint32_t nmodtab; uint32_t extrefsymoff; uint32_t nextrefsyms; uint32_t indirectsymoff; uint32_t nindirectsyms; uint32_t extreloff; uint32_t nextrel; uint32_t locreloff; uint32_t nlocrel; }; struct dylib_table_of_contents { uint32_t symbol_index; uint32_t module_index; }; struct dylib_module { uint32_t module_name; uint32_t iextdefsym; uint32_t nextdefsym; uint32_t irefsym; uint32_t nrefsym; uint32_t ilocalsym; uint32_t nlocalsym; uint32_t iextrel; uint32_t nextrel; uint32_t iinit_iterm; uint32_t ninit_nterm; uint32_t objc_module_info_addr; uint32_t objc_module_info_size; }; struct dylib_module_64 { uint32_t module_name; uint32_t iextdefsym; uint32_t nextdefsym; uint32_t irefsym; uint32_t nrefsym; uint32_t ilocalsym; uint32_t nlocalsym; uint32_t iextrel; uint32_t nextrel; uint32_t iinit_iterm; uint32_t ninit_nterm; uint32_t objc_module_info_size; uint64_t objc_module_info_addr; }; struct dylib_reference { uint32_t isym:24, flags:8; }; struct twolevel_hints_command { uint32_t cmd; uint32_t cmdsize; uint32_t offset; uint32_t nhints; }; struct twolevel_hint { uint32_t isub_image:8, itoc:24; }; struct prebind_cksum_command { uint32_t cmd; uint32_t cmdsize; uint32_t cksum; }; struct uuid_command { uint32_t cmd; uint32_t cmdsize; uint8_t uuid[16]; }; struct rpath_command { uint32_t cmd; uint32_t cmdsize; uint32_t path; }; struct linkedit_data_command { uint32_t cmd; uint32_t cmdsize; uint32_t dataoff; uint32_t datasize; }; struct data_in_code_entry { uint32_t offset; uint16_t length; uint16_t kind; }; struct source_version_command { uint32_t cmd; uint32_t cmdsize; uint64_t version; }; struct encryption_info_command { uint32_t cmd; uint32_t cmdsize; uint32_t cryptoff; uint32_t cryptsize; uint32_t cryptid; }; struct encryption_info_command_64 { uint32_t cmd; uint32_t cmdsize; uint32_t cryptoff; uint32_t cryptsize; uint32_t cryptid; uint32_t pad; }; struct version_min_command { uint32_t cmd; // LC_VERSION_MIN_MACOSX or // LC_VERSION_MIN_IPHONEOS uint32_t cmdsize; // sizeof(struct version_min_command) uint32_t version; // X.Y.Z is encoded in nibbles xxxx.yy.zz uint32_t sdk; // X.Y.Z is encoded in nibbles xxxx.yy.zz }; struct dyld_info_command { uint32_t cmd; uint32_t cmdsize; uint32_t rebase_off; uint32_t rebase_size; uint32_t bind_off; uint32_t bind_size; uint32_t weak_bind_off; uint32_t weak_bind_size; uint32_t lazy_bind_off; uint32_t lazy_bind_size; uint32_t export_off; uint32_t export_size; }; struct linker_option_command { uint32_t cmd; uint32_t cmdsize; uint32_t count; }; struct symseg_command { uint32_t cmd; uint32_t cmdsize; uint32_t offset; uint32_t size; }; struct ident_command { uint32_t cmd; uint32_t cmdsize; }; struct fvmfile_command { uint32_t cmd; uint32_t cmdsize; uint32_t name; uint32_t header_addr; }; struct tlv_descriptor_32 { uint32_t thunk; uint32_t key; uint32_t offset; }; struct tlv_descriptor_64 { uint64_t thunk; uint64_t key; uint64_t offset; }; struct tlv_descriptor { uintptr_t thunk; uintptr_t key; uintptr_t offset; }; struct entry_point_command { uint32_t cmd; uint32_t cmdsize; uint64_t entryoff; uint64_t stacksize; }; // Structs from <mach-o/fat.h> struct fat_header { uint32_t magic; uint32_t nfat_arch; }; struct fat_arch { uint32_t cputype; uint32_t cpusubtype; uint32_t offset; uint32_t size; uint32_t align; }; // Structs from <mach-o/reloc.h> struct relocation_info { int32_t r_address; uint32_t r_symbolnum:24, r_pcrel:1, r_length:2, r_extern:1, r_type:4; }; struct scattered_relocation_info { #if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN) uint32_t r_scattered:1, r_pcrel:1, r_length:2, r_type:4, r_address:24; #else uint32_t r_address:24, r_type:4, r_length:2, r_pcrel:1, r_scattered:1; #endif int32_t r_value; }; // Structs NOT from <mach-o/reloc.h>, but that make LLVM's life easier struct any_relocation_info { uint32_t r_word0, r_word1; }; // Structs from <mach-o/nlist.h> struct nlist_base { uint32_t n_strx; uint8_t n_type; uint8_t n_sect; uint16_t n_desc; }; struct nlist { uint32_t n_strx; uint8_t n_type; uint8_t n_sect; int16_t n_desc; uint32_t n_value; }; struct nlist_64 { uint32_t n_strx; uint8_t n_type; uint8_t n_sect; uint16_t n_desc; uint64_t n_value; }; // Byte order swapping functions for MachO structs inline void swapStruct(mach_header &mh) { sys::swapByteOrder(mh.magic); sys::swapByteOrder(mh.cputype); sys::swapByteOrder(mh.cpusubtype); sys::swapByteOrder(mh.filetype); sys::swapByteOrder(mh.ncmds); sys::swapByteOrder(mh.sizeofcmds); sys::swapByteOrder(mh.flags); } inline void swapStruct(mach_header_64 &H) { sys::swapByteOrder(H.magic); sys::swapByteOrder(H.cputype); sys::swapByteOrder(H.cpusubtype); sys::swapByteOrder(H.filetype); sys::swapByteOrder(H.ncmds); sys::swapByteOrder(H.sizeofcmds); sys::swapByteOrder(H.flags); sys::swapByteOrder(H.reserved); } inline void swapStruct(load_command &lc) { sys::swapByteOrder(lc.cmd); sys::swapByteOrder(lc.cmdsize); } inline void swapStruct(symtab_command &lc) { sys::swapByteOrder(lc.cmd); sys::swapByteOrder(lc.cmdsize); sys::swapByteOrder(lc.symoff); sys::swapByteOrder(lc.nsyms); sys::swapByteOrder(lc.stroff); sys::swapByteOrder(lc.strsize); } inline void swapStruct(segment_command_64 &seg) { sys::swapByteOrder(seg.cmd); sys::swapByteOrder(seg.cmdsize); sys::swapByteOrder(seg.vmaddr); sys::swapByteOrder(seg.vmsize); sys::swapByteOrder(seg.fileoff); sys::swapByteOrder(seg.filesize); sys::swapByteOrder(seg.maxprot); sys::swapByteOrder(seg.initprot); sys::swapByteOrder(seg.nsects); sys::swapByteOrder(seg.flags); } inline void swapStruct(segment_command &seg) { sys::swapByteOrder(seg.cmd); sys::swapByteOrder(seg.cmdsize); sys::swapByteOrder(seg.vmaddr); sys::swapByteOrder(seg.vmsize); sys::swapByteOrder(seg.fileoff); sys::swapByteOrder(seg.filesize); sys::swapByteOrder(seg.maxprot); sys::swapByteOrder(seg.initprot); sys::swapByteOrder(seg.nsects); sys::swapByteOrder(seg.flags); } inline void swapStruct(section_64 &sect) { sys::swapByteOrder(sect.addr); sys::swapByteOrder(sect.size); sys::swapByteOrder(sect.offset); sys::swapByteOrder(sect.align); sys::swapByteOrder(sect.reloff); sys::swapByteOrder(sect.nreloc); sys::swapByteOrder(sect.flags); sys::swapByteOrder(sect.reserved1); sys::swapByteOrder(sect.reserved2); } inline void swapStruct(section &sect) { sys::swapByteOrder(sect.addr); sys::swapByteOrder(sect.size); sys::swapByteOrder(sect.offset); sys::swapByteOrder(sect.align); sys::swapByteOrder(sect.reloff); sys::swapByteOrder(sect.nreloc); sys::swapByteOrder(sect.flags); sys::swapByteOrder(sect.reserved1); sys::swapByteOrder(sect.reserved2); } inline void swapStruct(dyld_info_command &info) { sys::swapByteOrder(info.cmd); sys::swapByteOrder(info.cmdsize); sys::swapByteOrder(info.rebase_off); sys::swapByteOrder(info.rebase_size); sys::swapByteOrder(info.bind_off); sys::swapByteOrder(info.bind_size); sys::swapByteOrder(info.weak_bind_off); sys::swapByteOrder(info.weak_bind_size); sys::swapByteOrder(info.lazy_bind_off); sys::swapByteOrder(info.lazy_bind_size); sys::swapByteOrder(info.export_off); sys::swapByteOrder(info.export_size); } inline void swapStruct(dylib_command &d) { sys::swapByteOrder(d.cmd); sys::swapByteOrder(d.cmdsize); sys::swapByteOrder(d.dylib.name); sys::swapByteOrder(d.dylib.timestamp); sys::swapByteOrder(d.dylib.current_version); sys::swapByteOrder(d.dylib.compatibility_version); } inline void swapStruct(sub_framework_command &s) { sys::swapByteOrder(s.cmd); sys::swapByteOrder(s.cmdsize); sys::swapByteOrder(s.umbrella); } inline void swapStruct(sub_umbrella_command &s) { sys::swapByteOrder(s.cmd); sys::swapByteOrder(s.cmdsize); sys::swapByteOrder(s.sub_umbrella); } inline void swapStruct(sub_library_command &s) { sys::swapByteOrder(s.cmd); sys::swapByteOrder(s.cmdsize); sys::swapByteOrder(s.sub_library); } inline void swapStruct(sub_client_command &s) { sys::swapByteOrder(s.cmd); sys::swapByteOrder(s.cmdsize); sys::swapByteOrder(s.client); } inline void swapStruct(routines_command &r) { sys::swapByteOrder(r.cmd); sys::swapByteOrder(r.cmdsize); sys::swapByteOrder(r.init_address); sys::swapByteOrder(r.init_module); sys::swapByteOrder(r.reserved1); sys::swapByteOrder(r.reserved2); sys::swapByteOrder(r.reserved3); sys::swapByteOrder(r.reserved4); sys::swapByteOrder(r.reserved5); sys::swapByteOrder(r.reserved6); } inline void swapStruct(routines_command_64 &r) { sys::swapByteOrder(r.cmd); sys::swapByteOrder(r.cmdsize); sys::swapByteOrder(r.init_address); sys::swapByteOrder(r.init_module); sys::swapByteOrder(r.reserved1); sys::swapByteOrder(r.reserved2); sys::swapByteOrder(r.reserved3); sys::swapByteOrder(r.reserved4); sys::swapByteOrder(r.reserved5); sys::swapByteOrder(r.reserved6); } inline void swapStruct(thread_command &t) { sys::swapByteOrder(t.cmd); sys::swapByteOrder(t.cmdsize); } inline void swapStruct(dylinker_command &d) { sys::swapByteOrder(d.cmd); sys::swapByteOrder(d.cmdsize); sys::swapByteOrder(d.name); } inline void swapStruct(uuid_command &u) { sys::swapByteOrder(u.cmd); sys::swapByteOrder(u.cmdsize); } inline void swapStruct(rpath_command &r) { sys::swapByteOrder(r.cmd); sys::swapByteOrder(r.cmdsize); sys::swapByteOrder(r.path); } inline void swapStruct(source_version_command &s) { sys::swapByteOrder(s.cmd); sys::swapByteOrder(s.cmdsize); sys::swapByteOrder(s.version); } inline void swapStruct(entry_point_command &e) { sys::swapByteOrder(e.cmd); sys::swapByteOrder(e.cmdsize); sys::swapByteOrder(e.entryoff); sys::swapByteOrder(e.stacksize); } inline void swapStruct(encryption_info_command &e) { sys::swapByteOrder(e.cmd); sys::swapByteOrder(e.cmdsize); sys::swapByteOrder(e.cryptoff); sys::swapByteOrder(e.cryptsize); sys::swapByteOrder(e.cryptid); } inline void swapStruct(encryption_info_command_64 &e) { sys::swapByteOrder(e.cmd); sys::swapByteOrder(e.cmdsize); sys::swapByteOrder(e.cryptoff); sys::swapByteOrder(e.cryptsize); sys::swapByteOrder(e.cryptid); sys::swapByteOrder(e.pad); } inline void swapStruct(dysymtab_command &dst) { sys::swapByteOrder(dst.cmd); sys::swapByteOrder(dst.cmdsize); sys::swapByteOrder(dst.ilocalsym); sys::swapByteOrder(dst.nlocalsym); sys::swapByteOrder(dst.iextdefsym); sys::swapByteOrder(dst.nextdefsym); sys::swapByteOrder(dst.iundefsym); sys::swapByteOrder(dst.nundefsym); sys::swapByteOrder(dst.tocoff); sys::swapByteOrder(dst.ntoc); sys::swapByteOrder(dst.modtaboff); sys::swapByteOrder(dst.nmodtab); sys::swapByteOrder(dst.extrefsymoff); sys::swapByteOrder(dst.nextrefsyms); sys::swapByteOrder(dst.indirectsymoff); sys::swapByteOrder(dst.nindirectsyms); sys::swapByteOrder(dst.extreloff); sys::swapByteOrder(dst.nextrel); sys::swapByteOrder(dst.locreloff); sys::swapByteOrder(dst.nlocrel); } inline void swapStruct(any_relocation_info &reloc) { sys::swapByteOrder(reloc.r_word0); sys::swapByteOrder(reloc.r_word1); } inline void swapStruct(nlist_base &S) { sys::swapByteOrder(S.n_strx); sys::swapByteOrder(S.n_desc); } inline void swapStruct(nlist &sym) { sys::swapByteOrder(sym.n_strx); sys::swapByteOrder(sym.n_desc); sys::swapByteOrder(sym.n_value); } inline void swapStruct(nlist_64 &sym) { sys::swapByteOrder(sym.n_strx); sys::swapByteOrder(sym.n_desc); sys::swapByteOrder(sym.n_value); } inline void swapStruct(linkedit_data_command &C) { sys::swapByteOrder(C.cmd); sys::swapByteOrder(C.cmdsize); sys::swapByteOrder(C.dataoff); sys::swapByteOrder(C.datasize); } inline void swapStruct(linker_option_command &C) { sys::swapByteOrder(C.cmd); sys::swapByteOrder(C.cmdsize); sys::swapByteOrder(C.count); } inline void swapStruct(version_min_command&C) { sys::swapByteOrder(C.cmd); sys::swapByteOrder(C.cmdsize); sys::swapByteOrder(C.version); sys::swapByteOrder(C.sdk); } inline void swapStruct(data_in_code_entry &C) { sys::swapByteOrder(C.offset); sys::swapByteOrder(C.length); sys::swapByteOrder(C.kind); } inline void swapStruct(uint32_t &C) { sys::swapByteOrder(C); } // Get/Set functions from <mach-o/nlist.h> static inline uint16_t GET_LIBRARY_ORDINAL(uint16_t n_desc) { return (((n_desc) >> 8u) & 0xffu); } static inline void SET_LIBRARY_ORDINAL(uint16_t &n_desc, uint8_t ordinal) { n_desc = (((n_desc) & 0x00ff) | (((ordinal) & 0xff) << 8)); } static inline uint8_t GET_COMM_ALIGN (uint16_t n_desc) { return (n_desc >> 8u) & 0x0fu; } static inline void SET_COMM_ALIGN (uint16_t &n_desc, uint8_t align) { n_desc = ((n_desc & 0xf0ffu) | ((align & 0x0fu) << 8u)); } // Enums from <mach/machine.h> enum : uint32_t { // Capability bits used in the definition of cpu_type. CPU_ARCH_MASK = 0xff000000, // Mask for architecture bits CPU_ARCH_ABI64 = 0x01000000 // 64 bit ABI }; // Constants for the cputype field. enum CPUType { CPU_TYPE_ANY = -1, CPU_TYPE_X86 = 7, CPU_TYPE_I386 = CPU_TYPE_X86, CPU_TYPE_X86_64 = CPU_TYPE_X86 | CPU_ARCH_ABI64, /* CPU_TYPE_MIPS = 8, */ CPU_TYPE_MC98000 = 10, // Old Motorola PowerPC CPU_TYPE_ARM = 12, CPU_TYPE_ARM64 = CPU_TYPE_ARM | CPU_ARCH_ABI64, CPU_TYPE_SPARC = 14, CPU_TYPE_POWERPC = 18, CPU_TYPE_POWERPC64 = CPU_TYPE_POWERPC | CPU_ARCH_ABI64 }; enum : uint32_t { // Capability bits used in the definition of cpusubtype. CPU_SUBTYPE_MASK = 0xff000000, // Mask for architecture bits CPU_SUBTYPE_LIB64 = 0x80000000, // 64 bit libraries // Special CPU subtype constants. CPU_SUBTYPE_MULTIPLE = ~0u }; // Constants for the cpusubtype field. enum CPUSubTypeX86 { CPU_SUBTYPE_I386_ALL = 3, CPU_SUBTYPE_386 = 3, CPU_SUBTYPE_486 = 4, CPU_SUBTYPE_486SX = 0x84, CPU_SUBTYPE_586 = 5, CPU_SUBTYPE_PENT = CPU_SUBTYPE_586, CPU_SUBTYPE_PENTPRO = 0x16, CPU_SUBTYPE_PENTII_M3 = 0x36, CPU_SUBTYPE_PENTII_M5 = 0x56, CPU_SUBTYPE_CELERON = 0x67, CPU_SUBTYPE_CELERON_MOBILE = 0x77, CPU_SUBTYPE_PENTIUM_3 = 0x08, CPU_SUBTYPE_PENTIUM_3_M = 0x18, CPU_SUBTYPE_PENTIUM_3_XEON = 0x28, CPU_SUBTYPE_PENTIUM_M = 0x09, CPU_SUBTYPE_PENTIUM_4 = 0x0a, CPU_SUBTYPE_PENTIUM_4_M = 0x1a, CPU_SUBTYPE_ITANIUM = 0x0b, CPU_SUBTYPE_ITANIUM_2 = 0x1b, CPU_SUBTYPE_XEON = 0x0c, CPU_SUBTYPE_XEON_MP = 0x1c, CPU_SUBTYPE_X86_ALL = 3, CPU_SUBTYPE_X86_64_ALL = 3, CPU_SUBTYPE_X86_ARCH1 = 4, CPU_SUBTYPE_X86_64_H = 8 }; static inline int CPU_SUBTYPE_INTEL(int Family, int Model) { return Family | (Model << 4); } static inline int CPU_SUBTYPE_INTEL_FAMILY(CPUSubTypeX86 ST) { return ((int)ST) & 0x0f; } static inline int CPU_SUBTYPE_INTEL_MODEL(CPUSubTypeX86 ST) { return ((int)ST) >> 4; } enum { CPU_SUBTYPE_INTEL_FAMILY_MAX = 15, CPU_SUBTYPE_INTEL_MODEL_ALL = 0 }; enum CPUSubTypeARM { CPU_SUBTYPE_ARM_ALL = 0, CPU_SUBTYPE_ARM_V4T = 5, CPU_SUBTYPE_ARM_V6 = 6, CPU_SUBTYPE_ARM_V5 = 7, CPU_SUBTYPE_ARM_V5TEJ = 7, CPU_SUBTYPE_ARM_XSCALE = 8, CPU_SUBTYPE_ARM_V7 = 9, // unused ARM_V7F = 10, CPU_SUBTYPE_ARM_V7S = 11, CPU_SUBTYPE_ARM_V7K = 12, CPU_SUBTYPE_ARM_V6M = 14, CPU_SUBTYPE_ARM_V7M = 15, CPU_SUBTYPE_ARM_V7EM = 16 }; enum CPUSubTypeARM64 { CPU_SUBTYPE_ARM64_ALL = 0 }; enum CPUSubTypeSPARC { CPU_SUBTYPE_SPARC_ALL = 0 }; enum CPUSubTypePowerPC { CPU_SUBTYPE_POWERPC_ALL = 0, CPU_SUBTYPE_POWERPC_601 = 1, CPU_SUBTYPE_POWERPC_602 = 2, CPU_SUBTYPE_POWERPC_603 = 3, CPU_SUBTYPE_POWERPC_603e = 4, CPU_SUBTYPE_POWERPC_603ev = 5, CPU_SUBTYPE_POWERPC_604 = 6, CPU_SUBTYPE_POWERPC_604e = 7, CPU_SUBTYPE_POWERPC_620 = 8, CPU_SUBTYPE_POWERPC_750 = 9, CPU_SUBTYPE_POWERPC_7400 = 10, CPU_SUBTYPE_POWERPC_7450 = 11, CPU_SUBTYPE_POWERPC_970 = 100, CPU_SUBTYPE_MC980000_ALL = CPU_SUBTYPE_POWERPC_ALL, CPU_SUBTYPE_MC98601 = CPU_SUBTYPE_POWERPC_601 }; struct x86_thread_state64_t { uint64_t rax; uint64_t rbx; uint64_t rcx; uint64_t rdx; uint64_t rdi; uint64_t rsi; uint64_t rbp; uint64_t rsp; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rip; uint64_t rflags; uint64_t cs; uint64_t fs; uint64_t gs; }; enum x86_fp_control_precis { x86_FP_PREC_24B = 0, x86_FP_PREC_53B = 2, x86_FP_PREC_64B = 3 }; enum x86_fp_control_rc { x86_FP_RND_NEAR = 0, x86_FP_RND_DOWN = 1, x86_FP_RND_UP = 2, x86_FP_CHOP = 3 }; struct fp_control_t { unsigned short invalid :1, denorm :1, zdiv :1, ovrfl :1, undfl :1, precis :1, :2, pc :2, rc :2, :1, :3; }; struct fp_status_t { unsigned short invalid :1, denorm :1, zdiv :1, ovrfl :1, undfl :1, precis :1, stkflt :1, errsumm :1, c0 :1, c1 :1, c2 :1, tos :3, c3 :1, busy :1; }; struct mmst_reg_t { char mmst_reg[10]; char mmst_rsrv[6]; }; struct xmm_reg_t { char xmm_reg[16]; }; struct x86_float_state64_t { int32_t fpu_reserved[2]; fp_control_t fpu_fcw; fp_status_t fpu_fsw; uint8_t fpu_ftw; uint8_t fpu_rsrv1; uint16_t fpu_fop; uint32_t fpu_ip; uint16_t fpu_cs; uint16_t fpu_rsrv2; uint32_t fpu_dp; uint16_t fpu_ds; uint16_t fpu_rsrv3; uint32_t fpu_mxcsr; uint32_t fpu_mxcsrmask; mmst_reg_t fpu_stmm0; mmst_reg_t fpu_stmm1; mmst_reg_t fpu_stmm2; mmst_reg_t fpu_stmm3; mmst_reg_t fpu_stmm4; mmst_reg_t fpu_stmm5; mmst_reg_t fpu_stmm6; mmst_reg_t fpu_stmm7; xmm_reg_t fpu_xmm0; xmm_reg_t fpu_xmm1; xmm_reg_t fpu_xmm2; xmm_reg_t fpu_xmm3; xmm_reg_t fpu_xmm4; xmm_reg_t fpu_xmm5; xmm_reg_t fpu_xmm6; xmm_reg_t fpu_xmm7; xmm_reg_t fpu_xmm8; xmm_reg_t fpu_xmm9; xmm_reg_t fpu_xmm10; xmm_reg_t fpu_xmm11; xmm_reg_t fpu_xmm12; xmm_reg_t fpu_xmm13; xmm_reg_t fpu_xmm14; xmm_reg_t fpu_xmm15; char fpu_rsrv4[6*16]; uint32_t fpu_reserved1; }; struct x86_exception_state64_t { uint16_t trapno; uint16_t cpu; uint32_t err; uint64_t faultvaddr; }; inline void swapStruct(x86_thread_state64_t &x) { sys::swapByteOrder(x.rax); sys::swapByteOrder(x.rbx); sys::swapByteOrder(x.rcx); sys::swapByteOrder(x.rdx); sys::swapByteOrder(x.rdi); sys::swapByteOrder(x.rsi); sys::swapByteOrder(x.rbp); sys::swapByteOrder(x.rsp); sys::swapByteOrder(x.r8); sys::swapByteOrder(x.r9); sys::swapByteOrder(x.r10); sys::swapByteOrder(x.r11); sys::swapByteOrder(x.r12); sys::swapByteOrder(x.r13); sys::swapByteOrder(x.r14); sys::swapByteOrder(x.r15); sys::swapByteOrder(x.rip); sys::swapByteOrder(x.rflags); sys::swapByteOrder(x.cs); sys::swapByteOrder(x.fs); sys::swapByteOrder(x.gs); } inline void swapStruct(x86_float_state64_t &x) { sys::swapByteOrder(x.fpu_reserved[0]); sys::swapByteOrder(x.fpu_reserved[1]); // TODO swap: fp_control_t fpu_fcw; // TODO swap: fp_status_t fpu_fsw; sys::swapByteOrder(x.fpu_fop); sys::swapByteOrder(x.fpu_ip); sys::swapByteOrder(x.fpu_cs); sys::swapByteOrder(x.fpu_rsrv2); sys::swapByteOrder(x.fpu_dp); sys::swapByteOrder(x.fpu_ds); sys::swapByteOrder(x.fpu_rsrv3); sys::swapByteOrder(x.fpu_mxcsr); sys::swapByteOrder(x.fpu_mxcsrmask); sys::swapByteOrder(x.fpu_reserved1); } inline void swapStruct(x86_exception_state64_t &x) { sys::swapByteOrder(x.trapno); sys::swapByteOrder(x.cpu); sys::swapByteOrder(x.err); sys::swapByteOrder(x.faultvaddr); } struct x86_state_hdr_t { uint32_t flavor; uint32_t count; }; struct x86_thread_state_t { x86_state_hdr_t tsh; union { x86_thread_state64_t ts64; } uts; }; struct x86_float_state_t { x86_state_hdr_t fsh; union { x86_float_state64_t fs64; } ufs; }; struct x86_exception_state_t { x86_state_hdr_t esh; union { x86_exception_state64_t es64; } ues; }; inline void swapStruct(x86_state_hdr_t &x) { sys::swapByteOrder(x.flavor); sys::swapByteOrder(x.count); } enum X86ThreadFlavors { x86_THREAD_STATE32 = 1, x86_FLOAT_STATE32 = 2, x86_EXCEPTION_STATE32 = 3, x86_THREAD_STATE64 = 4, x86_FLOAT_STATE64 = 5, x86_EXCEPTION_STATE64 = 6, x86_THREAD_STATE = 7, x86_FLOAT_STATE = 8, x86_EXCEPTION_STATE = 9, x86_DEBUG_STATE32 = 10, x86_DEBUG_STATE64 = 11, x86_DEBUG_STATE = 12 }; inline void swapStruct(x86_thread_state_t &x) { swapStruct(x.tsh); if (x.tsh.flavor == x86_THREAD_STATE64) swapStruct(x.uts.ts64); } inline void swapStruct(x86_float_state_t &x) { swapStruct(x.fsh); if (x.fsh.flavor == x86_FLOAT_STATE64) swapStruct(x.ufs.fs64); } inline void swapStruct(x86_exception_state_t &x) { swapStruct(x.esh); if (x.esh.flavor == x86_EXCEPTION_STATE64) swapStruct(x.ues.es64); } const uint32_t x86_THREAD_STATE64_COUNT = sizeof(x86_thread_state64_t) / sizeof(uint32_t); const uint32_t x86_FLOAT_STATE64_COUNT = sizeof(x86_float_state64_t) / sizeof(uint32_t); const uint32_t x86_EXCEPTION_STATE64_COUNT = sizeof(x86_exception_state64_t) / sizeof(uint32_t); const uint32_t x86_THREAD_STATE_COUNT = sizeof(x86_thread_state_t) / sizeof(uint32_t); const uint32_t x86_FLOAT_STATE_COUNT = sizeof(x86_float_state_t) / sizeof(uint32_t); const uint32_t x86_EXCEPTION_STATE_COUNT = sizeof(x86_exception_state_t) / sizeof(uint32_t); } // end namespace MachO } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Locale.h
#ifndef LLVM_SUPPORT_LOCALE_H #define LLVM_SUPPORT_LOCALE_H #include "llvm/ADT/StringRef.h" namespace llvm { namespace sys { namespace locale { int columnWidth(StringRef s); bool isPrint(int c); } } } #endif // LLVM_SUPPORT_LOCALE_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ConvertUTF.h
/*===--- ConvertUTF.h - Universal Character Names conversions ---------------=== * * The LLVM Compiler Infrastructure * * This file is distributed under the University of Illinois Open Source * License. See LICENSE.TXT for details. * *==------------------------------------------------------------------------==*/ /* * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Header file. Several funtions are included here, forming a complete set of conversions between the three formats. UTF-7 is not included here, but is handled in a separate source file. Each of these routines takes pointers to input buffers and output buffers. The input buffers are const. Each routine converts the text between *sourceStart and sourceEnd, putting the result into the buffer between *targetStart and targetEnd. Note: the end pointers are *after* the last item: e.g. *(sourceEnd - 1) is the last item. The return result indicates whether the conversion was successful, and if not, whether the problem was in the source or target buffers. (Only the first encountered problem is indicated.) After the conversion, *sourceStart and *targetStart are both updated to point to the end of last text successfully converted in the respective buffers. Input parameters: sourceStart - pointer to a pointer to the source buffer. The contents of this are modified on return so that it points at the next thing to be converted. targetStart - similarly, pointer to pointer to the target buffer. sourceEnd, targetEnd - respectively pointers to the ends of the two buffers, for overflow checking only. These conversion functions take a ConversionFlags argument. When this flag is set to strict, both irregular sequences and isolated surrogates will cause an error. When the flag is set to lenient, both irregular sequences and isolated surrogates are converted. Whether the flag is strict or lenient, all illegal sequences will cause an error return. This includes sequences such as: <F4 90 80 80>, <C0 80>, or <A0> in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code must check for illegal sequences. When the flag is set to lenient, characters over 0x10FFFF are converted to the replacement character; otherwise (when the flag is set to strict) they constitute an error. Output parameters: The value "sourceIllegal" is returned from some routines if the input sequence is malformed. When "sourceIllegal" is returned, the source value will point to the illegal value that caused the problem. E.g., in UTF-8 when a sequence is malformed, it points to the start of the malformed sequence. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Fixes & updates, Sept 2001. ------------------------------------------------------------------------ */ #ifndef LLVM_SUPPORT_CONVERTUTF_H #define LLVM_SUPPORT_CONVERTUTF_H /* --------------------------------------------------------------------- The following 4 definitions are compiler-specific. The C standard does not guarantee that wchar_t has at least 16 bits, so wchar_t is no less portable than unsigned short! All should be unsigned values to avoid sign extension during bit mask & shift operations. ------------------------------------------------------------------------ */ typedef unsigned int UTF32; /* at least 32 bits */ typedef unsigned short UTF16; /* at least 16 bits */ typedef unsigned char UTF8; /* typically 8 bits */ typedef unsigned char Boolean; /* 0 or 1 */ /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD #define UNI_MAX_BMP (UTF32)0x0000FFFF #define UNI_MAX_UTF16 (UTF32)0x0010FFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF #define UNI_MAX_UTF8_BYTES_PER_CODE_POINT 4 #define UNI_UTF16_BYTE_ORDER_MARK_NATIVE 0xFEFF #define UNI_UTF16_BYTE_ORDER_MARK_SWAPPED 0xFFFE typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; typedef enum { strictConversion = 0, lenientConversion } ConversionFlags; /* This is for C++ and does no harm in C */ #ifdef __cplusplus extern "C" { #endif ConversionResult ConvertUTF8toUTF16 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); /** * Convert a partial UTF8 sequence to UTF32. If the sequence ends in an * incomplete code unit sequence, returns \c sourceExhausted. */ ConversionResult ConvertUTF8toUTF32Partial( const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); /** * Convert a partial UTF8 sequence to UTF32. If the sequence ends in an * incomplete code unit sequence, returns \c sourceIllegal. */ ConversionResult ConvertUTF8toUTF32( const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF8 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF8 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF32 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF16 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd); unsigned getNumBytesForUTF8(UTF8 firstByte); #ifdef __cplusplus } /*************************************************************************/ /* Below are LLVM-specific wrappers of the functions above. */ #include "dxc/WinAdapter.h" // HLSL Change #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" namespace llvm { /** * Convert an UTF8 StringRef to UTF8, UTF16, or UTF32 depending on * WideCharWidth. The converted data is written to ResultPtr, which needs to * point to at least WideCharWidth * (Source.Size() + 1) bytes. On success, * ResultPtr will point one after the end of the copied string. On failure, * ResultPtr will not be changed, and ErrorPtr will be set to the location of * the first character which could not be converted. * \return true on success. */ bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source, char *&ResultPtr, const UTF8 *&ErrorPtr); /** * Convert an Unicode code point to UTF8 sequence. * * \param Source a Unicode code point. * \param [in,out] ResultPtr pointer to the output buffer, needs to be at least * \c UNI_MAX_UTF8_BYTES_PER_CODE_POINT bytes. On success \c ResultPtr is * updated one past end of the converted sequence. * * \returns true on success. */ bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr); /** * Convert the first UTF8 sequence in the given source buffer to a UTF32 * code point. * * \param [in,out] source A pointer to the source buffer. If the conversion * succeeds, this pointer will be updated to point to the byte just past the * end of the converted sequence. * \param sourceEnd A pointer just past the end of the source buffer. * \param [out] target The converted code * \param flags Whether the conversion is strict or lenient. * * \returns conversionOK on success * * \sa ConvertUTF8toUTF32 */ static inline ConversionResult convertUTF8Sequence(const UTF8 **source, const UTF8 *sourceEnd, UTF32 *target, ConversionFlags flags) { if (*source == sourceEnd) return sourceExhausted; unsigned size = getNumBytesForUTF8(**source); if ((ptrdiff_t)size > sourceEnd - *source) return sourceExhausted; return ConvertUTF8toUTF32(source, *source + size, &target, target + 1, flags); } /** * Returns true if a blob of text starts with a UTF-16 big or little endian byte * order mark. */ bool hasUTF16ByteOrderMark(ArrayRef<char> SrcBytes); /** * Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string. * * \param [in] SrcBytes A buffer of what is assumed to be UTF-16 encoded text. * \param [out] Out Converted UTF-8 is stored here on success. * \returns true on success */ bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out); /** * Converts a UTF-8 string into a UTF-16 string with native endianness. * * \returns true on success */ bool convertUTF8ToUTF16String(StringRef SrcUTF8, SmallVectorImpl<UTF16> &DstUTF16); } /* end namespace llvm */ #endif /* --------------------------------------------------------------------- */ #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/raw_os_ostream.h
//===- raw_os_ostream.h - std::ostream adaptor for raw_ostream --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the raw_os_ostream class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_RAW_OS_OSTREAM_H #define LLVM_SUPPORT_RAW_OS_OSTREAM_H #include "llvm/Support/raw_ostream.h" #include <iosfwd> namespace llvm { /// raw_os_ostream - A raw_ostream that writes to an std::ostream. This is a /// simple adaptor class. It does not check for output errors; clients should /// use the underlying stream to detect errors. class raw_os_ostream : public raw_ostream { std::ostream &OS; /// write_impl - See raw_ostream::write_impl. void write_impl(const char *Ptr, size_t Size) override; /// current_pos - Return the current position within the stream, not /// counting the bytes currently in the buffer. uint64_t current_pos() const override; public: raw_os_ostream(std::ostream &O) : OS(O) {} ~raw_os_ostream() override; }; } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/TargetSelect.h
//===- TargetSelect.h - Target Selection & Registration ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides utilities to make sure that certain classes of targets are // linked into the main application executable, and initialize them as // appropriate. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TARGETSELECT_H #define LLVM_SUPPORT_TARGETSELECT_H #include "llvm/Config/llvm-config.h" extern "C" { // Declare all of the target-initialization functions that are available. #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##TargetInfo(); #include "llvm/Config/Targets.def" #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##Target(); #include "llvm/Config/Targets.def" // Declare all of the target-MC-initialization functions that are available. #define LLVM_TARGET(TargetName) void LLVMInitialize##TargetName##TargetMC(); #include "llvm/Config/Targets.def" // Declare all of the available assembly printer initialization functions. #define LLVM_ASM_PRINTER(TargetName) void LLVMInitialize##TargetName##AsmPrinter(); #include "llvm/Config/AsmPrinters.def" // Declare all of the available assembly parser initialization functions. #define LLVM_ASM_PARSER(TargetName) void LLVMInitialize##TargetName##AsmParser(); #include "llvm/Config/AsmParsers.def" // Declare all of the available disassembler initialization functions. #define LLVM_DISASSEMBLER(TargetName) \ void LLVMInitialize##TargetName##Disassembler(); #include "llvm/Config/Disassemblers.def" } namespace llvm { /// InitializeAllTargetInfos - The main program should call this function if /// it wants access to all available targets that LLVM is configured to /// support, to make them available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllTargetInfos() { #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetInfo(); #include "llvm/Config/Targets.def" } /// InitializeAllTargets - The main program should call this function if it /// wants access to all available target machines that LLVM is configured to /// support, to make them available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllTargets() { // FIXME: Remove this, clients should do it. InitializeAllTargetInfos(); #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##Target(); #include "llvm/Config/Targets.def" } /// InitializeAllTargetMCs - The main program should call this function if it /// wants access to all available target MC that LLVM is configured to /// support, to make them available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllTargetMCs() { #define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC(); #include "llvm/Config/Targets.def" } /// InitializeAllAsmPrinters - The main program should call this function if /// it wants all asm printers that LLVM is configured to support, to make them /// available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllAsmPrinters() { #define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinter(); #include "llvm/Config/AsmPrinters.def" } /// InitializeAllAsmParsers - The main program should call this function if it /// wants all asm parsers that LLVM is configured to support, to make them /// available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllAsmParsers() { #define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser(); #include "llvm/Config/AsmParsers.def" } /// InitializeAllDisassemblers - The main program should call this function if /// it wants all disassemblers that LLVM is configured to support, to make /// them available via the TargetRegistry. /// /// It is legal for a client to make multiple calls to this function. inline void InitializeAllDisassemblers() { #define LLVM_DISASSEMBLER(TargetName) LLVMInitialize##TargetName##Disassembler(); #include "llvm/Config/Disassemblers.def" } /// InitializeNativeTarget - The main program should call this function to /// initialize the native target corresponding to the host. This is useful /// for JIT applications to ensure that the target gets linked in correctly. /// /// It is legal for a client to make multiple calls to this function. inline bool InitializeNativeTarget() { // If we have a native target, initialize it to ensure it is linked in. #ifdef LLVM_NATIVE_TARGET LLVM_NATIVE_TARGETINFO(); LLVM_NATIVE_TARGET(); LLVM_NATIVE_TARGETMC(); return false; #else return true; #endif } /// InitializeNativeTargetAsmPrinter - The main program should call /// this function to initialize the native target asm printer. inline bool InitializeNativeTargetAsmPrinter() { // If we have a native target, initialize the corresponding asm printer. #ifdef LLVM_NATIVE_ASMPRINTER LLVM_NATIVE_ASMPRINTER(); return false; #else return true; #endif } /// InitializeNativeTargetAsmParser - The main program should call /// this function to initialize the native target asm parser. inline bool InitializeNativeTargetAsmParser() { // If we have a native target, initialize the corresponding asm parser. #ifdef LLVM_NATIVE_ASMPARSER LLVM_NATIVE_ASMPARSER(); return false; #else return true; #endif } /// InitializeNativeTargetDisassembler - The main program should call /// this function to initialize the native target disassembler. inline bool InitializeNativeTargetDisassembler() { // If we have a native target, initialize the corresponding disassembler. #ifdef LLVM_NATIVE_DISASSEMBLER LLVM_NATIVE_DISASSEMBLER(); return false; #else return true; #endif } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Compiler.h
//===-- llvm/Support/Compiler.h - Compiler abstraction support --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several macros, based on the current compiler. This allows // use of compiler-specific features in a way that remains portable. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_COMPILER_H #define LLVM_SUPPORT_COMPILER_H #include "llvm/Config/llvm-config.h" #ifndef __has_feature # define __has_feature(x) 0 #endif #ifndef __has_extension # define __has_extension(x) 0 #endif #ifndef __has_attribute # define __has_attribute(x) 0 #endif #ifndef __has_builtin # define __has_builtin(x) 0 #endif /// \macro LLVM_GNUC_PREREQ /// \brief Extend the default __GNUC_PREREQ even if glibc's features.h isn't /// available. #ifndef LLVM_GNUC_PREREQ # if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) # define LLVM_GNUC_PREREQ(maj, min, patch) \ ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) + __GNUC_PATCHLEVEL__ >= \ ((maj) << 20) + ((min) << 10) + (patch)) # elif defined(__GNUC__) && defined(__GNUC_MINOR__) # define LLVM_GNUC_PREREQ(maj, min, patch) \ ((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) >= ((maj) << 20) + ((min) << 10)) # else # define LLVM_GNUC_PREREQ(maj, min, patch) 0 # endif #endif /// \macro LLVM_MSC_PREREQ /// \brief Is the compiler MSVC of at least the specified version? /// The common \param version values to check for are: /// * 1800: Microsoft Visual Studio 2013 / 12.0 /// * 1900: Microsoft Visual Studio 2015 / 14.0 #ifdef _MSC_VER #define LLVM_MSC_PREREQ(version) (_MSC_VER >= (version)) // We require at least MSVC 2013. #if !LLVM_MSC_PREREQ(1800) #error LLVM requires at least MSVC 2013. #endif #else #define LLVM_MSC_PREREQ(version) 0 #endif #if !defined(_MSC_VER) || defined(__clang__) || LLVM_MSC_PREREQ(1900) #define LLVM_NOEXCEPT noexcept #else #define LLVM_NOEXCEPT #endif /// \brief Does the compiler support ref-qualifiers for *this? /// /// Sadly, this is separate from just rvalue reference support because GCC /// and MSVC implemented this later than everything else. #if __has_feature(cxx_rvalue_references) || LLVM_GNUC_PREREQ(4, 8, 1) #define LLVM_HAS_RVALUE_REFERENCE_THIS 1 #else #define LLVM_HAS_RVALUE_REFERENCE_THIS 0 #endif /// Expands to '&' if ref-qualifiers for *this are supported. /// /// This can be used to provide lvalue/rvalue overrides of member functions. /// The rvalue override should be guarded by LLVM_HAS_RVALUE_REFERENCE_THIS #if LLVM_HAS_RVALUE_REFERENCE_THIS #define LLVM_LVALUE_FUNCTION & #else #define LLVM_LVALUE_FUNCTION #endif #if __has_feature(cxx_constexpr) || defined(__GXX_EXPERIMENTAL_CXX0X__) # define LLVM_CONSTEXPR constexpr #else # define LLVM_CONSTEXPR #endif /// LLVM_LIBRARY_VISIBILITY - If a class marked with this attribute is linked /// into a shared library, then the class should be private to the library and /// not accessible from outside it. Can also be used to mark variables and /// functions, making them private to any shared library they are linked into. /// On PE/COFF targets, library visibility is the default, so this isn't needed. #if (__has_attribute(visibility) || LLVM_GNUC_PREREQ(4, 0, 0)) && \ !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(LLVM_ON_WIN32) #define LLVM_LIBRARY_VISIBILITY __attribute__ ((visibility("hidden"))) #else #define LLVM_LIBRARY_VISIBILITY #endif #if __has_attribute(sentinel) || LLVM_GNUC_PREREQ(3, 0, 0) #define LLVM_END_WITH_NULL __attribute__((sentinel)) #else #define LLVM_END_WITH_NULL #endif #if __has_attribute(used) || LLVM_GNUC_PREREQ(3, 1, 0) #define LLVM_ATTRIBUTE_USED __attribute__((__used__)) #else #define LLVM_ATTRIBUTE_USED #endif #if __has_attribute(warn_unused_result) || LLVM_GNUC_PREREQ(3, 4, 0) #define LLVM_ATTRIBUTE_UNUSED_RESULT __attribute__((__warn_unused_result__)) #else #define LLVM_ATTRIBUTE_UNUSED_RESULT #endif // Some compilers warn about unused functions. When a function is sometimes // used or not depending on build settings (e.g. a function only called from // within "assert"), this attribute can be used to suppress such warnings. // // However, it shouldn't be used for unused *variables*, as those have a much // more portable solution: // (void)unused_var_name; // Prefer cast-to-void wherever it is sufficient. #if __has_attribute(unused) || LLVM_GNUC_PREREQ(3, 1, 0) #define LLVM_ATTRIBUTE_UNUSED __attribute__((__unused__)) #else #define LLVM_ATTRIBUTE_UNUSED #endif // FIXME: Provide this for PE/COFF targets. #if (__has_attribute(weak) || LLVM_GNUC_PREREQ(4, 0, 0)) && \ (!defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(LLVM_ON_WIN32)) #define LLVM_ATTRIBUTE_WEAK __attribute__((__weak__)) #else #define LLVM_ATTRIBUTE_WEAK #endif // Prior to clang 3.2, clang did not accept any spelling of // __has_attribute(const), so assume it is supported. #if defined(__clang__) || defined(__GNUC__) // aka 'CONST' but following LLVM Conventions. #define LLVM_READNONE __attribute__((__const__)) #else #define LLVM_READNONE #endif #if __has_attribute(pure) || defined(__GNUC__) // aka 'PURE' but following LLVM Conventions. #define LLVM_READONLY __attribute__((__pure__)) #else #define LLVM_READONLY #endif #if __has_builtin(__builtin_expect) || LLVM_GNUC_PREREQ(4, 0, 0) #define LLVM_LIKELY(EXPR) __builtin_expect((bool)(EXPR), true) #define LLVM_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false) #else #define LLVM_LIKELY(EXPR) (EXPR) #define LLVM_UNLIKELY(EXPR) (EXPR) #endif /// LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, /// mark a method "not for inlining". #if __has_attribute(noinline) || LLVM_GNUC_PREREQ(3, 4, 0) #define LLVM_ATTRIBUTE_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_NOINLINE __declspec(noinline) #else #define LLVM_ATTRIBUTE_NOINLINE #endif /// LLVM_ATTRIBUTE_ALWAYS_INLINE - On compilers where we have a directive to do /// so, mark a method "always inline" because it is performance sensitive. GCC /// 3.4 supported this but is buggy in various cases and produces unimplemented /// errors, just use it in GCC 4.0 and later. #if __has_attribute(always_inline) || LLVM_GNUC_PREREQ(4, 0, 0) #define LLVM_ATTRIBUTE_ALWAYS_INLINE inline __attribute__((always_inline)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_ALWAYS_INLINE __forceinline #else #define LLVM_ATTRIBUTE_ALWAYS_INLINE #endif #ifdef __GNUC__ #define LLVM_ATTRIBUTE_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_NORETURN __declspec(noreturn) #else #define LLVM_ATTRIBUTE_NORETURN #endif #if __has_attribute(returns_nonnull) || LLVM_GNUC_PREREQ(4, 9, 0) #define LLVM_ATTRIBUTE_RETURNS_NONNULL __attribute__((returns_nonnull)) #else #define LLVM_ATTRIBUTE_RETURNS_NONNULL #endif /// \macro LLVM_ATTRIBUTE_RETURNS_NOALIAS Used to mark a function as returning a /// pointer that does not alias any other valid pointer. #ifdef __GNUC__ #define LLVM_ATTRIBUTE_RETURNS_NOALIAS __attribute__((__malloc__)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_RETURNS_NOALIAS __declspec(restrict) #else #define LLVM_ATTRIBUTE_RETURNS_NOALIAS #endif #if __cplusplus > 201402L #define LLVM_FALLTHROUGH [[fallthrough]] #elif defined(__clang__) #define LLVM_FALLTHROUGH [[clang::fallthrough]] #elif defined(_MSC_VER) #define LLVM_FALLTHROUGH __fallthrough #else #define LLVM_FALLTHROUGH [[gnu::fallthrough]] #endif #if defined(_MSC_VER) #if __cplusplus > 201402L #define LLVM_C_FALLTHROUGH [[fallthrough]] #elif __has_attribute(fallthrough) #define LLVM_C_FALLTHROUGH __attribute__((fallthrough)) #else #define LLVM_C_FALLTHROUGH #endif #else #define LLVM_C_FALLTHROUGH __attribute__((fallthrough)); #endif /// LLVM_EXTENSION - Support compilers where we have a keyword to suppress /// pedantic diagnostics. #ifdef __GNUC__ #define LLVM_EXTENSION __extension__ #else #define LLVM_EXTENSION #endif // LLVM_ATTRIBUTE_DEPRECATED(decl, "message") #if __has_feature(attribute_deprecated_with_message) # define LLVM_ATTRIBUTE_DEPRECATED(decl, message) \ decl __attribute__((deprecated(message))) #elif defined(__GNUC__) # define LLVM_ATTRIBUTE_DEPRECATED(decl, message) \ decl __attribute__((deprecated)) #elif defined(_MSC_VER) # define LLVM_ATTRIBUTE_DEPRECATED(decl, message) \ __declspec(deprecated(message)) decl #else # define LLVM_ATTRIBUTE_DEPRECATED(decl, message) \ decl #endif /// LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands /// to an expression which states that it is undefined behavior for the /// compiler to reach this point. Otherwise is not defined. #if __has_builtin(__builtin_unreachable) || LLVM_GNUC_PREREQ(4, 5, 0) # define LLVM_BUILTIN_UNREACHABLE __builtin_unreachable() #elif defined(_MSC_VER) # define LLVM_BUILTIN_UNREACHABLE __assume(false) #endif /// LLVM_BUILTIN_TRAP - On compilers which support it, expands to an expression /// which causes the program to exit abnormally. #if __has_builtin(__builtin_trap) || LLVM_GNUC_PREREQ(4, 3, 0) # define LLVM_BUILTIN_TRAP __builtin_trap() #elif defined(_MSC_VER) // The __debugbreak intrinsic is supported by MSVC, does not require forward // declarations involving platform-specific typedefs (unlike RaiseException), // results in a call to vectored exception handlers, and encodes to a short // instruction that still causes the trapping behavior we want. # define LLVM_BUILTIN_TRAP __debugbreak() #else # define LLVM_BUILTIN_TRAP *(volatile int*)0x11 = 0 #endif /// \macro LLVM_ASSUME_ALIGNED /// \brief Returns a pointer with an assumed alignment. #if __has_builtin(__builtin_assume_aligned) || LLVM_GNUC_PREREQ(4, 7, 0) # define LLVM_ASSUME_ALIGNED(p, a) __builtin_assume_aligned(p, a) #elif defined(LLVM_BUILTIN_UNREACHABLE) // As of today, clang does not support __builtin_assume_aligned. # define LLVM_ASSUME_ALIGNED(p, a) \ (((uintptr_t(p) % (a)) == 0) ? (p) : (LLVM_BUILTIN_UNREACHABLE, (p))) #else # define LLVM_ASSUME_ALIGNED(p, a) (p) #endif /// \macro LLVM_ALIGNAS /// \brief Used to specify a minimum alignment for a structure or variable. The /// alignment must be a constant integer. Use LLVM_PTR_SIZE to compute /// alignments in terms of the size of a pointer. /// /// Note that __declspec(align) has special quirks, it's not legal to pass a /// structure with __declspec(align) as a formal parameter. #ifdef _MSC_VER # define LLVM_ALIGNAS(x) __declspec(align(x)) #elif __GNUC__ && !__has_feature(cxx_alignas) && !LLVM_GNUC_PREREQ(4, 8, 0) # define LLVM_ALIGNAS(x) __attribute__((aligned(x))) #else # define LLVM_ALIGNAS(x) alignas(x) #endif /// \macro LLVM_PTR_SIZE /// \brief A constant integer equivalent to the value of sizeof(void*). /// Generally used in combination with LLVM_ALIGNAS or when doing computation in /// the preprocessor. #ifdef __SIZEOF_POINTER__ # define LLVM_PTR_SIZE __SIZEOF_POINTER__ #elif defined(_WIN64) # define LLVM_PTR_SIZE 8 #elif defined(_WIN32) # define LLVM_PTR_SIZE 4 #elif defined(_MSC_VER) # error "could not determine LLVM_PTR_SIZE as a constant int for MSVC" #else # define LLVM_PTR_SIZE sizeof(void *) #endif /// \macro LLVM_FUNCTION_NAME /// \brief Expands to __func__ on compilers which support it. Otherwise, /// expands to a compiler-dependent replacement. #if defined(_MSC_VER) # define LLVM_FUNCTION_NAME __FUNCTION__ #else # define LLVM_FUNCTION_NAME __func__ #endif /// \macro LLVM_MEMORY_SANITIZER_BUILD /// \brief Whether LLVM itself is built with MemorySanitizer instrumentation. #if __has_feature(memory_sanitizer) # define LLVM_MEMORY_SANITIZER_BUILD 1 # include <sanitizer/msan_interface.h> #else # define LLVM_MEMORY_SANITIZER_BUILD 0 # define __msan_allocated_memory(p, size) # define __msan_unpoison(p, size) #endif /// \macro LLVM_ADDRESS_SANITIZER_BUILD /// \brief Whether LLVM itself is built with AddressSanitizer instrumentation. #if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__) # define LLVM_ADDRESS_SANITIZER_BUILD 1 #else # define LLVM_ADDRESS_SANITIZER_BUILD 0 #endif /// \brief Mark debug helper function definitions like dump() that should not be /// stripped from debug builds. // FIXME: Move this to a private config.h as it's not usable in public headers. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) #define LLVM_DUMP_METHOD LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED #else #define LLVM_DUMP_METHOD LLVM_ATTRIBUTE_NOINLINE #endif /// \macro LLVM_THREAD_LOCAL /// \brief A thread-local storage specifier which can be used with globals, /// extern globals, and static globals. /// /// This is essentially an extremely restricted analog to C++11's thread_local /// support, and uses that when available. However, it falls back on /// platform-specific or vendor-provided extensions when necessary. These /// extensions don't support many of the C++11 thread_local's features. You /// should only use this for PODs that you can statically initialize to /// some constant value. In almost all circumstances this is most appropriate /// for use with a pointer, integer, or small aggregation of pointers and /// integers. #if LLVM_ENABLE_THREADS #if __has_feature(cxx_thread_local) #define LLVM_THREAD_LOCAL thread_local #elif defined(_MSC_VER) // MSVC supports this with a __declspec. #define LLVM_THREAD_LOCAL __declspec(thread) #else // Clang, GCC, and other compatible compilers used __thread prior to C++11 and // we only need the restricted functionality that provides. #define LLVM_THREAD_LOCAL __thread #endif #else // !LLVM_ENABLE_THREADS // If threading is disabled entirely, this compiles to nothing and you get // a normal global variable. #define LLVM_THREAD_LOCAL #endif #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/RandomNumberGenerator.h
//==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an abstraction for deterministic random number // generation (RNG). Note that the current implementation is not // cryptographically secure as it uses the C++11 <random> facilities. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_ #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows. #include <random> namespace llvm { /// A random number generator. /// /// Instances of this class should not be shared across threads. The /// seed should be set by passing the -rng-seed=<uint64> option. Use /// Module::createRNG to create a new RNG instance for use with that /// module. class RandomNumberGenerator { public: /// Returns a random number in the range [0, Max). uint_fast64_t operator()(); private: /// Seeds and salts the underlying RNG engine. /// /// This constructor should not be used directly. Instead use /// Module::createRNG to create a new RNG salted with the Module ID. RandomNumberGenerator(StringRef Salt); // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000 // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine // This RNG is deterministically portable across C++11 // implementations. std::mt19937_64 Generator; // Noncopyable. RandomNumberGenerator(const RandomNumberGenerator &other) = delete; RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete; friend class Module; }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Errno.h
//===- llvm/Support/Errno.h - Portable+convenient errno handling -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares some portable and convenient functions to deal with errno. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ERRNO_H #define LLVM_SUPPORT_ERRNO_H #include <string> namespace llvm { namespace sys { /// Returns a string representation of the errno value, using whatever /// thread-safe variant of strerror() is available. Be sure to call this /// immediately after the function that set errno, or errno may have been /// overwritten by an intervening call. std::string StrError(); /// Like the no-argument version above, but uses \p errnum instead of errno. std::string StrError(int errnum); } // namespace sys } // namespace llvm #endif // LLVM_SYSTEM_ERRNO_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ARMWinEH.h
//===-- llvm/Support/WinARMEH.h - Windows on ARM EH Constants ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ARMWINEH_H #define LLVM_SUPPORT_ARMWINEH_H #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Endian.h" namespace llvm { namespace ARM { namespace WinEH { enum class RuntimeFunctionFlag { RFF_Unpacked, /// unpacked entry RFF_Packed, /// packed entry RFF_PackedFragment, /// packed entry representing a fragment RFF_Reserved, /// reserved }; enum class ReturnType { RT_POP, /// return via pop {pc} (L flag must be set) RT_B, /// 16-bit branch RT_BW, /// 32-bit branch RT_NoEpilogue, /// no epilogue (fragment) }; /// RuntimeFunction - An entry in the table of procedure data (.pdata) /// /// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 /// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 /// +---------------------------------------------------------------+ /// | Function Start RVA | /// +-------------------+-+-+-+-----+-+---+---------------------+---+ /// | Stack Adjust |C|L|R| Reg |H|Ret| Function Length |Flg| /// +-------------------+-+-+-+-----+-+---+---------------------+---+ /// /// Flag : 2-bit field with the following meanings: /// - 00 = packed unwind data not used; reamining bits point to .xdata record /// - 01 = packed unwind data /// - 10 = packed unwind data, function assumed to have no prologue; useful /// for function fragments that are discontiguous with the start of the /// function /// - 11 = reserved /// Function Length : 11-bit field providing the length of the entire function /// in bytes, divided by 2; if the function is greater than /// 4KB, a full .xdata record must be used instead /// Ret : 2-bit field indicating how the function returns /// - 00 = return via pop {pc} (the L bit must be set) /// - 01 = return via 16-bit branch /// - 10 = return via 32-bit branch /// - 11 = no epilogue; useful for function fragments that may only contain a /// prologue but the epilogue is elsewhere /// H : 1-bit flag indicating whether the function "homes" the integer parameter /// registers (r0-r3), allocating 16-bytes on the stack /// Reg : 3-bit field indicating the index of the last saved non-volatile /// register. If the R bit is set to 0, then only integer registers are /// saved (r4-rN, where N is 4 + Reg). If the R bit is set to 1, then /// only floating-point registers are being saved (d8-dN, where N is /// 8 + Reg). The special case of the R bit being set to 1 and Reg equal /// to 7 indicates that no registers are saved. /// R : 1-bit flag indicating whether the non-volatile registers are integer or /// floating-point. 0 indicates integer, 1 indicates floating-point. The /// special case of the R-flag being set and Reg being set to 7 indicates /// that no non-volatile registers are saved. /// L : 1-bit flag indicating whether the function saves/restores the link /// register (LR) /// C : 1-bit flag indicating whether the function includes extra instructions /// to setup a frame chain for fast walking. If this flag is set, r11 is /// implicitly added to the list of saved non-volatile integer registers. /// Stack Adjust : 10-bit field indicating the number of bytes of stack that are /// allocated for this function. Only values between 0x000 and /// 0x3f3 can be directly encoded. If the value is 0x3f4 or /// greater, then the low 4 bits have special meaning as follows: /// - Bit 0-1 /// indicate the number of words' of adjustment (1-4), minus 1 /// - Bit 2 /// indicates if the prologue combined adjustment into push /// - Bit 3 /// indicates if the epilogue combined adjustment into pop /// /// RESTRICTIONS: /// - IF C is SET: /// + L flag must be set since frame chaining requires r11 and lr /// + r11 must NOT be included in the set of registers described by Reg /// - IF Ret is 0: /// + L flag must be set // NOTE: RuntimeFunction is meant to be a simple class that provides raw access // to all fields in the structure. The accessor methods reflect the names of // the bitfields that they correspond to. Although some obvious simplifications // are possible via merging of methods, it would prevent the use of this class // to fully inspect the contents of the data structure which is particularly // useful for scenarios such as llvm-readobj to aid in testing. class RuntimeFunction { public: const support::ulittle32_t BeginAddress; const support::ulittle32_t UnwindData; RuntimeFunction(const support::ulittle32_t *Data) : BeginAddress(Data[0]), UnwindData(Data[1]) {} RuntimeFunction(const support::ulittle32_t BeginAddress, const support::ulittle32_t UnwindData) : BeginAddress(BeginAddress), UnwindData(UnwindData) {} RuntimeFunctionFlag Flag() const { return RuntimeFunctionFlag(UnwindData & 0x3); } uint32_t ExceptionInformationRVA() const { assert(Flag() == RuntimeFunctionFlag::RFF_Unpacked && "unpacked form required for this operation"); return (UnwindData & ~0x3); } uint32_t PackedUnwindData() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return (UnwindData & ~0x3); } uint32_t FunctionLength() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return (((UnwindData & 0x00001ffc) >> 2) << 1); } ReturnType Ret() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); assert(((UnwindData & 0x00006000) || L()) && "L must be set to 1"); return ReturnType((UnwindData & 0x00006000) >> 13); } bool H() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return ((UnwindData & 0x00008000) >> 15); } uint8_t Reg() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return ((UnwindData & 0x00070000) >> 16); } bool R() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return ((UnwindData & 0x00080000) >> 19); } bool L() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return ((UnwindData & 0x00100000) >> 20); } bool C() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); assert(((~UnwindData & 0x00200000) || L()) && "L flag must be set, chaining requires r11 and LR"); assert(((~UnwindData & 0x00200000) || (Reg() < 7) || R()) && "r11 must not be included in Reg; C implies r11"); return ((UnwindData & 0x00200000) >> 21); } uint16_t StackAdjust() const { assert((Flag() == RuntimeFunctionFlag::RFF_Packed || Flag() == RuntimeFunctionFlag::RFF_PackedFragment) && "packed form required for this operation"); return ((UnwindData & 0xffc00000) >> 22); } }; /// PrologueFolding - pseudo-flag derived from Stack Adjust indicating that the /// prologue has stack adjustment combined into the push inline bool PrologueFolding(const RuntimeFunction &RF) { return RF.StackAdjust() >= 0x3f4 && (RF.StackAdjust() & 0x4); } /// Epilogue - pseudo-flag derived from Stack Adjust indicating that the /// epilogue has stack adjustment combined into the pop inline bool EpilogueFolding(const RuntimeFunction &RF) { return RF.StackAdjust() >= 0x3f4 && (RF.StackAdjust() & 0x8); } /// StackAdjustment - calculated stack adjustment in words. The stack /// adjustment should be determined via this function to account for the special /// handling the special encoding when the value is >= 0x3f4. inline uint16_t StackAdjustment(const RuntimeFunction &RF) { uint16_t Adjustment = RF.StackAdjust(); if (Adjustment >= 0x3f4) return (Adjustment & 0x3) ? ((Adjustment & 0x3) << 2) - 1 : 0; return Adjustment; } /// SavedRegisterMask - Utility function to calculate the set of saved general /// purpose (r0-r15) and VFP (d0-d31) registers. std::pair<uint16_t, uint32_t> SavedRegisterMask(const RuntimeFunction &RF); /// ExceptionDataRecord - An entry in the table of exception data (.xdata) /// /// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 /// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 /// +-------+---------+-+-+-+---+-----------------------------------+ /// | C Wrd | Epi Cnt |F|E|X|Ver| Function Length | /// +-------+--------+'-'-'-'---'---+-------------------------------+ /// | Reserved |Ex. Code Words| (Extended Epilogue Count) | /// +-------+--------+--------------+-------------------------------+ /// /// Function Length : 18-bit field indicating the total length of the function /// in bytes divided by 2. If a function is larger than /// 512KB, then multiple pdata and xdata records must be used. /// Vers : 2-bit field describing the version of the remaining structure. Only /// version 0 is currently defined (values 1-3 are not permitted). /// X : 1-bit field indicating the presence of exception data /// E : 1-bit field indicating that the single epilogue is packed into the /// header /// F : 1-bit field indicating that the record describes a function fragment /// (implies that no prologue is present, and prologue processing should be /// skipped) /// Epilogue Count : 5-bit field that differs in meaning based on the E field. /// /// If E is set, then this field specifies the index of the /// first unwind code describing the (only) epilogue. /// /// Otherwise, this field indicates the number of exception /// scopes. If more than 31 scopes exist, then this field and /// the Code Words field must both be set to 0 to indicate that /// an extension word is required. /// Code Words : 4-bit field that species the number of 32-bit words needed to /// contain all the unwind codes. If more than 15 words (63 code /// bytes) are required, then this field and the Epilogue Count /// field must both be set to 0 to indicate that an extension word /// is required. /// Extended Epilogue Count, Extended Code Words : /// Valid only if Epilog Count and Code Words are both /// set to 0. Provides an 8-bit extended code word /// count and 16-bits for epilogue count /// /// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 /// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 /// +----------------+------+---+---+-------------------------------+ /// | Ep Start Idx | Cond |Res| Epilogue Start Offset | /// +----------------+------+---+-----------------------------------+ /// /// If the E bit is unset in the header, the header is followed by a series of /// epilogue scopes, which are sorted by their offset. /// /// Epilogue Start Offset: 18-bit field encoding the offset of epilogue relative /// to the start of the function in bytes divided by two /// Res : 2-bit field reserved for future expansion (must be set to 0) /// Condition : 4-bit field providing the condition under which the epilogue is /// executed. Unconditional epilogues should set this field to 0xe. /// Epilogues must be entirely conditional or unconditional, and in /// Thumb-2 mode. The epilogue beings with the first instruction /// after the IT opcode. /// Epilogue Start Index : 8-bit field indicating the byte index of the first /// unwind code describing the epilogue /// /// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 /// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 /// +---------------+---------------+---------------+---------------+ /// | Unwind Code 3 | Unwind Code 2 | Unwind Code 1 | Unwind Code 0 | /// +---------------+---------------+---------------+---------------+ /// /// Following the epilogue scopes, the byte code describing the unwinding /// follows. This is padded to align up to word alignment. Bytes are stored in /// little endian. /// /// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 /// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 /// +---------------------------------------------------------------+ /// | Exception Handler RVA (requires X = 1) | /// +---------------------------------------------------------------+ /// | (possibly followed by data required for exception handler) | /// +---------------------------------------------------------------+ /// /// If the X bit is set in the header, the unwind byte code is followed by the /// exception handler information. This constants of one Exception Handler RVA /// which is the address to the exception handler, followed immediately by the /// variable length data associated with the exception handler. /// struct EpilogueScope { const support::ulittle32_t ES; EpilogueScope(const support::ulittle32_t Data) : ES(Data) {} uint32_t EpilogueStartOffset() const { return (ES & 0x0003ffff); } uint8_t Res() const { return ((ES & 0x000c0000) >> 18); } uint8_t Condition() const { return ((ES & 0x00f00000) >> 20); } uint8_t EpilogueStartIndex() const { return ((ES & 0xff000000) >> 24); } }; struct ExceptionDataRecord; inline size_t HeaderWords(const ExceptionDataRecord &XR); struct ExceptionDataRecord { const support::ulittle32_t *Data; ExceptionDataRecord(const support::ulittle32_t *Data) : Data(Data) {} uint32_t FunctionLength() const { return (Data[0] & 0x0003ffff); } uint8_t Vers() const { return (Data[0] & 0x000C0000) >> 18; } bool X() const { return ((Data[0] & 0x00100000) >> 20); } bool E() const { return ((Data[0] & 0x00200000) >> 21); } bool F() const { return ((Data[0] & 0x00400000) >> 22); } uint8_t EpilogueCount() const { if (HeaderWords(*this) == 1) return (Data[0] & 0x0f800000) >> 23; return Data[1] & 0x0000ffff; } uint8_t CodeWords() const { if (HeaderWords(*this) == 1) return (Data[0] & 0xf0000000) >> 28; return (Data[1] & 0x00ff0000) >> 16; } ArrayRef<support::ulittle32_t> EpilogueScopes() const { assert(E() == 0 && "epilogue scopes are only present when the E bit is 0"); size_t Offset = HeaderWords(*this); return makeArrayRef(&Data[Offset], EpilogueCount()); } ArrayRef<uint8_t> UnwindByteCode() const { const size_t Offset = HeaderWords(*this) + (E() ? 0 : EpilogueCount()); const uint8_t *ByteCode = reinterpret_cast<const uint8_t *>(&Data[Offset]); return makeArrayRef(ByteCode, CodeWords() * sizeof(uint32_t)); } uint32_t ExceptionHandlerRVA() const { assert(X() && "Exception Handler RVA is only valid if the X bit is set"); return Data[HeaderWords(*this) + EpilogueCount() + CodeWords()]; } uint32_t ExceptionHandlerParameter() const { assert(X() && "Exception Handler RVA is only valid if the X bit is set"); return Data[HeaderWords(*this) + EpilogueCount() + CodeWords() + 1]; } }; inline size_t HeaderWords(const ExceptionDataRecord &XR) { return (XR.Data[0] & 0xff800000) ? 1 : 2; } } } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Process.h
//===- llvm/Support/Process.h -----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// Provides a library for accessing information about this process and other /// processes on the operating system. Also provides means of spawning /// subprocess for commands. The design of this library is modeled after the /// proposed design of the Boost.Process library, and is design specifically to /// follow the style of standard libraries and potentially become a proposal /// for a standard library. /// /// This file declares the llvm::sys::Process class which contains a collection /// of legacy static interfaces for extracting various information about the /// current process. The goal is to migrate users of this API over to the new /// interfaces. /// //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_PROCESS_H #define LLVM_SUPPORT_PROCESS_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/TimeValue.h" #include <system_error> namespace llvm { class StringRef; namespace sys { /// \brief A collection of legacy interfaces for querying information about the /// current executing process. class Process { public: static unsigned getPageSize(); /// \brief Return process memory usage. /// This static function will return the total amount of memory allocated /// by the process. This only counts the memory allocated via the malloc, /// calloc and realloc functions and includes any "free" holes in the /// allocated space. static size_t GetMallocUsage(); /// This static function will set \p user_time to the amount of CPU time /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU /// time spent in system (kernel) mode. If the operating system does not /// support collection of these metrics, a zero TimeValue will be for both /// values. /// \param elapsed Returns the TimeValue::now() giving current time /// \param user_time Returns the current amount of user time for the process /// \param sys_time Returns the current amount of system time for the process static void GetTimeUsage(TimeValue &elapsed, TimeValue &user_time, TimeValue &sys_time); /// This function makes the necessary calls to the operating system to /// prevent core files or any other kind of large memory dumps that can /// occur when a program fails. /// @brief Prevent core file generation. static void PreventCoreFiles(); // This function returns the environment variable \arg name's value as a UTF-8 // string. \arg Name is assumed to be in UTF-8 encoding too. static Optional<std::string> GetEnv(StringRef name); /// This function searches for an existing file in the list of directories /// in a PATH like environment variable, and returns the first file found, /// according to the order of the entries in the PATH like environment /// variable. static Optional<std::string> FindInEnvPath(const std::string& EnvName, const std::string& FileName); /// This function returns a SmallVector containing the arguments passed from /// the operating system to the program. This function expects to be handed /// the vector passed in from main. static std::error_code GetArgumentVector(SmallVectorImpl<const char *> &Args, ArrayRef<const char *> ArgsFromMain, SpecificBumpPtrAllocator<char> &ArgAllocator); // This functions ensures that the standard file descriptors (input, output, // and error) are properly mapped to a file descriptor before we use any of // them. This should only be called by standalone programs, library // components should not call this. static std::error_code FixupStandardFileDescriptors(); // This function safely closes a file descriptor. It is not safe to retry // close(2) when it returns with errno equivalent to EINTR; this is because // *nixen cannot agree if the file descriptor is, in fact, closed when this // occurs. // // N.B. Some operating systems, due to thread cancellation, cannot properly // guarantee that it will or will not be closed one way or the other! static std::error_code SafelyCloseFileDescriptor(int FD); /// This function determines if the standard input is connected directly /// to a user's input (keyboard probably), rather than coming from a file /// or pipe. static bool StandardInIsUserInput(); /// This function determines if the standard output is connected to a /// "tty" or "console" window. That is, the output would be displayed to /// the user rather than being put on a pipe or stored in a file. static bool StandardOutIsDisplayed(); /// This function determines if the standard error is connected to a /// "tty" or "console" window. That is, the output would be displayed to /// the user rather than being put on a pipe or stored in a file. static bool StandardErrIsDisplayed(); /// This function determines if the given file descriptor is connected to /// a "tty" or "console" window. That is, the output would be displayed to /// the user rather than being put on a pipe or stored in a file. static bool FileDescriptorIsDisplayed(int fd); /// This function determines if the given file descriptor is displayd and /// supports colors. static bool FileDescriptorHasColors(int fd); /// This function determines the number of columns in the window /// if standard output is connected to a "tty" or "console" /// window. If standard output is not connected to a tty or /// console, or if the number of columns cannot be determined, /// this routine returns zero. static unsigned StandardOutColumns(); /// This function determines the number of columns in the window /// if standard error is connected to a "tty" or "console" /// window. If standard error is not connected to a tty or /// console, or if the number of columns cannot be determined, /// this routine returns zero. static unsigned StandardErrColumns(); /// This function determines whether the terminal connected to standard /// output supports colors. If standard output is not connected to a /// terminal, this function returns false. static bool StandardOutHasColors(); /// This function determines whether the terminal connected to standard /// error supports colors. If standard error is not connected to a /// terminal, this function returns false. static bool StandardErrHasColors(); /// Enables or disables whether ANSI escape sequences are used to output /// colors. This only has an effect on Windows. /// Note: Setting this option is not thread-safe and should only be done /// during initialization. static void UseANSIEscapeCodes(bool enable); /// Whether changing colors requires the output to be flushed. /// This is needed on systems that don't support escape sequences for /// changing colors. static bool ColorNeedsFlush(); /// This function returns the colorcode escape sequences. /// If ColorNeedsFlush() is true then this function will change the colors /// and return an empty escape sequence. In that case it is the /// responsibility of the client to flush the output stream prior to /// calling this function. static const char *OutputColor(char c, bool bold, bool bg); /// Same as OutputColor, but only enables the bold attribute. static const char *OutputBold(bool bg); /// This function returns the escape sequence to reverse forground and /// background colors. static const char *OutputReverse(); /// Resets the terminals colors, or returns an escape sequence to do so. static const char *ResetColor(); /// Get the result of a process wide random number generator. The /// generator will be automatically seeded in non-deterministic fashion. static unsigned GetRandomNumber(); }; } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/PluginLoader.h
//===-- llvm/Support/PluginLoader.h - Plugin Loader for Tools ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // A tool can #include this file to get a -load option that allows the user to // load arbitrary shared objects into the tool's address space. Note that this // header can only be included by a program ONCE, so it should never to used by // library authors. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_PLUGINLOADER_H #define LLVM_SUPPORT_PLUGINLOADER_H #include "llvm/Support/CommandLine.h" #if 0 // HLSL Change Starts - no support for plug-in loader namespace llvm { struct PluginLoader { void operator=(const std::string &Filename); static unsigned getNumPlugins(); static std::string& getPlugin(unsigned num); }; #ifndef DONT_GET_PLUGIN_LOADER_OPTION // This causes operator= above to be invoked for every -load option. static cl::opt<PluginLoader, false, cl::parser<std::string> > LoadOpt("load", cl::ZeroOrMore, cl::value_desc("pluginfilename"), cl::desc("Load the specified plugin")); #endif } #endif // HLSL Change Ends - no support for plug-in loader #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/BlockFrequency.h
//===-------- BlockFrequency.h - Block Frequency Wrapper --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements Block Frequency class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_BLOCKFREQUENCY_H #define LLVM_SUPPORT_BLOCKFREQUENCY_H #include "llvm/Support/DataTypes.h" namespace llvm { class raw_ostream; class BranchProbability; // This class represents Block Frequency as a 64-bit value. class BlockFrequency { uint64_t Frequency; public: BlockFrequency(uint64_t Freq = 0) : Frequency(Freq) { } /// \brief Returns the maximum possible frequency, the saturation value. static uint64_t getMaxFrequency() { return -1ULL; } /// \brief Returns the frequency as a fixpoint number scaled by the entry /// frequency. uint64_t getFrequency() const { return Frequency; } /// \brief Multiplies with a branch probability. The computation will never /// overflow. BlockFrequency &operator*=(const BranchProbability &Prob); const BlockFrequency operator*(const BranchProbability &Prob) const; /// \brief Divide by a non-zero branch probability using saturating /// arithmetic. BlockFrequency &operator/=(const BranchProbability &Prob); BlockFrequency operator/(const BranchProbability &Prob) const; /// \brief Adds another block frequency using saturating arithmetic. BlockFrequency &operator+=(const BlockFrequency &Freq); const BlockFrequency operator+(const BlockFrequency &Freq) const; /// \brief Shift block frequency to the right by count digits saturating to 1. BlockFrequency &operator>>=(const unsigned count); bool operator<(const BlockFrequency &RHS) const { return Frequency < RHS.Frequency; } bool operator<=(const BlockFrequency &RHS) const { return Frequency <= RHS.Frequency; } bool operator>(const BlockFrequency &RHS) const { return Frequency > RHS.Frequency; } bool operator>=(const BlockFrequency &RHS) const { return Frequency >= RHS.Frequency; } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ErrorHandling.h
//===- llvm/Support/ErrorHandling.h - Fatal error handling ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an API used to indicate fatal error conditions. Non-fatal // errors (most of them) should be handled through LLVMContext. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ERRORHANDLING_H #define LLVM_SUPPORT_ERRORHANDLING_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Config/abi-breaking.h" #include <string> namespace llvm { class Twine; /// An error handler callback. typedef void (*fatal_error_handler_t)(void *user_data, const std::string& reason, bool gen_crash_diag); /// install_fatal_error_handler - Installs a new error handler to be used /// whenever a serious (non-recoverable) error is encountered by LLVM. /// /// If no error handler is installed the default is to print the error message /// to stderr, and call exit(1). If an error handler is installed then it is /// the handler's responsibility to log the message, it will no longer be /// printed to stderr. If the error handler returns, then exit(1) will be /// called. /// /// It is dangerous to naively use an error handler which throws an exception. /// Even though some applications desire to gracefully recover from arbitrary /// faults, blindly throwing exceptions through unfamiliar code isn't a way to /// achieve this. /// /// \param user_data - An argument which will be passed to the install error /// handler. void install_fatal_error_handler(fatal_error_handler_t handler, void *user_data = nullptr); /// Restores default error handling behaviour. void remove_fatal_error_handler(); /// ScopedFatalErrorHandler - This is a simple helper class which just /// calls install_fatal_error_handler in its constructor and /// remove_fatal_error_handler in its destructor. struct ScopedFatalErrorHandler { explicit ScopedFatalErrorHandler(fatal_error_handler_t handler, void *user_data = nullptr) { install_fatal_error_handler(handler, user_data); } ~ScopedFatalErrorHandler() { remove_fatal_error_handler(); } }; /// Reports a serious error, calling any installed error handler. These /// functions are intended to be used for error conditions which are outside /// the control of the compiler (I/O errors, invalid user input, etc.) /// /// If no error handler is installed the default is to print the message to /// standard error, followed by a newline. /// After the error handler is called this function will call exit(1), it /// does not return. LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag = true); LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const std::string &reason, bool gen_crash_diag = true); LLVM_ATTRIBUTE_NORETURN void report_fatal_error(StringRef reason, bool gen_crash_diag = true); LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const Twine &reason, bool gen_crash_diag = true); /// This function calls abort(), and prints the optional message to stderr. /// Use the llvm_unreachable macro (that adds location info), instead of /// calling this function directly. LLVM_ATTRIBUTE_NORETURN void llvm_unreachable_internal(const char *msg=nullptr, const char *file=nullptr, unsigned line=0); // HLSL Change - throw special exception for cast mismatch void llvm_cast_assert_internal(const char *func); } /// Marks that the current location is not supposed to be reachable. /// In !NDEBUG builds, prints the message and location info to stderr. /// In NDEBUG builds, becomes an optimizer hint that the current location /// is not supposed to be reachable. On compilers that don't support /// such hints, prints a reduced message instead. /// /// Use this instead of assert(0). It conveys intent more clearly and /// allows compilers to omit some unnecessary code. #if 1 // HLSL Change - always throw exception with message for unreachable #define llvm_unreachable(msg) \ ::llvm::llvm_unreachable_internal(msg, __FILE__, __LINE__) #elif defined(LLVM_BUILTIN_UNREACHABLE) #define llvm_unreachable(msg) LLVM_BUILTIN_UNREACHABLE #else #define llvm_unreachable(msg) ::llvm::llvm_unreachable_internal() #endif // HLSL Change - throw special exception for cast type mismatch #define llvm_cast_assert(X, Val) ((void)( (!!(isa<X>(Val))) || (::llvm::llvm_cast_assert_internal(__FUNCTION__), 0) )) #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/DataTypes.h.in
/*===-- include/Support/DataTypes.h - Define fixed size types -----*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file contains definitions to figure out the size of _HOST_ data types.*| |* This file is important because different host OS's define different macros,*| |* which makes portability tough. This file exports the following *| |* definitions: *| |* *| |* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| |* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| |* *| |* No library is required when using these functions. *| |* *| |*===----------------------------------------------------------------------===*/ /* Please leave this file C-compatible. */ /* Please keep this file in sync with DataTypes.h.cmake */ #ifndef SUPPORT_DATATYPES_H #define SUPPORT_DATATYPES_H #undef HAVE_INTTYPES_H #undef HAVE_STDINT_H #undef HAVE_UINT64_T #undef HAVE_U_INT64_T #ifdef __cplusplus #include <cmath> #else #include <math.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #else #error "Compiler must provide an implementation of stdint.h" #endif #ifndef _MSC_VER /* Note that this header's correct operation depends on __STDC_LIMIT_MACROS being defined. We would define it here, but in order to prevent Bad Things happening when system headers or C++ STL headers include stdint.h before we define it here, we define it on the g++ command line (in Makefile.rules). */ #if !defined(__STDC_LIMIT_MACROS) # error "Must #define __STDC_LIMIT_MACROS before #including Support/DataTypes.h" #endif #if !defined(__STDC_CONSTANT_MACROS) # error "Must #define __STDC_CONSTANT_MACROS before " \ "#including Support/DataTypes.h" #endif /* Note that <inttypes.h> includes <stdint.h>, if this is a C99 system. */ #include <sys/types.h> #ifdef _AIX #include "llvm/Support/AIXDataTypesFix.h" #endif /* Handle incorrect definition of uint64_t as u_int64_t */ #ifndef HAVE_UINT64_T #ifdef HAVE_U_INT64_T typedef u_int64_t uint64_t; #else # error "Don't have a definition for uint64_t on this platform" #endif #endif #else /* _MSC_VER */ #include <stdlib.h> #include <stddef.h> #include <sys/types.h> #ifdef __cplusplus #include <cmath> #else #include <math.h> #endif #if defined(_WIN64) typedef signed __int64 ssize_t; #else typedef signed int ssize_t; #endif /* _WIN64 */ #ifndef HAVE_INTTYPES_H #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #endif /* HAVE_INTTYPES_H */ #endif /* _MSC_VER */ /* Set defaults for constants which we cannot find. */ #if !defined(INT64_MAX) # define INT64_MAX 9223372036854775807LL #endif #if !defined(INT64_MIN) # define INT64_MIN ((-INT64_MAX)-1) #endif #if !defined(UINT64_MAX) # define UINT64_MAX 0xffffffffffffffffULL #endif #ifndef HUGE_VALF #define HUGE_VALF (float)HUGE_VAL #endif #endif /* SUPPORT_DATATYPES_H */
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/LineIterator.h
//===- LineIterator.h - Iterator to read a text buffer's lines --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_LINEITERATOR_H #define LLVM_SUPPORT_LINEITERATOR_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include <iterator> namespace llvm { class MemoryBuffer; /// \brief A forward iterator which reads text lines from a buffer. /// /// This class provides a forward iterator interface for reading one line at /// a time from a buffer. When default constructed the iterator will be the /// "end" iterator. /// /// The iterator is aware of what line number it is currently processing. It /// strips blank lines by default, and comment lines given a comment-starting /// character. /// /// Note that this iterator requires the buffer to be nul terminated. class line_iterator { const MemoryBuffer *Buffer; char CommentMarker; bool SkipBlanks; unsigned LineNumber; StringRef CurrentLine; public: using iterator_category = std::forward_iterator_tag; using value_type = StringRef; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; /// \brief Default construct an "end" iterator. line_iterator() : Buffer(nullptr) {} /// \brief Construct a new iterator around some memory buffer. explicit line_iterator(const MemoryBuffer &Buffer, bool SkipBlanks = true, char CommentMarker = '\0'); /// \brief Return true if we've reached EOF or are an "end" iterator. bool is_at_eof() const { return !Buffer; } /// \brief Return true if we're an "end" iterator or have reached EOF. bool is_at_end() const { return is_at_eof(); } /// \brief Return the current line number. May return any number at EOF. int64_t line_number() const { return LineNumber; } /// \brief Advance to the next (non-empty, non-comment) line. line_iterator &operator++() { advance(); return *this; } line_iterator operator++(int) { line_iterator tmp(*this); advance(); return tmp; } /// \brief Get the current line as a \c StringRef. StringRef operator*() const { return CurrentLine; } const StringRef *operator->() const { return &CurrentLine; } friend bool operator==(const line_iterator &LHS, const line_iterator &RHS) { return LHS.Buffer == RHS.Buffer && LHS.CurrentLine.begin() == RHS.CurrentLine.begin(); } friend bool operator!=(const line_iterator &LHS, const line_iterator &RHS) { return !(LHS == RHS); } private: /// \brief Advance the iterator to the next line. void advance(); }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/UniqueLock.h
//===-- Support/UniqueLock.h - Acquire/Release Mutex In Scope ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a guard for a block of code that ensures a Mutex is locked // upon construction and released upon destruction. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_UNIQUE_LOCK_H #define LLVM_SUPPORT_UNIQUE_LOCK_H #include "llvm/Support/Mutex.h" namespace llvm { /// A pared-down imitation of std::unique_lock from C++11. Contrary to the /// name, it's really more of a wrapper for a lock. It may or may not have /// an associated mutex, which is guaranteed to be locked upon creation /// and unlocked after destruction. unique_lock can also unlock the mutex /// and re-lock it freely during its lifetime. /// @brief Guard a section of code with a mutex. template<typename MutexT> class unique_lock { MutexT *M; bool locked; unique_lock(const unique_lock &) = delete; void operator=(const unique_lock &) = delete; public: unique_lock() : M(nullptr), locked(false) {} explicit unique_lock(MutexT &m) : M(&m), locked(true) { M->lock(); } void operator=(unique_lock &&o) { if (owns_lock()) M->unlock(); M = o.M; locked = o.locked; o.M = nullptr; o.locked = false; } ~unique_lock() { if (owns_lock()) M->unlock(); } void lock() { assert(!locked && "mutex already locked!"); assert(M && "no associated mutex!"); M->lock(); locked = true; } void unlock() { assert(locked && "unlocking a mutex that isn't locked!"); assert(M && "no associated mutex!"); M->unlock(); locked = false; } bool owns_lock() { return locked; } }; } #endif // LLVM_SUPPORT_UNIQUE_LOCK_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Allocator.h
//===--- Allocator.h - Simple memory allocation abstraction -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// This file defines the MallocAllocator and BumpPtrAllocator interfaces. Both /// of these conform to an LLVM "Allocator" concept which consists of an /// Allocate method accepting a size and alignment, and a Deallocate accepting /// a pointer and size. Further, the LLVM "Allocator" concept has overloads of /// Allocate and Deallocate for setting size and alignment based on the final /// type. These overloads are typically provided by a base class template \c /// AllocatorBase. /// //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ALLOCATOR_H #define LLVM_SUPPORT_ALLOCATOR_H #include "llvm/ADT/SmallVector.h" #include "llvm/Support/AlignOf.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/Memory.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdlib> namespace llvm { /// \brief CRTP base class providing obvious overloads for the core \c /// Allocate() methods of LLVM-style allocators. /// /// This base class both documents the full public interface exposed by all /// LLVM-style allocators, and redirects all of the overloads to a single core /// set of methods which the derived class must define. template <typename DerivedT> class AllocatorBase { public: /// \brief Allocate \a Size bytes of \a Alignment aligned memory. This method /// must be implemented by \c DerivedT. void *Allocate(size_t Size, size_t Alignment) { #ifdef __clang__ static_assert(static_cast<void *(AllocatorBase::*)(size_t, size_t)>( &AllocatorBase::Allocate) != static_cast<void *(DerivedT::*)(size_t, size_t)>( &DerivedT::Allocate), "Class derives from AllocatorBase without implementing the " "core Allocate(size_t, size_t) overload!"); #endif return static_cast<DerivedT *>(this)->Allocate(Size, Alignment); } /// \brief Deallocate \a Ptr to \a Size bytes of memory allocated by this /// allocator. void Deallocate(const void *Ptr, size_t Size) { #ifdef __clang__ static_assert(static_cast<void (AllocatorBase::*)(const void *, size_t)>( &AllocatorBase::Deallocate) != static_cast<void (DerivedT::*)(const void *, size_t)>( &DerivedT::Deallocate), "Class derives from AllocatorBase without implementing the " "core Deallocate(void *) overload!"); #endif return static_cast<DerivedT *>(this)->Deallocate(Ptr, Size); } // The rest of these methods are helpers that redirect to one of the above // core methods. /// \brief Allocate space for a sequence of objects without constructing them. template <typename T> T *Allocate(size_t Num = 1) { return static_cast<T *>(Allocate(Num * sizeof(T), AlignOf<T>::Alignment)); } /// \brief Deallocate space for a sequence of objects without constructing them. template <typename T> typename std::enable_if< !std::is_same<typename std::remove_cv<T>::type, void>::value, void>::type Deallocate(T *Ptr, size_t Num = 1) { Deallocate(static_cast<const void *>(Ptr), Num * sizeof(T)); } }; class MallocAllocator : public AllocatorBase<MallocAllocator> { public: void Reset() {} LLVM_ATTRIBUTE_RETURNS_NONNULL void *Allocate(size_t Size, size_t /*Alignment*/) { return ::operator new(Size); // HLSL Change: use overridable operator new and throw on OOM } // Pull in base class overloads. using AllocatorBase<MallocAllocator>::Allocate; void Deallocate(const void *Ptr, size_t /*Size*/) { ::operator delete(const_cast<void*>(Ptr)); // HLSL Change: use overridable operator delete } // Pull in base class overloads. using AllocatorBase<MallocAllocator>::Deallocate; void PrintStats() const {} }; namespace detail { // We call out to an external function to actually print the message as the // printing code uses Allocator.h in its implementation. void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated, size_t TotalMemory); } // End namespace detail. /// \brief Allocate memory in an ever growing pool, as if by bump-pointer. /// /// This isn't strictly a bump-pointer allocator as it uses backing slabs of /// memory rather than relying on a boundless contiguous heap. However, it has /// bump-pointer semantics in that it is a monotonically growing pool of memory /// where every allocation is found by merely allocating the next N bytes in /// the slab, or the next N bytes in the next slab. /// /// Note that this also has a threshold for forcing allocations above a certain /// size into their own slab. /// /// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator /// object, which wraps malloc, to allocate memory, but it can be changed to /// use a custom allocator. template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096, size_t SizeThreshold = SlabSize> class BumpPtrAllocatorImpl : public AllocatorBase< BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold>> { public: static_assert(SizeThreshold <= SlabSize, "The SizeThreshold must be at most the SlabSize to ensure " "that objects larger than a slab go into their own memory " "allocation."); BumpPtrAllocatorImpl() : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator() {} template <typename T> BumpPtrAllocatorImpl(T &&Allocator) : CurPtr(nullptr), End(nullptr), BytesAllocated(0), Allocator(std::forward<T &&>(Allocator)) {} // Manually implement a move constructor as we must clear the old allocator's // slabs as a matter of correctness. BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old) : CurPtr(Old.CurPtr), End(Old.End), Slabs(std::move(Old.Slabs)), CustomSizedSlabs(std::move(Old.CustomSizedSlabs)), BytesAllocated(Old.BytesAllocated), Allocator(std::move(Old.Allocator)) { Old.CurPtr = Old.End = nullptr; Old.BytesAllocated = 0; Old.Slabs.clear(); Old.CustomSizedSlabs.clear(); } ~BumpPtrAllocatorImpl() { DeallocateSlabs(Slabs.begin(), Slabs.end()); DeallocateCustomSizedSlabs(); } BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) { DeallocateSlabs(Slabs.begin(), Slabs.end()); DeallocateCustomSizedSlabs(); CurPtr = RHS.CurPtr; End = RHS.End; BytesAllocated = RHS.BytesAllocated; Slabs = std::move(RHS.Slabs); CustomSizedSlabs = std::move(RHS.CustomSizedSlabs); Allocator = std::move(RHS.Allocator); RHS.CurPtr = RHS.End = nullptr; RHS.BytesAllocated = 0; RHS.Slabs.clear(); RHS.CustomSizedSlabs.clear(); return *this; } /// \brief Deallocate all but the current slab and reset the current pointer /// to the beginning of it, freeing all memory allocated so far. void Reset() { DeallocateCustomSizedSlabs(); CustomSizedSlabs.clear(); if (Slabs.empty()) return; // Reset the state. BytesAllocated = 0; CurPtr = (char *)Slabs.front(); End = CurPtr + SlabSize; // Deallocate all but the first slab, and deallocate all custom-sized slabs. DeallocateSlabs(std::next(Slabs.begin()), Slabs.end()); Slabs.erase(std::next(Slabs.begin()), Slabs.end()); } /// \brief Allocate space at the specified alignment. LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment) { assert(Alignment > 0 && "0-byte alignnment is not allowed. Use 1 instead."); // Keep track of how many bytes we've allocated. BytesAllocated += Size; size_t Adjustment = alignmentAdjustment(CurPtr, Alignment); assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow"); // Check if we have enough space. if (Adjustment + Size <= size_t(End - CurPtr)) { char *AlignedPtr = CurPtr + Adjustment; CurPtr = AlignedPtr + Size; // Update the allocation point of this memory block in MemorySanitizer. // Without this, MemorySanitizer messages for values originated from here // will point to the allocation of the entire slab. __msan_allocated_memory(AlignedPtr, Size); return AlignedPtr; } // If Size is really big, allocate a separate slab for it. size_t PaddedSize = Size + Alignment - 1; if (PaddedSize > SizeThreshold) { void *NewSlab = Allocator.Allocate(PaddedSize, 0); CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize)); uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment); assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize); char *AlignedPtr = (char*)AlignedAddr; __msan_allocated_memory(AlignedPtr, Size); return AlignedPtr; } // Otherwise, start a new slab and try again. StartNewSlab(); uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment); assert(AlignedAddr + Size <= (uintptr_t)End && "Unable to allocate memory!"); char *AlignedPtr = (char*)AlignedAddr; CurPtr = AlignedPtr + Size; __msan_allocated_memory(AlignedPtr, Size); return AlignedPtr; } // Pull in base class overloads. using AllocatorBase<BumpPtrAllocatorImpl>::Allocate; void Deallocate(const void * /*Ptr*/, size_t /*Size*/) {} // Pull in base class overloads. using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate; size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); } size_t getTotalMemory() const { size_t TotalMemory = 0; for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I) TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I)); for (auto &PtrAndSize : CustomSizedSlabs) TotalMemory += PtrAndSize.second; return TotalMemory; } void PrintStats() const { detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated, getTotalMemory()); } private: /// \brief The current pointer into the current slab. /// /// This points to the next free byte in the slab. char *CurPtr; /// \brief The end of the current slab. char *End; /// \brief The slabs allocated so far. SmallVector<void *, 4> Slabs; /// \brief Custom-sized slabs allocated for too-large allocation requests. SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs; /// \brief How many bytes we've allocated. /// /// Used so that we can compute how much space was wasted. size_t BytesAllocated; /// \brief The allocator instance we use to get slabs of memory. AllocatorT Allocator; static size_t computeSlabSize(unsigned SlabIdx) { // Scale the actual allocated slab size based on the number of slabs // allocated. Every 128 slabs allocated, we double the allocated size to // reduce allocation frequency, but saturate at multiplying the slab size by // 2^30. return SlabSize * ((size_t)1 << std::min<size_t>(30, SlabIdx / 128)); } /// \brief Allocate a new slab and move the bump pointers over into the new /// slab, modifying CurPtr and End. void StartNewSlab() { size_t AllocatedSlabSize = computeSlabSize(Slabs.size()); Slabs.reserve(Slabs.size() + 1); // HLSL Change: Prevent leak on push_back exception void *NewSlab = Allocator.Allocate(AllocatedSlabSize, 0); Slabs.push_back(NewSlab); CurPtr = (char *)(NewSlab); End = ((char *)NewSlab) + AllocatedSlabSize; } /// \brief Deallocate a sequence of slabs. void DeallocateSlabs(SmallVectorImpl<void *>::iterator I, SmallVectorImpl<void *>::iterator E) { for (; I != E; ++I) { size_t AllocatedSlabSize = computeSlabSize(std::distance(Slabs.begin(), I)); Allocator.Deallocate(*I, AllocatedSlabSize); } } /// \brief Deallocate all memory for custom sized slabs. void DeallocateCustomSizedSlabs() { for (auto &PtrAndSize : CustomSizedSlabs) { void *Ptr = PtrAndSize.first; size_t Size = PtrAndSize.second; Allocator.Deallocate(Ptr, Size); } } template <typename T> friend class SpecificBumpPtrAllocator; }; /// \brief The standard BumpPtrAllocator which just uses the default template /// paramaters. typedef BumpPtrAllocatorImpl<> BumpPtrAllocator; /// \brief A BumpPtrAllocator that allows only elements of a specific type to be /// allocated. /// /// This allows calling the destructor in DestroyAll() and when the allocator is /// destroyed. template <typename T> class SpecificBumpPtrAllocator { BumpPtrAllocator Allocator; public: SpecificBumpPtrAllocator() : Allocator() {} SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old) : Allocator(std::move(Old.Allocator)) {} ~SpecificBumpPtrAllocator() { DestroyAll(); } SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) { Allocator = std::move(RHS.Allocator); return *this; } /// Call the destructor of each allocated object and deallocate all but the /// current slab and reset the current pointer to the beginning of it, freeing /// all memory allocated so far. void DestroyAll() { auto DestroyElements = [](char *Begin, char *End) { assert(Begin == (char*)alignAddr(Begin, alignOf<T>())); for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T)) reinterpret_cast<T *>(Ptr)->~T(); }; for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E; ++I) { size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize( std::distance(Allocator.Slabs.begin(), I)); char *Begin = (char*)alignAddr(*I, alignOf<T>()); char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr : (char *)*I + AllocatedSlabSize; DestroyElements(Begin, End); } for (auto &PtrAndSize : Allocator.CustomSizedSlabs) { void *Ptr = PtrAndSize.first; size_t Size = PtrAndSize.second; DestroyElements((char*)alignAddr(Ptr, alignOf<T>()), (char *)Ptr + Size); } Allocator.Reset(); } /// \brief Allocate space for an array of objects without constructing them. T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); } }; } // end namespace llvm // HLSL Change Starts - undef min due to conflict with std::min #ifdef min #undef min #endif // HLSL Change Ends template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold> void *operator new(size_t Size, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &Allocator) { struct S { char c; union { double D; long double LD; long long L; void *P; } x; }; return Allocator.Allocate( Size, std::min((size_t)llvm::NextPowerOf2(Size), offsetof(S, x))); } template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold> void operator delete( void *, llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold> &) { } #endif // LLVM_SUPPORT_ALLOCATOR_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Dwarf.h
//===-- llvm/Support/Dwarf.h ---Dwarf Constants------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // \file // \brief This file contains constants used for implementing Dwarf // debug support. // // For details on the Dwarf specfication see the latest DWARF Debugging // Information Format standard document on http://www.dwarfstd.org. This // file often includes support for non-released standard features. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_DWARF_H #define LLVM_SUPPORT_DWARF_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/DataTypes.h" namespace llvm { namespace dwarf { // // /////////////////////////////////////////////////////////////////////////////// // Dwarf constants as gleaned from the DWARF Debugging Information Format V.4 // reference manual http://www.dwarfstd.org/. // // Do not mix the following two enumerations sets. DW_TAG_invalid changes the // enumeration base type. enum LLVMConstants : uint32_t { // LLVM mock tags (see also llvm/Support/Dwarf.def). DW_TAG_invalid = ~0U, // Tag for invalid results. DW_VIRTUALITY_invalid = ~0U, // Virtuality for invalid results. // Other constants. DWARF_VERSION = 4, // Default dwarf version we output. DW_PUBTYPES_VERSION = 2, // Section version number for .debug_pubtypes. DW_PUBNAMES_VERSION = 2, // Section version number for .debug_pubnames. DW_ARANGES_VERSION = 2 // Section version number for .debug_aranges. }; // Special ID values that distinguish a CIE from a FDE in DWARF CFI. // Not inside an enum because a 64-bit value is needed. const uint32_t DW_CIE_ID = UINT32_MAX; const uint64_t DW64_CIE_ID = UINT64_MAX; enum Tag : uint16_t { #define HANDLE_DW_TAG(ID, NAME) DW_TAG_##NAME = ID, #include "llvm/Support/Dwarf.def" DW_TAG_lo_user = 0x4080, DW_TAG_hi_user = 0xffff, DW_TAG_user_base = 0x1000 // Recommended base for user tags. }; inline bool isType(Tag T) { switch (T) { case DW_TAG_array_type: case DW_TAG_class_type: case DW_TAG_interface_type: case DW_TAG_enumeration_type: case DW_TAG_pointer_type: case DW_TAG_reference_type: case DW_TAG_rvalue_reference_type: case DW_TAG_string_type: case DW_TAG_structure_type: case DW_TAG_subroutine_type: case DW_TAG_union_type: case DW_TAG_ptr_to_member_type: case DW_TAG_set_type: case DW_TAG_subrange_type: case DW_TAG_base_type: case DW_TAG_const_type: case DW_TAG_file_type: case DW_TAG_packed_type: case DW_TAG_volatile_type: case DW_TAG_typedef: return true; default: return false; } } enum Attribute : uint16_t { // Attributes DW_AT_sibling = 0x01, DW_AT_location = 0x02, DW_AT_name = 0x03, DW_AT_ordering = 0x09, DW_AT_byte_size = 0x0b, DW_AT_bit_offset = 0x0c, DW_AT_bit_size = 0x0d, DW_AT_stmt_list = 0x10, DW_AT_low_pc = 0x11, DW_AT_high_pc = 0x12, DW_AT_language = 0x13, DW_AT_discr = 0x15, DW_AT_discr_value = 0x16, DW_AT_visibility = 0x17, DW_AT_import = 0x18, DW_AT_string_length = 0x19, DW_AT_common_reference = 0x1a, DW_AT_comp_dir = 0x1b, DW_AT_const_value = 0x1c, DW_AT_containing_type = 0x1d, DW_AT_default_value = 0x1e, DW_AT_inline = 0x20, DW_AT_is_optional = 0x21, DW_AT_lower_bound = 0x22, DW_AT_producer = 0x25, DW_AT_prototyped = 0x27, DW_AT_return_addr = 0x2a, DW_AT_start_scope = 0x2c, DW_AT_bit_stride = 0x2e, DW_AT_upper_bound = 0x2f, DW_AT_abstract_origin = 0x31, DW_AT_accessibility = 0x32, DW_AT_address_class = 0x33, DW_AT_artificial = 0x34, DW_AT_base_types = 0x35, DW_AT_calling_convention = 0x36, DW_AT_count = 0x37, DW_AT_data_member_location = 0x38, DW_AT_decl_column = 0x39, DW_AT_decl_file = 0x3a, DW_AT_decl_line = 0x3b, DW_AT_declaration = 0x3c, DW_AT_discr_list = 0x3d, DW_AT_encoding = 0x3e, DW_AT_external = 0x3f, DW_AT_frame_base = 0x40, DW_AT_friend = 0x41, DW_AT_identifier_case = 0x42, DW_AT_macro_info = 0x43, DW_AT_namelist_item = 0x44, DW_AT_priority = 0x45, DW_AT_segment = 0x46, DW_AT_specification = 0x47, DW_AT_static_link = 0x48, DW_AT_type = 0x49, DW_AT_use_location = 0x4a, DW_AT_variable_parameter = 0x4b, DW_AT_virtuality = 0x4c, DW_AT_vtable_elem_location = 0x4d, DW_AT_allocated = 0x4e, DW_AT_associated = 0x4f, DW_AT_data_location = 0x50, DW_AT_byte_stride = 0x51, DW_AT_entry_pc = 0x52, DW_AT_use_UTF8 = 0x53, DW_AT_extension = 0x54, DW_AT_ranges = 0x55, DW_AT_trampoline = 0x56, DW_AT_call_column = 0x57, DW_AT_call_file = 0x58, DW_AT_call_line = 0x59, DW_AT_description = 0x5a, DW_AT_binary_scale = 0x5b, DW_AT_decimal_scale = 0x5c, DW_AT_small = 0x5d, DW_AT_decimal_sign = 0x5e, DW_AT_digit_count = 0x5f, DW_AT_picture_string = 0x60, DW_AT_mutable = 0x61, DW_AT_threads_scaled = 0x62, DW_AT_explicit = 0x63, DW_AT_object_pointer = 0x64, DW_AT_endianity = 0x65, DW_AT_elemental = 0x66, DW_AT_pure = 0x67, DW_AT_recursive = 0x68, DW_AT_signature = 0x69, DW_AT_main_subprogram = 0x6a, DW_AT_data_bit_offset = 0x6b, DW_AT_const_expr = 0x6c, DW_AT_enum_class = 0x6d, DW_AT_linkage_name = 0x6e, // New in DWARF 5: DW_AT_string_length_bit_size = 0x6f, DW_AT_string_length_byte_size = 0x70, DW_AT_rank = 0x71, DW_AT_str_offsets_base = 0x72, DW_AT_addr_base = 0x73, DW_AT_ranges_base = 0x74, DW_AT_dwo_id = 0x75, DW_AT_dwo_name = 0x76, DW_AT_reference = 0x77, DW_AT_rvalue_reference = 0x78, DW_AT_lo_user = 0x2000, DW_AT_hi_user = 0x3fff, DW_AT_MIPS_loop_begin = 0x2002, DW_AT_MIPS_tail_loop_begin = 0x2003, DW_AT_MIPS_epilog_begin = 0x2004, DW_AT_MIPS_loop_unroll_factor = 0x2005, DW_AT_MIPS_software_pipeline_depth = 0x2006, DW_AT_MIPS_linkage_name = 0x2007, DW_AT_MIPS_stride = 0x2008, DW_AT_MIPS_abstract_name = 0x2009, DW_AT_MIPS_clone_origin = 0x200a, DW_AT_MIPS_has_inlines = 0x200b, DW_AT_MIPS_stride_byte = 0x200c, DW_AT_MIPS_stride_elem = 0x200d, DW_AT_MIPS_ptr_dopetype = 0x200e, DW_AT_MIPS_allocatable_dopetype = 0x200f, DW_AT_MIPS_assumed_shape_dopetype = 0x2010, // This one appears to have only been implemented by Open64 for // fortran and may conflict with other extensions. DW_AT_MIPS_assumed_size = 0x2011, // GNU extensions DW_AT_sf_names = 0x2101, DW_AT_src_info = 0x2102, DW_AT_mac_info = 0x2103, DW_AT_src_coords = 0x2104, DW_AT_body_begin = 0x2105, DW_AT_body_end = 0x2106, DW_AT_GNU_vector = 0x2107, DW_AT_GNU_template_name = 0x2110, DW_AT_GNU_odr_signature = 0x210f, // Extensions for Fission proposal. DW_AT_GNU_dwo_name = 0x2130, DW_AT_GNU_dwo_id = 0x2131, DW_AT_GNU_ranges_base = 0x2132, DW_AT_GNU_addr_base = 0x2133, DW_AT_GNU_pubnames = 0x2134, DW_AT_GNU_pubtypes = 0x2135, // LLVM project extensions. DW_AT_LLVM_include_path = 0x3e00, DW_AT_LLVM_config_macros = 0x3e01, DW_AT_LLVM_isysroot = 0x3e02, // Apple extensions. DW_AT_APPLE_optimized = 0x3fe1, DW_AT_APPLE_flags = 0x3fe2, DW_AT_APPLE_isa = 0x3fe3, DW_AT_APPLE_block = 0x3fe4, DW_AT_APPLE_major_runtime_vers = 0x3fe5, DW_AT_APPLE_runtime_class = 0x3fe6, DW_AT_APPLE_omit_frame_ptr = 0x3fe7, DW_AT_APPLE_property_name = 0x3fe8, DW_AT_APPLE_property_getter = 0x3fe9, DW_AT_APPLE_property_setter = 0x3fea, DW_AT_APPLE_property_attribute = 0x3feb, DW_AT_APPLE_objc_complete_type = 0x3fec, DW_AT_APPLE_property = 0x3fed }; enum Form : uint16_t { // Attribute form encodings DW_FORM_addr = 0x01, DW_FORM_block2 = 0x03, DW_FORM_block4 = 0x04, DW_FORM_data2 = 0x05, DW_FORM_data4 = 0x06, DW_FORM_data8 = 0x07, DW_FORM_string = 0x08, DW_FORM_block = 0x09, DW_FORM_block1 = 0x0a, DW_FORM_data1 = 0x0b, DW_FORM_flag = 0x0c, DW_FORM_sdata = 0x0d, DW_FORM_strp = 0x0e, DW_FORM_udata = 0x0f, DW_FORM_ref_addr = 0x10, DW_FORM_ref1 = 0x11, DW_FORM_ref2 = 0x12, DW_FORM_ref4 = 0x13, DW_FORM_ref8 = 0x14, DW_FORM_ref_udata = 0x15, DW_FORM_indirect = 0x16, DW_FORM_sec_offset = 0x17, DW_FORM_exprloc = 0x18, DW_FORM_flag_present = 0x19, DW_FORM_ref_sig8 = 0x20, // Extensions for Fission proposal DW_FORM_GNU_addr_index = 0x1f01, DW_FORM_GNU_str_index = 0x1f02, // Alternate debug sections proposal (output of "dwz" tool). DW_FORM_GNU_ref_alt = 0x1f20, DW_FORM_GNU_strp_alt = 0x1f21 }; enum LocationAtom { #define HANDLE_DW_OP(ID, NAME) DW_OP_##NAME = ID, #include "llvm/Support/Dwarf.def" DW_OP_lo_user = 0xe0, DW_OP_hi_user = 0xff }; enum TypeKind { #define HANDLE_DW_ATE(ID, NAME) DW_ATE_##NAME = ID, #include "llvm/Support/Dwarf.def" DW_ATE_lo_user = 0x80, DW_ATE_hi_user = 0xff }; enum DecimalSignEncoding { // Decimal sign attribute values DW_DS_unsigned = 0x01, DW_DS_leading_overpunch = 0x02, DW_DS_trailing_overpunch = 0x03, DW_DS_leading_separate = 0x04, DW_DS_trailing_separate = 0x05 }; enum EndianityEncoding { // Endianity attribute values DW_END_default = 0x00, DW_END_big = 0x01, DW_END_little = 0x02, DW_END_lo_user = 0x40, DW_END_hi_user = 0xff }; enum AccessAttribute { // Accessibility codes DW_ACCESS_public = 0x01, DW_ACCESS_protected = 0x02, DW_ACCESS_private = 0x03 }; enum VisibilityAttribute { // Visibility codes DW_VIS_local = 0x01, DW_VIS_exported = 0x02, DW_VIS_qualified = 0x03 }; enum VirtualityAttribute { #define HANDLE_DW_VIRTUALITY(ID, NAME) DW_VIRTUALITY_##NAME = ID, #include "llvm/Support/Dwarf.def" DW_VIRTUALITY_max = 0x02 }; enum SourceLanguage { #define HANDLE_DW_LANG(ID, NAME) DW_LANG_##NAME = ID, #include "llvm/Support/Dwarf.def" DW_LANG_lo_user = 0x8000, DW_LANG_hi_user = 0xffff }; enum CaseSensitivity { // Identifier case codes DW_ID_case_sensitive = 0x00, DW_ID_up_case = 0x01, DW_ID_down_case = 0x02, DW_ID_case_insensitive = 0x03 }; enum CallingConvention { // Calling convention codes DW_CC_normal = 0x01, DW_CC_program = 0x02, DW_CC_nocall = 0x03, DW_CC_lo_user = 0x40, DW_CC_hi_user = 0xff }; enum InlineAttribute { // Inline codes DW_INL_not_inlined = 0x00, DW_INL_inlined = 0x01, DW_INL_declared_not_inlined = 0x02, DW_INL_declared_inlined = 0x03 }; enum ArrayDimensionOrdering { // Array ordering DW_ORD_row_major = 0x00, DW_ORD_col_major = 0x01 }; enum DiscriminantList { // Discriminant descriptor values DW_DSC_label = 0x00, DW_DSC_range = 0x01 }; enum LineNumberOps { // Line Number Standard Opcode Encodings DW_LNS_extended_op = 0x00, DW_LNS_copy = 0x01, DW_LNS_advance_pc = 0x02, DW_LNS_advance_line = 0x03, DW_LNS_set_file = 0x04, DW_LNS_set_column = 0x05, DW_LNS_negate_stmt = 0x06, DW_LNS_set_basic_block = 0x07, DW_LNS_const_add_pc = 0x08, DW_LNS_fixed_advance_pc = 0x09, DW_LNS_set_prologue_end = 0x0a, DW_LNS_set_epilogue_begin = 0x0b, DW_LNS_set_isa = 0x0c }; enum LineNumberExtendedOps { // Line Number Extended Opcode Encodings DW_LNE_end_sequence = 0x01, DW_LNE_set_address = 0x02, DW_LNE_define_file = 0x03, DW_LNE_set_discriminator = 0x04, DW_LNE_lo_user = 0x80, DW_LNE_hi_user = 0xff }; enum MacinfoRecordType { // Macinfo Type Encodings DW_MACINFO_define = 0x01, DW_MACINFO_undef = 0x02, DW_MACINFO_start_file = 0x03, DW_MACINFO_end_file = 0x04, DW_MACINFO_vendor_ext = 0xff }; enum CallFrameInfo { // Call frame instruction encodings DW_CFA_extended = 0x00, DW_CFA_nop = 0x00, DW_CFA_advance_loc = 0x40, DW_CFA_offset = 0x80, DW_CFA_restore = 0xc0, DW_CFA_set_loc = 0x01, DW_CFA_advance_loc1 = 0x02, DW_CFA_advance_loc2 = 0x03, DW_CFA_advance_loc4 = 0x04, DW_CFA_offset_extended = 0x05, DW_CFA_restore_extended = 0x06, DW_CFA_undefined = 0x07, DW_CFA_same_value = 0x08, DW_CFA_register = 0x09, DW_CFA_remember_state = 0x0a, DW_CFA_restore_state = 0x0b, DW_CFA_def_cfa = 0x0c, DW_CFA_def_cfa_register = 0x0d, DW_CFA_def_cfa_offset = 0x0e, DW_CFA_def_cfa_expression = 0x0f, DW_CFA_expression = 0x10, DW_CFA_offset_extended_sf = 0x11, DW_CFA_def_cfa_sf = 0x12, DW_CFA_def_cfa_offset_sf = 0x13, DW_CFA_val_offset = 0x14, DW_CFA_val_offset_sf = 0x15, DW_CFA_val_expression = 0x16, DW_CFA_MIPS_advance_loc8 = 0x1d, DW_CFA_GNU_window_save = 0x2d, DW_CFA_GNU_args_size = 0x2e, DW_CFA_lo_user = 0x1c, DW_CFA_hi_user = 0x3f }; enum Constants { // Children flag DW_CHILDREN_no = 0x00, DW_CHILDREN_yes = 0x01, DW_EH_PE_absptr = 0x00, DW_EH_PE_omit = 0xff, DW_EH_PE_uleb128 = 0x01, DW_EH_PE_udata2 = 0x02, DW_EH_PE_udata4 = 0x03, DW_EH_PE_udata8 = 0x04, DW_EH_PE_sleb128 = 0x09, DW_EH_PE_sdata2 = 0x0A, DW_EH_PE_sdata4 = 0x0B, DW_EH_PE_sdata8 = 0x0C, DW_EH_PE_signed = 0x08, DW_EH_PE_pcrel = 0x10, DW_EH_PE_textrel = 0x20, DW_EH_PE_datarel = 0x30, DW_EH_PE_funcrel = 0x40, DW_EH_PE_aligned = 0x50, DW_EH_PE_indirect = 0x80 }; // Constants for debug_loc.dwo in the DWARF5 Split Debug Info Proposal enum LocationListEntry : unsigned char { DW_LLE_end_of_list_entry, DW_LLE_base_address_selection_entry, DW_LLE_start_end_entry, DW_LLE_start_length_entry, DW_LLE_offset_pair_entry }; /// Contstants for the DW_APPLE_PROPERTY_attributes attribute. /// Keep this list in sync with clang's DeclSpec.h ObjCPropertyAttributeKind. enum ApplePropertyAttributes { // Apple Objective-C Property Attributes DW_APPLE_PROPERTY_readonly = 0x01, DW_APPLE_PROPERTY_getter = 0x02, DW_APPLE_PROPERTY_assign = 0x04, DW_APPLE_PROPERTY_readwrite = 0x08, DW_APPLE_PROPERTY_retain = 0x10, DW_APPLE_PROPERTY_copy = 0x20, DW_APPLE_PROPERTY_nonatomic = 0x40, DW_APPLE_PROPERTY_setter = 0x80, DW_APPLE_PROPERTY_atomic = 0x100, DW_APPLE_PROPERTY_weak = 0x200, DW_APPLE_PROPERTY_strong = 0x400, DW_APPLE_PROPERTY_unsafe_unretained = 0x800 }; // Constants for the DWARF5 Accelerator Table Proposal enum AcceleratorTable { // Data layout descriptors. DW_ATOM_null = 0u, // Marker as the end of a list of atoms. DW_ATOM_die_offset = 1u, // DIE offset in the debug_info section. DW_ATOM_cu_offset = 2u, // Offset of the compile unit header that contains the // item in question. DW_ATOM_die_tag = 3u, // A tag entry. DW_ATOM_type_flags = 4u, // Set of flags for a type. // DW_ATOM_type_flags values. // Always set for C++, only set for ObjC if this is the @implementation for a // class. DW_FLAG_type_implementation = 2u, // Hash functions. // Daniel J. Bernstein hash. DW_hash_function_djb = 0u }; // Constants for the GNU pubnames/pubtypes extensions supporting gdb index. enum GDBIndexEntryKind { GIEK_NONE, GIEK_TYPE, GIEK_VARIABLE, GIEK_FUNCTION, GIEK_OTHER, GIEK_UNUSED5, GIEK_UNUSED6, GIEK_UNUSED7 }; enum GDBIndexEntryLinkage { GIEL_EXTERNAL, GIEL_STATIC }; /// \defgroup DwarfConstantsDumping Dwarf constants dumping functions /// /// All these functions map their argument's value back to the /// corresponding enumerator name or return nullptr if the value isn't /// known. /// /// @{ const char *TagString(unsigned Tag); const char *ChildrenString(unsigned Children); const char *AttributeString(unsigned Attribute); const char *FormEncodingString(unsigned Encoding); const char *OperationEncodingString(unsigned Encoding); const char *AttributeEncodingString(unsigned Encoding); const char *DecimalSignString(unsigned Sign); const char *EndianityString(unsigned Endian); const char *AccessibilityString(unsigned Access); const char *VisibilityString(unsigned Visibility); const char *VirtualityString(unsigned Virtuality); const char *LanguageString(unsigned Language); const char *CaseString(unsigned Case); const char *ConventionString(unsigned Convention); const char *InlineCodeString(unsigned Code); const char *ArrayOrderString(unsigned Order); const char *DiscriminantString(unsigned Discriminant); const char *LNStandardString(unsigned Standard); const char *LNExtendedString(unsigned Encoding); const char *MacinfoString(unsigned Encoding); const char *CallFrameString(unsigned Encoding); const char *ApplePropertyString(unsigned); const char *AtomTypeString(unsigned Atom); const char *GDBIndexEntryKindString(GDBIndexEntryKind Kind); const char *GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage); /// @} /// \defgroup DwarfConstantsParsing Dwarf constants parsing functions /// /// These functions map their strings back to the corresponding enumeration /// value or return 0 if there is none, except for these exceptions: /// /// \li \a getTag() returns \a DW_TAG_invalid on invalid input. /// \li \a getVirtuality() returns \a DW_VIRTUALITY_invalid on invalid input. /// /// @{ unsigned getTag(StringRef TagString); unsigned getOperationEncoding(StringRef OperationEncodingString); unsigned getVirtuality(StringRef VirtualityString); unsigned getLanguage(StringRef LanguageString); unsigned getAttributeEncoding(StringRef EncodingString); /// @} /// \brief Returns the symbolic string representing Val when used as a value /// for attribute Attr. const char *AttributeValueString(uint16_t Attr, unsigned Val); /// \brief Decsribes an entry of the various gnu_pub* debug sections. /// /// The gnu_pub* kind looks like: /// /// 0-3 reserved /// 4-6 symbol kind /// 7 0 == global, 1 == static /// /// A gdb_index descriptor includes the above kind, shifted 24 bits up with the /// offset of the cu within the debug_info section stored in those 24 bits. struct PubIndexEntryDescriptor { GDBIndexEntryKind Kind; GDBIndexEntryLinkage Linkage; PubIndexEntryDescriptor(GDBIndexEntryKind Kind, GDBIndexEntryLinkage Linkage) : Kind(Kind), Linkage(Linkage) {} /* implicit */ PubIndexEntryDescriptor(GDBIndexEntryKind Kind) : Kind(Kind), Linkage(GIEL_EXTERNAL) {} explicit PubIndexEntryDescriptor(uint8_t Value) : Kind(static_cast<GDBIndexEntryKind>((Value & KIND_MASK) >> KIND_OFFSET)), Linkage(static_cast<GDBIndexEntryLinkage>((Value & LINKAGE_MASK) >> LINKAGE_OFFSET)) {} uint8_t toBits() { return Kind << KIND_OFFSET | Linkage << LINKAGE_OFFSET; } private: enum { KIND_OFFSET = 4, KIND_MASK = 7 << KIND_OFFSET, LINKAGE_OFFSET = 7, LINKAGE_MASK = 1 << LINKAGE_OFFSET }; }; } // End of namespace dwarf } // End of namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Memory.h
//===- llvm/Support/Memory.h - Memory Support --------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::Memory class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_MEMORY_H #define LLVM_SUPPORT_MEMORY_H #include "llvm/Support/DataTypes.h" #include <string> #include <system_error> namespace llvm { namespace sys { /// This class encapsulates the notion of a memory block which has an address /// and a size. It is used by the Memory class (a friend) as the result of /// various memory allocation operations. /// @see Memory /// @brief Memory block abstraction. class MemoryBlock { public: MemoryBlock() : Address(nullptr), Size(0) { } MemoryBlock(void *addr, size_t size) : Address(addr), Size(size) { } void *base() const { return Address; } size_t size() const { return Size; } private: void *Address; ///< Address of first byte of memory area size_t Size; ///< Size, in bytes of the memory area friend class Memory; }; /// This class provides various memory handling functions that manipulate /// MemoryBlock instances. /// @since 1.4 /// @brief An abstraction for memory operations. class Memory { public: enum ProtectionFlags { MF_READ = 0x1000000, MF_WRITE = 0x2000000, MF_EXEC = 0x4000000 }; /// This method allocates a block of memory that is suitable for loading /// dynamically generated code (e.g. JIT). An attempt to allocate /// \p NumBytes bytes of virtual memory is made. /// \p NearBlock may point to an existing allocation in which case /// an attempt is made to allocate more memory near the existing block. /// The actual allocated address is not guaranteed to be near the requested /// address. /// \p Flags is used to set the initial protection flags for the block /// of the memory. /// \p EC [out] returns an object describing any error that occurs. /// /// This method may allocate more than the number of bytes requested. The /// actual number of bytes allocated is indicated in the returned /// MemoryBlock. /// /// The start of the allocated block must be aligned with the /// system allocation granularity (64K on Windows, page size on Linux). /// If the address following \p NearBlock is not so aligned, it will be /// rounded up to the next allocation granularity boundary. /// /// \r a non-null MemoryBlock if the function was successful, /// otherwise a null MemoryBlock is with \p EC describing the error. /// /// @brief Allocate mapped memory. static MemoryBlock allocateMappedMemory(size_t NumBytes, const MemoryBlock *const NearBlock, unsigned Flags, std::error_code &EC); /// This method releases a block of memory that was allocated with the /// allocateMappedMemory method. It should not be used to release any /// memory block allocated any other way. /// \p Block describes the memory to be released. /// /// \r error_success if the function was successful, or an error_code /// describing the failure if an error occurred. /// /// @brief Release mapped memory. static std::error_code releaseMappedMemory(MemoryBlock &Block); /// This method sets the protection flags for a block of memory to the /// state specified by /p Flags. The behavior is not specified if the /// memory was not allocated using the allocateMappedMemory method. /// \p Block describes the memory block to be protected. /// \p Flags specifies the new protection state to be assigned to the block. /// \p ErrMsg [out] returns a string describing any error that occurred. /// /// If \p Flags is MF_WRITE, the actual behavior varies /// with the operating system (i.e. MF_READ | MF_WRITE on Windows) and the /// target architecture (i.e. MF_WRITE -> MF_READ | MF_WRITE on i386). /// /// \r error_success if the function was successful, or an error_code /// describing the failure if an error occurred. /// /// @brief Set memory protection state. static std::error_code protectMappedMemory(const MemoryBlock &Block, unsigned Flags); /// This method allocates a block of Read/Write/Execute memory that is /// suitable for executing dynamically generated code (e.g. JIT). An /// attempt to allocate \p NumBytes bytes of virtual memory is made. /// \p NearBlock may point to an existing allocation in which case /// an attempt is made to allocate more memory near the existing block. /// /// On success, this returns a non-null memory block, otherwise it returns /// a null memory block and fills in *ErrMsg. /// /// @brief Allocate Read/Write/Execute memory. static MemoryBlock AllocateRWX(size_t NumBytes, const MemoryBlock *NearBlock, std::string *ErrMsg = nullptr); /// This method releases a block of Read/Write/Execute memory that was /// allocated with the AllocateRWX method. It should not be used to /// release any memory block allocated any other way. /// /// On success, this returns false, otherwise it returns true and fills /// in *ErrMsg. /// @brief Release Read/Write/Execute memory. static bool ReleaseRWX(MemoryBlock &block, std::string *ErrMsg = nullptr); /// InvalidateInstructionCache - Before the JIT can run a block of code /// that has been emitted it must invalidate the instruction cache on some /// platforms. static void InvalidateInstructionCache(const void *Addr, size_t Len); /// setExecutable - Before the JIT can run a block of code, it has to be /// given read and executable privilege. Return true if it is already r-x /// or the system is able to change its previlege. static bool setExecutable(MemoryBlock &M, std::string *ErrMsg = nullptr); /// setWritable - When adding to a block of code, the JIT may need /// to mark a block of code as RW since the protections are on page /// boundaries, and the JIT internal allocations are not page aligned. static bool setWritable(MemoryBlock &M, std::string *ErrMsg = nullptr); /// setRangeExecutable - Mark the page containing a range of addresses /// as executable. static bool setRangeExecutable(const void *Addr, size_t Size); /// setRangeWritable - Mark the page containing a range of addresses /// as writable. static bool setRangeWritable(const void *Addr, size_t Size); }; } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/UnicodeCharRanges.h
//===--- UnicodeCharRanges.h - Types and functions for character ranges ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_UNICODECHARRANGES_H #define LLVM_SUPPORT_UNICODECHARRANGES_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> namespace llvm { namespace sys { #define DEBUG_TYPE "unicode" /// \brief Represents a closed range of Unicode code points [Lower, Upper]. struct UnicodeCharRange { uint32_t Lower; uint32_t Upper; }; inline bool operator<(uint32_t Value, UnicodeCharRange Range) { return Value < Range.Lower; } inline bool operator<(UnicodeCharRange Range, uint32_t Value) { return Range.Upper < Value; } /// \brief Holds a reference to an ordered array of UnicodeCharRange and allows /// to quickly check if a code point is contained in the set represented by this /// array. class UnicodeCharSet { public: typedef ArrayRef<UnicodeCharRange> CharRanges; /// \brief Constructs a UnicodeCharSet instance from an array of /// UnicodeCharRanges. /// /// Array pointed by \p Ranges should have the lifetime at least as long as /// the UnicodeCharSet instance, and should not change. Array is validated by /// the constructor, so it makes sense to create as few UnicodeCharSet /// instances per each array of ranges, as possible. #ifdef NDEBUG LLVM_CONSTEXPR UnicodeCharSet(CharRanges Ranges) : Ranges(Ranges) {} #else UnicodeCharSet(CharRanges Ranges) : Ranges(Ranges) { assert(rangesAreValid()); } #endif /// \brief Returns true if the character set contains the Unicode code point /// \p C. bool contains(uint32_t C) const { return std::binary_search(Ranges.begin(), Ranges.end(), C); } private: /// \brief Returns true if each of the ranges is a proper closed range /// [min, max], and if the ranges themselves are ordered and non-overlapping. bool rangesAreValid() const { uint32_t Prev = 0; for (CharRanges::const_iterator I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { if (I != Ranges.begin() && Prev >= I->Lower) { DEBUG(dbgs() << "Upper bound 0x"); DEBUG(dbgs().write_hex(Prev)); DEBUG(dbgs() << " should be less than succeeding lower bound 0x"); DEBUG(dbgs().write_hex(I->Lower) << "\n"); return false; } if (I->Upper < I->Lower) { DEBUG(dbgs() << "Upper bound 0x"); DEBUG(dbgs().write_hex(I->Lower)); DEBUG(dbgs() << " should not be less than lower bound 0x"); DEBUG(dbgs().write_hex(I->Upper) << "\n"); return false; } Prev = I->Upper; } return true; } const CharRanges Ranges; }; #undef DEBUG_TYPE // "unicode" } // namespace sys } // namespace llvm #endif // LLVM_SUPPORT_UNICODECHARRANGES_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/WindowsError.h
//===-- WindowsError.h - Support for mapping windows errors to posix-------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_WINDOWSERROR_H #define LLVM_SUPPORT_WINDOWSERROR_H #include <system_error> namespace llvm { std::error_code mapWindowsError(unsigned EV); } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Dwarf.def
//===- llvm/Support/Dwarf.def - Dwarf definitions ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Macros for running through Dwarf enumerators. // //===----------------------------------------------------------------------===// #if !(defined HANDLE_DW_TAG || defined HANDLE_DW_OP || \ defined HANDLE_DW_LANG || defined HANDLE_DW_ATE || \ defined HANDLE_DW_VIRTUALITY) #error "Missing macro definition of HANDLE_DW*" #endif #ifndef HANDLE_DW_TAG #define HANDLE_DW_TAG(ID, NAME) #endif #ifndef HANDLE_DW_OP #define HANDLE_DW_OP(ID, NAME) #endif #ifndef HANDLE_DW_LANG #define HANDLE_DW_LANG(ID, NAME) #endif #ifndef HANDLE_DW_ATE #define HANDLE_DW_ATE(ID, NAME) #endif #ifndef HANDLE_DW_VIRTUALITY #define HANDLE_DW_VIRTUALITY(ID, NAME) #endif HANDLE_DW_TAG(0x0001, array_type) HANDLE_DW_TAG(0x0002, class_type) HANDLE_DW_TAG(0x0003, entry_point) HANDLE_DW_TAG(0x0004, enumeration_type) HANDLE_DW_TAG(0x0005, formal_parameter) HANDLE_DW_TAG(0x0008, imported_declaration) HANDLE_DW_TAG(0x000a, label) HANDLE_DW_TAG(0x000b, lexical_block) HANDLE_DW_TAG(0x000d, member) HANDLE_DW_TAG(0x000f, pointer_type) HANDLE_DW_TAG(0x0010, reference_type) HANDLE_DW_TAG(0x0011, compile_unit) HANDLE_DW_TAG(0x0012, string_type) HANDLE_DW_TAG(0x0013, structure_type) HANDLE_DW_TAG(0x0015, subroutine_type) HANDLE_DW_TAG(0x0016, typedef) HANDLE_DW_TAG(0x0017, union_type) HANDLE_DW_TAG(0x0018, unspecified_parameters) HANDLE_DW_TAG(0x0019, variant) HANDLE_DW_TAG(0x001a, common_block) HANDLE_DW_TAG(0x001b, common_inclusion) HANDLE_DW_TAG(0x001c, inheritance) HANDLE_DW_TAG(0x001d, inlined_subroutine) HANDLE_DW_TAG(0x001e, module) HANDLE_DW_TAG(0x001f, ptr_to_member_type) HANDLE_DW_TAG(0x0020, set_type) HANDLE_DW_TAG(0x0021, subrange_type) HANDLE_DW_TAG(0x0022, with_stmt) HANDLE_DW_TAG(0x0023, access_declaration) HANDLE_DW_TAG(0x0024, base_type) HANDLE_DW_TAG(0x0025, catch_block) HANDLE_DW_TAG(0x0026, const_type) HANDLE_DW_TAG(0x0027, constant) HANDLE_DW_TAG(0x0028, enumerator) HANDLE_DW_TAG(0x0029, file_type) HANDLE_DW_TAG(0x002a, friend) HANDLE_DW_TAG(0x002b, namelist) HANDLE_DW_TAG(0x002c, namelist_item) HANDLE_DW_TAG(0x002d, packed_type) HANDLE_DW_TAG(0x002e, subprogram) HANDLE_DW_TAG(0x002f, template_type_parameter) HANDLE_DW_TAG(0x0030, template_value_parameter) HANDLE_DW_TAG(0x0031, thrown_type) HANDLE_DW_TAG(0x0032, try_block) HANDLE_DW_TAG(0x0033, variant_part) HANDLE_DW_TAG(0x0034, variable) HANDLE_DW_TAG(0x0035, volatile_type) HANDLE_DW_TAG(0x0036, dwarf_procedure) HANDLE_DW_TAG(0x0037, restrict_type) HANDLE_DW_TAG(0x0038, interface_type) HANDLE_DW_TAG(0x0039, namespace) HANDLE_DW_TAG(0x003a, imported_module) HANDLE_DW_TAG(0x003b, unspecified_type) HANDLE_DW_TAG(0x003c, partial_unit) HANDLE_DW_TAG(0x003d, imported_unit) HANDLE_DW_TAG(0x003f, condition) HANDLE_DW_TAG(0x0040, shared_type) HANDLE_DW_TAG(0x0041, type_unit) HANDLE_DW_TAG(0x0042, rvalue_reference_type) HANDLE_DW_TAG(0x0043, template_alias) // Mock tags we use as discriminators. HANDLE_DW_TAG(0x0100, auto_variable) // Tag for local (auto) variables. HANDLE_DW_TAG(0x0101, arg_variable) // Tag for argument variables. // New in DWARF v5. HANDLE_DW_TAG(0x0044, coarray_type) HANDLE_DW_TAG(0x0045, generic_subrange) HANDLE_DW_TAG(0x0046, dynamic_type) // User-defined tags. HANDLE_DW_TAG(0x4081, MIPS_loop) HANDLE_DW_TAG(0x4101, format_label) HANDLE_DW_TAG(0x4102, function_template) HANDLE_DW_TAG(0x4103, class_template) HANDLE_DW_TAG(0x4106, GNU_template_template_param) HANDLE_DW_TAG(0x4107, GNU_template_parameter_pack) HANDLE_DW_TAG(0x4108, GNU_formal_parameter_pack) HANDLE_DW_TAG(0x4200, APPLE_property) HANDLE_DW_OP(0x03, addr) HANDLE_DW_OP(0x06, deref) HANDLE_DW_OP(0x08, const1u) HANDLE_DW_OP(0x09, const1s) HANDLE_DW_OP(0x0a, const2u) HANDLE_DW_OP(0x0b, const2s) HANDLE_DW_OP(0x0c, const4u) HANDLE_DW_OP(0x0d, const4s) HANDLE_DW_OP(0x0e, const8u) HANDLE_DW_OP(0x0f, const8s) HANDLE_DW_OP(0x10, constu) HANDLE_DW_OP(0x11, consts) HANDLE_DW_OP(0x12, dup) HANDLE_DW_OP(0x13, drop) HANDLE_DW_OP(0x14, over) HANDLE_DW_OP(0x15, pick) HANDLE_DW_OP(0x16, swap) HANDLE_DW_OP(0x17, rot) HANDLE_DW_OP(0x18, xderef) HANDLE_DW_OP(0x19, abs) HANDLE_DW_OP(0x1a, and) HANDLE_DW_OP(0x1b, div) HANDLE_DW_OP(0x1c, minus) HANDLE_DW_OP(0x1d, mod) HANDLE_DW_OP(0x1e, mul) HANDLE_DW_OP(0x1f, neg) HANDLE_DW_OP(0x20, not) HANDLE_DW_OP(0x21, or ) HANDLE_DW_OP(0x22, plus) HANDLE_DW_OP(0x23, plus_uconst) HANDLE_DW_OP(0x24, shl) HANDLE_DW_OP(0x25, shr) HANDLE_DW_OP(0x26, shra) HANDLE_DW_OP(0x27, xor) HANDLE_DW_OP(0x2f, skip) HANDLE_DW_OP(0x28, bra) HANDLE_DW_OP(0x29, eq) HANDLE_DW_OP(0x2a, ge) HANDLE_DW_OP(0x2b, gt) HANDLE_DW_OP(0x2c, le) HANDLE_DW_OP(0x2d, lt) HANDLE_DW_OP(0x2e, ne) HANDLE_DW_OP(0x30, lit0) HANDLE_DW_OP(0x31, lit1) HANDLE_DW_OP(0x32, lit2) HANDLE_DW_OP(0x33, lit3) HANDLE_DW_OP(0x34, lit4) HANDLE_DW_OP(0x35, lit5) HANDLE_DW_OP(0x36, lit6) HANDLE_DW_OP(0x37, lit7) HANDLE_DW_OP(0x38, lit8) HANDLE_DW_OP(0x39, lit9) HANDLE_DW_OP(0x3a, lit10) HANDLE_DW_OP(0x3b, lit11) HANDLE_DW_OP(0x3c, lit12) HANDLE_DW_OP(0x3d, lit13) HANDLE_DW_OP(0x3e, lit14) HANDLE_DW_OP(0x3f, lit15) HANDLE_DW_OP(0x40, lit16) HANDLE_DW_OP(0x41, lit17) HANDLE_DW_OP(0x42, lit18) HANDLE_DW_OP(0x43, lit19) HANDLE_DW_OP(0x44, lit20) HANDLE_DW_OP(0x45, lit21) HANDLE_DW_OP(0x46, lit22) HANDLE_DW_OP(0x47, lit23) HANDLE_DW_OP(0x48, lit24) HANDLE_DW_OP(0x49, lit25) HANDLE_DW_OP(0x4a, lit26) HANDLE_DW_OP(0x4b, lit27) HANDLE_DW_OP(0x4c, lit28) HANDLE_DW_OP(0x4d, lit29) HANDLE_DW_OP(0x4e, lit30) HANDLE_DW_OP(0x4f, lit31) HANDLE_DW_OP(0x50, reg0) HANDLE_DW_OP(0x51, reg1) HANDLE_DW_OP(0x52, reg2) HANDLE_DW_OP(0x53, reg3) HANDLE_DW_OP(0x54, reg4) HANDLE_DW_OP(0x55, reg5) HANDLE_DW_OP(0x56, reg6) HANDLE_DW_OP(0x57, reg7) HANDLE_DW_OP(0x58, reg8) HANDLE_DW_OP(0x59, reg9) HANDLE_DW_OP(0x5a, reg10) HANDLE_DW_OP(0x5b, reg11) HANDLE_DW_OP(0x5c, reg12) HANDLE_DW_OP(0x5d, reg13) HANDLE_DW_OP(0x5e, reg14) HANDLE_DW_OP(0x5f, reg15) HANDLE_DW_OP(0x60, reg16) HANDLE_DW_OP(0x61, reg17) HANDLE_DW_OP(0x62, reg18) HANDLE_DW_OP(0x63, reg19) HANDLE_DW_OP(0x64, reg20) HANDLE_DW_OP(0x65, reg21) HANDLE_DW_OP(0x66, reg22) HANDLE_DW_OP(0x67, reg23) HANDLE_DW_OP(0x68, reg24) HANDLE_DW_OP(0x69, reg25) HANDLE_DW_OP(0x6a, reg26) HANDLE_DW_OP(0x6b, reg27) HANDLE_DW_OP(0x6c, reg28) HANDLE_DW_OP(0x6d, reg29) HANDLE_DW_OP(0x6e, reg30) HANDLE_DW_OP(0x6f, reg31) HANDLE_DW_OP(0x70, breg0) HANDLE_DW_OP(0x71, breg1) HANDLE_DW_OP(0x72, breg2) HANDLE_DW_OP(0x73, breg3) HANDLE_DW_OP(0x74, breg4) HANDLE_DW_OP(0x75, breg5) HANDLE_DW_OP(0x76, breg6) HANDLE_DW_OP(0x77, breg7) HANDLE_DW_OP(0x78, breg8) HANDLE_DW_OP(0x79, breg9) HANDLE_DW_OP(0x7a, breg10) HANDLE_DW_OP(0x7b, breg11) HANDLE_DW_OP(0x7c, breg12) HANDLE_DW_OP(0x7d, breg13) HANDLE_DW_OP(0x7e, breg14) HANDLE_DW_OP(0x7f, breg15) HANDLE_DW_OP(0x80, breg16) HANDLE_DW_OP(0x81, breg17) HANDLE_DW_OP(0x82, breg18) HANDLE_DW_OP(0x83, breg19) HANDLE_DW_OP(0x84, breg20) HANDLE_DW_OP(0x85, breg21) HANDLE_DW_OP(0x86, breg22) HANDLE_DW_OP(0x87, breg23) HANDLE_DW_OP(0x88, breg24) HANDLE_DW_OP(0x89, breg25) HANDLE_DW_OP(0x8a, breg26) HANDLE_DW_OP(0x8b, breg27) HANDLE_DW_OP(0x8c, breg28) HANDLE_DW_OP(0x8d, breg29) HANDLE_DW_OP(0x8e, breg30) HANDLE_DW_OP(0x8f, breg31) HANDLE_DW_OP(0x90, regx) HANDLE_DW_OP(0x91, fbreg) HANDLE_DW_OP(0x92, bregx) HANDLE_DW_OP(0x93, piece) HANDLE_DW_OP(0x94, deref_size) HANDLE_DW_OP(0x95, xderef_size) HANDLE_DW_OP(0x96, nop) HANDLE_DW_OP(0x97, push_object_address) HANDLE_DW_OP(0x98, call2) HANDLE_DW_OP(0x99, call4) HANDLE_DW_OP(0x9a, call_ref) HANDLE_DW_OP(0x9b, form_tls_address) HANDLE_DW_OP(0x9c, call_frame_cfa) HANDLE_DW_OP(0x9d, bit_piece) HANDLE_DW_OP(0x9e, implicit_value) HANDLE_DW_OP(0x9f, stack_value) // Extensions for GNU-style thread-local storage. HANDLE_DW_OP(0xe0, GNU_push_tls_address) // Extensions for Fission proposal. HANDLE_DW_OP(0xfb, GNU_addr_index) HANDLE_DW_OP(0xfc, GNU_const_index) // DWARF languages. HANDLE_DW_LANG(0x0001, C89) HANDLE_DW_LANG(0x0002, C) HANDLE_DW_LANG(0x0003, Ada83) HANDLE_DW_LANG(0x0004, C_plus_plus) HANDLE_DW_LANG(0x0005, Cobol74) HANDLE_DW_LANG(0x0006, Cobol85) HANDLE_DW_LANG(0x0007, Fortran77) HANDLE_DW_LANG(0x0008, Fortran90) HANDLE_DW_LANG(0x0009, Pascal83) HANDLE_DW_LANG(0x000a, Modula2) HANDLE_DW_LANG(0x000b, Java) HANDLE_DW_LANG(0x000c, C99) HANDLE_DW_LANG(0x000d, Ada95) HANDLE_DW_LANG(0x000e, Fortran95) HANDLE_DW_LANG(0x000f, PLI) HANDLE_DW_LANG(0x0010, ObjC) HANDLE_DW_LANG(0x0011, ObjC_plus_plus) HANDLE_DW_LANG(0x0012, UPC) HANDLE_DW_LANG(0x0013, D) // New in DWARF 5: HANDLE_DW_LANG(0x0014, Python) HANDLE_DW_LANG(0x0015, OpenCL) HANDLE_DW_LANG(0x0016, Go) HANDLE_DW_LANG(0x0017, Modula3) HANDLE_DW_LANG(0x0018, Haskell) HANDLE_DW_LANG(0x0019, C_plus_plus_03) HANDLE_DW_LANG(0x001a, C_plus_plus_11) HANDLE_DW_LANG(0x001b, OCaml) HANDLE_DW_LANG(0x001c, Rust) HANDLE_DW_LANG(0x001d, C11) HANDLE_DW_LANG(0x001e, Swift) HANDLE_DW_LANG(0x001f, Julia) HANDLE_DW_LANG(0x0020, Dylan) HANDLE_DW_LANG(0x0021, C_plus_plus_14) HANDLE_DW_LANG(0x0022, Fortran03) HANDLE_DW_LANG(0x0023, Fortran08) HANDLE_DW_LANG(0x8001, Mips_Assembler) // DWARF attribute type encodings. HANDLE_DW_ATE(0x01, address) HANDLE_DW_ATE(0x02, boolean) HANDLE_DW_ATE(0x03, complex_float) HANDLE_DW_ATE(0x04, float) HANDLE_DW_ATE(0x05, signed) HANDLE_DW_ATE(0x06, signed_char) HANDLE_DW_ATE(0x07, unsigned) HANDLE_DW_ATE(0x08, unsigned_char) HANDLE_DW_ATE(0x09, imaginary_float) HANDLE_DW_ATE(0x0a, packed_decimal) HANDLE_DW_ATE(0x0b, numeric_string) HANDLE_DW_ATE(0x0c, edited) HANDLE_DW_ATE(0x0d, signed_fixed) HANDLE_DW_ATE(0x0e, unsigned_fixed) HANDLE_DW_ATE(0x0f, decimal_float) HANDLE_DW_ATE(0x10, UTF) // DWARF virtuality codes. HANDLE_DW_VIRTUALITY(0x00, none) HANDLE_DW_VIRTUALITY(0x01, virtual) HANDLE_DW_VIRTUALITY(0x02, pure_virtual) #undef HANDLE_DW_TAG #undef HANDLE_DW_OP #undef HANDLE_DW_LANG #undef HANDLE_DW_ATE #undef HANDLE_DW_VIRTUALITY
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/DataExtractor.h
//===-- DataExtractor.h -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_DATAEXTRACTOR_H #define LLVM_SUPPORT_DATAEXTRACTOR_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" namespace llvm { class DataExtractor { StringRef Data; uint8_t IsLittleEndian; uint8_t AddressSize; public: /// Construct with a buffer that is owned by the caller. /// /// This constructor allows us to use data that is owned by the /// caller. The data must stay around as long as this object is /// valid. DataExtractor(StringRef Data, bool IsLittleEndian, uint8_t AddressSize) : Data(Data), IsLittleEndian(IsLittleEndian), AddressSize(AddressSize) {} /// \brief Get the data pointed to by this extractor. StringRef getData() const { return Data; } /// \brief Get the endianess for this extractor. bool isLittleEndian() const { return IsLittleEndian; } /// \brief Get the address size for this extractor. uint8_t getAddressSize() const { return AddressSize; } /// \brief Set the address size for this extractor. void setAddressSize(uint8_t Size) { AddressSize = Size; } /// Extract a C string from \a *offset_ptr. /// /// Returns a pointer to a C String from the data at the offset /// pointed to by \a offset_ptr. A variable length NULL terminated C /// string will be extracted and the \a offset_ptr will be /// updated with the offset of the byte that follows the NULL /// terminator byte. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// A pointer to the C string value in the data. If the offset /// pointed to by \a offset_ptr is out of bounds, or if the /// offset plus the length of the C string is out of bounds, /// NULL will be returned. const char *getCStr(uint32_t *offset_ptr) const; /// Extract an unsigned integer of size \a byte_size from \a /// *offset_ptr. /// /// Extract a single unsigned integer value and update the offset /// pointed to by \a offset_ptr. The size of the extracted integer /// is specified by the \a byte_size argument. \a byte_size should /// have a value greater than or equal to one and less than or equal /// to eight since the return value is 64 bits wide. Any /// \a byte_size values less than 1 or greater than 8 will result in /// nothing being extracted, and zero being returned. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[in] byte_size /// The size in byte of the integer to extract. /// /// @return /// The unsigned integer value that was extracted, or zero on /// failure. uint64_t getUnsigned(uint32_t *offset_ptr, uint32_t byte_size) const; /// Extract an signed integer of size \a byte_size from \a *offset_ptr. /// /// Extract a single signed integer value (sign extending if required) /// and update the offset pointed to by \a offset_ptr. The size of /// the extracted integer is specified by the \a byte_size argument. /// \a byte_size should have a value greater than or equal to one /// and less than or equal to eight since the return value is 64 /// bits wide. Any \a byte_size values less than 1 or greater than /// 8 will result in nothing being extracted, and zero being returned. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[in] size /// The size in bytes of the integer to extract. /// /// @return /// The sign extended signed integer value that was extracted, /// or zero on failure. int64_t getSigned(uint32_t *offset_ptr, uint32_t size) const; //------------------------------------------------------------------ /// Extract an pointer from \a *offset_ptr. /// /// Extract a single pointer from the data and update the offset /// pointed to by \a offset_ptr. The size of the extracted pointer /// is \a getAddressSize(), so the address size has to be /// set correctly prior to extracting any pointer values. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted pointer value as a 64 integer. uint64_t getAddress(uint32_t *offset_ptr) const { return getUnsigned(offset_ptr, AddressSize); } /// Extract a uint8_t value from \a *offset_ptr. /// /// Extract a single uint8_t from the binary data at the offset /// pointed to by \a offset_ptr, and advance the offset on success. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted uint8_t value. uint8_t getU8(uint32_t *offset_ptr) const; /// Extract \a count uint8_t values from \a *offset_ptr. /// /// Extract \a count uint8_t values from the binary data at the /// offset pointed to by \a offset_ptr, and advance the offset on /// success. The extracted values are copied into \a dst. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[out] dst /// A buffer to copy \a count uint8_t values into. \a dst must /// be large enough to hold all requested data. /// /// @param[in] count /// The number of uint8_t values to extract. /// /// @return /// \a dst if all values were properly extracted and copied, /// NULL otherise. uint8_t *getU8(uint32_t *offset_ptr, uint8_t *dst, uint32_t count) const; //------------------------------------------------------------------ /// Extract a uint16_t value from \a *offset_ptr. /// /// Extract a single uint16_t from the binary data at the offset /// pointed to by \a offset_ptr, and update the offset on success. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted uint16_t value. //------------------------------------------------------------------ uint16_t getU16(uint32_t *offset_ptr) const; /// Extract \a count uint16_t values from \a *offset_ptr. /// /// Extract \a count uint16_t values from the binary data at the /// offset pointed to by \a offset_ptr, and advance the offset on /// success. The extracted values are copied into \a dst. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[out] dst /// A buffer to copy \a count uint16_t values into. \a dst must /// be large enough to hold all requested data. /// /// @param[in] count /// The number of uint16_t values to extract. /// /// @return /// \a dst if all values were properly extracted and copied, /// NULL otherise. uint16_t *getU16(uint32_t *offset_ptr, uint16_t *dst, uint32_t count) const; /// Extract a uint32_t value from \a *offset_ptr. /// /// Extract a single uint32_t from the binary data at the offset /// pointed to by \a offset_ptr, and update the offset on success. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted uint32_t value. uint32_t getU32(uint32_t *offset_ptr) const; /// Extract \a count uint32_t values from \a *offset_ptr. /// /// Extract \a count uint32_t values from the binary data at the /// offset pointed to by \a offset_ptr, and advance the offset on /// success. The extracted values are copied into \a dst. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[out] dst /// A buffer to copy \a count uint32_t values into. \a dst must /// be large enough to hold all requested data. /// /// @param[in] count /// The number of uint32_t values to extract. /// /// @return /// \a dst if all values were properly extracted and copied, /// NULL otherise. uint32_t *getU32(uint32_t *offset_ptr, uint32_t *dst, uint32_t count) const; /// Extract a uint64_t value from \a *offset_ptr. /// /// Extract a single uint64_t from the binary data at the offset /// pointed to by \a offset_ptr, and update the offset on success. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted uint64_t value. uint64_t getU64(uint32_t *offset_ptr) const; /// Extract \a count uint64_t values from \a *offset_ptr. /// /// Extract \a count uint64_t values from the binary data at the /// offset pointed to by \a offset_ptr, and advance the offset on /// success. The extracted values are copied into \a dst. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @param[out] dst /// A buffer to copy \a count uint64_t values into. \a dst must /// be large enough to hold all requested data. /// /// @param[in] count /// The number of uint64_t values to extract. /// /// @return /// \a dst if all values were properly extracted and copied, /// NULL otherise. uint64_t *getU64(uint32_t *offset_ptr, uint64_t *dst, uint32_t count) const; /// Extract a signed LEB128 value from \a *offset_ptr. /// /// Extracts an signed LEB128 number from this object's data /// starting at the offset pointed to by \a offset_ptr. The offset /// pointed to by \a offset_ptr will be updated with the offset of /// the byte following the last extracted byte. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted signed integer value. int64_t getSLEB128(uint32_t *offset_ptr) const; /// Extract a unsigned LEB128 value from \a *offset_ptr. /// /// Extracts an unsigned LEB128 number from this object's data /// starting at the offset pointed to by \a offset_ptr. The offset /// pointed to by \a offset_ptr will be updated with the offset of /// the byte following the last extracted byte. /// /// @param[in,out] offset_ptr /// A pointer to an offset within the data that will be advanced /// by the appropriate number of bytes if the value is extracted /// correctly. If the offset is out of bounds or there are not /// enough bytes to extract this value, the offset will be left /// unmodified. /// /// @return /// The extracted unsigned integer value. uint64_t getULEB128(uint32_t *offset_ptr) const; /// Test the validity of \a offset. /// /// @return /// \b true if \a offset is a valid offset into the data in this /// object, \b false otherwise. bool isValidOffset(uint32_t offset) const { return Data.size() > offset; } /// Test the availability of \a length bytes of data from \a offset. /// /// @return /// \b true if \a offset is a valid offset and there are \a /// length bytes available at that offset, \b false otherwise. bool isValidOffsetForDataOfSize(uint32_t offset, uint32_t length) const { return offset + length >= offset && isValidOffset(offset + length - 1); } /// Test the availability of enough bytes of data for a pointer from /// \a offset. The size of a pointer is \a getAddressSize(). /// /// @return /// \b true if \a offset is a valid offset and there are enough /// bytes for a pointer available at that offset, \b false /// otherwise. bool isValidOffsetForAddress(uint32_t offset) const { return isValidOffsetForDataOfSize(offset, AddressSize); } }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ScaledNumber.h
//===- llvm/Support/ScaledNumber.h - Support for scaled numbers -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains functions (and a class) useful for working with scaled // numbers -- in particular, pairs of integers where one represents digits and // another represents a scale. The functions are helpers and live in the // namespace ScaledNumbers. The class ScaledNumber is useful for modelling // certain cost metrics that need simple, integer-like semantics that are easy // to reason about. // // These might remind you of soft-floats. If you want one of those, you're in // the wrong place. Look at include/llvm/ADT/APFloat.h instead. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_SCALEDNUMBER_H #define LLVM_SUPPORT_SCALEDNUMBER_H #include "llvm/Support/MathExtras.h" #include <algorithm> #include <cstdint> #include <limits> #include <string> #include <tuple> #include <utility> namespace llvm { namespace ScaledNumbers { /// \brief Maximum scale; same as APFloat for easy debug printing. const int32_t MaxScale = 16383; /// \brief Maximum scale; same as APFloat for easy debug printing. const int32_t MinScale = -16382; /// \brief Get the width of a number. template <class DigitsT> inline int getWidth() { return sizeof(DigitsT) * 8; } /// \brief Conditionally round up a scaled number. /// /// Given \c Digits and \c Scale, round up iff \c ShouldRound is \c true. /// Always returns \c Scale unless there's an overflow, in which case it /// returns \c 1+Scale. /// /// \pre adding 1 to \c Scale will not overflow INT16_MAX. template <class DigitsT> inline std::pair<DigitsT, int16_t> getRounded(DigitsT Digits, int16_t Scale, bool ShouldRound) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); if (ShouldRound) if (!++Digits) // Overflow. return std::make_pair(DigitsT(1) << (getWidth<DigitsT>() - 1), Scale + 1); return std::make_pair(Digits, Scale); } /// \brief Convenience helper for 32-bit rounding. inline std::pair<uint32_t, int16_t> getRounded32(uint32_t Digits, int16_t Scale, bool ShouldRound) { return getRounded(Digits, Scale, ShouldRound); } /// \brief Convenience helper for 64-bit rounding. inline std::pair<uint64_t, int16_t> getRounded64(uint64_t Digits, int16_t Scale, bool ShouldRound) { return getRounded(Digits, Scale, ShouldRound); } /// \brief Adjust a 64-bit scaled number down to the appropriate width. /// /// \pre Adding 64 to \c Scale will not overflow INT16_MAX. template <class DigitsT> inline std::pair<DigitsT, int16_t> getAdjusted(uint64_t Digits, int16_t Scale = 0) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); const int Width = getWidth<DigitsT>(); if (Width == 64 || Digits <= std::numeric_limits<DigitsT>::max()) return std::make_pair(Digits, Scale); // Shift right and round. int Shift = 64 - Width - countLeadingZeros(Digits); return getRounded<DigitsT>(Digits >> Shift, Scale + Shift, Digits & (UINT64_C(1) << (Shift - 1))); } /// \brief Convenience helper for adjusting to 32 bits. inline std::pair<uint32_t, int16_t> getAdjusted32(uint64_t Digits, int16_t Scale = 0) { return getAdjusted<uint32_t>(Digits, Scale); } /// \brief Convenience helper for adjusting to 64 bits. inline std::pair<uint64_t, int16_t> getAdjusted64(uint64_t Digits, int16_t Scale = 0) { return getAdjusted<uint64_t>(Digits, Scale); } /// \brief Multiply two 64-bit integers to create a 64-bit scaled number. /// /// Implemented with four 64-bit integer multiplies. std::pair<uint64_t, int16_t> multiply64(uint64_t LHS, uint64_t RHS); /// \brief Multiply two 32-bit integers to create a 32-bit scaled number. /// /// Implemented with one 64-bit integer multiply. template <class DigitsT> inline std::pair<DigitsT, int16_t> getProduct(DigitsT LHS, DigitsT RHS) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); if (getWidth<DigitsT>() <= 32 || (LHS <= UINT32_MAX && RHS <= UINT32_MAX)) return getAdjusted<DigitsT>(uint64_t(LHS) * RHS); return multiply64(LHS, RHS); } /// \brief Convenience helper for 32-bit product. inline std::pair<uint32_t, int16_t> getProduct32(uint32_t LHS, uint32_t RHS) { return getProduct(LHS, RHS); } /// \brief Convenience helper for 64-bit product. inline std::pair<uint64_t, int16_t> getProduct64(uint64_t LHS, uint64_t RHS) { return getProduct(LHS, RHS); } /// \brief Divide two 64-bit integers to create a 64-bit scaled number. /// /// Implemented with long division. /// /// \pre \c Dividend and \c Divisor are non-zero. std::pair<uint64_t, int16_t> divide64(uint64_t Dividend, uint64_t Divisor); /// \brief Divide two 32-bit integers to create a 32-bit scaled number. /// /// Implemented with one 64-bit integer divide/remainder pair. /// /// \pre \c Dividend and \c Divisor are non-zero. std::pair<uint32_t, int16_t> divide32(uint32_t Dividend, uint32_t Divisor); /// \brief Divide two 32-bit numbers to create a 32-bit scaled number. /// /// Implemented with one 64-bit integer divide/remainder pair. /// /// Returns \c (DigitsT_MAX, MaxScale) for divide-by-zero (0 for 0/0). template <class DigitsT> std::pair<DigitsT, int16_t> getQuotient(DigitsT Dividend, DigitsT Divisor) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); static_assert(sizeof(DigitsT) == 4 || sizeof(DigitsT) == 8, "expected 32-bit or 64-bit digits"); // Check for zero. if (!Dividend) return std::make_pair(0, 0); if (!Divisor) return std::make_pair(std::numeric_limits<DigitsT>::max(), MaxScale); if (getWidth<DigitsT>() == 64) return divide64(Dividend, Divisor); return divide32(Dividend, Divisor); } /// \brief Convenience helper for 32-bit quotient. inline std::pair<uint32_t, int16_t> getQuotient32(uint32_t Dividend, uint32_t Divisor) { return getQuotient(Dividend, Divisor); } /// \brief Convenience helper for 64-bit quotient. inline std::pair<uint64_t, int16_t> getQuotient64(uint64_t Dividend, uint64_t Divisor) { return getQuotient(Dividend, Divisor); } /// \brief Implementation of getLg() and friends. /// /// Returns the rounded lg of \c Digits*2^Scale and an int specifying whether /// this was rounded up (1), down (-1), or exact (0). /// /// Returns \c INT32_MIN when \c Digits is zero. template <class DigitsT> inline std::pair<int32_t, int> getLgImpl(DigitsT Digits, int16_t Scale) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); if (!Digits) return std::make_pair(INT32_MIN, 0); // Get the floor of the lg of Digits. int32_t LocalFloor = sizeof(Digits) * 8 - countLeadingZeros(Digits) - 1; // Get the actual floor. int32_t Floor = Scale + LocalFloor; if (Digits == UINT64_C(1) << LocalFloor) return std::make_pair(Floor, 0); // Round based on the next digit. assert(LocalFloor >= 1); bool Round = Digits & UINT64_C(1) << (LocalFloor - 1); return std::make_pair(Floor + Round, Round ? 1 : -1); } /// \brief Get the lg (rounded) of a scaled number. /// /// Get the lg of \c Digits*2^Scale. /// /// Returns \c INT32_MIN when \c Digits is zero. template <class DigitsT> int32_t getLg(DigitsT Digits, int16_t Scale) { return getLgImpl(Digits, Scale).first; } /// \brief Get the lg floor of a scaled number. /// /// Get the floor of the lg of \c Digits*2^Scale. /// /// Returns \c INT32_MIN when \c Digits is zero. template <class DigitsT> int32_t getLgFloor(DigitsT Digits, int16_t Scale) { auto Lg = getLgImpl(Digits, Scale); return Lg.first - (Lg.second > 0); } /// \brief Get the lg ceiling of a scaled number. /// /// Get the ceiling of the lg of \c Digits*2^Scale. /// /// Returns \c INT32_MIN when \c Digits is zero. template <class DigitsT> int32_t getLgCeiling(DigitsT Digits, int16_t Scale) { auto Lg = getLgImpl(Digits, Scale); return Lg.first + (Lg.second < 0); } /// \brief Implementation for comparing scaled numbers. /// /// Compare two 64-bit numbers with different scales. Given that the scale of /// \c L is higher than that of \c R by \c ScaleDiff, compare them. Return -1, /// 1, and 0 for less than, greater than, and equal, respectively. /// /// \pre 0 <= ScaleDiff < 64. int compareImpl(uint64_t L, uint64_t R, int ScaleDiff); /// \brief Compare two scaled numbers. /// /// Compare two scaled numbers. Returns 0 for equal, -1 for less than, and 1 /// for greater than. template <class DigitsT> int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); // Check for zero. if (!LDigits) return RDigits ? -1 : 0; if (!RDigits) return 1; // Check for the scale. Use getLgFloor to be sure that the scale difference // is always lower than 64. int32_t lgL = getLgFloor(LDigits, LScale), lgR = getLgFloor(RDigits, RScale); if (lgL != lgR) return lgL < lgR ? -1 : 1; // Compare digits. if (LScale < RScale) return compareImpl(LDigits, RDigits, RScale - LScale); return -compareImpl(RDigits, LDigits, LScale - RScale); } /// \brief Match scales of two numbers. /// /// Given two scaled numbers, match up their scales. Change the digits and /// scales in place. Shift the digits as necessary to form equivalent numbers, /// losing precision only when necessary. /// /// If the output value of \c LDigits (\c RDigits) is \c 0, the output value of /// \c LScale (\c RScale) is unspecified. /// /// As a convenience, returns the matching scale. If the output value of one /// number is zero, returns the scale of the other. If both are zero, which /// scale is returned is unspecifed. template <class DigitsT> int16_t matchScales(DigitsT &LDigits, int16_t &LScale, DigitsT &RDigits, int16_t &RScale) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); if (LScale < RScale) // Swap arguments. return matchScales(RDigits, RScale, LDigits, LScale); if (!LDigits) return RScale; if (!RDigits || LScale == RScale) return LScale; // Now LScale > RScale. Get the difference. int32_t ScaleDiff = int32_t(LScale) - RScale; if (ScaleDiff >= 2 * getWidth<DigitsT>()) { // Don't bother shifting. RDigits will get zero-ed out anyway. RDigits = 0; return LScale; } // Shift LDigits left as much as possible, then shift RDigits right. int32_t ShiftL = std::min<int32_t>(countLeadingZeros(LDigits), ScaleDiff); assert(ShiftL < getWidth<DigitsT>() && "can't shift more than width"); int32_t ShiftR = ScaleDiff - ShiftL; if (ShiftR >= getWidth<DigitsT>()) { // Don't bother shifting. RDigits will get zero-ed out anyway. RDigits = 0; return LScale; } LDigits <<= ShiftL; RDigits >>= ShiftR; LScale -= ShiftL; RScale += ShiftR; assert(LScale == RScale && "scales should match"); return LScale; } /// \brief Get the sum of two scaled numbers. /// /// Get the sum of two scaled numbers with as much precision as possible. /// /// \pre Adding 1 to \c LScale (or \c RScale) will not overflow INT16_MAX. template <class DigitsT> std::pair<DigitsT, int16_t> getSum(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); // Check inputs up front. This is only relevent if addition overflows, but // testing here should catch more bugs. assert(LScale < INT16_MAX && "scale too large"); assert(RScale < INT16_MAX && "scale too large"); // Normalize digits to match scales. int16_t Scale = matchScales(LDigits, LScale, RDigits, RScale); // Compute sum. DigitsT Sum = LDigits + RDigits; if (Sum >= RDigits) return std::make_pair(Sum, Scale); // Adjust sum after arithmetic overflow. DigitsT HighBit = DigitsT(1) << (getWidth<DigitsT>() - 1); return std::make_pair(HighBit | Sum >> 1, Scale + 1); } /// \brief Convenience helper for 32-bit sum. inline std::pair<uint32_t, int16_t> getSum32(uint32_t LDigits, int16_t LScale, uint32_t RDigits, int16_t RScale) { return getSum(LDigits, LScale, RDigits, RScale); } /// \brief Convenience helper for 64-bit sum. inline std::pair<uint64_t, int16_t> getSum64(uint64_t LDigits, int16_t LScale, uint64_t RDigits, int16_t RScale) { return getSum(LDigits, LScale, RDigits, RScale); } /// \brief Get the difference of two scaled numbers. /// /// Get LHS minus RHS with as much precision as possible. /// /// Returns \c (0, 0) if the RHS is larger than the LHS. template <class DigitsT> std::pair<DigitsT, int16_t> getDifference(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) { static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned"); // Normalize digits to match scales. const DigitsT SavedRDigits = RDigits; const int16_t SavedRScale = RScale; matchScales(LDigits, LScale, RDigits, RScale); // Compute difference. if (LDigits <= RDigits) return std::make_pair(0, 0); if (RDigits || !SavedRDigits) return std::make_pair(LDigits - RDigits, LScale); // Check if RDigits just barely lost its last bit. E.g., for 32-bit: // // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32 const auto RLgFloor = getLgFloor(SavedRDigits, SavedRScale); if (!compare(LDigits, LScale, DigitsT(1), RLgFloor + getWidth<DigitsT>())) return std::make_pair(std::numeric_limits<DigitsT>::max(), RLgFloor); return std::make_pair(LDigits, LScale); } /// \brief Convenience helper for 32-bit difference. inline std::pair<uint32_t, int16_t> getDifference32(uint32_t LDigits, int16_t LScale, uint32_t RDigits, int16_t RScale) { return getDifference(LDigits, LScale, RDigits, RScale); } /// \brief Convenience helper for 64-bit difference. inline std::pair<uint64_t, int16_t> getDifference64(uint64_t LDigits, int16_t LScale, uint64_t RDigits, int16_t RScale) { return getDifference(LDigits, LScale, RDigits, RScale); } } // end namespace ScaledNumbers } // end namespace llvm namespace llvm { class raw_ostream; class ScaledNumberBase { public: static const int DefaultPrecision = 10; static void dump(uint64_t D, int16_t E, int Width); static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width, unsigned Precision); static std::string toString(uint64_t D, int16_t E, int Width, unsigned Precision); static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); } static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); } static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); } static std::pair<uint64_t, bool> splitSigned(int64_t N) { if (N >= 0) return std::make_pair(N, false); uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N); return std::make_pair(Unsigned, true); } static int64_t joinSigned(uint64_t U, bool IsNeg) { if (U > uint64_t(INT64_MAX)) return IsNeg ? INT64_MIN : INT64_MAX; return IsNeg ? -int64_t(U) : int64_t(U); } }; /// \brief Simple representation of a scaled number. /// /// ScaledNumber is a number represented by digits and a scale. It uses simple /// saturation arithmetic and every operation is well-defined for every value. /// It's somewhat similar in behaviour to a soft-float, but is *not* a /// replacement for one. If you're doing numerics, look at \a APFloat instead. /// Nevertheless, we've found these semantics useful for modelling certain cost /// metrics. /// /// The number is split into a signed scale and unsigned digits. The number /// represented is \c getDigits()*2^getScale(). In this way, the digits are /// much like the mantissa in the x87 long double, but there is no canonical /// form so the same number can be represented by many bit representations. /// /// ScaledNumber is templated on the underlying integer type for digits, which /// is expected to be unsigned. /// /// Unlike APFloat, ScaledNumber does not model architecture floating point /// behaviour -- while this might make it a little faster and easier to reason /// about, it certainly makes it more dangerous for general numerics. /// /// ScaledNumber is totally ordered. However, there is no canonical form, so /// there are multiple representations of most scalars. E.g.: /// /// ScaledNumber(8u, 0) == ScaledNumber(4u, 1) /// ScaledNumber(4u, 1) == ScaledNumber(2u, 2) /// ScaledNumber(2u, 2) == ScaledNumber(1u, 3) /// /// ScaledNumber implements most arithmetic operations. Precision is kept /// where possible. Uses simple saturation arithmetic, so that operations /// saturate to 0.0 or getLargest() rather than under or overflowing. It has /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0. /// Any other division by 0.0 is defined to be getLargest(). /// /// As a convenience for modifying the exponent, left and right shifting are /// both implemented, and both interpret negative shifts as positive shifts in /// the opposite direction. /// /// Scales are limited to the range accepted by x87 long double. This makes /// it trivial to add functionality to convert to APFloat (this is already /// relied on for the implementation of printing). /// /// Possible (and conflicting) future directions: /// /// 1. Turn this into a wrapper around \a APFloat. /// 2. Share the algorithm implementations with \a APFloat. /// 3. Allow \a ScaledNumber to represent a signed number. template <class DigitsT> class ScaledNumber : ScaledNumberBase { public: static_assert(!std::numeric_limits<DigitsT>::is_signed, "only unsigned floats supported"); typedef DigitsT DigitsType; private: typedef std::numeric_limits<DigitsType> DigitsLimits; static const int Width = sizeof(DigitsType) * 8; static_assert(Width <= 64, "invalid integer width for digits"); private: DigitsType Digits; int16_t Scale; public: ScaledNumber() : Digits(0), Scale(0) {} ScaledNumber(DigitsType Digits, int16_t Scale) : Digits(Digits), Scale(Scale) {} private: ScaledNumber(const std::pair<DigitsT, int16_t> &X) : Digits(X.first), Scale(X.second) {} public: static ScaledNumber getZero() { return ScaledNumber(0, 0); } static ScaledNumber getOne() { return ScaledNumber(1, 0); } static ScaledNumber getLargest() { return ScaledNumber(DigitsLimits::max(), ScaledNumbers::MaxScale); } static ScaledNumber get(uint64_t N) { return adjustToWidth(N, 0); } static ScaledNumber getInverse(uint64_t N) { return get(N).invert(); } static ScaledNumber getFraction(DigitsType N, DigitsType D) { return getQuotient(N, D); } int16_t getScale() const { return Scale; } DigitsType getDigits() const { return Digits; } /// \brief Convert to the given integer type. /// /// Convert to \c IntT using simple saturating arithmetic, truncating if /// necessary. template <class IntT> IntT toInt() const; bool isZero() const { return !Digits; } bool isLargest() const { return *this == getLargest(); } bool isOne() const { if (Scale > 0 || Scale <= -Width) return false; return Digits == DigitsType(1) << -Scale; } /// \brief The log base 2, rounded. /// /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN. int32_t lg() const { return ScaledNumbers::getLg(Digits, Scale); } /// \brief The log base 2, rounded towards INT32_MIN. /// /// Get the lg floor. lg 0 is defined to be INT32_MIN. int32_t lgFloor() const { return ScaledNumbers::getLgFloor(Digits, Scale); } /// \brief The log base 2, rounded towards INT32_MAX. /// /// Get the lg ceiling. lg 0 is defined to be INT32_MIN. int32_t lgCeiling() const { return ScaledNumbers::getLgCeiling(Digits, Scale); } bool operator==(const ScaledNumber &X) const { return compare(X) == 0; } bool operator<(const ScaledNumber &X) const { return compare(X) < 0; } bool operator!=(const ScaledNumber &X) const { return compare(X) != 0; } bool operator>(const ScaledNumber &X) const { return compare(X) > 0; } bool operator<=(const ScaledNumber &X) const { return compare(X) <= 0; } bool operator>=(const ScaledNumber &X) const { return compare(X) >= 0; } bool operator!() const { return isZero(); } /// \brief Convert to a decimal representation in a string. /// /// Convert to a string. Uses scientific notation for very large/small /// numbers. Scientific notation is used roughly for numbers outside of the /// range 2^-64 through 2^64. /// /// \c Precision indicates the number of decimal digits of precision to use; /// 0 requests the maximum available. /// /// As a special case to make debugging easier, if the number is small enough /// to convert without scientific notation and has more than \c Precision /// digits before the decimal place, it's printed accurately to the first /// digit past zero. E.g., assuming 10 digits of precision: /// /// 98765432198.7654... => 98765432198.8 /// 8765432198.7654... => 8765432198.8 /// 765432198.7654... => 765432198.8 /// 65432198.7654... => 65432198.77 /// 5432198.7654... => 5432198.765 std::string toString(unsigned Precision = DefaultPrecision) { return ScaledNumberBase::toString(Digits, Scale, Width, Precision); } /// \brief Print a decimal representation. /// /// Print a string. See toString for documentation. raw_ostream &print(raw_ostream &OS, unsigned Precision = DefaultPrecision) const { return ScaledNumberBase::print(OS, Digits, Scale, Width, Precision); } void dump() const { return ScaledNumberBase::dump(Digits, Scale, Width); } ScaledNumber &operator+=(const ScaledNumber &X) { std::tie(Digits, Scale) = ScaledNumbers::getSum(Digits, Scale, X.Digits, X.Scale); // Check for exponent past MaxScale. if (Scale > ScaledNumbers::MaxScale) *this = getLargest(); return *this; } ScaledNumber &operator-=(const ScaledNumber &X) { std::tie(Digits, Scale) = ScaledNumbers::getDifference(Digits, Scale, X.Digits, X.Scale); return *this; } ScaledNumber &operator*=(const ScaledNumber &X); ScaledNumber &operator/=(const ScaledNumber &X); ScaledNumber &operator<<=(int16_t Shift) { shiftLeft(Shift); return *this; } ScaledNumber &operator>>=(int16_t Shift) { shiftRight(Shift); return *this; } private: void shiftLeft(int32_t Shift); void shiftRight(int32_t Shift); /// \brief Adjust two floats to have matching exponents. /// /// Adjust \c this and \c X to have matching exponents. Returns the new \c X /// by value. Does nothing if \a isZero() for either. /// /// The value that compares smaller will lose precision, and possibly become /// \a isZero(). ScaledNumber matchScales(ScaledNumber X) { ScaledNumbers::matchScales(Digits, Scale, X.Digits, X.Scale); return X; } public: /// \brief Scale a large number accurately. /// /// Scale N (multiply it by this). Uses full precision multiplication, even /// if Width is smaller than 64, so information is not lost. uint64_t scale(uint64_t N) const; uint64_t scaleByInverse(uint64_t N) const { // TODO: implement directly, rather than relying on inverse. Inverse is // expensive. return inverse().scale(N); } int64_t scale(int64_t N) const { std::pair<uint64_t, bool> Unsigned = splitSigned(N); return joinSigned(scale(Unsigned.first), Unsigned.second); } int64_t scaleByInverse(int64_t N) const { std::pair<uint64_t, bool> Unsigned = splitSigned(N); return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second); } int compare(const ScaledNumber &X) const { return ScaledNumbers::compare(Digits, Scale, X.Digits, X.Scale); } int compareTo(uint64_t N) const { return ScaledNumbers::compare<uint64_t>(Digits, Scale, N, 0); } int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); } ScaledNumber &invert() { return *this = ScaledNumber::get(1) / *this; } ScaledNumber inverse() const { return ScaledNumber(*this).invert(); } private: static ScaledNumber getProduct(DigitsType LHS, DigitsType RHS) { return ScaledNumbers::getProduct(LHS, RHS); } static ScaledNumber getQuotient(DigitsType Dividend, DigitsType Divisor) { return ScaledNumbers::getQuotient(Dividend, Divisor); } static int countLeadingZerosWidth(DigitsType Digits) { if (Width == 64) return countLeadingZeros64(Digits); if (Width == 32) return countLeadingZeros32(Digits); return countLeadingZeros32(Digits) + Width - 32; } /// \brief Adjust a number to width, rounding up if necessary. /// /// Should only be called for \c Shift close to zero. /// /// \pre Shift >= MinScale && Shift + 64 <= MaxScale. static ScaledNumber adjustToWidth(uint64_t N, int32_t Shift) { assert(Shift >= ScaledNumbers::MinScale && "Shift should be close to 0"); assert(Shift <= ScaledNumbers::MaxScale - 64 && "Shift should be close to 0"); auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift); return Adjusted; } static ScaledNumber getRounded(ScaledNumber P, bool Round) { // Saturate. if (P.isLargest()) return P; return ScaledNumbers::getRounded(P.Digits, P.Scale, Round); } }; #define SCALED_NUMBER_BOP(op, base) \ template <class DigitsT> \ ScaledNumber<DigitsT> operator op(const ScaledNumber<DigitsT> &L, \ const ScaledNumber<DigitsT> &R) { \ return ScaledNumber<DigitsT>(L) base R; \ } SCALED_NUMBER_BOP(+, += ) SCALED_NUMBER_BOP(-, -= ) SCALED_NUMBER_BOP(*, *= ) SCALED_NUMBER_BOP(/, /= ) #undef SCALED_NUMBER_BOP template <class DigitsT> ScaledNumber<DigitsT> operator<<(const ScaledNumber<DigitsT> &L, int16_t Shift) { return ScaledNumber<DigitsT>(L) <<= Shift; } template <class DigitsT> ScaledNumber<DigitsT> operator>>(const ScaledNumber<DigitsT> &L, int16_t Shift) { return ScaledNumber<DigitsT>(L) >>= Shift; } template <class DigitsT> raw_ostream &operator<<(raw_ostream &OS, const ScaledNumber<DigitsT> &X) { return X.print(OS, 10); } #define SCALED_NUMBER_COMPARE_TO_TYPE(op, T1, T2) \ template <class DigitsT> \ bool operator op(const ScaledNumber<DigitsT> &L, T1 R) { \ return L.compareTo(T2(R)) op 0; \ } \ template <class DigitsT> \ bool operator op(T1 L, const ScaledNumber<DigitsT> &R) { \ return 0 op R.compareTo(T2(L)); \ } #define SCALED_NUMBER_COMPARE_TO(op) \ SCALED_NUMBER_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \ SCALED_NUMBER_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \ SCALED_NUMBER_COMPARE_TO_TYPE(op, int64_t, int64_t) \ SCALED_NUMBER_COMPARE_TO_TYPE(op, int32_t, int64_t) SCALED_NUMBER_COMPARE_TO(< ) SCALED_NUMBER_COMPARE_TO(> ) SCALED_NUMBER_COMPARE_TO(== ) SCALED_NUMBER_COMPARE_TO(!= ) SCALED_NUMBER_COMPARE_TO(<= ) SCALED_NUMBER_COMPARE_TO(>= ) #undef SCALED_NUMBER_COMPARE_TO #undef SCALED_NUMBER_COMPARE_TO_TYPE template <class DigitsT> uint64_t ScaledNumber<DigitsT>::scale(uint64_t N) const { if (Width == 64 || N <= DigitsLimits::max()) return (get(N) * *this).template toInt<uint64_t>(); // Defer to the 64-bit version. return ScaledNumber<uint64_t>(Digits, Scale).scale(N); } template <class DigitsT> template <class IntT> IntT ScaledNumber<DigitsT>::toInt() const { typedef std::numeric_limits<IntT> Limits; if (*this < 1) return 0; if (*this >= Limits::max()) return Limits::max(); IntT N = Digits; if (Scale > 0) { assert(size_t(Scale) < sizeof(IntT) * 8); return N << Scale; } if (Scale < 0) { assert(size_t(-Scale) < sizeof(IntT) * 8); return N >> -Scale; } return N; } template <class DigitsT> ScaledNumber<DigitsT> &ScaledNumber<DigitsT>:: operator*=(const ScaledNumber &X) { if (isZero()) return *this; if (X.isZero()) return *this = X; // Save the exponents. int32_t Scales = int32_t(Scale) + int32_t(X.Scale); // Get the raw product. *this = getProduct(Digits, X.Digits); // Combine with exponents. return *this <<= Scales; } template <class DigitsT> ScaledNumber<DigitsT> &ScaledNumber<DigitsT>:: operator/=(const ScaledNumber &X) { if (isZero()) return *this; if (X.isZero()) return *this = getLargest(); // Save the exponents. int32_t Scales = int32_t(Scale) - int32_t(X.Scale); // Get the raw quotient. *this = getQuotient(Digits, X.Digits); // Combine with exponents. return *this <<= Scales; } template <class DigitsT> void ScaledNumber<DigitsT>::shiftLeft(int32_t Shift) { if (!Shift || isZero()) return; assert(Shift != INT32_MIN); if (Shift < 0) { shiftRight(-Shift); return; } // Shift as much as we can in the exponent. int32_t ScaleShift = std::min(Shift, ScaledNumbers::MaxScale - Scale); Scale += ScaleShift; if (ScaleShift == Shift) return; // Check this late, since it's rare. if (isLargest()) return; // Shift the digits themselves. Shift -= ScaleShift; if (Shift > countLeadingZerosWidth(Digits)) { // Saturate. *this = getLargest(); return; } Digits <<= Shift; return; } template <class DigitsT> void ScaledNumber<DigitsT>::shiftRight(int32_t Shift) { if (!Shift || isZero()) return; assert(Shift != INT32_MIN); if (Shift < 0) { shiftLeft(-Shift); return; } // Shift as much as we can in the exponent. int32_t ScaleShift = std::min(Shift, Scale - ScaledNumbers::MinScale); Scale -= ScaleShift; if (ScaleShift == Shift) return; // Shift the digits themselves. Shift -= ScaleShift; if (Shift >= Width) { // Saturate. *this = getZero(); return; } Digits >>= Shift; return; } template <typename T> struct isPodLike; template <typename T> struct isPodLike<ScaledNumber<T>> { static const bool value = true; }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/TimeValue.h
//===-- TimeValue.h - Declare OS TimeValue Concept --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file declares the operating system TimeValue concept. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TIMEVALUE_H #define LLVM_SUPPORT_TIMEVALUE_H #include "llvm/Support/DataTypes.h" #include <string> namespace llvm { namespace sys { /// This class is used where a precise fixed point in time is required. The /// range of TimeValue spans many hundreds of billions of years both past and /// present. The precision of TimeValue is to the nanosecond. However, the /// actual precision of its values will be determined by the resolution of /// the system clock. The TimeValue class is used in conjunction with several /// other lib/System interfaces to specify the time at which a call should /// timeout, etc. /// @since 1.4 /// @brief Provides an abstraction for a fixed point in time. class TimeValue { /// @name Constants /// @{ public: /// A constant TimeValue representing the smallest time /// value permissible by the class. MinTime is some point /// in the distant past, about 300 billion years BCE. /// @brief The smallest possible time value. static TimeValue MinTime() { return TimeValue ( INT64_MIN,0 ); } /// A constant TimeValue representing the largest time /// value permissible by the class. MaxTime is some point /// in the distant future, about 300 billion years AD. /// @brief The largest possible time value. static TimeValue MaxTime() { return TimeValue ( INT64_MAX,0 ); } /// A constant TimeValue representing the base time, /// or zero time of 00:00:00 (midnight) January 1st, 2000. /// @brief 00:00:00 Jan 1, 2000 UTC. static TimeValue ZeroTime() { return TimeValue ( 0,0 ); } /// A constant TimeValue for the Posix base time which is /// 00:00:00 (midnight) January 1st, 1970. /// @brief 00:00:00 Jan 1, 1970 UTC. static TimeValue PosixZeroTime() { return TimeValue ( PosixZeroTimeSeconds,0 ); } /// A constant TimeValue for the Win32 base time which is /// 00:00:00 (midnight) January 1st, 1601. /// @brief 00:00:00 Jan 1, 1601 UTC. static TimeValue Win32ZeroTime() { return TimeValue ( Win32ZeroTimeSeconds,0 ); } /// @} /// @name Types /// @{ public: typedef int64_t SecondsType; ///< Type used for representing seconds. typedef int32_t NanoSecondsType;///< Type used for representing nanoseconds. enum TimeConversions { NANOSECONDS_PER_SECOND = 1000000000, ///< One Billion MICROSECONDS_PER_SECOND = 1000000, ///< One Million MILLISECONDS_PER_SECOND = 1000, ///< One Thousand NANOSECONDS_PER_MICROSECOND = 1000, ///< One Thousand NANOSECONDS_PER_MILLISECOND = 1000000,///< One Million NANOSECONDS_PER_WIN32_TICK = 100 ///< Win32 tick is 10^7 Hz (10ns) }; /// @} /// @name Constructors /// @{ public: /// \brief Default construct a time value, initializing to ZeroTime. TimeValue() : seconds_(0), nanos_(0) {} /// Caller provides the exact value in seconds and nanoseconds. The /// \p nanos argument defaults to zero for convenience. /// @brief Explicit constructor explicit TimeValue (SecondsType seconds, NanoSecondsType nanos = 0) : seconds_( seconds ), nanos_( nanos ) { this->normalize(); } /// Caller provides the exact value as a double in seconds with the /// fractional part representing nanoseconds. /// @brief Double Constructor. explicit TimeValue( double new_time ) : seconds_( 0 ) , nanos_ ( 0 ) { SecondsType integer_part = static_cast<SecondsType>( new_time ); seconds_ = integer_part; nanos_ = static_cast<NanoSecondsType>( (new_time - static_cast<double>(integer_part)) * NANOSECONDS_PER_SECOND ); this->normalize(); } /// This is a static constructor that returns a TimeValue that represents /// the current time. /// @brief Creates a TimeValue with the current time (UTC). static TimeValue now(); /// @} /// @name Operators /// @{ public: /// Add \p that to \p this. /// @returns this /// @brief Incrementing assignment operator. TimeValue& operator += (const TimeValue& that ) { this->seconds_ += that.seconds_ ; this->nanos_ += that.nanos_ ; this->normalize(); return *this; } /// Subtract \p that from \p this. /// @returns this /// @brief Decrementing assignment operator. TimeValue& operator -= (const TimeValue &that ) { this->seconds_ -= that.seconds_ ; this->nanos_ -= that.nanos_ ; this->normalize(); return *this; } /// Determine if \p this is less than \p that. /// @returns True iff *this < that. /// @brief True if this < that. int operator < (const TimeValue &that) const { return that > *this; } /// Determine if \p this is greather than \p that. /// @returns True iff *this > that. /// @brief True if this > that. int operator > (const TimeValue &that) const { if ( this->seconds_ > that.seconds_ ) { return 1; } else if ( this->seconds_ == that.seconds_ ) { if ( this->nanos_ > that.nanos_ ) return 1; } return 0; } /// Determine if \p this is less than or equal to \p that. /// @returns True iff *this <= that. /// @brief True if this <= that. int operator <= (const TimeValue &that) const { return that >= *this; } /// Determine if \p this is greater than or equal to \p that. /// @returns True iff *this >= that. int operator >= (const TimeValue &that) const { if ( this->seconds_ > that.seconds_ ) { return 1; } else if ( this->seconds_ == that.seconds_ ) { if ( this->nanos_ >= that.nanos_ ) return 1; } return 0; } /// Determines if two TimeValue objects represent the same moment in time. /// @returns True iff *this == that. int operator == (const TimeValue &that) const { return (this->seconds_ == that.seconds_) && (this->nanos_ == that.nanos_); } /// Determines if two TimeValue objects represent times that are not the /// same. /// @returns True iff *this != that. int operator != (const TimeValue &that) const { return !(*this == that); } /// Adds two TimeValue objects together. /// @returns The sum of the two operands as a new TimeValue /// @brief Addition operator. friend TimeValue operator + (const TimeValue &tv1, const TimeValue &tv2); /// Subtracts two TimeValue objects. /// @returns The difference of the two operands as a new TimeValue /// @brief Subtraction operator. friend TimeValue operator - (const TimeValue &tv1, const TimeValue &tv2); /// @} /// @name Accessors /// @{ public: /// Returns only the seconds component of the TimeValue. The nanoseconds /// portion is ignored. No rounding is performed. /// @brief Retrieve the seconds component SecondsType seconds() const { return seconds_; } /// Returns only the nanoseconds component of the TimeValue. The seconds /// portion is ignored. /// @brief Retrieve the nanoseconds component. NanoSecondsType nanoseconds() const { return nanos_; } /// Returns only the fractional portion of the TimeValue rounded down to the /// nearest microsecond (divide by one thousand). /// @brief Retrieve the fractional part as microseconds; uint32_t microseconds() const { return nanos_ / NANOSECONDS_PER_MICROSECOND; } /// Returns only the fractional portion of the TimeValue rounded down to the /// nearest millisecond (divide by one million). /// @brief Retrieve the fractional part as milliseconds; uint32_t milliseconds() const { return nanos_ / NANOSECONDS_PER_MILLISECOND; } /// Returns the TimeValue as a number of microseconds. Note that the value /// returned can overflow because the range of a uint64_t is smaller than /// the range of a TimeValue. Nevertheless, this is useful on some operating /// systems and is therefore provided. /// @brief Convert to a number of microseconds (can overflow) uint64_t usec() const { return seconds_ * MICROSECONDS_PER_SECOND + ( nanos_ / NANOSECONDS_PER_MICROSECOND ); } /// Returns the TimeValue as a number of milliseconds. Note that the value /// returned can overflow because the range of a uint64_t is smaller than /// the range of a TimeValue. Nevertheless, this is useful on some operating /// systems and is therefore provided. /// @brief Convert to a number of milliseconds (can overflow) uint64_t msec() const { return seconds_ * MILLISECONDS_PER_SECOND + ( nanos_ / NANOSECONDS_PER_MILLISECOND ); } /// Converts the TimeValue into the corresponding number of seconds /// since the epoch (00:00:00 Jan 1,1970). uint64_t toEpochTime() const { return seconds_ - PosixZeroTimeSeconds; } /// Converts the TimeValue into the corresponding number of "ticks" for /// Win32 platforms, correcting for the difference in Win32 zero time. /// @brief Convert to Win32's FILETIME /// (100ns intervals since 00:00:00 Jan 1, 1601 UTC) uint64_t toWin32Time() const { uint64_t result = (uint64_t)10000000 * (seconds_ - Win32ZeroTimeSeconds); result += nanos_ / NANOSECONDS_PER_WIN32_TICK; return result; } /// Provides the seconds and nanoseconds as results in its arguments after /// correction for the Posix zero time. /// @brief Convert to timespec time (ala POSIX.1b) void getTimespecTime( uint64_t& seconds, uint32_t& nanos ) const { seconds = seconds_ - PosixZeroTimeSeconds; nanos = nanos_; } /// Provides conversion of the TimeValue into a readable time & date. /// @returns std::string containing the readable time value /// @brief Convert time to a string. std::string str() const; /// @} /// @name Mutators /// @{ public: /// The seconds component of the TimeValue is set to \p sec without /// modifying the nanoseconds part. This is useful for whole second /// arithmetic. /// @brief Set the seconds component. void seconds (SecondsType sec ) { this->seconds_ = sec; this->normalize(); } /// The nanoseconds component of the TimeValue is set to \p nanos without /// modifying the seconds part. This is useful for basic computations /// involving just the nanoseconds portion. Note that the TimeValue will be /// normalized after this call so that the fractional (nanoseconds) portion /// will have the smallest equivalent value. /// @brief Set the nanoseconds component using a number of nanoseconds. void nanoseconds ( NanoSecondsType nanos ) { this->nanos_ = nanos; this->normalize(); } /// The seconds component remains unchanged. /// @brief Set the nanoseconds component using a number of microseconds. void microseconds ( int32_t micros ) { this->nanos_ = micros * NANOSECONDS_PER_MICROSECOND; this->normalize(); } /// The seconds component remains unchanged. /// @brief Set the nanoseconds component using a number of milliseconds. void milliseconds ( int32_t millis ) { this->nanos_ = millis * NANOSECONDS_PER_MILLISECOND; this->normalize(); } /// @brief Converts from microsecond format to TimeValue format void usec( int64_t microseconds ) { this->seconds_ = microseconds / MICROSECONDS_PER_SECOND; this->nanos_ = NanoSecondsType(microseconds % MICROSECONDS_PER_SECOND) * NANOSECONDS_PER_MICROSECOND; this->normalize(); } /// @brief Converts from millisecond format to TimeValue format void msec( int64_t milliseconds ) { this->seconds_ = milliseconds / MILLISECONDS_PER_SECOND; this->nanos_ = NanoSecondsType(milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND; this->normalize(); } /// Converts the \p seconds argument from PosixTime to the corresponding /// TimeValue and assigns that value to \p this. /// @brief Convert seconds form PosixTime to TimeValue void fromEpochTime( SecondsType seconds ) { seconds_ = seconds + PosixZeroTimeSeconds; nanos_ = 0; this->normalize(); } /// Converts the \p win32Time argument from Windows FILETIME to the /// corresponding TimeValue and assigns that value to \p this. /// @brief Convert seconds form Windows FILETIME to TimeValue void fromWin32Time( uint64_t win32Time ) { this->seconds_ = win32Time / 10000000 + Win32ZeroTimeSeconds; this->nanos_ = NanoSecondsType(win32Time % 10000000) * 100; } /// @} /// @name Implementation /// @{ private: /// This causes the values to be represented so that the fractional /// part is minimized, possibly incrementing the seconds part. /// @brief Normalize to canonical form. void normalize(); /// @} /// @name Data /// @{ private: /// Store the values as a <timeval>. SecondsType seconds_;///< Stores the seconds part of the TimeVal NanoSecondsType nanos_; ///< Stores the nanoseconds part of the TimeVal static const SecondsType PosixZeroTimeSeconds; static const SecondsType Win32ZeroTimeSeconds; /// @} }; inline TimeValue operator + (const TimeValue &tv1, const TimeValue &tv2) { TimeValue sum (tv1.seconds_ + tv2.seconds_, tv1.nanos_ + tv2.nanos_); sum.normalize (); return sum; } inline TimeValue operator - (const TimeValue &tv1, const TimeValue &tv2) { TimeValue difference (tv1.seconds_ - tv2.seconds_, tv1.nanos_ - tv2.nanos_ ); difference.normalize (); return difference; } } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Registry.h
//=== Registry.h - Linker-supported plugin registries -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines a registry template for discovering pluggable modules. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_REGISTRY_H #define LLVM_SUPPORT_REGISTRY_H #include "llvm/ADT/iterator_range.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Compiler.h" #include <memory> namespace llvm { /// A simple registry entry which provides only a name, description, and /// no-argument constructor. template <typename T> class SimpleRegistryEntry { const char *Name, *Desc; std::unique_ptr<T> (*Ctor)(); public: SimpleRegistryEntry(const char *N, const char *D, std::unique_ptr<T> (*C)()) : Name(N), Desc(D), Ctor(C) {} const char *getName() const { return Name; } const char *getDesc() const { return Desc; } std::unique_ptr<T> instantiate() const { return Ctor(); } }; /// Traits for registry entries. If using other than SimpleRegistryEntry, it /// is necessary to define an alternate traits class. template <typename T> class RegistryTraits { RegistryTraits() = delete; public: typedef SimpleRegistryEntry<T> entry; /// nameof/descof - Accessors for name and description of entries. These are // used to generate help for command-line options. static const char *nameof(const entry &Entry) { return Entry.getName(); } static const char *descof(const entry &Entry) { return Entry.getDesc(); } }; /// A global registry used in conjunction with static constructors to make /// pluggable components (like targets or garbage collectors) "just work" when /// linked with an executable. template <typename T, typename U = RegistryTraits<T> > class Registry { public: typedef U traits; typedef typename U::entry entry; class node; class listener; class iterator; private: Registry() = delete; static void Announce(const entry &E) { for (listener *Cur = ListenerHead; Cur; Cur = Cur->Next) Cur->registered(E); } friend class node; static node *Head, *Tail; friend class listener; static listener *ListenerHead, *ListenerTail; public: /// Node in linked list of entries. /// class node { friend class iterator; node *Next; const entry& Val; public: node(const entry& V) : Next(nullptr), Val(V) { if (Tail) Tail->Next = this; else Head = this; Tail = this; Announce(V); } }; /// Iterators for registry entries. /// class iterator { const node *Cur; public: explicit iterator(const node *N) : Cur(N) {} bool operator==(const iterator &That) const { return Cur == That.Cur; } bool operator!=(const iterator &That) const { return Cur != That.Cur; } iterator &operator++() { Cur = Cur->Next; return *this; } const entry &operator*() const { return Cur->Val; } const entry *operator->() const { return &Cur->Val; } }; static iterator begin() { return iterator(Head); } static iterator end() { return iterator(nullptr); } static iterator_range<iterator> entries() { return iterator_range<iterator>(begin(), end()); } /// Abstract base class for registry listeners, which are informed when new /// entries are added to the registry. Simply subclass and instantiate: /// /// \code /// class CollectorPrinter : public Registry<Collector>::listener { /// protected: /// void registered(const Registry<Collector>::entry &e) { /// cerr << "collector now available: " << e->getName() << "\n"; /// } /// /// public: /// CollectorPrinter() { init(); } // Print those already registered. /// }; /// /// CollectorPrinter Printer; /// \endcode class listener { listener *Prev, *Next; friend void Registry::Announce(const entry &E); protected: /// Called when an entry is added to the registry. /// virtual void registered(const entry &) = 0; /// Calls 'registered' for each pre-existing entry. /// void init() { for (iterator I = begin(), E = end(); I != E; ++I) registered(*I); } public: listener() : Prev(ListenerTail), Next(0) { if (Prev) Prev->Next = this; else ListenerHead = this; ListenerTail = this; } virtual ~listener() { if (Next) Next->Prev = Prev; else ListenerTail = Prev; if (Prev) Prev->Next = Next; else ListenerHead = Next; } }; /// A static registration template. Use like such: /// /// Registry<Collector>::Add<FancyGC> /// X("fancy-gc", "Newfangled garbage collector."); /// /// Use of this template requires that: /// /// 1. The registered subclass has a default constructor. // /// 2. The registry entry type has a constructor compatible with this /// signature: /// /// entry(const char *Name, const char *ShortDesc, T *(*Ctor)()); /// /// If you have more elaborate requirements, then copy and modify. /// template <typename V> class Add { entry Entry; node Node; static std::unique_ptr<T> CtorFn() { return make_unique<V>(); } public: Add(const char *Name, const char *Desc) : Entry(Name, Desc, CtorFn), Node(Entry) {} }; /// Registry::Parser now lives in llvm/Support/RegistryParser.h. }; // Since these are defined in a header file, plugins must be sure to export // these symbols. template <typename T, typename U> typename Registry<T,U>::node *Registry<T,U>::Head; template <typename T, typename U> typename Registry<T,U>::node *Registry<T,U>::Tail; template <typename T, typename U> typename Registry<T,U>::listener *Registry<T,U>::ListenerHead; template <typename T, typename U> typename Registry<T,U>::listener *Registry<T,U>::ListenerTail; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Timer.h
//===-- llvm/Support/Timer.h - Interval Timing Support ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TIMER_H #define LLVM_SUPPORT_TIMER_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include <cassert> #include <string> #include <utility> #include <vector> namespace llvm { class Timer; class TimerGroup; class raw_ostream; class TimeRecord { double WallTime; // Wall clock time elapsed in seconds double UserTime; // User time elapsed double SystemTime; // System time elapsed ssize_t MemUsed; // Memory allocated (in bytes) public: TimeRecord() : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0) {} /// getCurrentTime - Get the current time and memory usage. If Start is true /// we get the memory usage before the time, otherwise we get time before /// memory usage. This matters if the time to get the memory usage is /// significant and shouldn't be counted as part of a duration. static TimeRecord getCurrentTime(bool Start = true); double getProcessTime() const { return UserTime+SystemTime; } double getUserTime() const { return UserTime; } double getSystemTime() const { return SystemTime; } double getWallTime() const { return WallTime; } ssize_t getMemUsed() const { return MemUsed; } // operator< - Allow sorting. bool operator<(const TimeRecord &T) const { // Sort by Wall Time elapsed, as it is the only thing really accurate return WallTime < T.WallTime; } void operator+=(const TimeRecord &RHS) { WallTime += RHS.WallTime; UserTime += RHS.UserTime; SystemTime += RHS.SystemTime; MemUsed += RHS.MemUsed; } void operator-=(const TimeRecord &RHS) { WallTime -= RHS.WallTime; UserTime -= RHS.UserTime; SystemTime -= RHS.SystemTime; MemUsed -= RHS.MemUsed; } /// print - Print the current timer to standard error, and reset the "Started" /// flag. void print(const TimeRecord &Total, raw_ostream &OS) const; }; /// Timer - This class is used to track the amount of time spent between /// invocations of its startTimer()/stopTimer() methods. Given appropriate OS /// support it can also keep track of the RSS of the program at various points. /// By default, the Timer will print the amount of time it has captured to /// standard error when the last timer is destroyed, otherwise it is printed /// when its TimerGroup is destroyed. Timers do not print their information /// if they are never started. /// class Timer { TimeRecord Time; std::string Name; // The name of this time variable. bool Started; // Has this time variable ever been started? TimerGroup *TG; // The TimerGroup this Timer is in. Timer **Prev, *Next; // Doubly linked list of timers in the group. public: explicit Timer(StringRef N) : TG(nullptr) { init(N); } Timer(StringRef N, TimerGroup &tg) : TG(nullptr) { init(N, tg); } Timer(const Timer &RHS) : TG(nullptr) { assert(!RHS.TG && "Can only copy uninitialized timers"); } const Timer &operator=(const Timer &T) { assert(!TG && !T.TG && "Can only assign uninit timers"); return *this; } ~Timer(); // Create an uninitialized timer, client must use 'init'. explicit Timer() : TG(nullptr) {} void init(StringRef N); void init(StringRef N, TimerGroup &tg); const std::string &getName() const { return Name; } bool isInitialized() const { return TG != nullptr; } /// startTimer - Start the timer running. Time between calls to /// startTimer/stopTimer is counted by the Timer class. Note that these calls /// must be correctly paired. /// void startTimer(); /// stopTimer - Stop the timer. /// void stopTimer(); private: friend class TimerGroup; }; /// The TimeRegion class is used as a helper class to call the startTimer() and /// stopTimer() methods of the Timer class. When the object is constructed, it /// starts the timer specified as its argument. When it is destroyed, it stops /// the relevant timer. This makes it easy to time a region of code. /// class TimeRegion { Timer *T; TimeRegion(const TimeRegion &) = delete; public: explicit TimeRegion(Timer &t) : T(&t) { T->startTimer(); } explicit TimeRegion(Timer *t) : T(t) { if (T) T->startTimer(); } ~TimeRegion() { if (T) T->stopTimer(); } }; /// NamedRegionTimer - This class is basically a combination of TimeRegion and /// Timer. It allows you to declare a new timer, AND specify the region to /// time, all in one statement. All timers with the same name are merged. This /// is primarily used for debugging and for hunting performance problems. /// struct NamedRegionTimer : public TimeRegion { explicit NamedRegionTimer(StringRef Name, bool Enabled = true); explicit NamedRegionTimer(StringRef Name, StringRef GroupName, bool Enabled = true); }; /// The TimerGroup class is used to group together related timers into a single /// report that is printed when the TimerGroup is destroyed. It is illegal to /// destroy a TimerGroup object before all of the Timers in it are gone. A /// TimerGroup can be specified for a newly created timer in its constructor. /// class TimerGroup { std::string Name; Timer *FirstTimer; // First timer in the group. std::vector<std::pair<TimeRecord, std::string> > TimersToPrint; TimerGroup **Prev, *Next; // Doubly linked list of TimerGroup's. TimerGroup(const TimerGroup &TG) = delete; void operator=(const TimerGroup &TG) = delete; public: explicit TimerGroup(StringRef name); ~TimerGroup(); void setName(StringRef name) { Name.assign(name.begin(), name.end()); } /// print - Print any started timers in this group and zero them. void print(raw_ostream &OS); /// printAll - This static method prints all timers and clears them all out. static void printAll(raw_ostream &OS); private: friend class Timer; void addTimer(Timer &T); void removeTimer(Timer &T); void PrintQueuedTimers(raw_ostream &OS); }; } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Debug.h
//===- llvm/Support/Debug.h - Easy way to add debug output ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a handy way of adding debugging information to your // code, without it being enabled all of the time, and without having to add // command line options to enable it. // // In particular, just wrap your code with the DEBUG() macro, and it will be // enabled automatically if you specify '-debug' on the command-line. // Alternatively, you can also define the DEBUG_TYPE macro to "foo" specify // that your debug code belongs to class "foo". Be careful that you only do // this after including Debug.h and not around any #include of headers. Headers // should define and undef the macro acround the code that needs to use the // DEBUG() macro. Then, on the command line, you can specify '-debug-only=foo' // to enable JUST the debug information for the foo class. // // When compiling without assertions, the -debug-* options and all code in // DEBUG() statements disappears, so it does not affect the runtime of the code. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_DEBUG_H #define LLVM_SUPPORT_DEBUG_H namespace llvm { class raw_ostream; #ifndef NDEBUG /// DebugFlag - This boolean is set to true if the '-debug' command line option /// is specified. This should probably not be referenced directly, instead, use /// the DEBUG macro below. /// extern bool DebugFlag; /// isCurrentDebugType - Return true if the specified string is the debug type /// specified on the command line, or if none was specified on the command line /// with the -debug-only=X option. /// bool isCurrentDebugType(const char *Type); /// setCurrentDebugType - Set the current debug type, as if the -debug-only=X /// option were specified. Note that DebugFlag also needs to be set to true for /// debug output to be produced. /// void setCurrentDebugType(const char *Type); /// DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug /// information. In the '-debug' option is specified on the commandline, and if /// this is a debug build, then the code specified as the option to the macro /// will be executed. Otherwise it will not be. Example: /// /// DEBUG_WITH_TYPE("bitset", dbgs() << "Bitset contains: " << Bitset << "\n"); /// /// This will emit the debug information if -debug is present, and -debug-only /// is not specified, or is specified as "bitset". #define DEBUG_WITH_TYPE(TYPE, X) \ do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)) { X; } \ } while (0) // HLSL Change #define DEBUG_WITH_TYPE_IF(C, TYPE, X) \ do { if ((C) && ::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)) { X; __BREAK_ON_FAIL; } \ } while (0) #else #define isCurrentDebugType(X) (false) #define setCurrentDebugType(X) #define DEBUG_WITH_TYPE(TYPE, X) do { } while (0) // HLSL Change #define DEBUG_WITH_TYPE_IF(C, TYPE, X) do { } while (0) #endif /// EnableDebugBuffering - This defaults to false. If true, the debug /// stream will install signal handlers to dump any buffered debug /// output. It allows clients to selectively allow the debug stream /// to install signal handlers if they are certain there will be no /// conflict. /// extern bool EnableDebugBuffering; /// dbgs() - This returns a reference to a raw_ostream for debugging /// messages. If debugging is disabled it returns errs(). Use it /// like: dbgs() << "foo" << "bar"; raw_ostream &dbgs(); // DEBUG macro - This macro should be used by passes to emit debug information. // In the '-debug' option is specified on the commandline, and if this is a // debug build, then the code specified as the option to the macro will be // executed. Otherwise it will not be. Example: // // DEBUG(dbgs() << "Bitset contains: " << Bitset << "\n"); // #define DEBUG(X) DEBUG_WITH_TYPE(DEBUG_TYPE, X) // HLSL Change #define DEBUG_IF(C, X) DEBUG_WITH_TYPE_IF(C, DEBUG_TYPE, X) } // End llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/DataStream.h
//===---- llvm/Support/DataStream.h - Lazy bitcode streaming ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines DataStreamer, which fetches bytes of data from // a stream source. It provides support for streaming (lazy reading) of // data, e.g. bitcode // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_DATASTREAM_H #define LLVM_SUPPORT_DATASTREAM_H #include <memory> #include <string> namespace llvm { class DataStreamer { public: /// Fetch bytes [start-end) from the stream, and write them to the /// buffer pointed to by buf. Returns the number of bytes actually written. virtual size_t GetBytes(unsigned char *buf, size_t len) = 0; virtual ~DataStreamer(); }; std::unique_ptr<DataStreamer> getDataFileStreamer(const std::string &Filename, std::string *Err); } #endif // LLVM_SUPPORT_DATASTREAM_H_
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Options.h
//===- llvm/Support/Options.h - Debug options support -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file declares helper objects for defining debug options that can be /// configured via the command line. The new API currently builds on the cl::opt /// API, but does not require the use of static globals. /// /// With this API options are registered during initialization. For passes, this /// happens during pass initialization. Passes with options will call a static /// registerOptions method during initialization that registers options with the /// OptionRegistry. An example implementation of registerOptions is: /// /// static void registerOptions() { /// OptionRegistry::registerOption<bool, Scalarizer, /// &Scalarizer::ScalarizeLoadStore>( /// "scalarize-load-store", /// "Allow the scalarizer pass to scalarize loads and store", false); /// } /// /// When reading data for options the interface is via the LLVMContext. Option /// data for passes should be read from the context during doInitialization. An /// example of reading the above option would be: /// /// ScalarizeLoadStore = /// M.getContext().getOption<bool, /// Scalarizer, /// &Scalarizer::ScalarizeLoadStore>(); /// //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_OPTIONS_H #define LLVM_SUPPORT_OPTIONS_H #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CommandLine.h" namespace llvm { namespace detail { // Options are keyed of the unique address of a static character synthesized // based on template arguments. template <typename ValT, typename Base, ValT(Base::*Mem)> class OptionKey { public: static char ID; }; template <typename ValT, typename Base, ValT(Base::*Mem)> char OptionKey<ValT, Base, Mem>::ID = 0; } // namespace detail /// \brief Singleton class used to register debug options. /// /// The OptionRegistry is responsible for managing lifetimes of the options and /// provides interfaces for option registration and reading values from options. /// This object is a singleton, only one instance should ever exist so that all /// options are registered in the same place. class OptionRegistry { private: DenseMap<void *, cl::Option *> Options; /// \brief Adds a cl::Option to the registry. /// /// \param Key unique key for option /// \param O option to map to \p Key /// /// Allocated cl::Options are owened by the OptionRegistry and are deallocated /// on destruction or removal void addOption(void *Key, cl::Option *O); public: ~OptionRegistry(); OptionRegistry() {} /// \brief Returns a reference to the singleton instance. static OptionRegistry &instance(); /// \brief Registers an option with the OptionRegistry singleton. /// /// \tparam ValT type of the option's data /// \tparam Base class used to key the option /// \tparam Mem member of \p Base used for keying the option /// /// Options are keyed off the template parameters to generate unique static /// characters. The template parameters are (1) the type of the data the /// option stores (\p ValT), the class that will read the option (\p Base), /// and the memeber that the class will store the data into (\p Mem). template <typename ValT, typename Base, ValT(Base::*Mem)> static void registerOption(const char *ArgStr, const char *Desc, const ValT &InitValue) { cl::opt<ValT> *Option = new cl::opt<ValT>(ArgStr, cl::desc(Desc), cl::Hidden, cl::init(InitValue)); instance().addOption(&detail::OptionKey<ValT, Base, Mem>::ID, Option); } /// \brief Returns the value of the option. /// /// \tparam ValT type of the option's data /// \tparam Base class used to key the option /// \tparam Mem member of \p Base used for keying the option /// /// Reads option values based on the key generated by the template parameters. /// Keying for get() is the same as keying for registerOption. template <typename ValT, typename Base, ValT(Base::*Mem)> ValT get() const { auto It = Options.find(&detail::OptionKey<ValT, Base, Mem>::ID); assert(It != Options.end() && "Option not in OptionRegistry"); return *(cl::opt<ValT> *)It->second; } }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/SpecialCaseList.h
//===-- SpecialCaseList.h - special case list for sanitizers ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. //===----------------------------------------------------------------------===// // // This is a utility class used to parse user-provided text files with // "special case lists" for code sanitizers. Such files are used to // define "ABI list" for DataFlowSanitizer and blacklists for another sanitizers // like AddressSanitizer or UndefinedBehaviorSanitizer. // // Empty lines and lines starting with "#" are ignored. All the rest lines // should have the form: // section:wildcard_expression[=category] // If category is not specified, it is assumed to be empty string. // Definitions of "section" and "category" are sanitizer-specific. For example, // sanitizer blacklists support sections "src", "fun" and "global". // Wildcard expressions define, respectively, source files, functions or // globals which shouldn't be instrumented. // Examples of categories: // "functional": used in DFSan to list functions with pure functional // semantics. // "init": used in ASan blacklist to disable initialization-order bugs // detection for certain globals or source files. // Full special case list file example: // --- // # Blacklisted items: // fun:*_ZN4base6subtle* // global:*global_with_bad_access_or_initialization* // global:*global_with_initialization_issues*=init // type:*Namespace::ClassName*=init // src:file_with_tricky_code.cc // src:ignore-global-initializers-issues.cc=init // // # Functions with pure functional semantics: // fun:cos=functional // fun:sin=functional // --- // Note that the wild card is in fact an llvm::Regex, but * is automatically // replaced with .* // This is similar to the "ignore" feature of ThreadSanitizer. // http://code.google.com/p/data-race-test/wiki/ThreadSanitizerIgnores // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_SPECIALCASELIST_H #define LLVM_SUPPORT_SPECIALCASELIST_H #include "llvm/ADT/StringMap.h" #include <string> #include <vector> namespace llvm { class MemoryBuffer; class Regex; class StringRef; class SpecialCaseList { public: /// Parses the special case list entries from files. On failure, returns /// 0 and writes an error message to string. static std::unique_ptr<SpecialCaseList> create(const std::vector<std::string> &Paths, std::string &Error); /// Parses the special case list from a memory buffer. On failure, returns /// 0 and writes an error message to string. static std::unique_ptr<SpecialCaseList> create(const MemoryBuffer *MB, std::string &Error); /// Parses the special case list entries from files. On failure, reports a /// fatal error. static std::unique_ptr<SpecialCaseList> createOrDie(const std::vector<std::string> &Paths); ~SpecialCaseList(); /// Returns true, if special case list contains a line /// \code /// @Section:<E>=@Category /// \endcode /// and @Query satisfies a wildcard expression <E>. bool inSection(StringRef Section, StringRef Query, StringRef Category = StringRef()) const; private: SpecialCaseList(SpecialCaseList const &) = delete; SpecialCaseList &operator=(SpecialCaseList const &) = delete; struct Entry; StringMap<StringMap<Entry>> Entries; StringMap<StringMap<std::string>> Regexps; bool IsCompiled; SpecialCaseList(); /// Parses just-constructed SpecialCaseList entries from a memory buffer. bool parse(const MemoryBuffer *MB, std::string &Error); /// compile() should be called once, after parsing all the memory buffers. void compile(); }; } // namespace llvm #endif // LLVM_SUPPORT_SPECIALCASELIST_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/YAMLParser.h
//===--- YAMLParser.h - Simple YAML parser --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is a YAML 1.2 parser. // // See http://www.yaml.org/spec/1.2/spec.html for the full standard. // // This currently does not implement the following: // * Multi-line literal folding. // * Tag resolution. // * UTF-16. // * BOMs anywhere other than the first Unicode scalar value in the file. // // The most important class here is Stream. This represents a YAML stream with // 0, 1, or many documents. // // SourceMgr sm; // StringRef input = getInput(); // yaml::Stream stream(input, sm); // // for (yaml::document_iterator di = stream.begin(), de = stream.end(); // di != de; ++di) { // yaml::Node *n = di->getRoot(); // if (n) { // // Do something with n... // } else // break; // } // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_YAMLPARSER_H #define LLVM_SUPPORT_YAMLPARSER_H #include "llvm/ADT/StringRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/SMLoc.h" #include <limits> #include <map> #include <utility> namespace llvm { class MemoryBufferRef; class SourceMgr; class Twine; class raw_ostream; namespace yaml { class document_iterator; class Document; class Node; class Scanner; struct Token; /// \brief Dump all the tokens in this stream to OS. /// \returns true if there was an error, false otherwise. bool dumpTokens(StringRef Input, raw_ostream &); /// \brief Scans all tokens in input without outputting anything. This is used /// for benchmarking the tokenizer. /// \returns true if there was an error, false otherwise. bool scanTokens(StringRef Input); /// \brief Escape \a Input for a double quoted scalar. std::string escape(StringRef Input); /// \brief This class represents a YAML stream potentially containing multiple /// documents. class Stream { public: /// \brief This keeps a reference to the string referenced by \p Input. Stream(StringRef Input, SourceMgr &, bool ShowColors = true); Stream(MemoryBufferRef InputBuffer, SourceMgr &, bool ShowColors = true); ~Stream(); document_iterator begin(); document_iterator end(); void skip(); bool failed(); bool validate() { skip(); return !failed(); } void printError(Node *N, const Twine &Msg); private: std::unique_ptr<Scanner> scanner; std::unique_ptr<Document> CurrentDoc; friend class Document; }; /// \brief Abstract base class for all Nodes. class Node { virtual void anchor(); public: enum NodeKind { NK_Null, NK_Scalar, NK_BlockScalar, NK_KeyValue, NK_Mapping, NK_Sequence, NK_Alias }; Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor, StringRef Tag); /// \brief Get the value of the anchor attached to this node. If it does not /// have one, getAnchor().size() will be 0. StringRef getAnchor() const { return Anchor; } /// \brief Get the tag as it was written in the document. This does not /// perform tag resolution. StringRef getRawTag() const { return Tag; } /// \brief Get the verbatium tag for a given Node. This performs tag resoluton /// and substitution. std::string getVerbatimTag() const; SMRange getSourceRange() const { return SourceRange; } void setSourceRange(SMRange SR) { SourceRange = SR; } // These functions forward to Document and Scanner. Token &peekNext(); Token getNext(); Node *parseBlockNode(); BumpPtrAllocator &getAllocator(); void setError(const Twine &Message, Token &Location) const; bool failed() const; virtual void skip() {} unsigned int getType() const { return TypeID; } void *operator new(size_t Size, BumpPtrAllocator &Alloc, size_t Alignment = 16) throw() { return Alloc.Allocate(Size, Alignment); } void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t Size) throw() { Alloc.Deallocate(Ptr, Size); } protected: std::unique_ptr<Document> &Doc; SMRange SourceRange; void operator delete(void *) throw() {} ~Node() = default; private: unsigned int TypeID; StringRef Anchor; /// \brief The tag as typed in the document. StringRef Tag; }; /// \brief A null value. /// /// Example: /// !!null null class NullNode final : public Node { void anchor() override; public: NullNode(std::unique_ptr<Document> &D) : Node(NK_Null, D, StringRef(), StringRef()) {} static inline bool classof(const Node *N) { return N->getType() == NK_Null; } }; /// \brief A scalar node is an opaque datum that can be presented as a /// series of zero or more Unicode scalar values. /// /// Example: /// Adena class ScalarNode final : public Node { void anchor() override; public: ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag, StringRef Val) : Node(NK_Scalar, D, Anchor, Tag), Value(Val) { SMLoc Start = SMLoc::getFromPointer(Val.begin()); SMLoc End = SMLoc::getFromPointer(Val.end()); SourceRange = SMRange(Start, End); } // Return Value without any escaping or folding or other fun YAML stuff. This // is the exact bytes that are contained in the file (after conversion to // utf8). StringRef getRawValue() const { return Value; } /// \brief Gets the value of this node as a StringRef. /// /// \param Storage is used to store the content of the returned StringRef iff /// it requires any modification from how it appeared in the source. /// This happens with escaped characters and multi-line literals. StringRef getValue(SmallVectorImpl<char> &Storage) const; static inline bool classof(const Node *N) { return N->getType() == NK_Scalar; } private: StringRef Value; StringRef unescapeDoubleQuoted(StringRef UnquotedValue, StringRef::size_type Start, SmallVectorImpl<char> &Storage) const; }; /// \brief A block scalar node is an opaque datum that can be presented as a /// series of zero or more Unicode scalar values. /// /// Example: /// | /// Hello /// World class BlockScalarNode final : public Node { void anchor() override; public: BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag, StringRef Value, StringRef RawVal) : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) { SMLoc Start = SMLoc::getFromPointer(RawVal.begin()); SMLoc End = SMLoc::getFromPointer(RawVal.end()); SourceRange = SMRange(Start, End); } /// \brief Gets the value of this node as a StringRef. StringRef getValue() const { return Value; } static inline bool classof(const Node *N) { return N->getType() == NK_BlockScalar; } private: StringRef Value; }; /// \brief A key and value pair. While not technically a Node under the YAML /// representation graph, it is easier to treat them this way. /// /// TODO: Consider making this not a child of Node. /// /// Example: /// Section: .text class KeyValueNode final : public Node { void anchor() override; public: KeyValueNode(std::unique_ptr<Document> &D) : Node(NK_KeyValue, D, StringRef(), StringRef()), Key(nullptr), Value(nullptr) {} /// \brief Parse and return the key. /// /// This may be called multiple times. /// /// \returns The key, or nullptr if failed() == true. Node *getKey(); /// \brief Parse and return the value. /// /// This may be called multiple times. /// /// \returns The value, or nullptr if failed() == true. Node *getValue(); void skip() override { getKey()->skip(); if (Node *Val = getValue()) Val->skip(); } static inline bool classof(const Node *N) { return N->getType() == NK_KeyValue; } private: Node *Key; Node *Value; }; /// \brief This is an iterator abstraction over YAML collections shared by both /// sequences and maps. /// /// BaseT must have a ValueT* member named CurrentEntry and a member function /// increment() which must set CurrentEntry to 0 to create an end iterator. template <class BaseT, class ValueT> class basic_collection_iterator { public: using iterator_category = std::forward_iterator_tag; using value_type = ValueT; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; basic_collection_iterator() : Base(nullptr) {} basic_collection_iterator(BaseT *B) : Base(B) {} ValueT *operator->() const { assert(Base && Base->CurrentEntry && "Attempted to access end iterator!"); return Base->CurrentEntry; } ValueT &operator*() const { assert(Base && Base->CurrentEntry && "Attempted to dereference end iterator!"); return *Base->CurrentEntry; } operator ValueT *() const { assert(Base && Base->CurrentEntry && "Attempted to access end iterator!"); return Base->CurrentEntry; } bool operator!=(const basic_collection_iterator &Other) const { if (Base != Other.Base) return true; return (Base && Other.Base) && Base->CurrentEntry != Other.Base->CurrentEntry; } basic_collection_iterator &operator++() { assert(Base && "Attempted to advance iterator past end!"); Base->increment(); // Create an end iterator. if (!Base->CurrentEntry) Base = nullptr; return *this; } private: BaseT *Base; }; // The following two templates are used for both MappingNode and Sequence Node. template <class CollectionType> typename CollectionType::iterator begin(CollectionType &C) { assert(C.IsAtBeginning && "You may only iterate over a collection once!"); C.IsAtBeginning = false; typename CollectionType::iterator ret(&C); ++ret; return ret; } template <class CollectionType> void skip(CollectionType &C) { // TODO: support skipping from the middle of a parsed collection ;/ assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!"); if (C.IsAtBeginning) for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e; ++i) i->skip(); } /// \brief Represents a YAML map created from either a block map for a flow map. /// /// This parses the YAML stream as increment() is called. /// /// Example: /// Name: _main /// Scope: Global class MappingNode final : public Node { void anchor() override; public: enum MappingType { MT_Block, MT_Flow, MT_Inline ///< An inline mapping node is used for "[key: value]". }; MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag, MappingType MT) : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true), IsAtEnd(false), CurrentEntry(nullptr) {} friend class basic_collection_iterator<MappingNode, KeyValueNode>; typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator; template <class T> friend typename T::iterator yaml::begin(T &); template <class T> friend void yaml::skip(T &); iterator begin() { return yaml::begin(*this); } iterator end() { return iterator(); } void skip() override { yaml::skip(*this); } static inline bool classof(const Node *N) { return N->getType() == NK_Mapping; } private: MappingType Type; bool IsAtBeginning; bool IsAtEnd; KeyValueNode *CurrentEntry; void increment(); }; /// \brief Represents a YAML sequence created from either a block sequence for a /// flow sequence. /// /// This parses the YAML stream as increment() is called. /// /// Example: /// - Hello /// - World class SequenceNode final : public Node { void anchor() override; public: enum SequenceType { ST_Block, ST_Flow, // Use for: // // key: // - val1 // - val2 // // As a BlockMappingEntry and BlockEnd are not created in this case. ST_Indentless }; SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag, SequenceType ST) : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true), IsAtEnd(false), WasPreviousTokenFlowEntry(true), // Start with an imaginary ','. CurrentEntry(nullptr) {} friend class basic_collection_iterator<SequenceNode, Node>; typedef basic_collection_iterator<SequenceNode, Node> iterator; template <class T> friend typename T::iterator yaml::begin(T &); template <class T> friend void yaml::skip(T &); void increment(); iterator begin() { return yaml::begin(*this); } iterator end() { return iterator(); } void skip() override { yaml::skip(*this); } static inline bool classof(const Node *N) { return N->getType() == NK_Sequence; } private: SequenceType SeqType; bool IsAtBeginning; bool IsAtEnd; bool WasPreviousTokenFlowEntry; Node *CurrentEntry; }; /// \brief Represents an alias to a Node with an anchor. /// /// Example: /// *AnchorName class AliasNode final : public Node { void anchor() override; public: AliasNode(std::unique_ptr<Document> &D, StringRef Val) : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {} StringRef getName() const { return Name; } Node *getTarget(); static inline bool classof(const Node *N) { return N->getType() == NK_Alias; } private: StringRef Name; }; /// \brief A YAML Stream is a sequence of Documents. A document contains a root /// node. class Document { public: /// \brief Root for parsing a node. Returns a single node. Node *parseBlockNode(); Document(Stream &ParentStream); /// \brief Finish parsing the current document and return true if there are /// more. Return false otherwise. bool skip(); /// \brief Parse and return the root level node. Node *getRoot() { if (Root) return Root; return Root = parseBlockNode(); } const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; } private: friend class Node; friend class document_iterator; /// \brief Stream to read tokens from. Stream &stream; /// \brief Used to allocate nodes to. All are destroyed without calling their /// destructor when the document is destroyed. BumpPtrAllocator NodeAllocator; /// \brief The root node. Used to support skipping a partially parsed /// document. Node *Root; /// \brief Maps tag prefixes to their expansion. std::map<StringRef, StringRef> TagMap; Token &peekNext(); Token getNext(); void setError(const Twine &Message, Token &Location) const; bool failed() const; /// \brief Parse %BLAH directives and return true if any were encountered. bool parseDirectives(); /// \brief Parse %YAML void parseYAMLDirective(); /// \brief Parse %TAG void parseTAGDirective(); /// \brief Consume the next token and error if it is not \a TK. bool expectToken(int TK); }; /// \brief Iterator abstraction for Documents over a Stream. class document_iterator { public: document_iterator() : Doc(nullptr) {} document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {} bool operator==(const document_iterator &Other) { if (isAtEnd() || Other.isAtEnd()) return isAtEnd() && Other.isAtEnd(); return Doc == Other.Doc; } bool operator!=(const document_iterator &Other) { return !(*this == Other); } document_iterator operator++() { assert(Doc && "incrementing iterator past the end."); if (!(*Doc)->skip()) { Doc->reset(nullptr); } else { Stream &S = (*Doc)->stream; Doc->reset(new Document(S)); } return *this; } Document &operator*() { return *Doc->get(); } std::unique_ptr<Document> &operator->() { return *Doc; } private: bool isAtEnd() const { return !Doc || !*Doc; } std::unique_ptr<Document> *Doc; }; } // End namespace yaml. } // End namespace llvm. #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/AIXDataTypesFix.h
//===-- llvm/Support/AIXDataTypesFix.h - Fix datatype defs ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file overrides default system-defined types and limits which cannot be // done in DataTypes.h.in because it is processed by autoheader first, which // comments out any #undef statement // //===----------------------------------------------------------------------===// // No include guards desired! #ifndef SUPPORT_DATATYPES_H #error "AIXDataTypesFix.h must only be included via DataTypes.h!" #endif // GCC is strict about defining large constants: they must have LL modifier. // These will be defined properly at the end of DataTypes.h #undef INT64_MAX #undef INT64_MIN
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ManagedStatic.h
//===-- llvm/Support/ManagedStatic.h - Static Global wrapper ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ManagedStatic class and the llvm_shutdown() function. // //===----------------------------------------------------------------------===// // // The following changes have been backported from upstream llvm: // // 56349e8b6d85 Fix for memory leak reported by Valgrind // 928071ae4ef5 [Support] Replace sys::Mutex with their standard equivalents. // 3d5360a4398b Replace llvm::MutexGuard/UniqueLock with their standard equivalents // c06a470fc843 Try once more to ensure constant initializaton of ManagedStatics // 41fe3a54c261 Ensure that ManagedStatic is constant initialized in MSVC 2017 & 2019 // 74de08031f5d [ManagedStatic] Avoid putting function pointers in template args. // f65e4ce2c48a [ADT, Support, TableGen] Fix some Clang-tidy modernize-use-default and Include What You Use warnings; other minor fixes (NFC). // 832d04207810 [ManagedStatic] Reimplement double-checked locking with std::atomic. // dd1463823a0c This is yet another attempt to re-instate r220932 as discussed in D19271. // #ifndef LLVM_SUPPORT_MANAGEDSTATIC_H #define LLVM_SUPPORT_MANAGEDSTATIC_H #include <atomic> #include <cstddef> namespace llvm { /// object_creator - Helper method for ManagedStatic. template <class C> struct object_creator { static void *call() { return new C(); } }; /// object_deleter - Helper method for ManagedStatic. /// template <typename T> struct object_deleter { static void call(void *Ptr) { delete (T *)Ptr; } }; template <typename T, size_t N> struct object_deleter<T[N]> { static void call(void *Ptr) { delete[](T *)Ptr; } }; // ManagedStatic must be initialized to zero, and it must *not* have a dynamic // initializer because managed statics are often created while running other // dynamic initializers. In standard C++11, the best way to accomplish this is // with a constexpr default constructor. However, different versions of the // Visual C++ compiler have had bugs where, even though the constructor may be // constexpr, a dynamic initializer may be emitted depending on optimization // settings. For the affected versions of MSVC, use the old linker // initialization pattern of not providing a constructor and leaving the fields // uninitialized. See http://llvm.org/PR41367 for details. #if !defined(_MSC_VER) || (_MSC_VER >= 1925) || defined(__clang__) #define LLVM_USE_CONSTEXPR_CTOR #endif /// ManagedStaticBase - Common base class for ManagedStatic instances. class ManagedStaticBase { protected: #ifdef LLVM_USE_CONSTEXPR_CTOR mutable std::atomic<void *> Ptr{}; mutable void (*DeleterFn)(void *) = nullptr; mutable const ManagedStaticBase *Next = nullptr; #else // This should only be used as a static variable, which guarantees that this // will be zero initialized. mutable std::atomic<void *> Ptr; mutable void (*DeleterFn)(void *); mutable const ManagedStaticBase *Next; #endif void RegisterManagedStatic(void *(*creator)(), void (*deleter)(void*)) const; public: #ifdef LLVM_USE_CONSTEXPR_CTOR constexpr ManagedStaticBase() = default; #endif /// isConstructed - Return true if this object has not been created yet. bool isConstructed() const { return Ptr != nullptr; } void destroy() const; }; /// ManagedStatic - This transparently changes the behavior of global statics to /// be lazily constructed on demand (good for reducing startup times of dynamic /// libraries that link in LLVM components) and for making destruction be /// explicit through the llvm_shutdown() function call. /// template <class C, class Creator = object_creator<C>, class Deleter = object_deleter<C>> class ManagedStatic : public ManagedStaticBase { public: // Accessors. C &operator*() { void *Tmp = Ptr.load(std::memory_order_acquire); if (!Tmp) RegisterManagedStatic(Creator::call, Deleter::call); return *static_cast<C *>(Ptr.load(std::memory_order_relaxed)); } C *operator->() { return &**this; } const C &operator*() const { void *Tmp = Ptr.load(std::memory_order_acquire); if (!Tmp) RegisterManagedStatic(Creator::call, Deleter::call); return *static_cast<C *>(Ptr.load(std::memory_order_relaxed)); } const C *operator->() const { return &**this; } // Extract the instance, leaving the ManagedStatic uninitialized. The // user is then responsible for the lifetime of the returned instance. C *claim() { return static_cast<C *>(Ptr.exchange(nullptr)); } }; /// llvm_shutdown - Deallocate and destroy all ManagedStatic variables. void llvm_shutdown(); /// llvm_shutdown_obj - This is a simple helper class that calls /// llvm_shutdown() when it is destroyed. struct llvm_shutdown_obj { llvm_shutdown_obj() = default; ~llvm_shutdown_obj() { llvm_shutdown(); } }; } // end namespace llvm #endif // LLVM_SUPPORT_MANAGEDSTATIC_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/FileSystem.h
//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::fs namespace. It is designed after // TR2/boost filesystem (v3), but modified to remove exception handling and the // path class. // // All functions return an error_code and their actual work via the last out // argument. The out argument is defined if and only if errc::success is // returned. A function may return any error code in the generic or system // category. However, they shall be equivalent to any error conditions listed // in each functions respective documentation if the condition applies. [ note: // this does not guarantee that error_code will be in the set of explicitly // listed codes, but it does guarantee that if any of the explicitly listed // errors occur, the correct error_code will be used ]. All functions may // return errc::not_enough_memory if there is not enough memory to complete the // operation. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_FILESYSTEM_H #define LLVM_SUPPORT_FILESYSTEM_H #include "dxc/WinAdapter.h" // HLSL Change #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TimeValue.h" #include <ctime> #include <iterator> #include <stack> #include <string> #include <system_error> #include <tuple> #include <vector> #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif namespace llvm { namespace sys { namespace fs { // HLSL Change Start class MSFileSystem; typedef MSFileSystem* MSFileSystemRef; std::error_code GetFileSystemTlsStatus() throw(); std::error_code SetupPerThreadFileSystem() throw(); void CleanupPerThreadFileSystem() throw(); struct AutoCleanupPerThreadFileSystem { ~AutoCleanupPerThreadFileSystem() { CleanupPerThreadFileSystem(); } }; /// <summary>Gets a reference to the file system installed for the current thread (possibly NULL).</summary> /// <remarks>In practice, consumers of the library should always install a file system.</remarks> MSFileSystemRef GetCurrentThreadFileSystem() throw(); /// <summary> /// Sets the specified file system reference for the current thread. /// </summary> std::error_code SetCurrentThreadFileSystem(MSFileSystemRef value) throw(); int msf_read(int fd, void* buffer, unsigned int count) throw(); int msf_write(int fd, const void* buffer, unsigned int count) throw(); int msf_close(int fd) throw(); int msf_setmode(int fd, int mode) throw(); long msf_lseek(int fd, long offset, int origin); class AutoPerThreadSystem { private: ::llvm::sys::fs::MSFileSystem* m_pOrigValue; std::error_code ec; public: AutoPerThreadSystem(::llvm::sys::fs::MSFileSystem *value) : m_pOrigValue(::llvm::sys::fs::GetCurrentThreadFileSystem()) { SetCurrentThreadFileSystem(nullptr); ec = ::llvm::sys::fs::SetCurrentThreadFileSystem(value); } ~AutoPerThreadSystem() { if (m_pOrigValue) { ::llvm::sys::fs::SetCurrentThreadFileSystem(nullptr); ::llvm::sys::fs::SetCurrentThreadFileSystem(m_pOrigValue); } else if (!ec) { ::llvm::sys::fs::SetCurrentThreadFileSystem(nullptr); } } const std::error_code& error_code() const { return ec; } }; // HLSL Change Ends /// An enumeration for the file system's view of the type. enum class file_type { status_error, file_not_found, regular_file, directory_file, symlink_file, block_file, character_file, fifo_file, socket_file, type_unknown }; /// space_info - Self explanatory. struct space_info { uint64_t capacity; uint64_t free; uint64_t available; }; enum perms { no_perms = 0, owner_read = 0400, owner_write = 0200, owner_exe = 0100, owner_all = owner_read | owner_write | owner_exe, group_read = 040, group_write = 020, group_exe = 010, group_all = group_read | group_write | group_exe, others_read = 04, others_write = 02, others_exe = 01, others_all = others_read | others_write | others_exe, all_read = owner_read | group_read | others_read, all_write = owner_write | group_write | others_write, all_exe = owner_exe | group_exe | others_exe, all_all = owner_all | group_all | others_all, set_uid_on_exe = 04000, set_gid_on_exe = 02000, sticky_bit = 01000, perms_not_known = 0xFFFF }; // Helper functions so that you can use & and | to manipulate perms bits: inline perms operator|(perms l , perms r) { return static_cast<perms>( static_cast<unsigned short>(l) | static_cast<unsigned short>(r)); } inline perms operator&(perms l , perms r) { return static_cast<perms>( static_cast<unsigned short>(l) & static_cast<unsigned short>(r)); } inline perms &operator|=(perms &l, perms r) { l = l | r; return l; } inline perms &operator&=(perms &l, perms r) { l = l & r; return l; } inline perms operator~(perms x) { return static_cast<perms>(~static_cast<unsigned short>(x)); } class UniqueID { uint64_t Device; uint64_t File; public: UniqueID() = default; UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {} bool operator==(const UniqueID &Other) const { return Device == Other.Device && File == Other.File; } bool operator!=(const UniqueID &Other) const { return !(*this == Other); } bool operator<(const UniqueID &Other) const { return std::tie(Device, File) < std::tie(Other.Device, Other.File); } uint64_t getDevice() const { return Device; } uint64_t getFile() const { return File; } }; /// file_status - Represents the result of a call to stat and friends. It has /// a platform-specific member to store the result. class file_status { #if defined(LLVM_ON_UNIX) dev_t fs_st_dev; ino_t fs_st_ino; time_t fs_st_mtime; uid_t fs_st_uid; gid_t fs_st_gid; off_t fs_st_size; #elif defined (LLVM_ON_WIN32) uint32_t LastWriteTimeHigh; uint32_t LastWriteTimeLow; uint32_t VolumeSerialNumber; uint32_t FileSizeHigh; uint32_t FileSizeLow; uint32_t FileIndexHigh; uint32_t FileIndexLow; #endif friend bool equivalent(file_status A, file_status B); file_type Type; perms Perms; public: #if defined(LLVM_ON_UNIX) file_status() : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0), fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(file_type::status_error), Perms(perms_not_known) {} file_status(file_type Type) : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0), fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type), Perms(perms_not_known) {} file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime, uid_t UID, gid_t GID, off_t Size) : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID), fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {} #elif defined(LLVM_ON_WIN32) file_status() : LastWriteTimeHigh(0), LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0), Type(file_type::status_error), Perms(perms_not_known) {} file_status(file_type Type) : LastWriteTimeHigh(0), LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0), Type(Type), Perms(perms_not_known) {} file_status(file_type Type, uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber, uint32_t FileSizeHigh, uint32_t FileSizeLow, uint32_t FileIndexHigh, uint32_t FileIndexLow) : LastWriteTimeHigh(LastWriteTimeHigh), LastWriteTimeLow(LastWriteTimeLow), VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh), FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {} #endif // getters file_type type() const { return Type; } perms permissions() const { return Perms; } TimeValue getLastModificationTime() const; UniqueID getUniqueID() const; #if defined(LLVM_ON_UNIX) uint32_t getUser() const { return fs_st_uid; } uint32_t getGroup() const { return fs_st_gid; } uint64_t getSize() const { return fs_st_size; } #elif defined (LLVM_ON_WIN32) uint32_t getUser() const { return 9999; // Not applicable to Windows, so... } uint32_t getGroup() const { return 9999; // Not applicable to Windows, so... } uint64_t getSize() const { return (uint64_t(FileSizeHigh) << 32) + FileSizeLow; } #endif // setters void type(file_type v) { Type = v; } void permissions(perms p) { Perms = p; } }; /// file_magic - An "enum class" enumeration of file types based on magic (the first /// N bytes of the file). struct file_magic { enum Impl { unknown = 0, ///< Unrecognized file bitcode, ///< Bitcode file archive, ///< ar style archive file elf, ///< ELF Unknown type elf_relocatable, ///< ELF Relocatable object file elf_executable, ///< ELF Executable image elf_shared_object, ///< ELF dynamically linked shared lib elf_core, ///< ELF core image macho_object, ///< Mach-O Object file macho_executable, ///< Mach-O Executable macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM macho_core, ///< Mach-O Core File macho_preload_executable, ///< Mach-O Preloaded Executable macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib macho_dynamic_linker, ///< The Mach-O dynamic linker macho_bundle, ///< Mach-O Bundle file macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub macho_dsym_companion, ///< Mach-O dSYM companion file macho_kext_bundle, ///< Mach-O kext bundle file macho_universal_binary, ///< Mach-O universal binary coff_object, ///< COFF object file coff_import_library, ///< COFF import library pecoff_executable, ///< PECOFF executable file windows_resource ///< Windows compiled resource file (.rc) }; bool is_object() const { return V == unknown ? false : true; } file_magic() : V(unknown) {} file_magic(Impl V) : V(V) {} operator Impl() const { return V; } private: Impl V; }; /// @} /// @name Physical Operators /// @{ /// @brief Make \a path an absolute path. /// /// Makes \a path absolute using the current directory if it is not already. An /// empty \a path will result in the current directory. /// /// /absolute/path => /absolute/path /// relative/../path => <current-directory>/relative/../path /// /// @param path A path that is modified to be an absolute path. /// @returns errc::success if \a path has been made absolute, otherwise a /// platform-specific error_code. std::error_code make_absolute(SmallVectorImpl<char> &path); /// @brief Create all the non-existent directories in path. /// /// @param path Directories to create. /// @returns errc::success if is_directory(path), otherwise a platform /// specific error_code. If IgnoreExisting is false, also returns /// error if the directory already existed. std::error_code create_directories(const Twine &path, bool IgnoreExisting = true); /// @brief Create the directory in path. /// /// @param path Directory to create. /// @returns errc::success if is_directory(path), otherwise a platform /// specific error_code. If IgnoreExisting is false, also returns /// error if the directory already existed. std::error_code create_directory(const Twine &path, bool IgnoreExisting = true); /// @brief Create a link from \a from to \a to. /// /// The link may be a soft or a hard link, depending on the platform. The caller /// may not assume which one. Currently on windows it creates a hard link since /// soft links require extra privileges. On unix, it creates a soft link since /// hard links don't work on SMB file systems. /// /// @param to The path to hard link to. /// @param from The path to hard link from. This is created. /// @returns errc::success if the link was created, otherwise a platform /// specific error_code. std::error_code create_link(const Twine &to, const Twine &from); /// @brief Get the current path. /// /// @param result Holds the current path on return. /// @returns errc::success if the current path has been stored in result, /// otherwise a platform-specific error_code. std::error_code current_path(SmallVectorImpl<char> &result); /// @brief Remove path. Equivalent to POSIX remove(). /// /// @param path Input path. /// @returns errc::success if path has been removed or didn't exist, otherwise a /// platform-specific error code. If IgnoreNonExisting is false, also /// returns error if the file didn't exist. std::error_code remove(const Twine &path, bool IgnoreNonExisting = true); /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename(). /// /// @param from The path to rename from. /// @param to The path to rename to. This is created. std::error_code rename(const Twine &from, const Twine &to); /// @brief Copy the contents of \a From to \a To. /// /// @param From The path to copy from. /// @param To The path to copy to. This is created. std::error_code copy_file(const Twine &From, const Twine &To); /// @brief Resize path to size. File is resized as if by POSIX truncate(). /// /// @param FD Input file descriptor. /// @param Size Size to resize to. /// @returns errc::success if \a path has been resized to \a size, otherwise a /// platform-specific error_code. std::error_code resize_file(int FD, uint64_t Size); /// @} /// @name Physical Observers /// @{ /// @brief Does file exist? /// /// @param status A file_status previously returned from stat. /// @returns True if the file represented by status exists, false if it does /// not. bool exists(file_status status); enum class AccessMode { Exist, Write, Execute }; /// @brief Can the file be accessed? /// /// @param Path Input path. /// @returns errc::success if the path can be accessed, otherwise a /// platform-specific error_code. std::error_code access(const Twine &Path, AccessMode Mode); /// @brief Does file exist? /// /// @param Path Input path. /// @returns True if it exists, false otherwise. inline bool exists(const Twine &Path) { return !access(Path, AccessMode::Exist); } /// @brief Can we execute this file? /// /// @param Path Input path. /// @returns True if we can execute it, false otherwise. inline bool can_execute(const Twine &Path) { return !access(Path, AccessMode::Execute); } /// @brief Can we write this file? /// /// @param Path Input path. /// @returns True if we can write to it, false otherwise. inline bool can_write(const Twine &Path) { return !access(Path, AccessMode::Write); } /// @brief Do file_status's represent the same thing? /// /// @param A Input file_status. /// @param B Input file_status. /// /// assert(status_known(A) || status_known(B)); /// /// @returns True if A and B both represent the same file system entity, false /// otherwise. bool equivalent(file_status A, file_status B); /// @brief Do paths represent the same thing? /// /// assert(status_known(A) || status_known(B)); /// /// @param A Input path A. /// @param B Input path B. /// @param result Set to true if stat(A) and stat(B) have the same device and /// inode (or equivalent). /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code equivalent(const Twine &A, const Twine &B, bool &result); /// @brief Simpler version of equivalent for clients that don't need to /// differentiate between an error and false. inline bool equivalent(const Twine &A, const Twine &B) { bool result; return !equivalent(A, B, result) && result; } /// @brief Does status represent a directory? /// /// @param status A file_status previously returned from status. /// @returns status.type() == file_type::directory_file. bool is_directory(file_status status); /// @brief Is path a directory? /// /// @param path Input path. /// @param result Set to true if \a path is a directory, false if it is not. /// Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code is_directory(const Twine &path, bool &result); /// @brief Simpler version of is_directory for clients that don't need to /// differentiate between an error and false. inline bool is_directory(const Twine &Path) { bool Result; return !is_directory(Path, Result) && Result; } /// @brief Does status represent a regular file? /// /// @param status A file_status previously returned from status. /// @returns status_known(status) && status.type() == file_type::regular_file. bool is_regular_file(file_status status); /// @brief Is path a regular file? /// /// @param path Input path. /// @param result Set to true if \a path is a regular file, false if it is not. /// Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code is_regular_file(const Twine &path, bool &result); /// @brief Simpler version of is_regular_file for clients that don't need to /// differentiate between an error and false. inline bool is_regular_file(const Twine &Path) { bool Result; if (is_regular_file(Path, Result)) return false; return Result; } /// @brief Does this status represent something that exists but is not a /// directory, regular file, or symlink? /// /// @param status A file_status previously returned from status. /// @returns exists(s) && !is_regular_file(s) && !is_directory(s) bool is_other(file_status status); /// @brief Is path something that exists but is not a directory, /// regular file, or symlink? /// /// @param path Input path. /// @param result Set to true if \a path exists, but is not a directory, regular /// file, or a symlink, false if it does not. Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code is_other(const Twine &path, bool &result); /// @brief Get file status as if by POSIX stat(). /// /// @param path Input path. /// @param result Set to the file status. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code status(const Twine &path, file_status &result); /// @brief A version for when a file descriptor is already available. std::error_code status(int FD, file_status &Result); /// @brief Get file size. /// /// @param Path Input path. /// @param Result Set to the size of the file in \a Path. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. inline std::error_code file_size(const Twine &Path, uint64_t &Result) { file_status Status; std::error_code EC = status(Path, Status); if (EC) return EC; Result = Status.getSize(); return std::error_code(); } /// @brief Set the file modification and access time. /// /// @returns errc::success if the file times were successfully set, otherwise a /// platform-specific error_code or errc::function_not_supported on /// platforms where the functionality isn't available. std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time); /// @brief Is status available? /// /// @param s Input file status. /// @returns True if status() != status_error. bool status_known(file_status s); /// @brief Is status available? /// /// @param path Input path. /// @param result Set to true if status() != status_error. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code status_known(const Twine &path, bool &result); /// @brief Create a uniquely named file. /// /// Generates a unique path suitable for a temporary file and then opens it as a /// file. The name is based on \a model with '%' replaced by a random char in /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary /// directory will be prepended. /// /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s /// /// This is an atomic operation. Either the file is created and opened, or the /// file system is left untouched. /// /// The intendend use is for files that are to be kept, possibly after /// renaming them. For example, when running 'clang -c foo.o', the file can /// be first created as foo-abc123.o and then renamed. /// /// @param Model Name to base unique path off of. /// @param ResultFD Set to the opened file's file descriptor. /// @param ResultPath Set to the opened file's absolute path. /// @returns errc::success if Result{FD,Path} have been successfully set, /// otherwise a platform-specific error_code. std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl<char> &ResultPath, unsigned Mode = all_read | all_write); /// @brief Simpler version for clients that don't want an open file. std::error_code createUniqueFile(const Twine &Model, SmallVectorImpl<char> &ResultPath); /// @brief Create a file in the system temporary directory. /// /// The filename is of the form prefix-random_chars.suffix. Since the directory /// is not know to the caller, Prefix and Suffix cannot have path separators. /// The files are created with mode 0600. /// /// This should be used for things like a temporary .s that is removed after /// running the assembler. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl<char> &ResultPath); /// @brief Simpler version for clients that don't want an open file. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, SmallVectorImpl<char> &ResultPath); std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl<char> &ResultPath); enum OpenFlags : unsigned { F_None = 0, /// F_Excl - When opening a file, this flag makes raw_fd_ostream /// report an error if the file already exists. F_Excl = 1, /// F_Append - When opening a file, if it already exists append to the /// existing file instead of returning an error. This may not be specified /// with F_Excl. F_Append = 2, /// The file should be opened in text mode on platforms that make this /// distinction. F_Text = 4, /// Open the file for read and write. F_RW = 8 }; inline OpenFlags operator|(OpenFlags A, OpenFlags B) { return OpenFlags(unsigned(A) | unsigned(B)); } inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) { A = A | B; return A; } std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode = 0666); std::error_code openFileForRead(const Twine &Name, int &ResultFD); /// @brief Identify the type of a binary file based on how magical it is. file_magic identify_magic(StringRef magic); /// @brief Get and identify \a path's type based on its content. /// /// @param path Input path. /// @param result Set to the type of file, or file_magic::unknown. /// @returns errc::success if result has been successfully set, otherwise a /// platform-specific error_code. std::error_code identify_magic(const Twine &path, file_magic &result); std::error_code getUniqueID(const Twine Path, UniqueID &Result); /// This class represents a memory mapped file. It is based on /// boost::iostreams::mapped_file. class mapped_file_region { mapped_file_region() = delete; mapped_file_region(mapped_file_region&) = delete; mapped_file_region &operator =(mapped_file_region&) = delete; public: enum mapmode { readonly, ///< May only access map via const_data as read only. readwrite, ///< May access map via data and modify it. Written to path. priv ///< May modify via data, but changes are lost on destruction. }; private: /// Platform-specific mapping state. uint64_t Size; void *Mapping; std::error_code init(int FD, uint64_t Offset, mapmode Mode); public: /// \param fd An open file descriptor to map. mapped_file_region takes /// ownership if closefd is true. It must have been opended in the correct /// mode. mapped_file_region(int fd, mapmode mode, uint64_t length, uint64_t offset, std::error_code &ec); ~mapped_file_region(); uint64_t size() const; char *data() const; /// Get a const view of the data. Modifying this memory has undefined /// behavior. const char *const_data() const; /// \returns The minimum alignment offset must be. static int alignment(); }; /// Return the path to the main executable, given the value of argv[0] from /// program startup and the address of main itself. In extremis, this function /// may fail and return an empty path. std::string getMainExecutable(const char *argv0, void *MainExecAddr); /// @} /// @name Iterators /// @{ /// directory_entry - A single entry in a directory. Caches the status either /// from the result of the iteration syscall, or the first time status is /// called. class directory_entry { std::string Path; mutable file_status Status; public: explicit directory_entry(const Twine &path, file_status st = file_status()) : Path(path.str()) , Status(st) {} directory_entry() {} void assign(const Twine &path, file_status st = file_status()) { Path = path.str(); Status = st; } void replace_filename(const Twine &filename, file_status st = file_status()); const std::string &path() const { return Path; } std::error_code status(file_status &result) const; bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; } bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); } bool operator< (const directory_entry& rhs) const; bool operator<=(const directory_entry& rhs) const; bool operator> (const directory_entry& rhs) const; bool operator>=(const directory_entry& rhs) const; }; namespace detail { struct DirIterState; std::error_code directory_iterator_construct(DirIterState &, StringRef); std::error_code directory_iterator_increment(DirIterState &); std::error_code directory_iterator_destruct(DirIterState &); /// DirIterState - Keeps state for the directory_iterator. It is reference /// counted in order to preserve InputIterator semantics on copy. struct DirIterState : public RefCountedBase<DirIterState> { DirIterState() : IterationHandle(0) {} ~DirIterState() { directory_iterator_destruct(*this); } intptr_t IterationHandle; directory_entry CurrentEntry; }; } /// directory_iterator - Iterates through the entries in path. There is no /// operator++ because we need an error_code. If it's really needed we can make /// it call report_fatal_error on error. class directory_iterator { IntrusiveRefCntPtr<detail::DirIterState> State; public: explicit directory_iterator(const Twine &path, std::error_code &ec) { State = new detail::DirIterState; SmallString<128> path_storage; ec = detail::directory_iterator_construct(*State, path.toStringRef(path_storage)); } explicit directory_iterator(const directory_entry &de, std::error_code &ec) { State = new detail::DirIterState; ec = detail::directory_iterator_construct(*State, de.path()); } /// Construct end iterator. directory_iterator() : State(nullptr) {} // No operator++ because we need error_code. directory_iterator &increment(std::error_code &ec) { ec = directory_iterator_increment(*State); return *this; } const directory_entry &operator*() const { return State->CurrentEntry; } const directory_entry *operator->() const { return &State->CurrentEntry; } bool operator==(const directory_iterator &RHS) const { if (State == RHS.State) return true; if (!RHS.State) return State->CurrentEntry == directory_entry(); if (!State) return RHS.State->CurrentEntry == directory_entry(); return State->CurrentEntry == RHS.State->CurrentEntry; } bool operator!=(const directory_iterator &RHS) const { return !(*this == RHS); } // Other members as required by // C++ Std, 24.1.1 Input iterators [input.iterators] }; namespace detail { /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is /// reference counted in order to preserve InputIterator semantics on copy. struct RecDirIterState : public RefCountedBase<RecDirIterState> { RecDirIterState() : Level(0) , HasNoPushRequest(false) {} std::stack<directory_iterator, std::vector<directory_iterator> > Stack; uint16_t Level; bool HasNoPushRequest; }; } /// recursive_directory_iterator - Same as directory_iterator except for it /// recurses down into child directories. class recursive_directory_iterator { IntrusiveRefCntPtr<detail::RecDirIterState> State; public: recursive_directory_iterator() {} explicit recursive_directory_iterator(const Twine &path, std::error_code &ec) : State(new detail::RecDirIterState) { State->Stack.push(directory_iterator(path, ec)); if (State->Stack.top() == directory_iterator()) State.reset(); } // No operator++ because we need error_code. recursive_directory_iterator &increment(std::error_code &ec) { const directory_iterator end_itr; if (State->HasNoPushRequest) State->HasNoPushRequest = false; else { file_status st; if ((ec = State->Stack.top()->status(st))) return *this; if (is_directory(st)) { State->Stack.push(directory_iterator(*State->Stack.top(), ec)); if (ec) return *this; if (State->Stack.top() != end_itr) { ++State->Level; return *this; } State->Stack.pop(); } } while (!State->Stack.empty() && State->Stack.top().increment(ec) == end_itr) { State->Stack.pop(); --State->Level; } // Check if we are done. If so, create an end iterator. if (State->Stack.empty()) State.reset(); return *this; } const directory_entry &operator*() const { return *State->Stack.top(); } const directory_entry *operator->() const { return &*State->Stack.top(); } // observers /// Gets the current level. Starting path is at level 0. int level() const { return State->Level; } /// Returns true if no_push has been called for this directory_entry. bool no_push_request() const { return State->HasNoPushRequest; } // modifiers /// Goes up one level if Level > 0. void pop() { assert(State && "Cannot pop an end iterator!"); assert(State->Level > 0 && "Cannot pop an iterator with level < 1"); const directory_iterator end_itr; std::error_code ec; do { if (ec) report_fatal_error("Error incrementing directory iterator."); State->Stack.pop(); --State->Level; } while (!State->Stack.empty() && State->Stack.top().increment(ec) == end_itr); // Check if we are done. If so, create an end iterator. if (State->Stack.empty()) State.reset(); } /// Does not go down into the current directory_entry. void no_push() { State->HasNoPushRequest = true; } bool operator==(const recursive_directory_iterator &RHS) const { return State == RHS.State; } bool operator!=(const recursive_directory_iterator &RHS) const { return !(*this == RHS); } // Other members as required by // C++ Std, 24.1.1 Input iterators [input.iterators] }; /// @} } // end namespace fs } // end namespace sys } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/TimeProfiler.h
//===- llvm/Support/TimeProfiler.h - Hierarchical Time Profiler -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TIME_PROFILER_H #define LLVM_SUPPORT_TIME_PROFILER_H #include "llvm/ADT/STLExtras.h" #include "llvm/Support/raw_ostream.h" namespace llvm { struct TimeTraceProfiler; extern TimeTraceProfiler *TimeTraceProfilerInstance; /// Initialize the time trace profiler. /// This sets up the global \p TimeTraceProfilerInstance /// variable to be the profiler instance. void timeTraceProfilerInitialize(unsigned TimeTraceGranularity); /// Cleanup the time trace profiler, if it was initialized. void timeTraceProfilerCleanup(); /// Is the time trace profiler enabled, i.e. initialized? inline bool timeTraceProfilerEnabled() { return TimeTraceProfilerInstance != nullptr; } /// Write profiling data to output file. /// Data produced is JSON, in Chrome "Trace Event" format, see /// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview void timeTraceProfilerWrite(raw_ostream &OS); /// Manually begin a time section, with the given \p Name and \p Detail. /// Profiler copies the string data, so the pointers can be given into /// temporaries. Time sections can be hierarchical; every Begin must have a /// matching End pair but they can nest. void timeTraceProfilerBegin(StringRef Name, StringRef Detail); void timeTraceProfilerBegin(StringRef Name, llvm::function_ref<std::string()> Detail); /// Manually end the last time section. void timeTraceProfilerEnd(); /// The TimeTraceScope is a helper class to call the begin and end functions /// of the time trace profiler. When the object is constructed, it begins /// the section; and when it is destroyed, it stops it. If the time profiler /// is not initialized, the overhead is a single branch. struct TimeTraceScope { TimeTraceScope(StringRef Name, StringRef Detail) { if (TimeTraceProfilerInstance != nullptr) timeTraceProfilerBegin(Name, Detail); } TimeTraceScope(StringRef Name, llvm::function_ref<std::string()> Detail) { if (TimeTraceProfilerInstance != nullptr) timeTraceProfilerBegin(Name, Detail); } ~TimeTraceScope() { if (TimeTraceProfilerInstance != nullptr) timeTraceProfilerEnd(); } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/PointerLikeTypeTraits.h
//===- llvm/Support/PointerLikeTypeTraits.h - Pointer Traits ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PointerLikeTypeTraits class. This allows data // structures to reason about pointers and other things that are pointer sized. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_POINTERLIKETYPETRAITS_H #define LLVM_SUPPORT_POINTERLIKETYPETRAITS_H #include "llvm/Support/DataTypes.h" namespace llvm { /// PointerLikeTypeTraits - This is a traits object that is used to handle /// pointer types and things that are just wrappers for pointers as a uniform /// entity. template <typename T> class PointerLikeTypeTraits { // getAsVoidPointer // getFromVoidPointer // getNumLowBitsAvailable }; // Provide PointerLikeTypeTraits for non-cvr pointers. template<typename T> class PointerLikeTypeTraits<T*> { public: static inline void *getAsVoidPointer(T* P) { return P; } static inline T *getFromVoidPointer(void *P) { return static_cast<T*>(P); } /// Note, we assume here that malloc returns objects at least 4-byte aligned. /// However, this may be wrong, or pointers may be from something other than /// malloc. In this case, you should specialize this template to reduce this. /// /// All clients should use assertions to do a run-time check to ensure that /// this is actually true. enum { NumLowBitsAvailable = 2 }; }; // Provide PointerLikeTypeTraits for const pointers. template<typename T> class PointerLikeTypeTraits<const T*> { typedef PointerLikeTypeTraits<T*> NonConst; public: static inline const void *getAsVoidPointer(const T* P) { return NonConst::getAsVoidPointer(const_cast<T*>(P)); } static inline const T *getFromVoidPointer(const void *P) { return NonConst::getFromVoidPointer(const_cast<void*>(P)); } enum { NumLowBitsAvailable = NonConst::NumLowBitsAvailable }; }; // Provide PointerLikeTypeTraits for uintptr_t. template<> class PointerLikeTypeTraits<uintptr_t> { public: static inline void *getAsVoidPointer(uintptr_t P) { return reinterpret_cast<void*>(P); } static inline uintptr_t getFromVoidPointer(void *P) { return reinterpret_cast<uintptr_t>(P); } // No bits are available! enum { NumLowBitsAvailable = 0 }; }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ELF.h
//===-- llvm/Support/ELF.h - ELF constants and data structures --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header contains common, non-processor-specific data structures and // constants for the ELF file format. // // The details of the ELF32 bits in this file are largely based on the Tool // Interface Standard (TIS) Executable and Linking Format (ELF) Specification // Version 1.2, May 1995. The ELF64 stuff is based on ELF-64 Object File Format // Version 1.5, Draft 2, May 1998 as well as OpenBSD header files. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ELF_H #define LLVM_SUPPORT_ELF_H #include "llvm/Support/Compiler.h" #include "llvm/Support/DataTypes.h" #include <cstring> namespace llvm { namespace ELF { typedef uint32_t Elf32_Addr; // Program address typedef uint32_t Elf32_Off; // File offset typedef uint16_t Elf32_Half; typedef uint32_t Elf32_Word; typedef int32_t Elf32_Sword; typedef uint64_t Elf64_Addr; typedef uint64_t Elf64_Off; typedef uint16_t Elf64_Half; typedef uint32_t Elf64_Word; typedef int32_t Elf64_Sword; typedef uint64_t Elf64_Xword; typedef int64_t Elf64_Sxword; // Object file magic string. static const char ElfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' }; // e_ident size and indices. enum { EI_MAG0 = 0, // File identification index. EI_MAG1 = 1, // File identification index. EI_MAG2 = 2, // File identification index. EI_MAG3 = 3, // File identification index. EI_CLASS = 4, // File class. EI_DATA = 5, // Data encoding. EI_VERSION = 6, // File version. EI_OSABI = 7, // OS/ABI identification. EI_ABIVERSION = 8, // ABI version. EI_PAD = 9, // Start of padding bytes. EI_NIDENT = 16 // Number of bytes in e_ident. }; struct Elf32_Ehdr { unsigned char e_ident[EI_NIDENT]; // ELF Identification bytes Elf32_Half e_type; // Type of file (see ET_* below) Elf32_Half e_machine; // Required architecture for this file (see EM_*) Elf32_Word e_version; // Must be equal to 1 Elf32_Addr e_entry; // Address to jump to in order to start program Elf32_Off e_phoff; // Program header table's file offset, in bytes Elf32_Off e_shoff; // Section header table's file offset, in bytes Elf32_Word e_flags; // Processor-specific flags Elf32_Half e_ehsize; // Size of ELF header, in bytes Elf32_Half e_phentsize; // Size of an entry in the program header table Elf32_Half e_phnum; // Number of entries in the program header table Elf32_Half e_shentsize; // Size of an entry in the section header table Elf32_Half e_shnum; // Number of entries in the section header table Elf32_Half e_shstrndx; // Sect hdr table index of sect name string table bool checkMagic() const { return (memcmp(e_ident, ElfMagic, strlen(ElfMagic))) == 0; } unsigned char getFileClass() const { return e_ident[EI_CLASS]; } unsigned char getDataEncoding() const { return e_ident[EI_DATA]; } }; // 64-bit ELF header. Fields are the same as for ELF32, but with different // types (see above). struct Elf64_Ehdr { unsigned char e_ident[EI_NIDENT]; Elf64_Half e_type; Elf64_Half e_machine; Elf64_Word e_version; Elf64_Addr e_entry; Elf64_Off e_phoff; Elf64_Off e_shoff; Elf64_Word e_flags; Elf64_Half e_ehsize; Elf64_Half e_phentsize; Elf64_Half e_phnum; Elf64_Half e_shentsize; Elf64_Half e_shnum; Elf64_Half e_shstrndx; bool checkMagic() const { return (memcmp(e_ident, ElfMagic, strlen(ElfMagic))) == 0; } unsigned char getFileClass() const { return e_ident[EI_CLASS]; } unsigned char getDataEncoding() const { return e_ident[EI_DATA]; } }; // File types enum { ET_NONE = 0, // No file type ET_REL = 1, // Relocatable file ET_EXEC = 2, // Executable file ET_DYN = 3, // Shared object file ET_CORE = 4, // Core file ET_LOPROC = 0xff00, // Beginning of processor-specific codes ET_HIPROC = 0xffff // Processor-specific }; // Versioning enum { EV_NONE = 0, EV_CURRENT = 1 }; // Machine architectures // See current registered ELF machine architectures at: // http://www.uxsglobal.com/developers/gabi/latest/ch4.eheader.html enum { EM_NONE = 0, // No machine EM_M32 = 1, // AT&T WE 32100 EM_SPARC = 2, // SPARC EM_386 = 3, // Intel 386 EM_68K = 4, // Motorola 68000 EM_88K = 5, // Motorola 88000 EM_IAMCU = 6, // Intel MCU EM_860 = 7, // Intel 80860 EM_MIPS = 8, // MIPS R3000 EM_S370 = 9, // IBM System/370 EM_MIPS_RS3_LE = 10, // MIPS RS3000 Little-endian EM_PARISC = 15, // Hewlett-Packard PA-RISC EM_VPP500 = 17, // Fujitsu VPP500 EM_SPARC32PLUS = 18, // Enhanced instruction set SPARC EM_960 = 19, // Intel 80960 EM_PPC = 20, // PowerPC EM_PPC64 = 21, // PowerPC64 EM_S390 = 22, // IBM System/390 EM_SPU = 23, // IBM SPU/SPC EM_V800 = 36, // NEC V800 EM_FR20 = 37, // Fujitsu FR20 EM_RH32 = 38, // TRW RH-32 EM_RCE = 39, // Motorola RCE EM_ARM = 40, // ARM EM_ALPHA = 41, // DEC Alpha EM_SH = 42, // Hitachi SH EM_SPARCV9 = 43, // SPARC V9 EM_TRICORE = 44, // Siemens TriCore EM_ARC = 45, // Argonaut RISC Core EM_H8_300 = 46, // Hitachi H8/300 EM_H8_300H = 47, // Hitachi H8/300H EM_H8S = 48, // Hitachi H8S EM_H8_500 = 49, // Hitachi H8/500 EM_IA_64 = 50, // Intel IA-64 processor architecture EM_MIPS_X = 51, // Stanford MIPS-X EM_COLDFIRE = 52, // Motorola ColdFire EM_68HC12 = 53, // Motorola M68HC12 EM_MMA = 54, // Fujitsu MMA Multimedia Accelerator EM_PCP = 55, // Siemens PCP EM_NCPU = 56, // Sony nCPU embedded RISC processor EM_NDR1 = 57, // Denso NDR1 microprocessor EM_STARCORE = 58, // Motorola Star*Core processor EM_ME16 = 59, // Toyota ME16 processor EM_ST100 = 60, // STMicroelectronics ST100 processor EM_TINYJ = 61, // Advanced Logic Corp. TinyJ embedded processor family EM_X86_64 = 62, // AMD x86-64 architecture EM_PDSP = 63, // Sony DSP Processor EM_PDP10 = 64, // Digital Equipment Corp. PDP-10 EM_PDP11 = 65, // Digital Equipment Corp. PDP-11 EM_FX66 = 66, // Siemens FX66 microcontroller EM_ST9PLUS = 67, // STMicroelectronics ST9+ 8/16 bit microcontroller EM_ST7 = 68, // STMicroelectronics ST7 8-bit microcontroller EM_68HC16 = 69, // Motorola MC68HC16 Microcontroller EM_68HC11 = 70, // Motorola MC68HC11 Microcontroller EM_68HC08 = 71, // Motorola MC68HC08 Microcontroller EM_68HC05 = 72, // Motorola MC68HC05 Microcontroller EM_SVX = 73, // Silicon Graphics SVx EM_ST19 = 74, // STMicroelectronics ST19 8-bit microcontroller EM_VAX = 75, // Digital VAX EM_CRIS = 76, // Axis Communications 32-bit embedded processor EM_JAVELIN = 77, // Infineon Technologies 32-bit embedded processor EM_FIREPATH = 78, // Element 14 64-bit DSP Processor EM_ZSP = 79, // LSI Logic 16-bit DSP Processor EM_MMIX = 80, // Donald Knuth's educational 64-bit processor EM_HUANY = 81, // Harvard University machine-independent object files EM_PRISM = 82, // SiTera Prism EM_AVR = 83, // Atmel AVR 8-bit microcontroller EM_FR30 = 84, // Fujitsu FR30 EM_D10V = 85, // Mitsubishi D10V EM_D30V = 86, // Mitsubishi D30V EM_V850 = 87, // NEC v850 EM_M32R = 88, // Mitsubishi M32R EM_MN10300 = 89, // Matsushita MN10300 EM_MN10200 = 90, // Matsushita MN10200 EM_PJ = 91, // picoJava EM_OPENRISC = 92, // OpenRISC 32-bit embedded processor EM_ARC_COMPACT = 93, // ARC International ARCompact processor (old // spelling/synonym: EM_ARC_A5) EM_XTENSA = 94, // Tensilica Xtensa Architecture EM_VIDEOCORE = 95, // Alphamosaic VideoCore processor EM_TMM_GPP = 96, // Thompson Multimedia General Purpose Processor EM_NS32K = 97, // National Semiconductor 32000 series EM_TPC = 98, // Tenor Network TPC processor EM_SNP1K = 99, // Trebia SNP 1000 processor EM_ST200 = 100, // STMicroelectronics (www.st.com) ST200 EM_IP2K = 101, // Ubicom IP2xxx microcontroller family EM_MAX = 102, // MAX Processor EM_CR = 103, // National Semiconductor CompactRISC microprocessor EM_F2MC16 = 104, // Fujitsu F2MC16 EM_MSP430 = 105, // Texas Instruments embedded microcontroller msp430 EM_BLACKFIN = 106, // Analog Devices Blackfin (DSP) processor EM_SE_C33 = 107, // S1C33 Family of Seiko Epson processors EM_SEP = 108, // Sharp embedded microprocessor EM_ARCA = 109, // Arca RISC Microprocessor EM_UNICORE = 110, // Microprocessor series from PKU-Unity Ltd. and MPRC // of Peking University EM_EXCESS = 111, // eXcess: 16/32/64-bit configurable embedded CPU EM_DXP = 112, // Icera Semiconductor Inc. Deep Execution Processor EM_ALTERA_NIOS2 = 113, // Altera Nios II soft-core processor EM_CRX = 114, // National Semiconductor CompactRISC CRX EM_XGATE = 115, // Motorola XGATE embedded processor EM_C166 = 116, // Infineon C16x/XC16x processor EM_M16C = 117, // Renesas M16C series microprocessors EM_DSPIC30F = 118, // Microchip Technology dsPIC30F Digital Signal // Controller EM_CE = 119, // Freescale Communication Engine RISC core EM_M32C = 120, // Renesas M32C series microprocessors EM_TSK3000 = 131, // Altium TSK3000 core EM_RS08 = 132, // Freescale RS08 embedded processor EM_SHARC = 133, // Analog Devices SHARC family of 32-bit DSP // processors EM_ECOG2 = 134, // Cyan Technology eCOG2 microprocessor EM_SCORE7 = 135, // Sunplus S+core7 RISC processor EM_DSP24 = 136, // New Japan Radio (NJR) 24-bit DSP Processor EM_VIDEOCORE3 = 137, // Broadcom VideoCore III processor EM_LATTICEMICO32 = 138, // RISC processor for Lattice FPGA architecture EM_SE_C17 = 139, // Seiko Epson C17 family EM_TI_C6000 = 140, // The Texas Instruments TMS320C6000 DSP family EM_TI_C2000 = 141, // The Texas Instruments TMS320C2000 DSP family EM_TI_C5500 = 142, // The Texas Instruments TMS320C55x DSP family EM_MMDSP_PLUS = 160, // STMicroelectronics 64bit VLIW Data Signal Processor EM_CYPRESS_M8C = 161, // Cypress M8C microprocessor EM_R32C = 162, // Renesas R32C series microprocessors EM_TRIMEDIA = 163, // NXP Semiconductors TriMedia architecture family EM_HEXAGON = 164, // Qualcomm Hexagon processor EM_8051 = 165, // Intel 8051 and variants EM_STXP7X = 166, // STMicroelectronics STxP7x family of configurable // and extensible RISC processors EM_NDS32 = 167, // Andes Technology compact code size embedded RISC // processor family EM_ECOG1 = 168, // Cyan Technology eCOG1X family EM_ECOG1X = 168, // Cyan Technology eCOG1X family EM_MAXQ30 = 169, // Dallas Semiconductor MAXQ30 Core Micro-controllers EM_XIMO16 = 170, // New Japan Radio (NJR) 16-bit DSP Processor EM_MANIK = 171, // M2000 Reconfigurable RISC Microprocessor EM_CRAYNV2 = 172, // Cray Inc. NV2 vector architecture EM_RX = 173, // Renesas RX family EM_METAG = 174, // Imagination Technologies META processor // architecture EM_MCST_ELBRUS = 175, // MCST Elbrus general purpose hardware architecture EM_ECOG16 = 176, // Cyan Technology eCOG16 family EM_CR16 = 177, // National Semiconductor CompactRISC CR16 16-bit // microprocessor EM_ETPU = 178, // Freescale Extended Time Processing Unit EM_SLE9X = 179, // Infineon Technologies SLE9X core EM_L10M = 180, // Intel L10M EM_K10M = 181, // Intel K10M EM_AARCH64 = 183, // ARM AArch64 EM_AVR32 = 185, // Atmel Corporation 32-bit microprocessor family EM_STM8 = 186, // STMicroeletronics STM8 8-bit microcontroller EM_TILE64 = 187, // Tilera TILE64 multicore architecture family EM_TILEPRO = 188, // Tilera TILEPro multicore architecture family EM_CUDA = 190, // NVIDIA CUDA architecture EM_TILEGX = 191, // Tilera TILE-Gx multicore architecture family EM_CLOUDSHIELD = 192, // CloudShield architecture family EM_COREA_1ST = 193, // KIPO-KAIST Core-A 1st generation processor family EM_COREA_2ND = 194, // KIPO-KAIST Core-A 2nd generation processor family EM_ARC_COMPACT2 = 195, // Synopsys ARCompact V2 EM_OPEN8 = 196, // Open8 8-bit RISC soft processor core EM_RL78 = 197, // Renesas RL78 family EM_VIDEOCORE5 = 198, // Broadcom VideoCore V processor EM_78KOR = 199, // Renesas 78KOR family EM_56800EX = 200, // Freescale 56800EX Digital Signal Controller (DSC) EM_BA1 = 201, // Beyond BA1 CPU architecture EM_BA2 = 202, // Beyond BA2 CPU architecture EM_XCORE = 203, // XMOS xCORE processor family EM_MCHP_PIC = 204, // Microchip 8-bit PIC(r) family EM_INTEL205 = 205, // Reserved by Intel EM_INTEL206 = 206, // Reserved by Intel EM_INTEL207 = 207, // Reserved by Intel EM_INTEL208 = 208, // Reserved by Intel EM_INTEL209 = 209, // Reserved by Intel EM_KM32 = 210, // KM211 KM32 32-bit processor EM_KMX32 = 211, // KM211 KMX32 32-bit processor EM_KMX16 = 212, // KM211 KMX16 16-bit processor EM_KMX8 = 213, // KM211 KMX8 8-bit processor EM_KVARC = 214, // KM211 KVARC processor EM_CDP = 215, // Paneve CDP architecture family EM_COGE = 216, // Cognitive Smart Memory Processor EM_COOL = 217, // iCelero CoolEngine EM_NORC = 218, // Nanoradio Optimized RISC EM_CSR_KALIMBA = 219, // CSR Kalimba architecture family EM_AMDGPU = 224 // AMD GPU architecture }; // Object file classes. enum { ELFCLASSNONE = 0, ELFCLASS32 = 1, // 32-bit object file ELFCLASS64 = 2 // 64-bit object file }; // Object file byte orderings. enum { ELFDATANONE = 0, // Invalid data encoding. ELFDATA2LSB = 1, // Little-endian object file ELFDATA2MSB = 2 // Big-endian object file }; // OS ABI identification. enum { ELFOSABI_NONE = 0, // UNIX System V ABI ELFOSABI_HPUX = 1, // HP-UX operating system ELFOSABI_NETBSD = 2, // NetBSD ELFOSABI_GNU = 3, // GNU/Linux ELFOSABI_LINUX = 3, // Historical alias for ELFOSABI_GNU. ELFOSABI_HURD = 4, // GNU/Hurd ELFOSABI_SOLARIS = 6, // Solaris ELFOSABI_AIX = 7, // AIX ELFOSABI_IRIX = 8, // IRIX ELFOSABI_FREEBSD = 9, // FreeBSD ELFOSABI_TRU64 = 10, // TRU64 UNIX ELFOSABI_MODESTO = 11, // Novell Modesto ELFOSABI_OPENBSD = 12, // OpenBSD ELFOSABI_OPENVMS = 13, // OpenVMS ELFOSABI_NSK = 14, // Hewlett-Packard Non-Stop Kernel ELFOSABI_AROS = 15, // AROS ELFOSABI_FENIXOS = 16, // FenixOS ELFOSABI_CLOUDABI = 17, // Nuxi CloudABI ELFOSABI_C6000_ELFABI = 64, // Bare-metal TMS320C6000 ELFOSABI_AMDGPU_HSA = 64, // AMD HSA runtime ELFOSABI_C6000_LINUX = 65, // Linux TMS320C6000 ELFOSABI_ARM = 97, // ARM ELFOSABI_STANDALONE = 255 // Standalone (embedded) application }; #define ELF_RELOC(name, value) name = value, // X86_64 relocations. enum { #include "ELFRelocs/x86_64.def" }; // i386 relocations. enum { #include "ELFRelocs/i386.def" }; // ELF Relocation types for PPC32 enum { #include "ELFRelocs/PowerPC.def" }; // Specific e_flags for PPC64 enum { // e_flags bits specifying ABI: // 1 for original ABI using function descriptors, // 2 for revised ABI without function descriptors, // 0 for unspecified or not using any features affected by the differences. EF_PPC64_ABI = 3 }; // Special values for the st_other field in the symbol table entry for PPC64. enum { STO_PPC64_LOCAL_BIT = 5, STO_PPC64_LOCAL_MASK = (7 << STO_PPC64_LOCAL_BIT) }; static inline int64_t decodePPC64LocalEntryOffset(unsigned Other) { unsigned Val = (Other & STO_PPC64_LOCAL_MASK) >> STO_PPC64_LOCAL_BIT; return ((1 << Val) >> 2) << 2; } static inline unsigned encodePPC64LocalEntryOffset(int64_t Offset) { unsigned Val = (Offset >= 4 * 4 ? (Offset >= 8 * 4 ? (Offset >= 16 * 4 ? 6 : 5) : 4) : (Offset >= 2 * 4 ? 3 : (Offset >= 1 * 4 ? 2 : 0))); return Val << STO_PPC64_LOCAL_BIT; } // ELF Relocation types for PPC64 enum { #include "ELFRelocs/PowerPC64.def" }; // ELF Relocation types for AArch64 enum { #include "ELFRelocs/AArch64.def" }; // ARM Specific e_flags enum : unsigned { EF_ARM_SOFT_FLOAT = 0x00000200U, EF_ARM_VFP_FLOAT = 0x00000400U, EF_ARM_EABI_UNKNOWN = 0x00000000U, EF_ARM_EABI_VER1 = 0x01000000U, EF_ARM_EABI_VER2 = 0x02000000U, EF_ARM_EABI_VER3 = 0x03000000U, EF_ARM_EABI_VER4 = 0x04000000U, EF_ARM_EABI_VER5 = 0x05000000U, EF_ARM_EABIMASK = 0xFF000000U }; // ELF Relocation types for ARM enum { #include "ELFRelocs/ARM.def" }; // Mips Specific e_flags enum : unsigned { EF_MIPS_NOREORDER = 0x00000001, // Don't reorder instructions EF_MIPS_PIC = 0x00000002, // Position independent code EF_MIPS_CPIC = 0x00000004, // Call object with Position independent code EF_MIPS_ABI2 = 0x00000020, // File uses N32 ABI EF_MIPS_32BITMODE = 0x00000100, // Code compiled for a 64-bit machine // in 32-bit mode EF_MIPS_FP64 = 0x00000200, // Code compiled for a 32-bit machine // but uses 64-bit FP registers EF_MIPS_NAN2008 = 0x00000400, // Uses IEE 754-2008 NaN encoding // ABI flags EF_MIPS_ABI_O32 = 0x00001000, // This file follows the first MIPS 32 bit ABI EF_MIPS_ABI_O64 = 0x00002000, // O32 ABI extended for 64-bit architecture. EF_MIPS_ABI_EABI32 = 0x00003000, // EABI in 32 bit mode. EF_MIPS_ABI_EABI64 = 0x00004000, // EABI in 64 bit mode. EF_MIPS_ABI = 0x0000f000, // Mask for selecting EF_MIPS_ABI_ variant. // MIPS machine variant EF_MIPS_MACH_3900 = 0x00810000, // Toshiba R3900 EF_MIPS_MACH_4010 = 0x00820000, // LSI R4010 EF_MIPS_MACH_4100 = 0x00830000, // NEC VR4100 EF_MIPS_MACH_4650 = 0x00850000, // MIPS R4650 EF_MIPS_MACH_4120 = 0x00870000, // NEC VR4120 EF_MIPS_MACH_4111 = 0x00880000, // NEC VR4111/VR4181 EF_MIPS_MACH_SB1 = 0x008a0000, // Broadcom SB-1 EF_MIPS_MACH_OCTEON = 0x008b0000, // Cavium Networks Octeon EF_MIPS_MACH_XLR = 0x008c0000, // RMI Xlr EF_MIPS_MACH_OCTEON2 = 0x008d0000, // Cavium Networks Octeon2 EF_MIPS_MACH_OCTEON3 = 0x008e0000, // Cavium Networks Octeon3 EF_MIPS_MACH_5400 = 0x00910000, // NEC VR5400 EF_MIPS_MACH_5900 = 0x00920000, // MIPS R5900 EF_MIPS_MACH_5500 = 0x00980000, // NEC VR5500 EF_MIPS_MACH_9000 = 0x00990000, // Unknown EF_MIPS_MACH_LS2E = 0x00a00000, // ST Microelectronics Loongson 2E EF_MIPS_MACH_LS2F = 0x00a10000, // ST Microelectronics Loongson 2F EF_MIPS_MACH_LS3A = 0x00a20000, // Loongson 3A EF_MIPS_MACH = 0x00ff0000, // EF_MIPS_MACH_xxx selection mask // ARCH_ASE EF_MIPS_MICROMIPS = 0x02000000, // microMIPS EF_MIPS_ARCH_ASE_M16 = 0x04000000, // Has Mips-16 ISA extensions EF_MIPS_ARCH_ASE_MDMX = 0x08000000, // Has MDMX multimedia extensions EF_MIPS_ARCH_ASE = 0x0f000000, // Mask for EF_MIPS_ARCH_ASE_xxx flags // ARCH EF_MIPS_ARCH_1 = 0x00000000, // MIPS1 instruction set EF_MIPS_ARCH_2 = 0x10000000, // MIPS2 instruction set EF_MIPS_ARCH_3 = 0x20000000, // MIPS3 instruction set EF_MIPS_ARCH_4 = 0x30000000, // MIPS4 instruction set EF_MIPS_ARCH_5 = 0x40000000, // MIPS5 instruction set EF_MIPS_ARCH_32 = 0x50000000, // MIPS32 instruction set per linux not elf.h EF_MIPS_ARCH_64 = 0x60000000, // MIPS64 instruction set per linux not elf.h EF_MIPS_ARCH_32R2 = 0x70000000, // mips32r2, mips32r3, mips32r5 EF_MIPS_ARCH_64R2 = 0x80000000, // mips64r2, mips64r3, mips64r5 EF_MIPS_ARCH_32R6 = 0x90000000, // mips32r6 EF_MIPS_ARCH_64R6 = 0xa0000000, // mips64r6 EF_MIPS_ARCH = 0xf0000000 // Mask for applying EF_MIPS_ARCH_ variant }; // ELF Relocation types for Mips enum { #include "ELFRelocs/Mips.def" }; // Special values for the st_other field in the symbol table entry for MIPS. enum { STO_MIPS_OPTIONAL = 0x04, // Symbol whose definition is optional STO_MIPS_PLT = 0x08, // PLT entry related dynamic table record STO_MIPS_PIC = 0x20, // PIC func in an object mixes PIC/non-PIC STO_MIPS_MICROMIPS = 0x80, // MIPS Specific ISA for MicroMips STO_MIPS_MIPS16 = 0xf0 // MIPS Specific ISA for Mips16 }; // .MIPS.options section descriptor kinds enum { ODK_NULL = 0, // Undefined ODK_REGINFO = 1, // Register usage information ODK_EXCEPTIONS = 2, // Exception processing options ODK_PAD = 3, // Section padding options ODK_HWPATCH = 4, // Hardware patches applied ODK_FILL = 5, // Linker fill value ODK_TAGS = 6, // Space for tool identification ODK_HWAND = 7, // Hardware AND patches applied ODK_HWOR = 8, // Hardware OR patches applied ODK_GP_GROUP = 9, // GP group to use for text/data sections ODK_IDENT = 10, // ID information ODK_PAGESIZE = 11 // Page size information }; // Hexagon Specific e_flags // Release 5 ABI enum { // Object processor version flags, bits[3:0] EF_HEXAGON_MACH_V2 = 0x00000001, // Hexagon V2 EF_HEXAGON_MACH_V3 = 0x00000002, // Hexagon V3 EF_HEXAGON_MACH_V4 = 0x00000003, // Hexagon V4 EF_HEXAGON_MACH_V5 = 0x00000004, // Hexagon V5 // Highest ISA version flags EF_HEXAGON_ISA_MACH = 0x00000000, // Same as specified in bits[3:0] // of e_flags EF_HEXAGON_ISA_V2 = 0x00000010, // Hexagon V2 ISA EF_HEXAGON_ISA_V3 = 0x00000020, // Hexagon V3 ISA EF_HEXAGON_ISA_V4 = 0x00000030, // Hexagon V4 ISA EF_HEXAGON_ISA_V5 = 0x00000040 // Hexagon V5 ISA }; // Hexagon specific Section indexes for common small data // Release 5 ABI enum { SHN_HEXAGON_SCOMMON = 0xff00, // Other access sizes SHN_HEXAGON_SCOMMON_1 = 0xff01, // Byte-sized access SHN_HEXAGON_SCOMMON_2 = 0xff02, // Half-word-sized access SHN_HEXAGON_SCOMMON_4 = 0xff03, // Word-sized access SHN_HEXAGON_SCOMMON_8 = 0xff04 // Double-word-size access }; // ELF Relocation types for Hexagon enum { #include "ELFRelocs/Hexagon.def" }; // ELF Relocation types for S390/zSeries enum { #include "ELFRelocs/SystemZ.def" }; // ELF Relocation type for Sparc. enum { #include "ELFRelocs/Sparc.def" }; #undef ELF_RELOC // Section header. struct Elf32_Shdr { Elf32_Word sh_name; // Section name (index into string table) Elf32_Word sh_type; // Section type (SHT_*) Elf32_Word sh_flags; // Section flags (SHF_*) Elf32_Addr sh_addr; // Address where section is to be loaded Elf32_Off sh_offset; // File offset of section data, in bytes Elf32_Word sh_size; // Size of section, in bytes Elf32_Word sh_link; // Section type-specific header table index link Elf32_Word sh_info; // Section type-specific extra information Elf32_Word sh_addralign; // Section address alignment Elf32_Word sh_entsize; // Size of records contained within the section }; // Section header for ELF64 - same fields as ELF32, different types. struct Elf64_Shdr { Elf64_Word sh_name; Elf64_Word sh_type; Elf64_Xword sh_flags; Elf64_Addr sh_addr; Elf64_Off sh_offset; Elf64_Xword sh_size; Elf64_Word sh_link; Elf64_Word sh_info; Elf64_Xword sh_addralign; Elf64_Xword sh_entsize; }; // Special section indices. enum { SHN_UNDEF = 0, // Undefined, missing, irrelevant, or meaningless SHN_LORESERVE = 0xff00, // Lowest reserved index SHN_LOPROC = 0xff00, // Lowest processor-specific index SHN_HIPROC = 0xff1f, // Highest processor-specific index SHN_LOOS = 0xff20, // Lowest operating system-specific index SHN_HIOS = 0xff3f, // Highest operating system-specific index SHN_ABS = 0xfff1, // Symbol has absolute value; does not need relocation SHN_COMMON = 0xfff2, // FORTRAN COMMON or C external global variables SHN_XINDEX = 0xffff, // Mark that the index is >= SHN_LORESERVE SHN_HIRESERVE = 0xffff // Highest reserved index }; // Section types. enum : unsigned { SHT_NULL = 0, // No associated section (inactive entry). SHT_PROGBITS = 1, // Program-defined contents. SHT_SYMTAB = 2, // Symbol table. SHT_STRTAB = 3, // String table. SHT_RELA = 4, // Relocation entries; explicit addends. SHT_HASH = 5, // Symbol hash table. SHT_DYNAMIC = 6, // Information for dynamic linking. SHT_NOTE = 7, // Information about the file. SHT_NOBITS = 8, // Data occupies no space in the file. SHT_REL = 9, // Relocation entries; no explicit addends. SHT_SHLIB = 10, // Reserved. SHT_DYNSYM = 11, // Symbol table. SHT_INIT_ARRAY = 14, // Pointers to initialization functions. SHT_FINI_ARRAY = 15, // Pointers to termination functions. SHT_PREINIT_ARRAY = 16, // Pointers to pre-init functions. SHT_GROUP = 17, // Section group. SHT_SYMTAB_SHNDX = 18, // Indices for SHN_XINDEX entries. SHT_LOOS = 0x60000000, // Lowest operating system-specific type. SHT_GNU_ATTRIBUTES= 0x6ffffff5, // Object attributes. SHT_GNU_HASH = 0x6ffffff6, // GNU-style hash table. SHT_GNU_verdef = 0x6ffffffd, // GNU version definitions. SHT_GNU_verneed = 0x6ffffffe, // GNU version references. SHT_GNU_versym = 0x6fffffff, // GNU symbol versions table. SHT_HIOS = 0x6fffffff, // Highest operating system-specific type. SHT_LOPROC = 0x70000000, // Lowest processor arch-specific type. // Fixme: All this is duplicated in MCSectionELF. Why?? // Exception Index table SHT_ARM_EXIDX = 0x70000001U, // BPABI DLL dynamic linking pre-emption map SHT_ARM_PREEMPTMAP = 0x70000002U, // Object file compatibility attributes SHT_ARM_ATTRIBUTES = 0x70000003U, SHT_ARM_DEBUGOVERLAY = 0x70000004U, SHT_ARM_OVERLAYSECTION = 0x70000005U, SHT_HEX_ORDERED = 0x70000000, // Link editor is to sort the entries in // this section based on their sizes SHT_X86_64_UNWIND = 0x70000001, // Unwind information SHT_MIPS_REGINFO = 0x70000006, // Register usage information SHT_MIPS_OPTIONS = 0x7000000d, // General options SHT_MIPS_ABIFLAGS = 0x7000002a, // ABI information. SHT_HIPROC = 0x7fffffff, // Highest processor arch-specific type. SHT_LOUSER = 0x80000000, // Lowest type reserved for applications. SHT_HIUSER = 0xffffffff // Highest type reserved for applications. }; // Section flags. enum : unsigned { // Section data should be writable during execution. SHF_WRITE = 0x1, // Section occupies memory during program execution. SHF_ALLOC = 0x2, // Section contains executable machine instructions. SHF_EXECINSTR = 0x4, // The data in this section may be merged. SHF_MERGE = 0x10, // The data in this section is null-terminated strings. SHF_STRINGS = 0x20, // A field in this section holds a section header table index. SHF_INFO_LINK = 0x40U, // Adds special ordering requirements for link editors. SHF_LINK_ORDER = 0x80U, // This section requires special OS-specific processing to avoid incorrect // behavior. SHF_OS_NONCONFORMING = 0x100U, // This section is a member of a section group. SHF_GROUP = 0x200U, // This section holds Thread-Local Storage. SHF_TLS = 0x400U, // This section is excluded from the final executable or shared library. SHF_EXCLUDE = 0x80000000U, // Start of target-specific flags. /// XCORE_SHF_CP_SECTION - All sections with the "c" flag are grouped /// together by the linker to form the constant pool and the cp register is /// set to the start of the constant pool by the boot code. XCORE_SHF_CP_SECTION = 0x800U, /// XCORE_SHF_DP_SECTION - All sections with the "d" flag are grouped /// together by the linker to form the data section and the dp register is /// set to the start of the section by the boot code. XCORE_SHF_DP_SECTION = 0x1000U, SHF_MASKOS = 0x0ff00000, // Bits indicating processor-specific flags. SHF_MASKPROC = 0xf0000000, // If an object file section does not have this flag set, then it may not hold // more than 2GB and can be freely referred to in objects using smaller code // models. Otherwise, only objects using larger code models can refer to them. // For example, a medium code model object can refer to data in a section that // sets this flag besides being able to refer to data in a section that does // not set it; likewise, a small code model object can refer only to code in a // section that does not set this flag. SHF_X86_64_LARGE = 0x10000000, // All sections with the GPREL flag are grouped into a global data area // for faster accesses SHF_HEX_GPREL = 0x10000000, // Section contains text/data which may be replicated in other sections. // Linker must retain only one copy. SHF_MIPS_NODUPES = 0x01000000, // Linker must generate implicit hidden weak names. SHF_MIPS_NAMES = 0x02000000, // Section data local to process. SHF_MIPS_LOCAL = 0x04000000, // Do not strip this section. SHF_MIPS_NOSTRIP = 0x08000000, // Section must be part of global data area. SHF_MIPS_GPREL = 0x10000000, // This section should be merged. SHF_MIPS_MERGE = 0x20000000, // Address size to be inferred from section entry size. SHF_MIPS_ADDR = 0x40000000, // Section data is string data by default. SHF_MIPS_STRING = 0x80000000 }; // Section Group Flags enum : unsigned { GRP_COMDAT = 0x1, GRP_MASKOS = 0x0ff00000, GRP_MASKPROC = 0xf0000000 }; // Symbol table entries for ELF32. struct Elf32_Sym { Elf32_Word st_name; // Symbol name (index into string table) Elf32_Addr st_value; // Value or address associated with the symbol Elf32_Word st_size; // Size of the symbol unsigned char st_info; // Symbol's type and binding attributes unsigned char st_other; // Must be zero; reserved Elf32_Half st_shndx; // Which section (header table index) it's defined in // These accessors and mutators correspond to the ELF32_ST_BIND, // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification: unsigned char getBinding() const { return st_info >> 4; } unsigned char getType() const { return st_info & 0x0f; } void setBinding(unsigned char b) { setBindingAndType(b, getType()); } void setType(unsigned char t) { setBindingAndType(getBinding(), t); } void setBindingAndType(unsigned char b, unsigned char t) { st_info = (b << 4) + (t & 0x0f); } }; // Symbol table entries for ELF64. struct Elf64_Sym { Elf64_Word st_name; // Symbol name (index into string table) unsigned char st_info; // Symbol's type and binding attributes unsigned char st_other; // Must be zero; reserved Elf64_Half st_shndx; // Which section (header tbl index) it's defined in Elf64_Addr st_value; // Value or address associated with the symbol Elf64_Xword st_size; // Size of the symbol // These accessors and mutators are identical to those defined for ELF32 // symbol table entries. unsigned char getBinding() const { return st_info >> 4; } unsigned char getType() const { return st_info & 0x0f; } void setBinding(unsigned char b) { setBindingAndType(b, getType()); } void setType(unsigned char t) { setBindingAndType(getBinding(), t); } void setBindingAndType(unsigned char b, unsigned char t) { st_info = (b << 4) + (t & 0x0f); } }; // The size (in bytes) of symbol table entries. enum { SYMENTRY_SIZE32 = 16, // 32-bit symbol entry size SYMENTRY_SIZE64 = 24 // 64-bit symbol entry size. }; // Symbol bindings. enum { STB_LOCAL = 0, // Local symbol, not visible outside obj file containing def STB_GLOBAL = 1, // Global symbol, visible to all object files being combined STB_WEAK = 2, // Weak symbol, like global but lower-precedence STB_GNU_UNIQUE = 10, STB_LOOS = 10, // Lowest operating system-specific binding type STB_HIOS = 12, // Highest operating system-specific binding type STB_LOPROC = 13, // Lowest processor-specific binding type STB_HIPROC = 15 // Highest processor-specific binding type }; // Symbol types. enum { STT_NOTYPE = 0, // Symbol's type is not specified STT_OBJECT = 1, // Symbol is a data object (variable, array, etc.) STT_FUNC = 2, // Symbol is executable code (function, etc.) STT_SECTION = 3, // Symbol refers to a section STT_FILE = 4, // Local, absolute symbol that refers to a file STT_COMMON = 5, // An uninitialized common block STT_TLS = 6, // Thread local data object STT_GNU_IFUNC = 10, // GNU indirect function STT_LOOS = 10, // Lowest operating system-specific symbol type STT_HIOS = 12, // Highest operating system-specific symbol type STT_LOPROC = 13, // Lowest processor-specific symbol type STT_HIPROC = 15 // Highest processor-specific symbol type }; enum { STV_DEFAULT = 0, // Visibility is specified by binding type STV_INTERNAL = 1, // Defined by processor supplements STV_HIDDEN = 2, // Not visible to other components STV_PROTECTED = 3 // Visible in other components but not preemptable }; // Symbol number. enum { STN_UNDEF = 0 }; // Special relocation symbols used in the MIPS64 ELF relocation entries enum { RSS_UNDEF = 0, // None RSS_GP = 1, // Value of gp RSS_GP0 = 2, // Value of gp used to create object being relocated RSS_LOC = 3 // Address of location being relocated }; // Relocation entry, without explicit addend. struct Elf32_Rel { Elf32_Addr r_offset; // Location (file byte offset, or program virtual addr) Elf32_Word r_info; // Symbol table index and type of relocation to apply // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE, // and ELF32_R_INFO macros defined in the ELF specification: Elf32_Word getSymbol() const { return (r_info >> 8); } unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); } void setSymbol(Elf32_Word s) { setSymbolAndType(s, getType()); } void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); } void setSymbolAndType(Elf32_Word s, unsigned char t) { r_info = (s << 8) + t; } }; // Relocation entry with explicit addend. struct Elf32_Rela { Elf32_Addr r_offset; // Location (file byte offset, or program virtual addr) Elf32_Word r_info; // Symbol table index and type of relocation to apply Elf32_Sword r_addend; // Compute value for relocatable field by adding this // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE, // and ELF32_R_INFO macros defined in the ELF specification: Elf32_Word getSymbol() const { return (r_info >> 8); } unsigned char getType() const { return (unsigned char) (r_info & 0x0ff); } void setSymbol(Elf32_Word s) { setSymbolAndType(s, getType()); } void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); } void setSymbolAndType(Elf32_Word s, unsigned char t) { r_info = (s << 8) + t; } }; // Relocation entry, without explicit addend. struct Elf64_Rel { Elf64_Addr r_offset; // Location (file byte offset, or program virtual addr). Elf64_Xword r_info; // Symbol table index and type of relocation to apply. // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE, // and ELF64_R_INFO macros defined in the ELF specification: Elf64_Word getSymbol() const { return (r_info >> 32); } Elf64_Word getType() const { return (Elf64_Word) (r_info & 0xffffffffL); } void setSymbol(Elf64_Word s) { setSymbolAndType(s, getType()); } void setType(Elf64_Word t) { setSymbolAndType(getSymbol(), t); } void setSymbolAndType(Elf64_Word s, Elf64_Word t) { r_info = ((Elf64_Xword)s << 32) + (t&0xffffffffL); } }; // Relocation entry with explicit addend. struct Elf64_Rela { Elf64_Addr r_offset; // Location (file byte offset, or program virtual addr). Elf64_Xword r_info; // Symbol table index and type of relocation to apply. Elf64_Sxword r_addend; // Compute value for relocatable field by adding this. // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE, // and ELF64_R_INFO macros defined in the ELF specification: Elf64_Word getSymbol() const { return (r_info >> 32); } Elf64_Word getType() const { return (Elf64_Word) (r_info & 0xffffffffL); } void setSymbol(Elf64_Word s) { setSymbolAndType(s, getType()); } void setType(Elf64_Word t) { setSymbolAndType(getSymbol(), t); } void setSymbolAndType(Elf64_Word s, Elf64_Word t) { r_info = ((Elf64_Xword)s << 32) + (t&0xffffffffL); } }; // Program header for ELF32. struct Elf32_Phdr { Elf32_Word p_type; // Type of segment Elf32_Off p_offset; // File offset where segment is located, in bytes Elf32_Addr p_vaddr; // Virtual address of beginning of segment Elf32_Addr p_paddr; // Physical address of beginning of segment (OS-specific) Elf32_Word p_filesz; // Num. of bytes in file image of segment (may be zero) Elf32_Word p_memsz; // Num. of bytes in mem image of segment (may be zero) Elf32_Word p_flags; // Segment flags Elf32_Word p_align; // Segment alignment constraint }; // Program header for ELF64. struct Elf64_Phdr { Elf64_Word p_type; // Type of segment Elf64_Word p_flags; // Segment flags Elf64_Off p_offset; // File offset where segment is located, in bytes Elf64_Addr p_vaddr; // Virtual address of beginning of segment Elf64_Addr p_paddr; // Physical addr of beginning of segment (OS-specific) Elf64_Xword p_filesz; // Num. of bytes in file image of segment (may be zero) Elf64_Xword p_memsz; // Num. of bytes in mem image of segment (may be zero) Elf64_Xword p_align; // Segment alignment constraint }; // Segment types. enum { PT_NULL = 0, // Unused segment. PT_LOAD = 1, // Loadable segment. PT_DYNAMIC = 2, // Dynamic linking information. PT_INTERP = 3, // Interpreter pathname. PT_NOTE = 4, // Auxiliary information. PT_SHLIB = 5, // Reserved. PT_PHDR = 6, // The program header table itself. PT_TLS = 7, // The thread-local storage template. PT_LOOS = 0x60000000, // Lowest operating system-specific pt entry type. PT_HIOS = 0x6fffffff, // Highest operating system-specific pt entry type. PT_LOPROC = 0x70000000, // Lowest processor-specific program hdr entry type. PT_HIPROC = 0x7fffffff, // Highest processor-specific program hdr entry type. // x86-64 program header types. // These all contain stack unwind tables. PT_GNU_EH_FRAME = 0x6474e550, PT_SUNW_EH_FRAME = 0x6474e550, PT_SUNW_UNWIND = 0x6464e550, PT_GNU_STACK = 0x6474e551, // Indicates stack executability. PT_GNU_RELRO = 0x6474e552, // Read-only after relocation. // ARM program header types. PT_ARM_ARCHEXT = 0x70000000, // Platform architecture compatibility info // These all contain stack unwind tables. PT_ARM_EXIDX = 0x70000001, PT_ARM_UNWIND = 0x70000001, // MIPS program header types. PT_MIPS_REGINFO = 0x70000000, // Register usage information. PT_MIPS_RTPROC = 0x70000001, // Runtime procedure table. PT_MIPS_OPTIONS = 0x70000002, // Options segment. PT_MIPS_ABIFLAGS = 0x70000003 // Abiflags segment. }; // Segment flag bits. enum : unsigned { PF_X = 1, // Execute PF_W = 2, // Write PF_R = 4, // Read PF_MASKOS = 0x0ff00000,// Bits for operating system-specific semantics. PF_MASKPROC = 0xf0000000 // Bits for processor-specific semantics. }; // Dynamic table entry for ELF32. struct Elf32_Dyn { Elf32_Sword d_tag; // Type of dynamic table entry. union { Elf32_Word d_val; // Integer value of entry. Elf32_Addr d_ptr; // Pointer value of entry. } d_un; }; // Dynamic table entry for ELF64. struct Elf64_Dyn { Elf64_Sxword d_tag; // Type of dynamic table entry. union { Elf64_Xword d_val; // Integer value of entry. Elf64_Addr d_ptr; // Pointer value of entry. } d_un; }; // Dynamic table entry tags. enum { DT_NULL = 0, // Marks end of dynamic array. DT_NEEDED = 1, // String table offset of needed library. DT_PLTRELSZ = 2, // Size of relocation entries in PLT. DT_PLTGOT = 3, // Address associated with linkage table. DT_HASH = 4, // Address of symbolic hash table. DT_STRTAB = 5, // Address of dynamic string table. DT_SYMTAB = 6, // Address of dynamic symbol table. DT_RELA = 7, // Address of relocation table (Rela entries). DT_RELASZ = 8, // Size of Rela relocation table. DT_RELAENT = 9, // Size of a Rela relocation entry. DT_STRSZ = 10, // Total size of the string table. DT_SYMENT = 11, // Size of a symbol table entry. DT_INIT = 12, // Address of initialization function. DT_FINI = 13, // Address of termination function. DT_SONAME = 14, // String table offset of a shared objects name. DT_RPATH = 15, // String table offset of library search path. DT_SYMBOLIC = 16, // Changes symbol resolution algorithm. DT_REL = 17, // Address of relocation table (Rel entries). DT_RELSZ = 18, // Size of Rel relocation table. DT_RELENT = 19, // Size of a Rel relocation entry. DT_PLTREL = 20, // Type of relocation entry used for linking. DT_DEBUG = 21, // Reserved for debugger. DT_TEXTREL = 22, // Relocations exist for non-writable segments. DT_JMPREL = 23, // Address of relocations associated with PLT. DT_BIND_NOW = 24, // Process all relocations before execution. DT_INIT_ARRAY = 25, // Pointer to array of initialization functions. DT_FINI_ARRAY = 26, // Pointer to array of termination functions. DT_INIT_ARRAYSZ = 27, // Size of DT_INIT_ARRAY. DT_FINI_ARRAYSZ = 28, // Size of DT_FINI_ARRAY. DT_RUNPATH = 29, // String table offset of lib search path. DT_FLAGS = 30, // Flags. DT_ENCODING = 32, // Values from here to DT_LOOS follow the rules // for the interpretation of the d_un union. DT_PREINIT_ARRAY = 32, // Pointer to array of preinit functions. DT_PREINIT_ARRAYSZ = 33, // Size of the DT_PREINIT_ARRAY array. DT_LOOS = 0x60000000, // Start of environment specific tags. DT_HIOS = 0x6FFFFFFF, // End of environment specific tags. DT_LOPROC = 0x70000000, // Start of processor specific tags. DT_HIPROC = 0x7FFFFFFF, // End of processor specific tags. DT_GNU_HASH = 0x6FFFFEF5, // Reference to the GNU hash table. DT_RELACOUNT = 0x6FFFFFF9, // ELF32_Rela count. DT_RELCOUNT = 0x6FFFFFFA, // ELF32_Rel count. DT_FLAGS_1 = 0X6FFFFFFB, // Flags_1. DT_VERSYM = 0x6FFFFFF0, // The address of .gnu.version section. DT_VERDEF = 0X6FFFFFFC, // The address of the version definition table. DT_VERDEFNUM = 0X6FFFFFFD, // The number of entries in DT_VERDEF. DT_VERNEED = 0X6FFFFFFE, // The address of the version Dependency table. DT_VERNEEDNUM = 0X6FFFFFFF, // The number of entries in DT_VERNEED. // Mips specific dynamic table entry tags. DT_MIPS_RLD_VERSION = 0x70000001, // 32 bit version number for runtime // linker interface. DT_MIPS_TIME_STAMP = 0x70000002, // Time stamp. DT_MIPS_ICHECKSUM = 0x70000003, // Checksum of external strings // and common sizes. DT_MIPS_IVERSION = 0x70000004, // Index of version string // in string table. DT_MIPS_FLAGS = 0x70000005, // 32 bits of flags. DT_MIPS_BASE_ADDRESS = 0x70000006, // Base address of the segment. DT_MIPS_MSYM = 0x70000007, // Address of .msym section. DT_MIPS_CONFLICT = 0x70000008, // Address of .conflict section. DT_MIPS_LIBLIST = 0x70000009, // Address of .liblist section. DT_MIPS_LOCAL_GOTNO = 0x7000000a, // Number of local global offset // table entries. DT_MIPS_CONFLICTNO = 0x7000000b, // Number of entries // in the .conflict section. DT_MIPS_LIBLISTNO = 0x70000010, // Number of entries // in the .liblist section. DT_MIPS_SYMTABNO = 0x70000011, // Number of entries // in the .dynsym section. DT_MIPS_UNREFEXTNO = 0x70000012, // Index of first external dynamic symbol // not referenced locally. DT_MIPS_GOTSYM = 0x70000013, // Index of first dynamic symbol // in global offset table. DT_MIPS_HIPAGENO = 0x70000014, // Number of page table entries // in global offset table. DT_MIPS_RLD_MAP = 0x70000016, // Address of run time loader map, // used for debugging. DT_MIPS_DELTA_CLASS = 0x70000017, // Delta C++ class definition. DT_MIPS_DELTA_CLASS_NO = 0x70000018, // Number of entries // in DT_MIPS_DELTA_CLASS. DT_MIPS_DELTA_INSTANCE = 0x70000019, // Delta C++ class instances. DT_MIPS_DELTA_INSTANCE_NO = 0x7000001A, // Number of entries // in DT_MIPS_DELTA_INSTANCE. DT_MIPS_DELTA_RELOC = 0x7000001B, // Delta relocations. DT_MIPS_DELTA_RELOC_NO = 0x7000001C, // Number of entries // in DT_MIPS_DELTA_RELOC. DT_MIPS_DELTA_SYM = 0x7000001D, // Delta symbols that Delta // relocations refer to. DT_MIPS_DELTA_SYM_NO = 0x7000001E, // Number of entries // in DT_MIPS_DELTA_SYM. DT_MIPS_DELTA_CLASSSYM = 0x70000020, // Delta symbols that hold // class declarations. DT_MIPS_DELTA_CLASSSYM_NO = 0x70000021, // Number of entries // in DT_MIPS_DELTA_CLASSSYM. DT_MIPS_CXX_FLAGS = 0x70000022, // Flags indicating information // about C++ flavor. DT_MIPS_PIXIE_INIT = 0x70000023, // Pixie information. DT_MIPS_SYMBOL_LIB = 0x70000024, // Address of .MIPS.symlib DT_MIPS_LOCALPAGE_GOTIDX = 0x70000025, // The GOT index of the first PTE // for a segment DT_MIPS_LOCAL_GOTIDX = 0x70000026, // The GOT index of the first PTE // for a local symbol DT_MIPS_HIDDEN_GOTIDX = 0x70000027, // The GOT index of the first PTE // for a hidden symbol DT_MIPS_PROTECTED_GOTIDX = 0x70000028, // The GOT index of the first PTE // for a protected symbol DT_MIPS_OPTIONS = 0x70000029, // Address of `.MIPS.options'. DT_MIPS_INTERFACE = 0x7000002A, // Address of `.interface'. DT_MIPS_DYNSTR_ALIGN = 0x7000002B, // Unknown. DT_MIPS_INTERFACE_SIZE = 0x7000002C, // Size of the .interface section. DT_MIPS_RLD_TEXT_RESOLVE_ADDR = 0x7000002D, // Size of rld_text_resolve // function stored in the GOT. DT_MIPS_PERF_SUFFIX = 0x7000002E, // Default suffix of DSO to be added // by rld on dlopen() calls. DT_MIPS_COMPACT_SIZE = 0x7000002F, // Size of compact relocation // section (O32). DT_MIPS_GP_VALUE = 0x70000030, // GP value for auxiliary GOTs. DT_MIPS_AUX_DYNAMIC = 0x70000031, // Address of auxiliary .dynamic. DT_MIPS_PLTGOT = 0x70000032, // Address of the base of the PLTGOT. DT_MIPS_RWPLT = 0x70000034 // Points to the base // of a writable PLT. }; // DT_FLAGS values. enum { DF_ORIGIN = 0x01, // The object may reference $ORIGIN. DF_SYMBOLIC = 0x02, // Search the shared lib before searching the exe. DF_TEXTREL = 0x04, // Relocations may modify a non-writable segment. DF_BIND_NOW = 0x08, // Process all relocations on load. DF_STATIC_TLS = 0x10 // Reject attempts to load dynamically. }; // State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1 entry. enum { DF_1_NOW = 0x00000001, // Set RTLD_NOW for this object. DF_1_GLOBAL = 0x00000002, // Set RTLD_GLOBAL for this object. DF_1_GROUP = 0x00000004, // Set RTLD_GROUP for this object. DF_1_NODELETE = 0x00000008, // Set RTLD_NODELETE for this object. DF_1_LOADFLTR = 0x00000010, // Trigger filtee loading at runtime. DF_1_INITFIRST = 0x00000020, // Set RTLD_INITFIRST for this object. DF_1_NOOPEN = 0x00000040, // Set RTLD_NOOPEN for this object. DF_1_ORIGIN = 0x00000080, // $ORIGIN must be handled. DF_1_DIRECT = 0x00000100, // Direct binding enabled. DF_1_TRANS = 0x00000200, DF_1_INTERPOSE = 0x00000400, // Object is used to interpose. DF_1_NODEFLIB = 0x00000800, // Ignore default lib search path. DF_1_NODUMP = 0x00001000, // Object can't be dldump'ed. DF_1_CONFALT = 0x00002000, // Configuration alternative created. DF_1_ENDFILTEE = 0x00004000, // Filtee terminates filters search. DF_1_DISPRELDNE = 0x00008000, // Disp reloc applied at build time. DF_1_DISPRELPND = 0x00010000, // Disp reloc applied at run-time. DF_1_NODIRECT = 0x00020000, // Object has no-direct binding. DF_1_IGNMULDEF = 0x00040000, DF_1_NOKSYMS = 0x00080000, DF_1_NOHDR = 0x00100000, DF_1_EDITED = 0x00200000, // Object is modified after built. DF_1_NORELOC = 0x00400000, DF_1_SYMINTPOSE = 0x00800000, // Object has individual interposers. DF_1_GLOBAUDIT = 0x01000000, // Global auditing required. DF_1_SINGLETON = 0x02000000 // Singleton symbols are used. }; // DT_MIPS_FLAGS values. enum { RHF_NONE = 0x00000000, // No flags. RHF_QUICKSTART = 0x00000001, // Uses shortcut pointers. RHF_NOTPOT = 0x00000002, // Hash size is not a power of two. RHS_NO_LIBRARY_REPLACEMENT = 0x00000004, // Ignore LD_LIBRARY_PATH. RHF_NO_MOVE = 0x00000008, // DSO address may not be relocated. RHF_SGI_ONLY = 0x00000010, // SGI specific features. RHF_GUARANTEE_INIT = 0x00000020, // Guarantee that .init will finish // executing before any non-init // code in DSO is called. RHF_DELTA_C_PLUS_PLUS = 0x00000040, // Contains Delta C++ code. RHF_GUARANTEE_START_INIT = 0x00000080, // Guarantee that .init will start // executing before any non-init // code in DSO is called. RHF_PIXIE = 0x00000100, // Generated by pixie. RHF_DEFAULT_DELAY_LOAD = 0x00000200, // Delay-load DSO by default. RHF_REQUICKSTART = 0x00000400, // Object may be requickstarted RHF_REQUICKSTARTED = 0x00000800, // Object has been requickstarted RHF_CORD = 0x00001000, // Generated by cord. RHF_NO_UNRES_UNDEF = 0x00002000, // Object contains no unresolved // undef symbols. RHF_RLD_ORDER_SAFE = 0x00004000 // Symbol table is in a safe order. }; // ElfXX_VerDef structure version (GNU versioning) enum { VER_DEF_NONE = 0, VER_DEF_CURRENT = 1 }; // VerDef Flags (ElfXX_VerDef::vd_flags) enum { VER_FLG_BASE = 0x1, VER_FLG_WEAK = 0x2, VER_FLG_INFO = 0x4 }; // Special constants for the version table. (SHT_GNU_versym/.gnu.version) enum { VER_NDX_LOCAL = 0, // Unversioned local symbol VER_NDX_GLOBAL = 1, // Unversioned global symbol VERSYM_VERSION = 0x7fff, // Version Index mask VERSYM_HIDDEN = 0x8000 // Hidden bit (non-default version) }; // ElfXX_VerNeed structure version (GNU versioning) enum { VER_NEED_NONE = 0, VER_NEED_CURRENT = 1 }; } // end namespace ELF } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Endian.h
//===- Endian.h - Utilities for IO with endian specific data ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares generic functions to read and write endian specific data. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ENDIAN_H #define LLVM_SUPPORT_ENDIAN_H #include "llvm/Support/AlignOf.h" #include "llvm/Support/Host.h" #include "llvm/Support/SwapByteOrder.h" #pragma warning( push ) // HLSL Change - constant comparisons are done for portability #pragma warning( disable : 6326 ) // 'Potential comparison of a constant with another constant.' namespace llvm { namespace support { enum endianness {big, little, native}; // These are named values for common alignments. enum {aligned = 0, unaligned = 1}; namespace detail { /// \brief ::value is either alignment, or alignof(T) if alignment is 0. template<class T, int alignment> struct PickAlignment { enum {value = alignment == 0 ? AlignOf<T>::Alignment : alignment}; }; } // end namespace detail namespace endian { /// Swap the bytes of value to match the given endianness. template<typename value_type, endianness endian> inline value_type byte_swap(value_type value) { if (endian != native && sys::IsBigEndianHost != (endian == big)) sys::swapByteOrder(value); return value; } /// Read a value of a particular endianness from memory. template<typename value_type, endianness endian, std::size_t alignment> inline value_type read(const void *memory) { value_type ret; memcpy(&ret, LLVM_ASSUME_ALIGNED(memory, (detail::PickAlignment<value_type, alignment>::value)), sizeof(value_type)); return byte_swap<value_type, endian>(ret); } /// Read a value of a particular endianness from a buffer, and increment the /// buffer past that value. template<typename value_type, endianness endian, std::size_t alignment, typename CharT> inline value_type readNext(const CharT *&memory) { value_type ret = read<value_type, endian, alignment>(memory); memory += sizeof(value_type); return ret; } /// Write a value to memory with a particular endianness. template<typename value_type, endianness endian, std::size_t alignment> inline void write(void *memory, value_type value) { value = byte_swap<value_type, endian>(value); memcpy(LLVM_ASSUME_ALIGNED(memory, (detail::PickAlignment<value_type, alignment>::value)), &value, sizeof(value_type)); } } // end namespace endian namespace detail { template<typename value_type, endianness endian, std::size_t alignment> struct packed_endian_specific_integral { operator value_type() const { return endian::read<value_type, endian, alignment>( (const void*)Value.buffer); } void operator=(value_type newValue) { endian::write<value_type, endian, alignment>( (void*)Value.buffer, newValue); } packed_endian_specific_integral &operator+=(value_type newValue) { *this = *this + newValue; return *this; } packed_endian_specific_integral &operator-=(value_type newValue) { *this = *this - newValue; return *this; } packed_endian_specific_integral &operator|=(value_type newValue) { *this = *this | newValue; return *this; } packed_endian_specific_integral &operator&=(value_type newValue) { *this = *this & newValue; return *this; } private: AlignedCharArray<PickAlignment<value_type, alignment>::value, sizeof(value_type)> Value; public: struct ref { explicit ref(void *Ptr) : Ptr(Ptr) {} operator value_type() const { return endian::read<value_type, endian, alignment>(Ptr); } void operator=(value_type NewValue) { endian::write<value_type, endian, alignment>(Ptr, NewValue); } private: void *Ptr; }; }; } // end namespace detail typedef detail::packed_endian_specific_integral <uint16_t, little, unaligned> ulittle16_t; typedef detail::packed_endian_specific_integral <uint32_t, little, unaligned> ulittle32_t; typedef detail::packed_endian_specific_integral <uint64_t, little, unaligned> ulittle64_t; typedef detail::packed_endian_specific_integral <int16_t, little, unaligned> little16_t; typedef detail::packed_endian_specific_integral <int32_t, little, unaligned> little32_t; typedef detail::packed_endian_specific_integral <int64_t, little, unaligned> little64_t; typedef detail::packed_endian_specific_integral <uint16_t, little, aligned> aligned_ulittle16_t; typedef detail::packed_endian_specific_integral <uint32_t, little, aligned> aligned_ulittle32_t; typedef detail::packed_endian_specific_integral <uint64_t, little, aligned> aligned_ulittle64_t; typedef detail::packed_endian_specific_integral <int16_t, little, aligned> aligned_little16_t; typedef detail::packed_endian_specific_integral <int32_t, little, aligned> aligned_little32_t; typedef detail::packed_endian_specific_integral <int64_t, little, aligned> aligned_little64_t; typedef detail::packed_endian_specific_integral <uint16_t, big, unaligned> ubig16_t; typedef detail::packed_endian_specific_integral <uint32_t, big, unaligned> ubig32_t; typedef detail::packed_endian_specific_integral <uint64_t, big, unaligned> ubig64_t; typedef detail::packed_endian_specific_integral <int16_t, big, unaligned> big16_t; typedef detail::packed_endian_specific_integral <int32_t, big, unaligned> big32_t; typedef detail::packed_endian_specific_integral <int64_t, big, unaligned> big64_t; typedef detail::packed_endian_specific_integral <uint16_t, big, aligned> aligned_ubig16_t; typedef detail::packed_endian_specific_integral <uint32_t, big, aligned> aligned_ubig32_t; typedef detail::packed_endian_specific_integral <uint64_t, big, aligned> aligned_ubig64_t; typedef detail::packed_endian_specific_integral <int16_t, big, aligned> aligned_big16_t; typedef detail::packed_endian_specific_integral <int32_t, big, aligned> aligned_big32_t; typedef detail::packed_endian_specific_integral <int64_t, big, aligned> aligned_big64_t; typedef detail::packed_endian_specific_integral <uint16_t, native, unaligned> unaligned_uint16_t; typedef detail::packed_endian_specific_integral <uint32_t, native, unaligned> unaligned_uint32_t; typedef detail::packed_endian_specific_integral <uint64_t, native, unaligned> unaligned_uint64_t; typedef detail::packed_endian_specific_integral <int16_t, native, unaligned> unaligned_int16_t; typedef detail::packed_endian_specific_integral <int32_t, native, unaligned> unaligned_int32_t; typedef detail::packed_endian_specific_integral <int64_t, native, unaligned> unaligned_int64_t; namespace endian { inline uint16_t read16le(const void *p) { return *(const ulittle16_t *)p; } inline uint32_t read32le(const void *p) { return *(const ulittle32_t *)p; } inline uint64_t read64le(const void *p) { return *(const ulittle64_t *)p; } inline uint16_t read16be(const void *p) { return *(const ubig16_t *)p; } inline uint32_t read32be(const void *p) { return *(const ubig32_t *)p; } inline uint64_t read64be(const void *p) { return *(const ubig64_t *)p; } inline void write16le(void *p, uint16_t v) { *(ulittle16_t *)p = v; } inline void write32le(void *p, uint32_t v) { *(ulittle32_t *)p = v; } inline void write64le(void *p, uint64_t v) { *(ulittle64_t *)p = v; } inline void write16be(void *p, uint16_t v) { *(ubig16_t *)p = v; } inline void write32be(void *p, uint32_t v) { *(ubig32_t *)p = v; } inline void write64be(void *p, uint64_t v) { *(ubig64_t *)p = v; } } // end namespace endian } // end namespace support } // end namespace llvm #pragma warning( pop ) // HLSL Change - pop warning level #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/MemoryBuffer.h
//===--- MemoryBuffer.h - Memory Buffer Interface ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the MemoryBuffer interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_MEMORYBUFFER_H #define LLVM_SUPPORT_MEMORYBUFFER_H #include "llvm-c/Support.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorOr.h" #include <memory> namespace llvm { class MemoryBufferRef; /// This interface provides simple read-only access to a block of memory, and /// provides simple methods for reading files and standard input into a memory /// buffer. In addition to basic access to the characters in the file, this /// interface guarantees you can read one character past the end of the file, /// and that this character will read as '\0'. /// /// The '\0' guarantee is needed to support an optimization -- it's intended to /// be more efficient for clients which are reading all the data to stop /// reading when they encounter a '\0' than to continually check the file /// position to see if it has reached the end of the file. class MemoryBuffer { const char *BufferStart; // Start of the buffer. const char *BufferEnd; // End of the buffer. MemoryBuffer(const MemoryBuffer &) = delete; MemoryBuffer &operator=(const MemoryBuffer &) = delete; protected: MemoryBuffer() {} void init(const char *BufStart, const char *BufEnd, bool RequiresNullTerminator); public: virtual ~MemoryBuffer(); const char *getBufferStart() const { return BufferStart; } const char *getBufferEnd() const { return BufferEnd; } size_t getBufferSize() const { return BufferEnd-BufferStart; } StringRef getBuffer() const { return StringRef(BufferStart, getBufferSize()); } /// Return an identifier for this buffer, typically the filename it was read /// from. virtual const char *getBufferIdentifier() const { return "Unknown buffer"; } /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer /// if successful, otherwise returning null. If FileSize is specified, this /// means that the client knows that the file exists and that it has the /// specified size. /// /// \param IsVolatileSize Set to true to indicate that the file size may be /// changing, e.g. when libclang tries to parse while the user is /// editing/updating the file. static ErrorOr<std::unique_ptr<MemoryBuffer>> getFile(const Twine &Filename, int64_t FileSize = -1, bool RequiresNullTerminator = true, bool IsVolatileSize = false); /// Given an already-open file descriptor, map some slice of it into a /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize. /// Since this is in the middle of a file, the buffer is not null terminated. static ErrorOr<std::unique_ptr<MemoryBuffer>> getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize, int64_t Offset); /// Given an already-open file descriptor, read the file and return a /// MemoryBuffer. /// /// \param IsVolatileSize Set to true to indicate that the file size may be /// changing, e.g. when libclang tries to parse while the user is /// editing/updating the file. static ErrorOr<std::unique_ptr<MemoryBuffer>> getOpenFile(int FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator = true, bool IsVolatileSize = false); /// Open the specified memory range as a MemoryBuffer. Note that InputData /// must be null terminated if RequiresNullTerminator is true. static std::unique_ptr<MemoryBuffer> getMemBuffer(StringRef InputData, StringRef BufferName = "", bool RequiresNullTerminator = true); static std::unique_ptr<MemoryBuffer> getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator = true); /// Open the specified memory range as a MemoryBuffer, copying the contents /// and taking ownership of it. InputData does not have to be null terminated. static std::unique_ptr<MemoryBuffer> getMemBufferCopy(StringRef InputData, const Twine &BufferName = ""); /// Allocate a new zero-initialized MemoryBuffer of the specified size. Note /// that the caller need not initialize the memory allocated by this method. /// The memory is owned by the MemoryBuffer object. static std::unique_ptr<MemoryBuffer> getNewMemBuffer(size_t Size, StringRef BufferName = ""); /// Allocate a new MemoryBuffer of the specified size that is not initialized. /// Note that the caller should initialize the memory allocated by this /// method. The memory is owned by the MemoryBuffer object. static std::unique_ptr<MemoryBuffer> getNewUninitMemBuffer(size_t Size, const Twine &BufferName = ""); /// Read all of stdin into a file buffer, and return it. static ErrorOr<std::unique_ptr<MemoryBuffer>> getSTDIN(); /// Open the specified file as a MemoryBuffer, or open stdin if the Filename /// is "-". static ErrorOr<std::unique_ptr<MemoryBuffer>> getFileOrSTDIN(const Twine &Filename, int64_t FileSize = -1); /// Map a subrange of the specified file as a MemoryBuffer. static ErrorOr<std::unique_ptr<MemoryBuffer>> getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset); //===--------------------------------------------------------------------===// // Provided for performance analysis. //===--------------------------------------------------------------------===// /// The kind of memory backing used to support the MemoryBuffer. enum BufferKind { MemoryBuffer_Malloc, MemoryBuffer_MMap }; /// Return information on the memory mechanism used to support the /// MemoryBuffer. virtual BufferKind getBufferKind() const = 0; MemoryBufferRef getMemBufferRef() const; }; class MemoryBufferRef { StringRef Buffer; StringRef Identifier; public: MemoryBufferRef() {} MemoryBufferRef(StringRef Buffer, StringRef Identifier) : Buffer(Buffer), Identifier(Identifier) {} StringRef getBuffer() const { return Buffer; } StringRef getBufferIdentifier() const { return Identifier; } const char *getBufferStart() const { return Buffer.begin(); } const char *getBufferEnd() const { return Buffer.end(); } size_t getBufferSize() const { return Buffer.size(); } }; // Create wrappers for C Binding types (see CBindingWrapping.h). DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer, LLVMMemoryBufferRef) } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/TargetParser.h
//===-- TargetParser - Parser for target features ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a target parser to recognise hardware features such as // FPU/CPU/ARCH names as well as specific support such as HDIV, etc. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TARGETPARSER_H #define LLVM_SUPPORT_TARGETPARSER_H // FIXME: vector is used because that's what clang uses for subtarget feature // lists, but SmallVector would probably be better #include <vector> namespace llvm { class StringRef; // Target specific information into their own namespaces. These should be // generated from TableGen because the information is already there, and there // is where new information about targets will be added. // FIXME: To TableGen this we need to make some table generated files available // even if the back-end is not compiled with LLVM, plus we need to create a new // back-end to TableGen to create these clean tables. namespace ARM { // FPU names. enum FPUKind { FK_INVALID = 0, FK_NONE, FK_VFP, FK_VFPV2, FK_VFPV3, FK_VFPV3_FP16, FK_VFPV3_D16, FK_VFPV3_D16_FP16, FK_VFPV3XD, FK_VFPV3XD_FP16, FK_VFPV4, FK_VFPV4_D16, FK_FPV4_SP_D16, FK_FPV5_D16, FK_FPV5_SP_D16, FK_FP_ARMV8, FK_NEON, FK_NEON_FP16, FK_NEON_VFPV4, FK_NEON_FP_ARMV8, FK_CRYPTO_NEON_FP_ARMV8, FK_SOFTVFP, FK_LAST }; // FPU Version enum FPUVersion { FV_NONE = 0, FV_VFPV2, FV_VFPV3, FV_VFPV3_FP16, FV_VFPV4, FV_VFPV5 }; // An FPU name implies one of three levels of Neon support: enum NeonSupportLevel { NS_None = 0, ///< No Neon NS_Neon, ///< Neon NS_Crypto ///< Neon with Crypto }; // An FPU name restricts the FPU in one of three ways: enum FPURestriction { FR_None = 0, ///< No restriction FR_D16, ///< Only 16 D registers FR_SP_D16 ///< Only single-precision instructions, with 16 D registers }; // Arch names. enum ArchKind { AK_INVALID = 0, AK_ARMV2, AK_ARMV2A, AK_ARMV3, AK_ARMV3M, AK_ARMV4, AK_ARMV4T, AK_ARMV5T, AK_ARMV5TE, AK_ARMV5TEJ, AK_ARMV6, AK_ARMV6K, AK_ARMV6T2, AK_ARMV6Z, AK_ARMV6ZK, AK_ARMV6M, AK_ARMV6SM, AK_ARMV7A, AK_ARMV7R, AK_ARMV7M, AK_ARMV7EM, AK_ARMV8A, AK_ARMV8_1A, // Non-standard Arch names. AK_IWMMXT, AK_IWMMXT2, AK_XSCALE, AK_ARMV5, AK_ARMV5E, AK_ARMV6J, AK_ARMV6HL, AK_ARMV7, AK_ARMV7L, AK_ARMV7HL, AK_ARMV7S, AK_LAST }; // Arch extension modifiers for CPUs. enum ArchExtKind { AEK_INVALID = 0, AEK_CRC, AEK_CRYPTO, AEK_FP, AEK_HWDIV, AEK_MP, AEK_SIMD, AEK_SEC, AEK_VIRT, // Unsupported extensions. AEK_OS, AEK_IWMMXT, AEK_IWMMXT2, AEK_MAVERICK, AEK_XSCALE, AEK_LAST }; // ISA kinds. enum ISAKind { IK_INVALID = 0, IK_ARM, IK_THUMB, IK_AARCH64 }; // Endianness // FIXME: BE8 vs. BE32? enum EndianKind { EK_INVALID = 0, EK_LITTLE, EK_BIG }; // v6/v7/v8 Profile enum ProfileKind { PK_INVALID = 0, PK_A, PK_R, PK_M }; } // namespace ARM // Target Parsers, one per architecture. class ARMTargetParser { static StringRef getFPUSynonym(StringRef FPU); static StringRef getArchSynonym(StringRef Arch); public: static StringRef getCanonicalArchName(StringRef Arch); // Information by ID static const char * getFPUName(unsigned FPUKind); static unsigned getFPUVersion(unsigned FPUKind); static unsigned getFPUNeonSupportLevel(unsigned FPUKind); static unsigned getFPURestriction(unsigned FPUKind); // FIXME: This should be moved to TargetTuple once it exists static bool getFPUFeatures(unsigned FPUKind, std::vector<const char*> &Features); static const char * getArchName(unsigned ArchKind); static unsigned getArchAttr(unsigned ArchKind); static const char * getCPUAttr(unsigned ArchKind); static const char * getSubArch(unsigned ArchKind); static const char * getArchExtName(unsigned ArchExtKind); static const char * getDefaultCPU(StringRef Arch); // Parser static unsigned parseFPU(StringRef FPU); static unsigned parseArch(StringRef Arch); static unsigned parseArchExt(StringRef ArchExt); static unsigned parseCPUArch(StringRef CPU); static unsigned parseArchISA(StringRef Arch); static unsigned parseArchEndian(StringRef Arch); static unsigned parseArchProfile(StringRef Arch); static unsigned parseArchVersion(StringRef Arch); }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/SaveAndRestore.h
//===-- SaveAndRestore.h - Utility -------------------------------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file provides utility classes that use RAII to save and restore /// values. /// //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_SAVEANDRESTORE_H #define LLVM_SUPPORT_SAVEANDRESTORE_H namespace llvm { /// A utility class that uses RAII to save and restore the value of a variable. template <typename T> struct SaveAndRestore { SaveAndRestore(T &X) : X(X), OldValue(X) {} SaveAndRestore(T &X, const T &NewValue) : X(X), OldValue(X) { X = NewValue; } ~SaveAndRestore() { X = OldValue; } T get() { return OldValue; } private: T &X; T OldValue; }; /// Similar to \c SaveAndRestore. Operates only on bools; the old value of a /// variable is saved, and during the dstor the old value is or'ed with the new /// value. struct SaveOr { SaveOr(bool &X) : X(X), OldValue(X) { X = false; } ~SaveOr() { X |= OldValue; } private: bool &X; const bool OldValue; }; } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Path.h
//===- llvm/Support/Path.h - Path Operating System Concept ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::path namespace. It is designed after // TR2/boost filesystem (v3), but modified to remove exception handling and the // path class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_PATH_H #define LLVM_SUPPORT_PATH_H #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/ADT/iterator.h" #include "llvm/Support/DataTypes.h" #include <iterator> namespace llvm { namespace sys { namespace path { /// @name Lexical Component Iterator /// @{ /// @brief Path iterator. /// /// This is an input iterator that iterates over the individual components in /// \a path. The traversal order is as follows: /// * The root-name element, if present. /// * The root-directory element, if present. /// * Each successive filename element, if present. /// * Dot, if one or more trailing non-root slash characters are present. /// Traversing backwards is possible with \a reverse_iterator /// /// Iteration examples. Each component is separated by ',': /// @code /// / => / /// /foo => /,foo /// foo/ => foo,. /// /foo/bar => /,foo,bar /// ../ => ..,. /// C:\foo\bar => C:,/,foo,bar /// @endcode class const_iterator : public iterator_facade_base<const_iterator, std::input_iterator_tag, const StringRef> { StringRef Path; ///< The entire path. StringRef Component; ///< The current component. Not necessarily in Path. size_t Position; ///< The iterators current position within Path. // An end iterator has Position = Path.size() + 1. friend const_iterator begin(StringRef path); friend const_iterator end(StringRef path); public: reference operator*() const { return Component; } const_iterator &operator++(); // preincrement const_iterator &operator++(int); // postincrement bool operator==(const const_iterator &RHS) const; /// @brief Difference in bytes between this and RHS. ptrdiff_t operator-(const const_iterator &RHS) const; }; /// @brief Reverse path iterator. /// /// This is an input iterator that iterates over the individual components in /// \a path in reverse order. The traversal order is exactly reversed from that /// of \a const_iterator class reverse_iterator : public iterator_facade_base<reverse_iterator, std::input_iterator_tag, const StringRef> { StringRef Path; ///< The entire path. StringRef Component; ///< The current component. Not necessarily in Path. size_t Position; ///< The iterators current position within Path. friend reverse_iterator rbegin(StringRef path); friend reverse_iterator rend(StringRef path); public: reference operator*() const { return Component; } reverse_iterator &operator++(); // preincrement reverse_iterator &operator++(int); // postincrement bool operator==(const reverse_iterator &RHS) const; }; /// @brief Get begin iterator over \a path. /// @param path Input path. /// @returns Iterator initialized with the first component of \a path. const_iterator begin(StringRef path); /// @brief Get end iterator over \a path. /// @param path Input path. /// @returns Iterator initialized to the end of \a path. const_iterator end(StringRef path); /// @brief Get reverse begin iterator over \a path. /// @param path Input path. /// @returns Iterator initialized with the first reverse component of \a path. reverse_iterator rbegin(StringRef path); /// @brief Get reverse end iterator over \a path. /// @param path Input path. /// @returns Iterator initialized to the reverse end of \a path. reverse_iterator rend(StringRef path); /// @} /// @name Lexical Modifiers /// @{ /// @brief Remove the last component from \a path unless it is the root dir. /// /// @code /// directory/filename.cpp => directory/ /// directory/ => directory /// filename.cpp => <empty> /// / => / /// @endcode /// /// @param path A path that is modified to not have a file component. void remove_filename(SmallVectorImpl<char> &path); /// @brief Replace the file extension of \a path with \a extension. /// /// @code /// ./filename.cpp => ./filename.extension /// ./filename => ./filename.extension /// ./ => ./.extension /// @endcode /// /// @param path A path that has its extension replaced with \a extension. /// @param extension The extension to be added. It may be empty. It may also /// optionally start with a '.', if it does not, one will be /// prepended. void replace_extension(SmallVectorImpl<char> &path, const Twine &extension); /// @brief Append to path. /// /// @code /// /foo + bar/f => /foo/bar/f /// /foo/ + bar/f => /foo/bar/f /// foo + bar/f => foo/bar/f /// @endcode /// /// @param path Set to \a path + \a component. /// @param a The component to be appended to \a path. void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b = "", const Twine &c = "", const Twine &d = ""); /// @brief Append to path. /// /// @code /// /foo + [bar,f] => /foo/bar/f /// /foo/ + [bar,f] => /foo/bar/f /// foo + [bar,f] => foo/bar/f /// @endcode /// /// @param path Set to \a path + [\a begin, \a end). /// @param begin Start of components to append. /// @param end One past the end of components to append. void append(SmallVectorImpl<char> &path, const_iterator begin, const_iterator end); /// @} /// @name Transforms (or some other better name) /// @{ /// Convert path to the native form. This is used to give paths to users and /// operating system calls in the platform's normal way. For example, on Windows /// all '/' are converted to '\'. /// /// @param path A path that is transformed to native format. /// @param result Holds the result of the transformation. void native(const Twine &path, SmallVectorImpl<char> &result); /// Convert path to the native form in place. This is used to give paths to /// users and operating system calls in the platform's normal way. For example, /// on Windows all '/' are converted to '\'. /// /// @param path A path that is transformed to native format. void native(SmallVectorImpl<char> &path); /// @} /// @name Lexical Observers /// @{ /// @brief Get root name. /// /// @code /// //net/hello => //net /// c:/hello => c: (on Windows, on other platforms nothing) /// /hello => <empty> /// @endcode /// /// @param path Input path. /// @result The root name of \a path if it has one, otherwise "". StringRef root_name(StringRef path); /// @brief Get root directory. /// /// @code /// /goo/hello => / /// c:/hello => / /// d/file.txt => <empty> /// @endcode /// /// @param path Input path. /// @result The root directory of \a path if it has one, otherwise /// "". StringRef root_directory(StringRef path); /// @brief Get root path. /// /// Equivalent to root_name + root_directory. /// /// @param path Input path. /// @result The root path of \a path if it has one, otherwise "". StringRef root_path(StringRef path); /// @brief Get relative path. /// /// @code /// C:\hello\world => hello\world /// foo/bar => foo/bar /// /foo/bar => foo/bar /// @endcode /// /// @param path Input path. /// @result The path starting after root_path if one exists, otherwise "". StringRef relative_path(StringRef path); /// @brief Get parent path. /// /// @code /// / => <empty> /// /foo => / /// foo/../bar => foo/.. /// @endcode /// /// @param path Input path. /// @result The parent path of \a path if one exists, otherwise "". StringRef parent_path(StringRef path); /// @brief Get filename. /// /// @code /// /foo.txt => foo.txt /// . => . /// .. => .. /// / => / /// @endcode /// /// @param path Input path. /// @result The filename part of \a path. This is defined as the last component /// of \a path. StringRef filename(StringRef path); /// @brief Get stem. /// /// If filename contains a dot but not solely one or two dots, result is the /// substring of filename ending at (but not including) the last dot. Otherwise /// it is filename. /// /// @code /// /foo/bar.txt => bar /// /foo/bar => bar /// /foo/.txt => <empty> /// /foo/. => . /// /foo/.. => .. /// @endcode /// /// @param path Input path. /// @result The stem of \a path. StringRef stem(StringRef path); /// @brief Get extension. /// /// If filename contains a dot but not solely one or two dots, result is the /// substring of filename starting at (and including) the last dot, and ending /// at the end of \a path. Otherwise "". /// /// @code /// /foo/bar.txt => .txt /// /foo/bar => <empty> /// /foo/.txt => .txt /// @endcode /// /// @param path Input path. /// @result The extension of \a path. StringRef extension(StringRef path); /// @brief Check whether the given char is a path separator on the host OS. /// /// @param value a character /// @result true if \a value is a path separator character on the host OS bool is_separator(char value); /// @brief Return the preferred separator for this platform. /// /// @result StringRef of the preferred separator, null-terminated. StringRef get_separator(); /// @brief Get the typical temporary directory for the system, e.g., /// "/var/tmp" or "C:/TEMP" /// /// @param erasedOnReboot Whether to favor a path that is erased on reboot /// rather than one that potentially persists longer. This parameter will be /// ignored if the user or system has set the typical environment variable /// (e.g., TEMP on Windows, TMPDIR on *nix) to specify a temporary directory. /// /// @param result Holds the resulting path name. void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result); /// @brief Get the user's home directory. /// /// @param result Holds the resulting path name. /// @result True if a home directory is set, false otherwise. bool home_directory(SmallVectorImpl<char> &result); /// @brief Has root name? /// /// root_name != "" /// /// @param path Input path. /// @result True if the path has a root name, false otherwise. bool has_root_name(const Twine &path); /// @brief Has root directory? /// /// root_directory != "" /// /// @param path Input path. /// @result True if the path has a root directory, false otherwise. bool has_root_directory(const Twine &path); /// @brief Has root path? /// /// root_path != "" /// /// @param path Input path. /// @result True if the path has a root path, false otherwise. bool has_root_path(const Twine &path); /// @brief Has relative path? /// /// relative_path != "" /// /// @param path Input path. /// @result True if the path has a relative path, false otherwise. bool has_relative_path(const Twine &path); /// @brief Has parent path? /// /// parent_path != "" /// /// @param path Input path. /// @result True if the path has a parent path, false otherwise. bool has_parent_path(const Twine &path); /// @brief Has filename? /// /// filename != "" /// /// @param path Input path. /// @result True if the path has a filename, false otherwise. bool has_filename(const Twine &path); /// @brief Has stem? /// /// stem != "" /// /// @param path Input path. /// @result True if the path has a stem, false otherwise. bool has_stem(const Twine &path); /// @brief Has extension? /// /// extension != "" /// /// @param path Input path. /// @result True if the path has a extension, false otherwise. bool has_extension(const Twine &path); /// @brief Is path absolute? /// /// @param path Input path. /// @result True if the path is absolute, false if it is not. bool is_absolute(const Twine &path); /// @brief Is path relative? /// /// @param path Input path. /// @result True if the path is relative, false if it is not. bool is_relative(const Twine &path); } // end namespace path } // end namespace sys } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Capacity.h
//===--- Capacity.h - Generic computation of ADT memory use -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the capacity function that computes the amount of // memory used by an ADT. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_CAPACITY_H #define LLVM_SUPPORT_CAPACITY_H #include <cstddef> namespace llvm { template <typename T> static inline size_t capacity_in_bytes(const T &x) { // This default definition of capacity should work for things like std::vector // and friends. More specialized versions will work for others. return x.capacity() * sizeof(typename T::value_type); } } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/EndianStream.h
//===- EndianStream.h - Stream ops with endian specific data ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines utilities for operating on streams that have endian // specific data. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ENDIANSTREAM_H #define LLVM_SUPPORT_ENDIANSTREAM_H #include "llvm/Support/Endian.h" #include "llvm/Support/raw_ostream.h" namespace llvm { namespace support { namespace endian { /// Adapter to write values to a stream in a particular byte order. template <endianness endian> struct Writer { raw_ostream &OS; Writer(raw_ostream &OS) : OS(OS) {} template <typename value_type> void write(value_type Val) { Val = byte_swap<value_type, endian>(Val); OS.write((const char *)&Val, sizeof(value_type)); } }; template <> template <> inline void Writer<little>::write<float>(float Val) { write(FloatToBits(Val)); } template <> template <> inline void Writer<little>::write<double>(double Val) { write(DoubleToBits(Val)); } template <> template <> inline void Writer<big>::write<float>(float Val) { write(FloatToBits(Val)); } template <> template <> inline void Writer<big>::write<double>(double Val) { write(DoubleToBits(Val)); } } // end namespace endian } // end namespace support } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/SMLoc.h
//===- SMLoc.h - Source location for use with diagnostics -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the SMLoc class. This class encapsulates a location in // source code for use in diagnostics. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_SMLOC_H #define LLVM_SUPPORT_SMLOC_H #include <cassert> namespace llvm { /// Represents a location in source code. class SMLoc { const char *Ptr; public: SMLoc() : Ptr(nullptr) {} bool isValid() const { return Ptr != nullptr; } bool operator==(const SMLoc &RHS) const { return RHS.Ptr == Ptr; } bool operator!=(const SMLoc &RHS) const { return RHS.Ptr != Ptr; } const char *getPointer() const { return Ptr; } static SMLoc getFromPointer(const char *Ptr) { SMLoc L; L.Ptr = Ptr; return L; } }; /// Represents a range in source code. /// /// SMRange is implemented using a half-open range, as is the convention in C++. /// In the string "abc", the range (1,3] represents the substring "bc", and the /// range (2,2] represents an empty range between the characters "b" and "c". class SMRange { public: SMLoc Start, End; SMRange() {} SMRange(SMLoc St, SMLoc En) : Start(St), End(En) { assert(Start.isValid() == End.isValid() && "Start and end should either both be valid or both be invalid!"); } bool isValid() const { return Start.isValid(); } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/OnDiskHashTable.h
//===--- OnDiskHashTable.h - On-Disk Hash Table Implementation --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines facilities for reading and writing on-disk hash tables. /// //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_ONDISKHASHTABLE_H #define LLVM_SUPPORT_ONDISKHASHTABLE_H #include "llvm/Support/AlignOf.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/Host.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> namespace llvm { /// \brief Generates an on disk hash table. /// /// This needs an \c Info that handles storing values into the hash table's /// payload and computes the hash for a given key. This should provide the /// following interface: /// /// \code /// class ExampleInfo { /// public: /// typedef ExampleKey key_type; // Must be copy constructible /// typedef ExampleKey &key_type_ref; /// typedef ExampleData data_type; // Must be copy constructible /// typedef ExampleData &data_type_ref; /// typedef uint32_t hash_value_type; // The type the hash function returns. /// typedef uint32_t offset_type; // The type for offsets into the table. /// /// /// Calculate the hash for Key /// static hash_value_type ComputeHash(key_type_ref Key); /// /// Return the lengths, in bytes, of the given Key/Data pair. /// static std::pair<offset_type, offset_type> /// EmitKeyDataLength(raw_ostream &Out, key_type_ref Key, data_type_ref Data); /// /// Write Key to Out. KeyLen is the length from EmitKeyDataLength. /// static void EmitKey(raw_ostream &Out, key_type_ref Key, /// offset_type KeyLen); /// /// Write Data to Out. DataLen is the length from EmitKeyDataLength. /// static void EmitData(raw_ostream &Out, key_type_ref Key, /// data_type_ref Data, offset_type DataLen); /// }; /// \endcode template <typename Info> class OnDiskChainedHashTableGenerator { /// \brief A single item in the hash table. class Item { public: typename Info::key_type Key; typename Info::data_type Data; Item *Next; const typename Info::hash_value_type Hash; Item(typename Info::key_type_ref Key, typename Info::data_type_ref Data, Info &InfoObj) : Key(Key), Data(Data), Next(nullptr), Hash(InfoObj.ComputeHash(Key)) {} }; typedef typename Info::offset_type offset_type; offset_type NumBuckets; offset_type NumEntries; llvm::SpecificBumpPtrAllocator<Item> BA; /// \brief A linked list of values in a particular hash bucket. struct Bucket { offset_type Off; unsigned Length; Item *Head; }; Bucket *Buckets; private: /// \brief Insert an item into the appropriate hash bucket. void insert(Bucket *Buckets, size_t Size, Item *E) { Bucket &B = Buckets[E->Hash & (Size - 1)]; E->Next = B.Head; ++B.Length; B.Head = E; } /// \brief Resize the hash table, moving the old entries into the new buckets. void resize(size_t NewSize) { // HLSL Change Begin: Use overridable operator new Bucket* NewBuckets = new Bucket[NewSize]; std::memset(NewBuckets, 0, NewSize * sizeof(Bucket)); // HLSL Change End // Populate NewBuckets with the old entries. for (size_t I = 0; I < NumBuckets; ++I) for (Item *E = Buckets[I].Head; E;) { Item *N = E->Next; E->Next = nullptr; insert(NewBuckets, NewSize, E); E = N; } delete[] Buckets; // HLSL Change: Use overridable operator delete NumBuckets = NewSize; Buckets = NewBuckets; } public: /// \brief Insert an entry into the table. void insert(typename Info::key_type_ref Key, typename Info::data_type_ref Data) { Info InfoObj; insert(Key, Data, InfoObj); } /// \brief Insert an entry into the table. /// /// Uses the provided Info instead of a stack allocated one. void insert(typename Info::key_type_ref Key, typename Info::data_type_ref Data, Info &InfoObj) { ++NumEntries; if (4 * NumEntries >= 3 * NumBuckets) resize(NumBuckets * 2); insert(Buckets, NumBuckets, new (BA.Allocate()) Item(Key, Data, InfoObj)); } /// \brief Emit the table to Out, which must not be at offset 0. offset_type Emit(raw_ostream &Out) { Info InfoObj; return Emit(Out, InfoObj); } /// \brief Emit the table to Out, which must not be at offset 0. /// /// Uses the provided Info instead of a stack allocated one. offset_type Emit(raw_ostream &Out, Info &InfoObj) { using namespace llvm::support; endian::Writer<little> LE(Out); // Emit the payload of the table. for (offset_type I = 0; I < NumBuckets; ++I) { Bucket &B = Buckets[I]; if (!B.Head) continue; // Store the offset for the data of this bucket. B.Off = Out.tell(); assert(B.Off && "Cannot write a bucket at offset 0. Please add padding."); // Write out the number of items in the bucket. LE.write<uint16_t>(B.Length); assert(B.Length != 0 && "Bucket has a head but zero length?"); // Write out the entries in the bucket. for (Item *I = B.Head; I; I = I->Next) { LE.write<typename Info::hash_value_type>(I->Hash); const std::pair<offset_type, offset_type> &Len = InfoObj.EmitKeyDataLength(Out, I->Key, I->Data); InfoObj.EmitKey(Out, I->Key, Len.first); InfoObj.EmitData(Out, I->Key, I->Data, Len.second); } } // Pad with zeros so that we can start the hashtable at an aligned address. offset_type TableOff = Out.tell(); uint64_t N = llvm::OffsetToAlignment(TableOff, alignOf<offset_type>()); TableOff += N; while (N--) LE.write<uint8_t>(0); // Emit the hashtable itself. LE.write<offset_type>(NumBuckets); LE.write<offset_type>(NumEntries); for (offset_type I = 0; I < NumBuckets; ++I) LE.write<offset_type>(Buckets[I].Off); return TableOff; } OnDiskChainedHashTableGenerator() { NumEntries = 0; NumBuckets = 64; // Note that we do not need to run the constructors of the individual // Bucket objects since 'calloc' returns bytes that are all 0. // HLSL Change Begin: Use overridable operator new Buckets = new Bucket[NumBuckets]; std::memset(Buckets, 0, NumBuckets * sizeof(Bucket)); // HLSL Change End } ~OnDiskChainedHashTableGenerator() { delete[] Buckets; } // HLSL Change: Use overridable operator delete }; /// \brief Provides lookup on an on disk hash table. /// /// This needs an \c Info that handles reading values from the hash table's /// payload and computes the hash for a given key. This should provide the /// following interface: /// /// \code /// class ExampleLookupInfo { /// public: /// typedef ExampleData data_type; /// typedef ExampleInternalKey internal_key_type; // The stored key type. /// typedef ExampleKey external_key_type; // The type to pass to find(). /// typedef uint32_t hash_value_type; // The type the hash function returns. /// typedef uint32_t offset_type; // The type for offsets into the table. /// /// /// Compare two keys for equality. /// static bool EqualKey(internal_key_type &Key1, internal_key_type &Key2); /// /// Calculate the hash for the given key. /// static hash_value_type ComputeHash(internal_key_type &IKey); /// /// Translate from the semantic type of a key in the hash table to the /// /// type that is actually stored and used for hashing and comparisons. /// /// The internal and external types are often the same, in which case this /// /// can simply return the passed in value. /// static const internal_key_type &GetInternalKey(external_key_type &EKey); /// /// Read the key and data length from Buffer, leaving it pointing at the /// /// following byte. /// static std::pair<offset_type, offset_type> /// ReadKeyDataLength(const unsigned char *&Buffer); /// /// Read the key from Buffer, given the KeyLen as reported from /// /// ReadKeyDataLength. /// const internal_key_type &ReadKey(const unsigned char *Buffer, /// offset_type KeyLen); /// /// Read the data for Key from Buffer, given the DataLen as reported from /// /// ReadKeyDataLength. /// data_type ReadData(StringRef Key, const unsigned char *Buffer, /// offset_type DataLen); /// }; /// \endcode template <typename Info> class OnDiskChainedHashTable { const typename Info::offset_type NumBuckets; const typename Info::offset_type NumEntries; const unsigned char *const Buckets; const unsigned char *const Base; Info InfoObj; public: typedef typename Info::internal_key_type internal_key_type; typedef typename Info::external_key_type external_key_type; typedef typename Info::data_type data_type; typedef typename Info::hash_value_type hash_value_type; typedef typename Info::offset_type offset_type; OnDiskChainedHashTable(offset_type NumBuckets, offset_type NumEntries, const unsigned char *Buckets, const unsigned char *Base, const Info &InfoObj = Info()) : NumBuckets(NumBuckets), NumEntries(NumEntries), Buckets(Buckets), Base(Base), InfoObj(InfoObj) { assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 && "'buckets' must have a 4-byte alignment"); } offset_type getNumBuckets() const { return NumBuckets; } offset_type getNumEntries() const { return NumEntries; } const unsigned char *getBase() const { return Base; } const unsigned char *getBuckets() const { return Buckets; } bool isEmpty() const { return NumEntries == 0; } class iterator { internal_key_type Key; const unsigned char *const Data; const offset_type Len; Info *InfoObj; public: iterator() : Data(nullptr), Len(0) {} iterator(const internal_key_type K, const unsigned char *D, offset_type L, Info *InfoObj) : Key(K), Data(D), Len(L), InfoObj(InfoObj) {} data_type operator*() const { return InfoObj->ReadData(Key, Data, Len); } bool operator==(const iterator &X) const { return X.Data == Data; } bool operator!=(const iterator &X) const { return X.Data != Data; } }; /// \brief Look up the stored data for a particular key. iterator find(const external_key_type &EKey, Info *InfoPtr = nullptr) { const internal_key_type &IKey = InfoObj.GetInternalKey(EKey); hash_value_type KeyHash = InfoObj.ComputeHash(IKey); return find_hashed(IKey, KeyHash, InfoPtr); } /// \brief Look up the stored data for a particular key with a known hash. iterator find_hashed(const internal_key_type &IKey, hash_value_type KeyHash, Info *InfoPtr = nullptr) { using namespace llvm::support; if (!InfoPtr) InfoPtr = &InfoObj; // Each bucket is just an offset into the hash table file. offset_type Idx = KeyHash & (NumBuckets - 1); const unsigned char *Bucket = Buckets + sizeof(offset_type) * Idx; offset_type Offset = endian::readNext<offset_type, little, aligned>(Bucket); if (Offset == 0) return iterator(); // Empty bucket. const unsigned char *Items = Base + Offset; // 'Items' starts with a 16-bit unsigned integer representing the // number of items in this bucket. unsigned Len = endian::readNext<uint16_t, little, unaligned>(Items); for (unsigned i = 0; i < Len; ++i) { // Read the hash. hash_value_type ItemHash = endian::readNext<hash_value_type, little, unaligned>(Items); // Determine the length of the key and the data. const std::pair<offset_type, offset_type> &L = Info::ReadKeyDataLength(Items); offset_type ItemLen = L.first + L.second; // Compare the hashes. If they are not the same, skip the entry entirely. if (ItemHash != KeyHash) { Items += ItemLen; continue; } // Read the key. const internal_key_type &X = InfoPtr->ReadKey((const unsigned char *const)Items, L.first); // If the key doesn't match just skip reading the value. if (!InfoPtr->EqualKey(X, IKey)) { Items += ItemLen; continue; } // The key matches! return iterator(X, Items + L.first, L.second, InfoPtr); } return iterator(); } iterator end() const { return iterator(); } Info &getInfoObj() { return InfoObj; } /// \brief Create the hash table. /// /// \param Buckets is the beginning of the hash table itself, which follows /// the payload of entire structure. This is the value returned by /// OnDiskHashTableGenerator::Emit. /// /// \param Base is the point from which all offsets into the structure are /// based. This is offset 0 in the stream that was used when Emitting the /// table. static OnDiskChainedHashTable *Create(const unsigned char *Buckets, const unsigned char *const Base, const Info &InfoObj = Info()) { using namespace llvm::support; assert(Buckets > Base); assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 && "buckets should be 4-byte aligned."); offset_type NumBuckets = endian::readNext<offset_type, little, aligned>(Buckets); offset_type NumEntries = endian::readNext<offset_type, little, aligned>(Buckets); return new OnDiskChainedHashTable<Info>(NumBuckets, NumEntries, Buckets, Base, InfoObj); } }; /// \brief Provides lookup and iteration over an on disk hash table. /// /// \copydetails llvm::OnDiskChainedHashTable template <typename Info> class OnDiskIterableChainedHashTable : public OnDiskChainedHashTable<Info> { const unsigned char *Payload; public: typedef OnDiskChainedHashTable<Info> base_type; typedef typename base_type::internal_key_type internal_key_type; typedef typename base_type::external_key_type external_key_type; typedef typename base_type::data_type data_type; typedef typename base_type::hash_value_type hash_value_type; typedef typename base_type::offset_type offset_type; OnDiskIterableChainedHashTable(offset_type NumBuckets, offset_type NumEntries, const unsigned char *Buckets, const unsigned char *Payload, const unsigned char *Base, const Info &InfoObj = Info()) : base_type(NumBuckets, NumEntries, Buckets, Base, InfoObj), Payload(Payload) {} /// \brief Iterates over all of the keys in the table. class key_iterator { const unsigned char *Ptr; offset_type NumItemsInBucketLeft; offset_type NumEntriesLeft; Info *InfoObj; public: typedef external_key_type value_type; key_iterator(const unsigned char *const Ptr, offset_type NumEntries, Info *InfoObj) : Ptr(Ptr), NumItemsInBucketLeft(0), NumEntriesLeft(NumEntries), InfoObj(InfoObj) {} key_iterator() : Ptr(nullptr), NumItemsInBucketLeft(0), NumEntriesLeft(0), InfoObj(0) {} friend bool operator==(const key_iterator &X, const key_iterator &Y) { return X.NumEntriesLeft == Y.NumEntriesLeft; } friend bool operator!=(const key_iterator &X, const key_iterator &Y) { return X.NumEntriesLeft != Y.NumEntriesLeft; } key_iterator &operator++() { // Preincrement using namespace llvm::support; if (!NumItemsInBucketLeft) { // 'Items' starts with a 16-bit unsigned integer representing the // number of items in this bucket. NumItemsInBucketLeft = endian::readNext<uint16_t, little, unaligned>(Ptr); } Ptr += sizeof(hash_value_type); // Skip the hash. // Determine the length of the key and the data. const std::pair<offset_type, offset_type> &L = Info::ReadKeyDataLength(Ptr); Ptr += L.first + L.second; assert(NumItemsInBucketLeft); --NumItemsInBucketLeft; assert(NumEntriesLeft); --NumEntriesLeft; return *this; } key_iterator operator++(int) { // Postincrement key_iterator tmp = *this; ++*this; return tmp; } value_type operator*() const { const unsigned char *LocalPtr = Ptr; if (!NumItemsInBucketLeft) LocalPtr += 2; // number of items in bucket LocalPtr += sizeof(hash_value_type); // Skip the hash. // Determine the length of the key and the data. const std::pair<offset_type, offset_type> &L = Info::ReadKeyDataLength(LocalPtr); // Read the key. const internal_key_type &Key = InfoObj->ReadKey(LocalPtr, L.first); return InfoObj->GetExternalKey(Key); } }; key_iterator key_begin() { return key_iterator(Payload, this->getNumEntries(), &this->getInfoObj()); } key_iterator key_end() { return key_iterator(); } iterator_range<key_iterator> keys() { return make_range(key_begin(), key_end()); } /// \brief Iterates over all the entries in the table, returning the data. class data_iterator { const unsigned char *Ptr; offset_type NumItemsInBucketLeft; offset_type NumEntriesLeft; Info *InfoObj; public: typedef data_type value_type; data_iterator(const unsigned char *const Ptr, offset_type NumEntries, Info *InfoObj) : Ptr(Ptr), NumItemsInBucketLeft(0), NumEntriesLeft(NumEntries), InfoObj(InfoObj) {} data_iterator() : Ptr(nullptr), NumItemsInBucketLeft(0), NumEntriesLeft(0), InfoObj(nullptr) {} bool operator==(const data_iterator &X) const { return X.NumEntriesLeft == NumEntriesLeft; } bool operator!=(const data_iterator &X) const { return X.NumEntriesLeft != NumEntriesLeft; } data_iterator &operator++() { // Preincrement using namespace llvm::support; if (!NumItemsInBucketLeft) { // 'Items' starts with a 16-bit unsigned integer representing the // number of items in this bucket. NumItemsInBucketLeft = endian::readNext<uint16_t, little, unaligned>(Ptr); } Ptr += sizeof(hash_value_type); // Skip the hash. // Determine the length of the key and the data. const std::pair<offset_type, offset_type> &L = Info::ReadKeyDataLength(Ptr); Ptr += L.first + L.second; assert(NumItemsInBucketLeft); --NumItemsInBucketLeft; assert(NumEntriesLeft); --NumEntriesLeft; return *this; } data_iterator operator++(int) { // Postincrement data_iterator tmp = *this; ++*this; return tmp; } value_type operator*() const { const unsigned char *LocalPtr = Ptr; if (!NumItemsInBucketLeft) LocalPtr += 2; // number of items in bucket LocalPtr += sizeof(hash_value_type); // Skip the hash. // Determine the length of the key and the data. const std::pair<offset_type, offset_type> &L = Info::ReadKeyDataLength(LocalPtr); // Read the key. const internal_key_type &Key = InfoObj->ReadKey(LocalPtr, L.first); return InfoObj->ReadData(Key, LocalPtr + L.first, L.second); } }; data_iterator data_begin() { return data_iterator(Payload, this->getNumEntries(), &this->getInfoObj()); } data_iterator data_end() { return data_iterator(); } iterator_range<data_iterator> data() { return make_range(data_begin(), data_end()); } /// \brief Create the hash table. /// /// \param Buckets is the beginning of the hash table itself, which follows /// the payload of entire structure. This is the value returned by /// OnDiskHashTableGenerator::Emit. /// /// \param Payload is the beginning of the data contained in the table. This /// is Base plus any padding or header data that was stored, ie, the offset /// that the stream was at when calling Emit. /// /// \param Base is the point from which all offsets into the structure are /// based. This is offset 0 in the stream that was used when Emitting the /// table. static OnDiskIterableChainedHashTable * Create(const unsigned char *Buckets, const unsigned char *const Payload, const unsigned char *const Base, const Info &InfoObj = Info()) { using namespace llvm::support; assert(Buckets > Base); assert((reinterpret_cast<uintptr_t>(Buckets) & 0x3) == 0 && "buckets should be 4-byte aligned."); offset_type NumBuckets = endian::readNext<offset_type, little, aligned>(Buckets); offset_type NumEntries = endian::readNext<offset_type, little, aligned>(Buckets); return new OnDiskIterableChainedHashTable<Info>( NumBuckets, NumEntries, Buckets, Payload, Base, InfoObj); } }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/DataTypes.h.cmake
/*===-- include/Support/DataTypes.h - Define fixed size types -----*- C -*-===*\ |* *| |* The LLVM Compiler Infrastructure *| |* *| |* This file is distributed under the University of Illinois Open Source *| |* License. See LICENSE.TXT for details. *| |* *| |*===----------------------------------------------------------------------===*| |* *| |* This file contains definitions to figure out the size of _HOST_ data types.*| |* This file is important because different host OS's define different macros,*| |* which makes portability tough. This file exports the following *| |* definitions: *| |* *| |* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| |* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| |* *| |* No library is required when using these functions. *| |* *| |*===----------------------------------------------------------------------===*/ /* Please leave this file C-compatible. */ /* Please keep this file in sync with DataTypes.h.in */ #ifndef SUPPORT_DATATYPES_H #define SUPPORT_DATATYPES_H #cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H} #cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H} #cmakedefine HAVE_UINT64_T ${HAVE_UINT64_T} #cmakedefine HAVE_U_INT64_T ${HAVE_U_INT64_T} #ifdef __cplusplus #include <cmath> #else #include <math.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #else #error "Compiler must provide an implementation of stdint.h" #endif #ifndef _MSC_VER /* Note that this header's correct operation depends on __STDC_LIMIT_MACROS being defined. We would define it here, but in order to prevent Bad Things happening when system headers or C++ STL headers include stdint.h before we define it here, we define it on the g++ command line (in Makefile.rules). */ #if !defined(__STDC_LIMIT_MACROS) # error "Must #define __STDC_LIMIT_MACROS before #including Support/DataTypes.h" #endif #if !defined(__STDC_CONSTANT_MACROS) # error "Must #define __STDC_CONSTANT_MACROS before " \ "#including Support/DataTypes.h" #endif /* Note that <inttypes.h> includes <stdint.h>, if this is a C99 system. */ #include <sys/types.h> #ifdef _AIX #include "llvm/Support/AIXDataTypesFix.h" #endif /* Handle incorrect definition of uint64_t as u_int64_t */ #ifndef HAVE_UINT64_T #ifdef HAVE_U_INT64_T typedef u_int64_t uint64_t; #else # error "Don't have a definition for uint64_t on this platform" #endif #endif #else /* _MSC_VER */ #include <stdlib.h> #include <stddef.h> #include <sys/types.h> #ifdef __cplusplus #include <cmath> #else #include <math.h> #endif #if defined(_WIN64) typedef signed __int64 ssize_t; #else typedef signed int ssize_t; #endif /* _WIN64 */ #ifndef HAVE_INTTYPES_H #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #define PRId32 "d" #define PRIi32 "i" #define PRIo32 "o" #define PRIu32 "u" #define PRIx32 "x" #define PRIX32 "X" #endif /* HAVE_INTTYPES_H */ #endif /* _MSC_VER */ /* Set defaults for constants which we cannot find. */ #if !defined(INT64_MAX) # define INT64_MAX 9223372036854775807LL #endif #if !defined(INT64_MIN) # define INT64_MIN ((-INT64_MAX)-1) #endif #if !defined(UINT64_MAX) # define UINT64_MAX 0xffffffffffffffffULL #endif #ifndef HUGE_VALF #define HUGE_VALF (float)HUGE_VAL #endif #endif /* SUPPORT_DATATYPES_H */
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/ToolOutputFile.h
//===- ToolOutputFile.h - Output files for compiler-like tools -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the tool_output_file class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TOOLOUTPUTFILE_H #define LLVM_SUPPORT_TOOLOUTPUTFILE_H #include "llvm/Support/raw_ostream.h" namespace llvm { /// This class contains a raw_fd_ostream and adds a few extra features commonly /// needed for compiler-like tool output files: /// - The file is automatically deleted if the process is killed. /// - The file is automatically deleted when the tool_output_file /// object is destroyed unless the client calls keep(). class tool_output_file { /// This class is declared before the raw_fd_ostream so that it is constructed /// before the raw_fd_ostream is constructed and destructed after the /// raw_fd_ostream is destructed. It installs cleanups in its constructor and /// uninstalls them in its destructor. class CleanupInstaller { /// The name of the file. std::string Filename; public: /// The flag which indicates whether we should not delete the file. bool Keep; explicit CleanupInstaller(StringRef ilename); ~CleanupInstaller(); } Installer; /// The contained stream. This is intentionally declared after Installer. raw_fd_ostream OS; public: /// This constructor's arguments are passed to to raw_fd_ostream's /// constructor. tool_output_file(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags); tool_output_file(StringRef Filename, int FD); /// Return the contained raw_fd_ostream. raw_fd_ostream &os() { return OS; } /// Indicate that the tool's job wrt this output file has been successful and /// the file should not be deleted. void keep() { Installer.Keep = true; } }; } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/CBindingWrapping.h
//===- llvm/Support/CBindingWrapph.h - C Interface Wrapping -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the wrapping macros for the C interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_CBINDINGWRAPPING_H #define LLVM_SUPPORT_CBINDINGWRAPPING_H #include "llvm/Support/Casting.h" #define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ inline ty *unwrap(ref P) { \ return reinterpret_cast<ty*>(P); \ } \ \ inline ref wrap(const ty *P) { \ return reinterpret_cast<ref>(const_cast<ty*>(P)); \ } #define DEFINE_ISA_CONVERSION_FUNCTIONS(ty, ref) \ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ \ template<typename T> \ inline T *unwrap(ref P) { \ return cast<T>(unwrap(P)); \ } #define DEFINE_STDCXX_CONVERSION_FUNCTIONS(ty, ref) \ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ \ template<typename T> \ inline T *unwrap(ref P) { \ T *Q = (T*)unwrap(P); \ assert(Q && "Invalid cast!"); \ return Q; \ } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/MipsABIFlags.h
//===--- MipsABIFlags.h - MIPS ABI flags ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the constants for the ABI flags structure contained // in the .MIPS.abiflags section. // // https://dmz-portal.mips.com/wiki/MIPS_O32_ABI_-_FR0_and_FR1_Interlinking // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_MIPSABIFLAGS_H #define LLVM_SUPPORT_MIPSABIFLAGS_H namespace llvm { namespace Mips { // Values for the xxx_size bytes of an ABI flags structure. enum AFL_REG { AFL_REG_NONE = 0x00, // No registers AFL_REG_32 = 0x01, // 32-bit registers AFL_REG_64 = 0x02, // 64-bit registers AFL_REG_128 = 0x03 // 128-bit registers }; // Masks for the ases word of an ABI flags structure. enum AFL_ASE { AFL_ASE_DSP = 0x00000001, // DSP ASE AFL_ASE_DSPR2 = 0x00000002, // DSP R2 ASE AFL_ASE_EVA = 0x00000004, // Enhanced VA Scheme AFL_ASE_MCU = 0x00000008, // MCU (MicroController) ASE AFL_ASE_MDMX = 0x00000010, // MDMX ASE AFL_ASE_MIPS3D = 0x00000020, // MIPS-3D ASE AFL_ASE_MT = 0x00000040, // MT ASE AFL_ASE_SMARTMIPS = 0x00000080, // SmartMIPS ASE AFL_ASE_VIRT = 0x00000100, // VZ ASE AFL_ASE_MSA = 0x00000200, // MSA ASE AFL_ASE_MIPS16 = 0x00000400, // MIPS16 ASE AFL_ASE_MICROMIPS = 0x00000800, // MICROMIPS ASE AFL_ASE_XPA = 0x00001000 // XPA ASE }; // Values for the isa_ext word of an ABI flags structure. enum AFL_EXT { AFL_EXT_NONE = 0, // None AFL_EXT_XLR = 1, // RMI Xlr instruction AFL_EXT_OCTEON2 = 2, // Cavium Networks Octeon2 AFL_EXT_OCTEONP = 3, // Cavium Networks OcteonP AFL_EXT_LOONGSON_3A = 4, // Loongson 3A AFL_EXT_OCTEON = 5, // Cavium Networks Octeon AFL_EXT_5900 = 6, // MIPS R5900 instruction AFL_EXT_4650 = 7, // MIPS R4650 instruction AFL_EXT_4010 = 8, // LSI R4010 instruction AFL_EXT_4100 = 9, // NEC VR4100 instruction AFL_EXT_3900 = 10, // Toshiba R3900 instruction AFL_EXT_10000 = 11, // MIPS R10000 instruction AFL_EXT_SB1 = 12, // Broadcom SB-1 instruction AFL_EXT_4111 = 13, // NEC VR4111/VR4181 instruction AFL_EXT_4120 = 14, // NEC VR4120 instruction AFL_EXT_5400 = 15, // NEC VR5400 instruction AFL_EXT_5500 = 16, // NEC VR5500 instruction AFL_EXT_LOONGSON_2E = 17, // ST Microelectronics Loongson 2E AFL_EXT_LOONGSON_2F = 18, // ST Microelectronics Loongson 2F AFL_EXT_OCTEON3 = 19 // Cavium Networks Octeon3 }; // Values for the flags1 word of an ABI flags structure. enum AFL_FLAGS1 { AFL_FLAGS1_ODDSPREG = 1 }; // MIPS object attribute tags enum { Tag_GNU_MIPS_ABI_FP = 4, // Floating-point ABI used by this object file Tag_GNU_MIPS_ABI_MSA = 8, // MSA ABI used by this object file }; // Values for the fp_abi word of an ABI flags structure // and for the Tag_GNU_MIPS_ABI_FP attribute tag. enum Val_GNU_MIPS_ABI_FP { Val_GNU_MIPS_ABI_FP_ANY = 0, // not tagged Val_GNU_MIPS_ABI_FP_DOUBLE = 1, // hard float / -mdouble-float Val_GNU_MIPS_ABI_FP_SINGLE = 2, // hard float / -msingle-float Val_GNU_MIPS_ABI_FP_SOFT = 3, // soft float Val_GNU_MIPS_ABI_FP_OLD_64 = 4, // -mips32r2 -mfp64 Val_GNU_MIPS_ABI_FP_XX = 5, // -mfpxx Val_GNU_MIPS_ABI_FP_64 = 6, // -mips32r2 -mfp64 Val_GNU_MIPS_ABI_FP_64A = 7 // -mips32r2 -mfp64 -mno-odd-spreg }; // Values for the Tag_GNU_MIPS_ABI_MSA attribute tag. enum Val_GNU_MIPS_ABI_MSA { Val_GNU_MIPS_ABI_MSA_ANY = 0, // not tagged Val_GNU_MIPS_ABI_MSA_128 = 1 // 128-bit MSA }; } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/CrashRecoveryContext.h
//===--- CrashRecoveryContext.h - Crash Recovery ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H #define LLVM_SUPPORT_CRASHRECOVERYCONTEXT_H #include "llvm/ADT/STLExtras.h" #include <string> namespace llvm { class CrashRecoveryContextCleanup; /// \brief Crash recovery helper object. /// /// This class implements support for running operations in a safe context so /// that crashes (memory errors, stack overflow, assertion violations) can be /// detected and control restored to the crashing thread. Crash detection is /// purely "best effort", the exact set of failures which can be recovered from /// is platform dependent. /// /// Clients make use of this code by first calling /// CrashRecoveryContext::Enable(), and then executing unsafe operations via a /// CrashRecoveryContext object. For example: /// /// void actual_work(void *); /// /// void foo() { /// CrashRecoveryContext CRC; /// /// if (!CRC.RunSafely(actual_work, 0)) { /// ... a crash was detected, report error to user ... /// } /// /// ... no crash was detected ... /// } /// /// Crash recovery contexts may not be nested. class CrashRecoveryContext { void *Impl; CrashRecoveryContextCleanup *head; public: CrashRecoveryContext() : Impl(nullptr), head(nullptr) {} ~CrashRecoveryContext(); void registerCleanup(CrashRecoveryContextCleanup *cleanup); void unregisterCleanup(CrashRecoveryContextCleanup *cleanup); /// \brief Enable crash recovery. static void Enable(); /// \brief Disable crash recovery. static void Disable(); /// \brief Return the active context, if the code is currently executing in a /// thread which is in a protected context. static CrashRecoveryContext *GetCurrent(); /// \brief Return true if the current thread is recovering from a /// crash. static bool isRecoveringFromCrash(); /// \brief Execute the provide callback function (with the given arguments) in /// a protected context. /// /// \return True if the function completed successfully, and false if the /// function crashed (or HandleCrash was called explicitly). Clients should /// make as little assumptions as possible about the program state when /// RunSafely has returned false. Clients can use getBacktrace() to retrieve /// the backtrace of the crash on failures. bool RunSafely(function_ref<void()> Fn); bool RunSafely(void (*Fn)(void*), void *UserData) { return RunSafely([&]() { Fn(UserData); }); } /// \brief Execute the provide callback function (with the given arguments) in /// a protected context which is run in another thread (optionally with a /// requested stack size). /// /// See RunSafely() and llvm_execute_on_thread(). /// /// On Darwin, if PRIO_DARWIN_BG is set on the calling thread, it will be /// propagated to the new thread as well. bool RunSafelyOnThread(function_ref<void()>, unsigned RequestedStackSize = 0); bool RunSafelyOnThread(void (*Fn)(void*), void *UserData, unsigned RequestedStackSize = 0) { return RunSafelyOnThread([&]() { Fn(UserData); }, RequestedStackSize); } /// \brief Explicitly trigger a crash recovery in the current process, and /// return failure from RunSafely(). This function does not return. void HandleCrash(); /// \brief Return a string containing the backtrace where the crash was /// detected; or empty if the backtrace wasn't recovered. /// /// This function is only valid when a crash has been detected (i.e., /// RunSafely() has returned false. const std::string &getBacktrace() const; }; class CrashRecoveryContextCleanup { protected: CrashRecoveryContext *context; CrashRecoveryContextCleanup(CrashRecoveryContext *context) : context(context), cleanupFired(false) {} public: bool cleanupFired; virtual ~CrashRecoveryContextCleanup(); virtual void recoverResources() = 0; CrashRecoveryContext *getContext() const { return context; } private: friend class CrashRecoveryContext; CrashRecoveryContextCleanup *prev, *next; }; template<typename DERIVED, typename T> class CrashRecoveryContextCleanupBase : public CrashRecoveryContextCleanup { protected: T *resource; CrashRecoveryContextCleanupBase(CrashRecoveryContext *context, T* resource) : CrashRecoveryContextCleanup(context), resource(resource) {} public: static DERIVED *create(T *x) { if (x) { if (CrashRecoveryContext *context = CrashRecoveryContext::GetCurrent()) return new DERIVED(context, x); } return 0; } }; template <typename T> class CrashRecoveryContextDestructorCleanup : public CrashRecoveryContextCleanupBase<CrashRecoveryContextDestructorCleanup<T>, T> { public: CrashRecoveryContextDestructorCleanup(CrashRecoveryContext *context, T *resource) : CrashRecoveryContextCleanupBase< CrashRecoveryContextDestructorCleanup<T>, T>(context, resource) {} virtual void recoverResources() { this->resource->~T(); } }; template <typename T> class CrashRecoveryContextDeleteCleanup : public CrashRecoveryContextCleanupBase<CrashRecoveryContextDeleteCleanup<T>, T> { public: CrashRecoveryContextDeleteCleanup(CrashRecoveryContext *context, T *resource) : CrashRecoveryContextCleanupBase< CrashRecoveryContextDeleteCleanup<T>, T>(context, resource) {} void recoverResources() override { delete this->resource; } }; template <typename T> class CrashRecoveryContextReleaseRefCleanup : public CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, T> { public: CrashRecoveryContextReleaseRefCleanup(CrashRecoveryContext *context, T *resource) : CrashRecoveryContextCleanupBase<CrashRecoveryContextReleaseRefCleanup<T>, T>(context, resource) {} void recoverResources() override { this->resource->Release(); } }; template <typename T, typename Cleanup = CrashRecoveryContextDeleteCleanup<T> > class CrashRecoveryContextCleanupRegistrar { CrashRecoveryContextCleanup *cleanup; public: CrashRecoveryContextCleanupRegistrar(T *x) : cleanup(Cleanup::create(x)) { if (cleanup) cleanup->getContext()->registerCleanup(cleanup); } ~CrashRecoveryContextCleanupRegistrar() { unregister(); } void unregister() { if (cleanup && !cleanup->cleanupFired) cleanup->getContext()->unregisterCleanup(cleanup); cleanup = 0; } }; } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/RecyclingAllocator.h
//==- llvm/Support/RecyclingAllocator.h - Recycling Allocator ----*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RecyclingAllocator class. See the doxygen comment for // RecyclingAllocator for more details on the implementation. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_RECYCLINGALLOCATOR_H #define LLVM_SUPPORT_RECYCLINGALLOCATOR_H #include "llvm/Support/Recycler.h" namespace llvm { /// RecyclingAllocator - This class wraps an Allocator, adding the /// functionality of recycling deleted objects. /// template<class AllocatorType, class T, size_t Size = sizeof(T), size_t Align = AlignOf<T>::Alignment> class RecyclingAllocator { private: /// Base - Implementation details. /// Recycler<T, Size, Align> Base; /// Allocator - The wrapped allocator. /// AllocatorType Allocator; public: ~RecyclingAllocator() { Base.clear(Allocator); } /// Allocate - Return a pointer to storage for an object of type /// SubClass. The storage may be either newly allocated or recycled. /// template<class SubClass> SubClass *Allocate() { return Base.template Allocate<SubClass>(Allocator); } T *Allocate() { return Base.Allocate(Allocator); } /// Deallocate - Release storage for the pointed-to object. The /// storage will be kept track of and may be recycled. /// template<class SubClass> void Deallocate(SubClass* E) { return Base.Deallocate(Allocator, E); } void PrintStats() { Allocator.PrintStats(); Base.PrintStats(); } }; } template<class AllocatorType, class T, size_t Size, size_t Align> inline void *operator new(size_t size, llvm::RecyclingAllocator<AllocatorType, T, Size, Align> &Allocator) { assert(size <= Size && "allocation size exceeded"); return Allocator.Allocate(); } template<class AllocatorType, class T, size_t Size, size_t Align> inline void operator delete(void *E, llvm::RecyclingAllocator<AllocatorType, T, Size, Align> &A) { A.Deallocate(E); } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/raw_ostream.h
//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the raw_ostream class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_RAW_OSTREAM_H #define LLVM_SUPPORT_RAW_OSTREAM_H #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/DataTypes.h" #include <system_error> namespace llvm { class format_object_base; class FormattedString; class FormattedNumber; template <typename T> class SmallVectorImpl; namespace sys { namespace fs { enum OpenFlags : unsigned; } } /// This class implements an extremely fast bulk output stream that can *only* /// output to a stream. It does not support seeking, reopening, rewinding, line /// buffered disciplines etc. It is a simple buffer that outputs /// a chunk at a time. class raw_ostream { private: void operator=(const raw_ostream &) = delete; raw_ostream(const raw_ostream &) = delete; /// The buffer is handled in such a way that the buffer is /// uninitialized, unbuffered, or out of space when OutBufCur >= /// OutBufEnd. Thus a single comparison suffices to determine if we /// need to take the slow path to write a single character. /// /// The buffer is in one of three states: /// 1. Unbuffered (BufferMode == Unbuffered) /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0). /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 && /// OutBufEnd - OutBufStart >= 1). /// /// If buffered, then the raw_ostream owns the buffer if (BufferMode == /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is /// managed by the subclass. /// /// If a subclass installs an external buffer using SetBuffer then it can wait /// for a \see write_impl() call to handle the data which has been put into /// this buffer. char *OutBufStart, *OutBufEnd, *OutBufCur; /// The base in which numbers will be written. default is 10. 8 and 16 are /// also possible. int writeBase; // HLSL Change enum BufferKind { Unbuffered = 0, InternalBuffer, ExternalBuffer } BufferMode; public: // color order matches ANSI escape sequence, don't change enum Colors { BLACK=0, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, SAVEDCOLOR }; explicit raw_ostream(bool unbuffered = false) : BufferMode(unbuffered ? Unbuffered : InternalBuffer) { // Start out ready to flush. OutBufStart = OutBufEnd = OutBufCur = nullptr; writeBase = 10; // HLSL Change } virtual ~raw_ostream(); /// tell - Return the current offset with the file. uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); } // HLSL Change Starts - needed to clean up properly virtual void close() { flush(); } virtual bool has_error() const { return false; } virtual void clear_error() { } // HLSL Change Ends //===--------------------------------------------------------------------===// // Configuration Interface //===--------------------------------------------------------------------===// /// Set the stream to be buffered, with an automatically determined buffer /// size. void SetBuffered(); /// Set the stream to be buffered, using the specified buffer size. void SetBufferSize(size_t Size) { flush(); SetBufferAndMode(new char[Size], Size, InternalBuffer); } size_t GetBufferSize() const { // If we're supposed to be buffered but haven't actually gotten around // to allocating the buffer yet, return the value that would be used. if (BufferMode != Unbuffered && OutBufStart == nullptr) return preferred_buffer_size(); // Otherwise just return the size of the allocated buffer. return OutBufEnd - OutBufStart; } /// Set the stream to be unbuffered. When unbuffered, the stream will flush /// after every write. This routine will also flush the buffer immediately /// when the stream is being set to unbuffered. void SetUnbuffered() { flush(); SetBufferAndMode(nullptr, 0, Unbuffered); } size_t GetNumBytesInBuffer() const { return OutBufCur - OutBufStart; } //===--------------------------------------------------------------------===// // Data Output Interface //===--------------------------------------------------------------------===// void flush() { if (OutBufCur != OutBufStart) flush_nonempty(); } raw_ostream &operator<<(char C) { if (OutBufCur >= OutBufEnd) return write(C); *OutBufCur++ = C; return *this; } raw_ostream &operator<<(unsigned char C) { if (OutBufCur >= OutBufEnd) return write(C); *OutBufCur++ = C; return *this; } raw_ostream &operator<<(signed char C) { if (OutBufCur >= OutBufEnd) return write(C); *OutBufCur++ = C; return *this; } raw_ostream &operator<<(StringRef Str) { // Inline fast path, particularly for strings with a known length. size_t Size = Str.size(); // Make sure we can use the fast path. if (Size > (size_t)(OutBufEnd - OutBufCur)) return write(Str.data(), Size); if (Size) { memcpy(OutBufCur, Str.data(), Size); OutBufCur += Size; } return *this; } raw_ostream &operator<<(const char *Str) { // Inline fast path, particularly for constant strings where a sufficiently // smart compiler will simplify strlen. return this->operator<<(StringRef(Str)); } raw_ostream &operator<<(const std::string &Str) { // Avoid the fast path, it would only increase code size for a marginal win. return write(Str.data(), Str.length()); } raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) { return write(Str.data(), Str.size()); } raw_ostream &operator<<(unsigned long N); raw_ostream &operator<<(long N); raw_ostream &operator<<(unsigned long long N); raw_ostream &operator<<(long long N); raw_ostream &operator<<(const void *P); raw_ostream &operator<<(unsigned int N) { return this->operator<<(static_cast<unsigned long>(N)); } raw_ostream &operator<<(int N) { return this->operator<<(static_cast<long>(N)); } raw_ostream &operator<<(double N); /// Output \p N in hexadecimal, without any prefix or padding. raw_ostream &write_hex(unsigned long long N); /// Output \p N in writeBase, without any prefix or padding. raw_ostream &write_base(unsigned long long N); // HLSL Change /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't /// satisfy std::isprint into an escape sequence. raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); raw_ostream &write(unsigned char C); raw_ostream &write(const char *Ptr, size_t Size); // Formatted output, see the format() function in Support/Format.h. raw_ostream &operator<<(const format_object_base &Fmt); // Formatted output, see the leftJustify() function in Support/Format.h. raw_ostream &operator<<(const FormattedString &); // Formatted output, see the formatHex() function in Support/Format.h. raw_ostream &operator<<(const FormattedNumber &); raw_ostream & operator<<(std::ios_base &(__cdecl*iomanip)(std::ios_base &)); // HLSL Change /// indent - Insert 'NumSpaces' spaces. raw_ostream &indent(unsigned NumSpaces); /// Changes the foreground color of text that will be output from this point /// forward. /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to /// change only the bold attribute, and keep colors untouched /// @param Bold bold/brighter text, default false /// @param BG if true change the background, default: change foreground /// @returns itself so it can be used within << invocations virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false, bool BG = false) { (void)Color; (void)Bold; (void)BG; return *this; } /// Resets the colors to terminal defaults. Call this when you are done /// outputting colored text, or before program exit. virtual raw_ostream &resetColor() { return *this; } /// Reverses the forground and background colors. virtual raw_ostream &reverseColor() { return *this; } /// This function determines if this stream is connected to a "tty" or /// "console" window. That is, the output would be displayed to the user /// rather than being put on a pipe or stored in a file. virtual bool is_displayed() const { return false; } /// This function determines if this stream is displayed and supports colors. virtual bool has_colors() const { return is_displayed(); } //===--------------------------------------------------------------------===// // Subclass Interface //===--------------------------------------------------------------------===// private: /// The is the piece of the class that is implemented by subclasses. This /// writes the \p Size bytes starting at /// \p Ptr to the underlying stream. /// /// This function is guaranteed to only be called at a point at which it is /// safe for the subclass to install a new buffer via SetBuffer. /// /// \param Ptr The start of the data to be written. For buffered streams this /// is guaranteed to be the start of the buffer. /// /// \param Size The number of bytes to be written. /// /// \invariant { Size > 0 } virtual void write_impl(const char *Ptr, size_t Size) = 0; // An out of line virtual method to provide a home for the class vtable. virtual void handle(); /// Return the current position within the stream, not counting the bytes /// currently in the buffer. virtual uint64_t current_pos() const = 0; protected: /// Use the provided buffer as the raw_ostream buffer. This is intended for /// use only by subclasses which can arrange for the output to go directly /// into the desired output buffer, instead of being copied on each flush. void SetBuffer(char *BufferStart, size_t Size) { SetBufferAndMode(BufferStart, Size, ExternalBuffer); } /// Return an efficient buffer size for the underlying output mechanism. virtual size_t preferred_buffer_size() const; /// Return the beginning of the current stream buffer, or 0 if the stream is /// unbuffered. const char *getBufferStart() const { return OutBufStart; } //===--------------------------------------------------------------------===// // Private Interface //===--------------------------------------------------------------------===// private: /// Install the given buffer and mode. void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); /// Flush the current buffer, which is known to be non-empty. This outputs the /// currently buffered data and resets the buffer to empty. void flush_nonempty(); /// Copy data into the buffer. Size must not be greater than the number of /// unused bytes in the buffer. void copy_to_buffer(const char *Ptr, size_t Size); }; /// An abstract base class for streams implementations that also support a /// pwrite operation. This is usefull for code that can mostly stream out data, /// but needs to patch in a header that needs to know the output size. class raw_pwrite_stream : public raw_ostream { virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0; public: explicit raw_pwrite_stream(bool Unbuffered = false) : raw_ostream(Unbuffered) {} void pwrite(const char *Ptr, size_t Size, uint64_t Offset) { #ifndef NDBEBUG uint64_t Pos = tell(); // /dev/null always reports a pos of 0, so we cannot perform this check // in that case. if (Pos) assert(Size + Offset <= Pos && "We don't support extending the stream"); #endif pwrite_impl(Ptr, Size, Offset); } }; //===----------------------------------------------------------------------===// // File Output Streams //===----------------------------------------------------------------------===// /// A raw_ostream that writes to a file descriptor. /// class raw_fd_ostream : public raw_pwrite_stream { int FD; bool ShouldClose; /// Error This flag is true if an error of any kind has been detected. /// bool Error; /// Controls whether the stream should attempt to use atomic writes, when /// possible. bool UseAtomicWrites; uint64_t pos; bool SupportsSeeking; /// See raw_ostream::write_impl. void write_impl(const char *Ptr, size_t Size) override; void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t current_pos() const override { return pos; } /// Determine an efficient buffer size. size_t preferred_buffer_size() const override; /// Set the flag indicating that an output error has been encountered. void error_detected() { Error = true; } public: /// Open the specified file for writing. If an error occurs, information /// about the error is put into EC, and the stream should be immediately /// destroyed; /// \p Flags allows optional flags to control how the file will be opened. /// /// As a special case, if Filename is "-", then the stream will use /// STDOUT_FILENO instead of opening a file. Note that it will still consider /// itself to own the file descriptor. In particular, it will close the /// file descriptor when it is done (this is necessary to detect /// output errors). raw_fd_ostream(StringRef Filename, std::error_code &EC, sys::fs::OpenFlags Flags); /// FD is the file descriptor that this writes to. If ShouldClose is true, /// this closes the file when the stream is destroyed. raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false); ~raw_fd_ostream() override; /// Manually flush the stream and close the file. Note that this does not call /// fsync. void close() override; bool supportsSeeking() { return SupportsSeeking; } /// Flushes the stream and repositions the underlying file descriptor position /// to the offset specified from the beginning of the file. uint64_t seek(uint64_t off); /// Set the stream to attempt to use atomic writes for individual output /// routines where possible. /// /// Note that because raw_ostream's are typically buffered, this flag is only /// sensible when used on unbuffered streams which will flush their output /// immediately. void SetUseAtomicWrites(bool Value) { UseAtomicWrites = Value; } raw_ostream &changeColor(enum Colors colors, bool bold=false, bool bg=false) override; raw_ostream &resetColor() override; raw_ostream &reverseColor() override; bool is_displayed() const override; bool has_colors() const override; /// Return the value of the flag in this raw_fd_ostream indicating whether an /// output error has been encountered. /// This doesn't implicitly flush any pending output. Also, it doesn't /// guarantee to detect all errors unless the stream has been closed. bool has_error() const override { return Error; } /// Set the flag read by has_error() to false. If the error flag is set at the /// time when this raw_ostream's destructor is called, report_fatal_error is /// called to report the error. Use clear_error() after handling the error to /// avoid this behavior. /// /// "Errors should never pass silently. /// Unless explicitly silenced." /// - from The Zen of Python, by Tim Peters /// void clear_error() override { Error = false; } }; /// This returns a reference to a raw_ostream for standard output. Use it like: /// outs() << "foo" << "bar"; raw_ostream &outs(); /// This returns a reference to a raw_ostream for standard error. Use it like: /// errs() << "foo" << "bar"; raw_ostream &errs(); /// This returns a reference to a raw_ostream which simply discards output. raw_ostream &nulls(); // HLSL Change Starts // Flush and close STDOUT/STDERR streams before MSFileSystem goes down, // otherwise static destructors will attempt to close after we no longer // have a file system, which will raise an exception on static shutdown. // This is a temporary work around until outs() and errs() is fixed to // do the right thing. // The usage pattern is to create an instance in main() after a console-based // MSFileSystem has been installed. class STDStreamCloser { public: ~STDStreamCloser() { llvm::raw_fd_ostream& fo = static_cast<llvm::raw_fd_ostream&>(llvm::outs()); llvm::raw_fd_ostream& fe = static_cast<llvm::raw_fd_ostream&>(llvm::errs()); fo.flush(); fe.flush(); fo.close(); // do not close fe (STDERR), since it was initialized with ShouldClose to false. // (see errs() definition). } }; // HLSL Change Ends //===----------------------------------------------------------------------===// // Output Stream Adaptors // // /////////////////////////////////////////////////////////////////////////////// /// A raw_ostream that writes to an std::string. This is a simple adaptor /// class. This class does not encounter output errors. class raw_string_ostream : public raw_ostream { std::string &OS; /// See raw_ostream::write_impl. void write_impl(const char *Ptr, size_t Size) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t current_pos() const override { return OS.size(); } public: explicit raw_string_ostream(std::string &O) : OS(O) { SetUnbuffered(); } ~raw_string_ostream() override; /// Flushes the stream contents to the target string and returns the string's /// reference. std::string& str() { flush(); return OS; } }; /// A raw_ostream that writes to an SmallVector or SmallString. This is a /// simple adaptor class. This class does not encounter output errors. class raw_svector_ostream : public raw_pwrite_stream { SmallVectorImpl<char> &OS; /// See raw_ostream::write_impl. void write_impl(const char *Ptr, size_t Size) override; void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t current_pos() const override; protected: // Like the regular constructor, but doesn't call init. explicit raw_svector_ostream(SmallVectorImpl<char> &O, unsigned); void init(); public: /// Construct a new raw_svector_ostream. /// /// \param O The vector to write to; this should generally have at least 128 /// bytes free to avoid any extraneous memory overhead. explicit raw_svector_ostream(SmallVectorImpl<char> &O); ~raw_svector_ostream() override; /// This is called when the SmallVector we're appending to is changed outside /// of the raw_svector_ostream's control. It is only safe to do this if the /// raw_svector_ostream has previously been flushed. void resync(); /// Flushes the stream contents to the target vector and return a StringRef /// for the vector contents. StringRef str(); }; /// A raw_ostream that discards all output. class raw_null_ostream : public raw_pwrite_stream { /// See raw_ostream::write_impl. void write_impl(const char *Ptr, size_t size) override; void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t current_pos() const override; public: explicit raw_null_ostream() {} ~raw_null_ostream() override; }; class buffer_ostream : public raw_svector_ostream { raw_ostream &OS; SmallVector<char, 0> Buffer; public: buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer, 0), OS(OS) { init(); } ~buffer_ostream() { OS << str(); } }; } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/StreamingMemoryObject.h
//===- StreamingMemoryObject.h - Streamable data interface -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_STREAMINGMEMORYOBJECT_H #define LLVM_SUPPORT_STREAMINGMEMORYOBJECT_H #include "llvm/Support/Compiler.h" #include "llvm/Support/DataStream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryObject.h" #include <memory> #include <vector> namespace llvm { /// Interface to data which is actually streamed from a DataStreamer. In /// addition to inherited members, it has the dropLeadingBytes and /// setKnownObjectSize methods which are not applicable to non-streamed objects. class StreamingMemoryObject : public MemoryObject { public: StreamingMemoryObject(std::unique_ptr<DataStreamer> Streamer); uint64_t getExtent() const override; uint64_t readBytes(uint8_t *Buf, uint64_t Size, uint64_t Address) const override; const uint8_t *getPointer(uint64_t address, uint64_t size) const override { // FIXME: This could be fixed by ensuring the bytes are fetched and // making a copy, requiring that the bitcode size be known, or // otherwise ensuring that the memory doesn't go away/get reallocated, // but it's not currently necessary. Users that need the pointer (any // that need Blobs) don't stream. report_fatal_error("getPointer in streaming memory objects not allowed"); return nullptr; } bool isValidAddress(uint64_t address) const override; /// Drop s bytes from the front of the stream, pushing the positions of the /// remaining bytes down by s. This is used to skip past the bitcode header, /// since we don't know a priori if it's present, and we can't put bytes /// back into the stream once we've read them. bool dropLeadingBytes(size_t s); /// If the data object size is known in advance, many of the operations can /// be made more efficient, so this method should be called before reading /// starts (although it can be called anytime). void setKnownObjectSize(size_t size); private: const static uint32_t kChunkSize = 4096 * 4; mutable std::vector<unsigned char> Bytes; std::unique_ptr<DataStreamer> Streamer; mutable size_t BytesRead; // Bytes read from stream size_t BytesSkipped;// Bytes skipped at start of stream (e.g. wrapper/header) mutable size_t ObjectSize; // 0 if unknown, set if wrapper seen or EOF reached mutable bool EOFReached; // Fetch enough bytes such that Pos can be read (i.e. BytesRead > // Pos). Returns true if Pos can be read. Unlike most of the // functions in BitcodeReader, returns true on success. Most of the // requests will be small, but we fetch at kChunkSize bytes at a // time to avoid making too many potentially expensive GetBytes // calls. bool fetchToPos(size_t Pos) const { while (Pos >= BytesRead) { if (EOFReached) return false; Bytes.resize(BytesRead + BytesSkipped + kChunkSize); size_t bytes = Streamer->GetBytes(&Bytes[BytesRead + BytesSkipped], kChunkSize); BytesRead += bytes; if (bytes == 0) { // reached EOF/ran out of bytes if (ObjectSize == 0) ObjectSize = BytesRead; EOFReached = true; } } return !ObjectSize || Pos < ObjectSize; } StreamingMemoryObject(const StreamingMemoryObject&) = delete; void operator=(const StreamingMemoryObject&) = delete; }; MemoryObject *getNonStreamedMemoryObject( const unsigned char *Start, const unsigned char *End); } #endif // STREAMINGMEMORYOBJECT_H_
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Watchdog.h
//===--- Watchdog.h - Watchdog timer ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::Watchdog class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_WATCHDOG_H #define LLVM_SUPPORT_WATCHDOG_H #include "llvm/Support/Compiler.h" namespace llvm { namespace sys { /// This class provides an abstraction for a timeout around an operation /// that must complete in a given amount of time. Failure to complete before /// the timeout is an unrecoverable situation and no mechanisms to attempt /// to handle it are provided. class Watchdog { public: Watchdog(unsigned int seconds); ~Watchdog(); private: // Noncopyable. Watchdog(const Watchdog &other) = delete; Watchdog &operator=(const Watchdog &other) = delete; }; } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Unicode.h
//===- llvm/Support/Unicode.h - Unicode character properties -*- C++ -*-=====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines functions that allow querying certain properties of Unicode // characters. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_UNICODE_H #define LLVM_SUPPORT_UNICODE_H #include "llvm/ADT/StringRef.h" namespace llvm { namespace sys { namespace unicode { enum ColumnWidthErrors { ErrorInvalidUTF8 = -2, ErrorNonPrintableCharacter = -1 }; /// Determines if a character is likely to be displayed correctly on the /// terminal. Exact implementation would have to depend on the specific /// terminal, so we define the semantic that should be suitable for generic case /// of a terminal capable to output Unicode characters. /// /// All characters from the Unicode code point range are considered printable /// except for: /// * C0 and C1 control character ranges; /// * default ignorable code points as per 5.21 of /// http://www.unicode.org/versions/Unicode6.2.0/UnicodeStandard-6.2.pdf /// except for U+00AD SOFT HYPHEN, as it's actually displayed on most /// terminals; /// * format characters (category = Cf); /// * surrogates (category = Cs); /// * unassigned characters (category = Cn). /// \return true if the character is considered printable. bool isPrintable(int UCS); /// Gets the number of positions the UTF8-encoded \p Text is likely to occupy /// when output on a terminal ("character width"). This depends on the /// implementation of the terminal, and there's no standard definition of /// character width. /// /// The implementation defines it in a way that is expected to be compatible /// with a generic Unicode-capable terminal. /// /// \return Character width: /// * ErrorNonPrintableCharacter (-1) if \p Text contains non-printable /// characters (as identified by isPrintable); /// * 0 for each non-spacing and enclosing combining mark; /// * 2 for each CJK character excluding halfwidth forms; /// * 1 for each of the remaining characters. int columnWidthUTF8(StringRef Text); } // namespace unicode } // namespace sys } // namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Win64EH.h
//===-- llvm/Support/Win64EH.h ---Win64 EH Constants-------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains constants and structures used for implementing // exception handling on Win64 platforms. For more information, see // http://msdn.microsoft.com/en-us/library/1eyas8tf.aspx // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_WIN64EH_H #define LLVM_SUPPORT_WIN64EH_H #include "llvm/Support/DataTypes.h" #include "llvm/Support/Endian.h" namespace llvm { namespace Win64EH { /// UnwindOpcodes - Enumeration whose values specify a single operation in /// the prolog of a function. enum UnwindOpcodes { UOP_PushNonVol = 0, UOP_AllocLarge, UOP_AllocSmall, UOP_SetFPReg, UOP_SaveNonVol, UOP_SaveNonVolBig, UOP_SaveXMM128 = 8, UOP_SaveXMM128Big, UOP_PushMachFrame }; /// UnwindCode - This union describes a single operation in a function prolog, /// or part thereof. union UnwindCode { struct { uint8_t CodeOffset; uint8_t UnwindOpAndOpInfo; } u; support::ulittle16_t FrameOffset; uint8_t getUnwindOp() const { return u.UnwindOpAndOpInfo & 0x0F; } uint8_t getOpInfo() const { return (u.UnwindOpAndOpInfo >> 4) & 0x0F; } }; enum { /// UNW_ExceptionHandler - Specifies that this function has an exception /// handler. UNW_ExceptionHandler = 0x01, /// UNW_TerminateHandler - Specifies that this function has a termination /// handler. UNW_TerminateHandler = 0x02, /// UNW_ChainInfo - Specifies that this UnwindInfo structure is chained to /// another one. UNW_ChainInfo = 0x04 }; /// RuntimeFunction - An entry in the table of functions with unwind info. struct RuntimeFunction { support::ulittle32_t StartAddress; support::ulittle32_t EndAddress; support::ulittle32_t UnwindInfoOffset; }; /// UnwindInfo - An entry in the exception table. struct UnwindInfo { uint8_t VersionAndFlags; uint8_t PrologSize; uint8_t NumCodes; uint8_t FrameRegisterAndOffset; UnwindCode UnwindCodes[1]; uint8_t getVersion() const { return VersionAndFlags & 0x07; } uint8_t getFlags() const { return (VersionAndFlags >> 3) & 0x1f; } uint8_t getFrameRegister() const { return FrameRegisterAndOffset & 0x0f; } uint8_t getFrameOffset() const { return (FrameRegisterAndOffset >> 4) & 0x0f; } // The data after unwindCodes depends on flags. // If UNW_ExceptionHandler or UNW_TerminateHandler is set then follows // the address of the language-specific exception handler. // If UNW_ChainInfo is set then follows a RuntimeFunction which defines // the chained unwind info. // For more information please see MSDN at: // http://msdn.microsoft.com/en-us/library/ddssxxy8.aspx /// \brief Return pointer to language specific data part of UnwindInfo. void *getLanguageSpecificData() { return reinterpret_cast<void *>(&UnwindCodes[(NumCodes+1) & ~1]); } /// \brief Return pointer to language specific data part of UnwindInfo. const void *getLanguageSpecificData() const { return reinterpret_cast<const void *>(&UnwindCodes[(NumCodes + 1) & ~1]); } /// \brief Return image-relative offset of language-specific exception handler. uint32_t getLanguageSpecificHandlerOffset() const { return *reinterpret_cast<const support::ulittle32_t *>( getLanguageSpecificData()); } /// \brief Set image-relative offset of language-specific exception handler. void setLanguageSpecificHandlerOffset(uint32_t offset) { *reinterpret_cast<support::ulittle32_t *>(getLanguageSpecificData()) = offset; } /// \brief Return pointer to exception-specific data. void *getExceptionData() { return reinterpret_cast<void *>(reinterpret_cast<uint32_t *>( getLanguageSpecificData())+1); } /// \brief Return pointer to chained unwind info. RuntimeFunction *getChainedFunctionEntry() { return reinterpret_cast<RuntimeFunction *>(getLanguageSpecificData()); } /// \brief Return pointer to chained unwind info. const RuntimeFunction *getChainedFunctionEntry() const { return reinterpret_cast<const RuntimeFunction *>(getLanguageSpecificData()); } }; } // End of namespace Win64EH } // End of namespace llvm #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/Host.h
//===- llvm/Support/Host.h - Host machine characteristics --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Methods for querying the nature of the host machine. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_HOST_H #define LLVM_SUPPORT_HOST_H #include "llvm/ADT/StringMap.h" #if defined(__linux__) || defined(__GNU__) #include <endian.h> #else #if !defined(BYTE_ORDER) && !defined(LLVM_ON_WIN32) #include <machine/endian.h> #endif #endif #include <string> namespace llvm { namespace sys { #if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN static const bool IsBigEndianHost = true; #else static const bool IsBigEndianHost = false; #endif static const bool IsLittleEndianHost = !IsBigEndianHost; /// getDefaultTargetTriple() - Return the default target triple the compiler /// has been configured to produce code for. /// /// The target triple is a string in the format of: /// CPU_TYPE-VENDOR-OPERATING_SYSTEM /// or /// CPU_TYPE-VENDOR-KERNEL-OPERATING_SYSTEM // HLSL Change - single triple supported, no allocation required #ifdef _WIN32 const char *getDefaultTargetTriple(); #else std::string getDefaultTargetTriple(); #endif /// getProcessTriple() - Return an appropriate target triple for generating /// code to be loaded into the current process, e.g. when using the JIT. std::string getProcessTriple(); /// getHostCPUName - Get the LLVM name for the host CPU. The particular format /// of the name is target dependent, and suitable for passing as -mcpu to the /// target which matches the host. /// /// \return - The host CPU name, or empty if the CPU could not be determined. StringRef getHostCPUName(); /// getHostCPUFeatures - Get the LLVM names for the host CPU features. /// The particular format of the names are target dependent, and suitable for /// passing as -mattr to the target which matches the host. /// /// \param Features - A string mapping feature names to either /// true (if enabled) or false (if disabled). This routine makes no guarantees /// about exactly which features may appear in this map, except that they are /// all valid LLVM feature names. /// /// \return - True on success. bool getHostCPUFeatures(StringMap<bool> &Features); } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/YAMLTraits.h
//===- llvm/Support/YAMLTraits.h --------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_YAMLTRAITS_H #define LLVM_SUPPORT_YAMLTRAITS_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Regex.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/raw_ostream.h" #include <system_error> namespace llvm { namespace yaml { /// This class should be specialized by any type that needs to be converted /// to/from a YAML mapping. For example: /// /// struct MappingTraits<MyStruct> { /// static void mapping(IO &io, MyStruct &s) { /// io.mapRequired("name", s.name); /// io.mapRequired("size", s.size); /// io.mapOptional("age", s.age); /// } /// }; template<class T> struct MappingTraits { // Must provide: // static void mapping(IO &io, T &fields); // Optionally may provide: // static StringRef validate(IO &io, T &fields); // // The optional flow flag will cause generated YAML to use a flow mapping // (e.g. { a: 0, b: 1 }): // static const bool flow = true; }; /// This class should be specialized by any integral type that converts /// to/from a YAML scalar where there is a one-to-one mapping between /// in-memory values and a string in YAML. For example: /// /// struct ScalarEnumerationTraits<Colors> { /// static void enumeration(IO &io, Colors &value) { /// io.enumCase(value, "red", cRed); /// io.enumCase(value, "blue", cBlue); /// io.enumCase(value, "green", cGreen); /// } /// }; template<typename T> struct ScalarEnumerationTraits { // Must provide: // static void enumeration(IO &io, T &value); }; /// This class should be specialized by any integer type that is a union /// of bit values and the YAML representation is a flow sequence of /// strings. For example: /// /// struct ScalarBitSetTraits<MyFlags> { /// static void bitset(IO &io, MyFlags &value) { /// io.bitSetCase(value, "big", flagBig); /// io.bitSetCase(value, "flat", flagFlat); /// io.bitSetCase(value, "round", flagRound); /// } /// }; template<typename T> struct ScalarBitSetTraits { // Must provide: // static void bitset(IO &io, T &value); }; /// This class should be specialized by type that requires custom conversion /// to/from a yaml scalar. For example: /// /// template<> /// struct ScalarTraits<MyType> { /// static void output(const MyType &val, void*, llvm::raw_ostream &out) { /// // stream out custom formatting /// out << llvm::format("%x", val); /// } /// static StringRef input(StringRef scalar, void*, MyType &value) { /// // parse scalar and set `value` /// // return empty string on success, or error string /// return StringRef(); /// } /// static bool mustQuote(StringRef) { return true; } /// }; template<typename T> struct ScalarTraits { // Must provide: // // Function to write the value as a string: //static void output(const T &value, void *ctxt, llvm::raw_ostream &out); // // Function to convert a string to a value. Returns the empty // StringRef on success or an error string if string is malformed: //static StringRef input(StringRef scalar, void *ctxt, T &value); // // Function to determine if the value should be quoted. //static bool mustQuote(StringRef); }; /// This class should be specialized by type that requires custom conversion /// to/from a YAML literal block scalar. For example: /// /// template <> /// struct BlockScalarTraits<MyType> { /// static void output(const MyType &Value, void*, llvm::raw_ostream &Out) /// { /// // stream out custom formatting /// Out << Val; /// } /// static StringRef input(StringRef Scalar, void*, MyType &Value) { /// // parse scalar and set `value` /// // return empty string on success, or error string /// return StringRef(); /// } /// }; template <typename T> struct BlockScalarTraits { // Must provide: // // Function to write the value as a string: // static void output(const T &Value, void *ctx, llvm::raw_ostream &Out); // // Function to convert a string to a value. Returns the empty // StringRef on success or an error string if string is malformed: // static StringRef input(StringRef Scalar, void *ctxt, T &Value); }; /// This class should be specialized by any type that needs to be converted /// to/from a YAML sequence. For example: /// /// template<> /// struct SequenceTraits< std::vector<MyType> > { /// static size_t size(IO &io, std::vector<MyType> &seq) { /// return seq.size(); /// } /// static MyType& element(IO &, std::vector<MyType> &seq, size_t index) { /// if ( index >= seq.size() ) /// seq.resize(index+1); /// return seq[index]; /// } /// }; template<typename T> struct SequenceTraits { // Must provide: // static size_t size(IO &io, T &seq); // static T::value_type& element(IO &io, T &seq, size_t index); // // The following is option and will cause generated YAML to use // a flow sequence (e.g. [a,b,c]). // static const bool flow = true; }; /// This class should be specialized by any type that needs to be converted /// to/from a list of YAML documents. template<typename T> struct DocumentListTraits { // Must provide: // static size_t size(IO &io, T &seq); // static T::value_type& element(IO &io, T &seq, size_t index); }; // Only used by compiler if both template types are the same template <typename T, T> struct SameType; // Only used for better diagnostics of missing traits template <typename T> struct MissingTrait; // Test if ScalarEnumerationTraits<T> is defined on type T. template <class T> struct has_ScalarEnumerationTraits { typedef void (*Signature_enumeration)(class IO&, T&); template <typename U> static char test(SameType<Signature_enumeration, &U::enumeration>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<ScalarEnumerationTraits<T> >(nullptr)) == 1); }; // Test if ScalarBitSetTraits<T> is defined on type T. template <class T> struct has_ScalarBitSetTraits { typedef void (*Signature_bitset)(class IO&, T&); template <typename U> static char test(SameType<Signature_bitset, &U::bitset>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<ScalarBitSetTraits<T> >(nullptr)) == 1); }; // Test if ScalarTraits<T> is defined on type T. template <class T> struct has_ScalarTraits { typedef StringRef (*Signature_input)(StringRef, void*, T&); typedef void (*Signature_output)(const T&, void*, llvm::raw_ostream&); typedef bool (*Signature_mustQuote)(StringRef); template <typename U> static char test(SameType<Signature_input, &U::input> *, SameType<Signature_output, &U::output> *, SameType<Signature_mustQuote, &U::mustQuote> *); template <typename U> static double test(...); public: static bool const value = (sizeof(test<ScalarTraits<T>>(nullptr, nullptr, nullptr)) == 1); }; // Test if BlockScalarTraits<T> is defined on type T. template <class T> struct has_BlockScalarTraits { typedef StringRef (*Signature_input)(StringRef, void *, T &); typedef void (*Signature_output)(const T &, void *, llvm::raw_ostream &); template <typename U> static char test(SameType<Signature_input, &U::input> *, SameType<Signature_output, &U::output> *); template <typename U> static double test(...); public: static bool const value = (sizeof(test<BlockScalarTraits<T>>(nullptr, nullptr)) == 1); }; // Test if MappingTraits<T> is defined on type T. template <class T> struct has_MappingTraits { typedef void (*Signature_mapping)(class IO&, T&); template <typename U> static char test(SameType<Signature_mapping, &U::mapping>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<MappingTraits<T> >(nullptr)) == 1); }; // Test if MappingTraits<T>::validate() is defined on type T. template <class T> struct has_MappingValidateTraits { typedef StringRef (*Signature_validate)(class IO&, T&); template <typename U> static char test(SameType<Signature_validate, &U::validate>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<MappingTraits<T> >(nullptr)) == 1); }; // Test if SequenceTraits<T> is defined on type T. template <class T> struct has_SequenceMethodTraits { typedef size_t (*Signature_size)(class IO&, T&); template <typename U> static char test(SameType<Signature_size, &U::size>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<SequenceTraits<T> >(nullptr)) == 1); }; // has_FlowTraits<int> will cause an error with some compilers because // it subclasses int. Using this wrapper only instantiates the // real has_FlowTraits only if the template type is a class. template <typename T, bool Enabled = std::is_class<T>::value> class has_FlowTraits { public: static const bool value = false; }; // Some older gcc compilers don't support straight forward tests // for members, so test for ambiguity cause by the base and derived // classes both defining the member. template <class T> struct has_FlowTraits<T, true> { struct Fallback { bool flow; }; struct Derived : T, Fallback { }; template<typename C> static char (&f(SameType<bool Fallback::*, &C::flow>*))[1]; template<typename C> static char (&f(...))[2]; public: static bool const value = sizeof(f<Derived>(nullptr)) == 2; }; // Test if SequenceTraits<T> is defined on type T template<typename T> struct has_SequenceTraits : public std::integral_constant<bool, has_SequenceMethodTraits<T>::value > { }; // Test if DocumentListTraits<T> is defined on type T template <class T> struct has_DocumentListTraits { typedef size_t (*Signature_size)(class IO&, T&); template <typename U> static char test(SameType<Signature_size, &U::size>*); template <typename U> static double test(...); public: static bool const value = (sizeof(test<DocumentListTraits<T> >(nullptr))==1); }; inline bool isNumber(StringRef S) { static const char OctalChars[] = "01234567"; if (S.startswith("0") && S.drop_front().find_first_not_of(OctalChars) == StringRef::npos) return true; if (S.startswith("0o") && S.drop_front(2).find_first_not_of(OctalChars) == StringRef::npos) return true; static const char HexChars[] = "0123456789abcdefABCDEF"; if (S.startswith("0x") && S.drop_front(2).find_first_not_of(HexChars) == StringRef::npos) return true; static const char DecChars[] = "0123456789"; if (S.find_first_not_of(DecChars) == StringRef::npos) return true; if (S.equals(".inf") || S.equals(".Inf") || S.equals(".INF")) return true; Regex FloatMatcher("^(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$"); if (FloatMatcher.match(S)) return true; return false; } inline bool isNumeric(StringRef S) { if ((S.front() == '-' || S.front() == '+') && isNumber(S.drop_front())) return true; if (isNumber(S)) return true; if (S.equals(".nan") || S.equals(".NaN") || S.equals(".NAN")) return true; return false; } inline bool isNull(StringRef S) { return S.equals("null") || S.equals("Null") || S.equals("NULL") || S.equals("~"); } inline bool isBool(StringRef S) { return S.equals("true") || S.equals("True") || S.equals("TRUE") || S.equals("false") || S.equals("False") || S.equals("FALSE"); } inline bool needsQuotes(StringRef S) { if (S.empty()) return true; if (isspace(S.front()) || isspace(S.back())) return true; if (S.front() == ',') return true; static const char ScalarSafeChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/^., \t"; if (S.find_first_not_of(ScalarSafeChars) != StringRef::npos) return true; if (isNull(S)) return true; if (isBool(S)) return true; if (isNumeric(S)) return true; return false; } template<typename T> struct missingTraits : public std::integral_constant<bool, !has_ScalarEnumerationTraits<T>::value && !has_ScalarBitSetTraits<T>::value && !has_ScalarTraits<T>::value && !has_BlockScalarTraits<T>::value && !has_MappingTraits<T>::value && !has_SequenceTraits<T>::value && !has_DocumentListTraits<T>::value > {}; template<typename T> struct validatedMappingTraits : public std::integral_constant<bool, has_MappingTraits<T>::value && has_MappingValidateTraits<T>::value> {}; template<typename T> struct unvalidatedMappingTraits : public std::integral_constant<bool, has_MappingTraits<T>::value && !has_MappingValidateTraits<T>::value> {}; // Base class for Input and Output. class IO { public: IO(void *Ctxt=nullptr); virtual ~IO(); virtual bool outputting() = 0; virtual unsigned beginSequence() = 0; virtual bool preflightElement(unsigned, void *&) = 0; virtual void postflightElement(void*) = 0; virtual void endSequence() = 0; virtual bool canElideEmptySequence() = 0; virtual unsigned beginFlowSequence() = 0; virtual bool preflightFlowElement(unsigned, void *&) = 0; virtual void postflightFlowElement(void*) = 0; virtual void endFlowSequence() = 0; virtual bool mapTag(StringRef Tag, bool Default=false) = 0; virtual void beginMapping() = 0; virtual void endMapping() = 0; virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0; virtual void postflightKey(void*) = 0; virtual void beginFlowMapping() = 0; virtual void endFlowMapping() = 0; virtual void beginEnumScalar() = 0; virtual bool matchEnumScalar(const char*, bool) = 0; virtual bool matchEnumFallback() = 0; virtual void endEnumScalar() = 0; virtual bool beginBitSetScalar(bool &) = 0; virtual bool bitSetMatch(const char*, bool) = 0; virtual void endBitSetScalar() = 0; virtual void scalarString(StringRef &, bool) = 0; virtual void blockScalarString(StringRef &) = 0; virtual void setError(const Twine &) = 0; template <typename T> void enumCase(T &Val, const char* Str, const T ConstVal) { if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) { Val = ConstVal; } } // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF template <typename T> void enumCase(T &Val, const char* Str, const uint32_t ConstVal) { if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) { Val = ConstVal; } } template <typename FBT, typename T> void enumFallback(T &Val) { if ( matchEnumFallback() ) { // FIXME: Force integral conversion to allow strong typedefs to convert. FBT Res = (uint64_t)Val; yamlize(*this, Res, true); Val = (uint64_t)Res; } } template <typename T> void bitSetCase(T &Val, const char* Str, const T ConstVal) { if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) { Val = Val | ConstVal; } } // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF template <typename T> void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) { if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) { Val = Val | ConstVal; } } template <typename T> void maskedBitSetCase(T &Val, const char *Str, T ConstVal, T Mask) { if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal)) Val = Val | ConstVal; } template <typename T> void maskedBitSetCase(T &Val, const char *Str, uint32_t ConstVal, uint32_t Mask) { if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal)) Val = Val | ConstVal; } void *getContext(); void setContext(void *); template <typename T> void mapRequired(const char* Key, T& Val) { this->processKey(Key, Val, true); } template <typename T> typename std::enable_if<has_SequenceTraits<T>::value,void>::type mapOptional(const char* Key, T& Val) { // omit key/value instead of outputting empty sequence if ( this->canElideEmptySequence() && !(Val.begin() != Val.end()) ) return; this->processKey(Key, Val, false); } template <typename T> void mapOptional(const char* Key, Optional<T> &Val) { processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false); } template <typename T> typename std::enable_if<!has_SequenceTraits<T>::value,void>::type mapOptional(const char* Key, T& Val) { this->processKey(Key, Val, false); } template <typename T> void mapOptional(const char* Key, T& Val, const T& Default) { this->processKeyWithDefault(Key, Val, Default, false); } private: template <typename T> void processKeyWithDefault(const char *Key, Optional<T> &Val, const Optional<T> &DefaultValue, bool Required) { assert(DefaultValue.hasValue() == false && "Optional<T> shouldn't have a value!"); void *SaveInfo; bool UseDefault; const bool sameAsDefault = outputting() && !Val.hasValue(); if (!outputting() && !Val.hasValue()) Val = T(); if (this->preflightKey(Key, Required, sameAsDefault, UseDefault, SaveInfo)) { yamlize(*this, Val.getValue(), Required); this->postflightKey(SaveInfo); } else { if (UseDefault) Val = DefaultValue; } } template <typename T> void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue, bool Required) { void *SaveInfo; bool UseDefault; const bool sameAsDefault = outputting() && Val == DefaultValue; if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault, SaveInfo) ) { yamlize(*this, Val, Required); this->postflightKey(SaveInfo); } else { if ( UseDefault ) Val = DefaultValue; } } template <typename T> void processKey(const char *Key, T &Val, bool Required) { void *SaveInfo; bool UseDefault; if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) { yamlize(*this, Val, Required); this->postflightKey(SaveInfo); } } private: void *Ctxt; }; template<typename T> typename std::enable_if<has_ScalarEnumerationTraits<T>::value,void>::type yamlize(IO &io, T &Val, bool) { io.beginEnumScalar(); ScalarEnumerationTraits<T>::enumeration(io, Val); io.endEnumScalar(); } template<typename T> typename std::enable_if<has_ScalarBitSetTraits<T>::value,void>::type yamlize(IO &io, T &Val, bool) { bool DoClear; if ( io.beginBitSetScalar(DoClear) ) { if ( DoClear ) Val = static_cast<T>(0); ScalarBitSetTraits<T>::bitset(io, Val); io.endBitSetScalar(); } } template<typename T> typename std::enable_if<has_ScalarTraits<T>::value,void>::type yamlize(IO &io, T &Val, bool) { if ( io.outputting() ) { std::string Storage; llvm::raw_string_ostream Buffer(Storage); ScalarTraits<T>::output(Val, io.getContext(), Buffer); StringRef Str = Buffer.str(); io.scalarString(Str, ScalarTraits<T>::mustQuote(Str)); } else { StringRef Str; io.scalarString(Str, ScalarTraits<T>::mustQuote(Str)); StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val); if ( !Result.empty() ) { io.setError(llvm::Twine(Result)); } } } template <typename T> typename std::enable_if<has_BlockScalarTraits<T>::value, void>::type yamlize(IO &YamlIO, T &Val, bool) { if (YamlIO.outputting()) { std::string Storage; llvm::raw_string_ostream Buffer(Storage); BlockScalarTraits<T>::output(Val, YamlIO.getContext(), Buffer); StringRef Str = Buffer.str(); YamlIO.blockScalarString(Str); } else { StringRef Str; YamlIO.blockScalarString(Str); StringRef Result = BlockScalarTraits<T>::input(Str, YamlIO.getContext(), Val); if (!Result.empty()) YamlIO.setError(llvm::Twine(Result)); } } template<typename T> typename std::enable_if<validatedMappingTraits<T>::value, void>::type yamlize(IO &io, T &Val, bool) { if (has_FlowTraits<MappingTraits<T>>::value) io.beginFlowMapping(); else io.beginMapping(); if (io.outputting()) { StringRef Err = MappingTraits<T>::validate(io, Val); if (!Err.empty()) { llvm::errs() << Err << "\n"; assert(Err.empty() && "invalid struct trying to be written as yaml"); } } MappingTraits<T>::mapping(io, Val); if (!io.outputting()) { StringRef Err = MappingTraits<T>::validate(io, Val); if (!Err.empty()) io.setError(Err); } if (has_FlowTraits<MappingTraits<T>>::value) io.endFlowMapping(); else io.endMapping(); } template<typename T> typename std::enable_if<unvalidatedMappingTraits<T>::value, void>::type yamlize(IO &io, T &Val, bool) { if (has_FlowTraits<MappingTraits<T>>::value) { io.beginFlowMapping(); MappingTraits<T>::mapping(io, Val); io.endFlowMapping(); } else { io.beginMapping(); MappingTraits<T>::mapping(io, Val); io.endMapping(); } } template<typename T> typename std::enable_if<missingTraits<T>::value, void>::type yamlize(IO &io, T &Val, bool) { char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)]; } template<typename T> typename std::enable_if<has_SequenceTraits<T>::value,void>::type yamlize(IO &io, T &Seq, bool) { if ( has_FlowTraits< SequenceTraits<T> >::value ) { unsigned incnt = io.beginFlowSequence(); unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt; for(unsigned i=0; i < count; ++i) { void *SaveInfo; if ( io.preflightFlowElement(i, SaveInfo) ) { yamlize(io, SequenceTraits<T>::element(io, Seq, i), true); io.postflightFlowElement(SaveInfo); } } io.endFlowSequence(); } else { unsigned incnt = io.beginSequence(); unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt; for(unsigned i=0; i < count; ++i) { void *SaveInfo; if ( io.preflightElement(i, SaveInfo) ) { yamlize(io, SequenceTraits<T>::element(io, Seq, i), true); io.postflightElement(SaveInfo); } } io.endSequence(); } } template<> struct ScalarTraits<bool> { static void output(const bool &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, bool &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<StringRef> { static void output(const StringRef &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, StringRef &); static bool mustQuote(StringRef S) { return needsQuotes(S); } }; template<> struct ScalarTraits<std::string> { static void output(const std::string &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, std::string &); static bool mustQuote(StringRef S) { return needsQuotes(S); } }; template<> struct ScalarTraits<uint8_t> { static void output(const uint8_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, uint8_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<uint16_t> { static void output(const uint16_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, uint16_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<uint32_t> { static void output(const uint32_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, uint32_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<uint64_t> { static void output(const uint64_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, uint64_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<int8_t> { static void output(const int8_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, int8_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<int16_t> { static void output(const int16_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, int16_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<int32_t> { static void output(const int32_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, int32_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<int64_t> { static void output(const int64_t &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, int64_t &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<float> { static void output(const float &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, float &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<double> { static void output(const double &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, double &); static bool mustQuote(StringRef) { return false; } }; // Utility for use within MappingTraits<>::mapping() method // to [de]normalize an object for use with YAML conversion. template <typename TNorm, typename TFinal> struct MappingNormalization { MappingNormalization(IO &i_o, TFinal &Obj) : io(i_o), BufPtr(nullptr), Result(Obj) { if ( io.outputting() ) { BufPtr = new (&Buffer) TNorm(io, Obj); } else { BufPtr = new (&Buffer) TNorm(io); } } ~MappingNormalization() { if ( ! io.outputting() ) { Result = BufPtr->denormalize(io); } BufPtr->~TNorm(); } TNorm* operator->() { return BufPtr; } private: typedef llvm::AlignedCharArrayUnion<TNorm> Storage; Storage Buffer; IO &io; TNorm *BufPtr; TFinal &Result; }; // Utility for use within MappingTraits<>::mapping() method // to [de]normalize an object for use with YAML conversion. template <typename TNorm, typename TFinal> struct MappingNormalizationHeap { MappingNormalizationHeap(IO &i_o, TFinal &Obj) : io(i_o), BufPtr(NULL), Result(Obj) { if ( io.outputting() ) { BufPtr = new (&Buffer) TNorm(io, Obj); } else { BufPtr = new TNorm(io); } } ~MappingNormalizationHeap() { if ( io.outputting() ) { BufPtr->~TNorm(); } else { Result = BufPtr->denormalize(io); } } TNorm* operator->() { return BufPtr; } private: typedef llvm::AlignedCharArrayUnion<TNorm> Storage; Storage Buffer; IO &io; TNorm *BufPtr; TFinal &Result; }; /// /// The Input class is used to parse a yaml document into in-memory structs /// and vectors. /// /// It works by using YAMLParser to do a syntax parse of the entire yaml /// document, then the Input class builds a graph of HNodes which wraps /// each yaml Node. The extra layer is buffering. The low level yaml /// parser only lets you look at each node once. The buffering layer lets /// you search and interate multiple times. This is necessary because /// the mapRequired() method calls may not be in the same order /// as the keys in the document. /// class Input : public IO { public: // Construct a yaml Input object from a StringRef and optional // user-data. The DiagHandler can be specified to provide // alternative error reporting. Input(StringRef InputContent, void *Ctxt = nullptr, SourceMgr::DiagHandlerTy DiagHandler = nullptr, void *DiagHandlerCtxt = nullptr); ~Input() override; // Check if there was an syntax or semantic error during parsing. std::error_code error(); private: bool outputting() override; bool mapTag(StringRef, bool) override; void beginMapping() override; void endMapping() override; bool preflightKey(const char *, bool, bool, bool &, void *&) override; void postflightKey(void *) override; void beginFlowMapping() override; void endFlowMapping() override; unsigned beginSequence() override; void endSequence() override; bool preflightElement(unsigned index, void *&) override; void postflightElement(void *) override; unsigned beginFlowSequence() override; bool preflightFlowElement(unsigned , void *&) override; void postflightFlowElement(void *) override; void endFlowSequence() override; void beginEnumScalar() override; bool matchEnumScalar(const char*, bool) override; bool matchEnumFallback() override; void endEnumScalar() override; bool beginBitSetScalar(bool &) override; bool bitSetMatch(const char *, bool ) override; void endBitSetScalar() override; void scalarString(StringRef &, bool) override; void blockScalarString(StringRef &) override; void setError(const Twine &message) override; bool canElideEmptySequence() override; class HNode { virtual void anchor(); public: HNode(Node *n) : _node(n) { } virtual ~HNode() { } static inline bool classof(const HNode *) { return true; } Node *_node; }; class EmptyHNode : public HNode { void anchor() override; public: EmptyHNode(Node *n) : HNode(n) { } static inline bool classof(const HNode *n) { return NullNode::classof(n->_node); } static inline bool classof(const EmptyHNode *) { return true; } }; class ScalarHNode : public HNode { void anchor() override; public: ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { } StringRef value() const { return _value; } static inline bool classof(const HNode *n) { return ScalarNode::classof(n->_node) || BlockScalarNode::classof(n->_node); } static inline bool classof(const ScalarHNode *) { return true; } protected: StringRef _value; }; class MapHNode : public HNode { void anchor() override; public: MapHNode(Node *n) : HNode(n) { } static inline bool classof(const HNode *n) { return MappingNode::classof(n->_node); } static inline bool classof(const MapHNode *) { return true; } typedef llvm::StringMap<std::unique_ptr<HNode>> NameToNode; bool isValidKey(StringRef key); NameToNode Mapping; llvm::SmallVector<const char*, 6> ValidKeys; }; class SequenceHNode : public HNode { void anchor() override; public: SequenceHNode(Node *n) : HNode(n) { } static inline bool classof(const HNode *n) { return SequenceNode::classof(n->_node); } static inline bool classof(const SequenceHNode *) { return true; } std::vector<std::unique_ptr<HNode>> Entries; }; std::unique_ptr<Input::HNode> createHNodes(Node *node); void setError(HNode *hnode, const Twine &message); void setError(Node *node, const Twine &message); public: // These are only used by operator>>. They could be private // if those templated things could be made friends. bool setCurrentDocument(); bool nextDocument(); /// Returns the current node that's being parsed by the YAML Parser. const Node *getCurrentNode() const; private: llvm::SourceMgr SrcMgr; // must be before Strm std::unique_ptr<llvm::yaml::Stream> Strm; std::unique_ptr<HNode> TopNode; std::error_code EC; llvm::BumpPtrAllocator StringAllocator; llvm::yaml::document_iterator DocIterator; std::vector<bool> BitValuesUsed; HNode *CurrentNode; bool ScalarMatchFound; }; /// /// The Output class is used to generate a yaml document from in-memory structs /// and vectors. /// class Output : public IO { public: Output(llvm::raw_ostream &, void *Ctxt = nullptr, int WrapColumn = 70); ~Output() override; bool outputting() override; bool mapTag(StringRef, bool) override; void beginMapping() override; void endMapping() override; bool preflightKey(const char *key, bool, bool, bool &, void *&) override; void postflightKey(void *) override; void beginFlowMapping() override; void endFlowMapping() override; unsigned beginSequence() override; void endSequence() override; bool preflightElement(unsigned, void *&) override; void postflightElement(void *) override; unsigned beginFlowSequence() override; bool preflightFlowElement(unsigned, void *&) override; void postflightFlowElement(void *) override; void endFlowSequence() override; void beginEnumScalar() override; bool matchEnumScalar(const char*, bool) override; bool matchEnumFallback() override; void endEnumScalar() override; bool beginBitSetScalar(bool &) override; bool bitSetMatch(const char *, bool ) override; void endBitSetScalar() override; void scalarString(StringRef &, bool) override; void blockScalarString(StringRef &) override; void setError(const Twine &message) override; bool canElideEmptySequence() override; public: // These are only used by operator<<. They could be private // if that templated operator could be made a friend. void beginDocuments(); bool preflightDocument(unsigned); void postflightDocument(); void endDocuments(); private: void output(StringRef s); void outputUpToEndOfLine(StringRef s); void newLineCheck(); void outputNewLine(); void paddedKey(StringRef key); void flowKey(StringRef Key); enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey, inFlowMapFirstKey, inFlowMapOtherKey }; llvm::raw_ostream &Out; int WrapColumn; SmallVector<InState, 8> StateStack; int Column; int ColumnAtFlowStart; int ColumnAtMapFlowStart; bool NeedBitValueComma; bool NeedFlowSequenceComma; bool EnumerationMatchFound; bool NeedsNewLine; }; /// YAML I/O does conversion based on types. But often native data types /// are just a typedef of built in intergral types (e.g. int). But the C++ /// type matching system sees through the typedef and all the typedefed types /// look like a built in type. This will cause the generic YAML I/O conversion /// to be used. To provide better control over the YAML conversion, you can /// use this macro instead of typedef. It will create a class with one field /// and automatic conversion operators to and from the base type. /// Based on BOOST_STRONG_TYPEDEF #define LLVM_YAML_STRONG_TYPEDEF(_base, _type) \ struct _type { \ _type() { } \ _type(const _base v) : value(v) { } \ _type(const _type &v) : value(v.value) {} \ _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\ _type &operator=(const _base &rhs) { value = rhs; return *this; } \ operator const _base & () const { return value; } \ bool operator==(const _type &rhs) const { return value == rhs.value; } \ bool operator==(const _base &rhs) const { return value == rhs; } \ bool operator<(const _type &rhs) const { return value < rhs.value; } \ _base value; \ }; /// /// Use these types instead of uintXX_t in any mapping to have /// its yaml output formatted as hexadecimal. /// LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8) LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16) LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32) LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64) template<> struct ScalarTraits<Hex8> { static void output(const Hex8 &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, Hex8 &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<Hex16> { static void output(const Hex16 &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, Hex16 &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<Hex32> { static void output(const Hex32 &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, Hex32 &); static bool mustQuote(StringRef) { return false; } }; template<> struct ScalarTraits<Hex64> { static void output(const Hex64 &, void*, llvm::raw_ostream &); static StringRef input(StringRef, void*, Hex64 &); static bool mustQuote(StringRef) { return false; } }; // Define non-member operator>> so that Input can stream in a document list. template <typename T> inline typename std::enable_if<has_DocumentListTraits<T>::value, Input &>::type operator>>(Input &yin, T &docList) { int i = 0; while ( yin.setCurrentDocument() ) { yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true); if ( yin.error() ) return yin; yin.nextDocument(); ++i; } return yin; } // Define non-member operator>> so that Input can stream in a map as a document. template <typename T> inline typename std::enable_if<has_MappingTraits<T>::value, Input &>::type operator>>(Input &yin, T &docMap) { yin.setCurrentDocument(); yamlize(yin, docMap, true); return yin; } // Define non-member operator>> so that Input can stream in a sequence as // a document. template <typename T> inline typename std::enable_if<has_SequenceTraits<T>::value, Input &>::type operator>>(Input &yin, T &docSeq) { if (yin.setCurrentDocument()) yamlize(yin, docSeq, true); return yin; } // Define non-member operator>> so that Input can stream in a block scalar. template <typename T> inline typename std::enable_if<has_BlockScalarTraits<T>::value, Input &>::type operator>>(Input &In, T &Val) { if (In.setCurrentDocument()) yamlize(In, Val, true); return In; } // Provide better error message about types missing a trait specialization template <typename T> inline typename std::enable_if<missingTraits<T>::value, Input &>::type operator>>(Input &yin, T &docSeq) { char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)]; return yin; } // Define non-member operator<< so that Output can stream out document list. template <typename T> inline typename std::enable_if<has_DocumentListTraits<T>::value, Output &>::type operator<<(Output &yout, T &docList) { yout.beginDocuments(); const size_t count = DocumentListTraits<T>::size(yout, docList); for(size_t i=0; i < count; ++i) { if ( yout.preflightDocument(i) ) { yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true); yout.postflightDocument(); } } yout.endDocuments(); return yout; } // Define non-member operator<< so that Output can stream out a map. template <typename T> inline typename std::enable_if<has_MappingTraits<T>::value, Output &>::type operator<<(Output &yout, T &map) { yout.beginDocuments(); if ( yout.preflightDocument(0) ) { yamlize(yout, map, true); yout.postflightDocument(); } yout.endDocuments(); return yout; } // Define non-member operator<< so that Output can stream out a sequence. template <typename T> inline typename std::enable_if<has_SequenceTraits<T>::value, Output &>::type operator<<(Output &yout, T &seq) { yout.beginDocuments(); if ( yout.preflightDocument(0) ) { yamlize(yout, seq, true); yout.postflightDocument(); } yout.endDocuments(); return yout; } // Define non-member operator<< so that Output can stream out a block scalar. template <typename T> inline typename std::enable_if<has_BlockScalarTraits<T>::value, Output &>::type operator<<(Output &Out, T &Val) { Out.beginDocuments(); if (Out.preflightDocument(0)) { yamlize(Out, Val, true); Out.postflightDocument(); } Out.endDocuments(); return Out; } // Provide better error message about types missing a trait specialization template <typename T> inline typename std::enable_if<missingTraits<T>::value, Output &>::type operator<<(Output &yout, T &seq) { char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)]; return yout; } } // namespace yaml } // namespace llvm /// Utility for declaring that a std::vector of a particular type /// should be considered a YAML sequence. #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type) \ namespace llvm { \ namespace yaml { \ template<> \ struct SequenceTraits< std::vector<_type> > { \ static size_t size(IO &io, std::vector<_type> &seq) { \ return seq.size(); \ } \ static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\ if ( index >= seq.size() ) \ seq.resize(index+1); \ return seq[index]; \ } \ }; \ } \ } /// Utility for declaring that a std::vector of a particular type /// should be considered a YAML flow sequence. #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type) \ namespace llvm { \ namespace yaml { \ template<> \ struct SequenceTraits< std::vector<_type> > { \ static size_t size(IO &io, std::vector<_type> &seq) { \ return seq.size(); \ } \ static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\ (void)flow; /* Remove this workaround after PR17897 is fixed */ \ if ( index >= seq.size() ) \ seq.resize(index+1); \ return seq[index]; \ } \ static const bool flow = true; \ }; \ } \ } /// Utility for declaring that a std::vector of a particular type /// should be considered a YAML document list. #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type) \ namespace llvm { \ namespace yaml { \ template<> \ struct DocumentListTraits< std::vector<_type> > { \ static size_t size(IO &io, std::vector<_type> &seq) { \ return seq.size(); \ } \ static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\ if ( index >= seq.size() ) \ seq.resize(index+1); \ return seq[index]; \ } \ }; \ } \ } #endif // LLVM_SUPPORT_YAMLTRAITS_H
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/RWMutex.h
//===- RWMutex.h - Reader/Writer Mutual Exclusion Lock ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::RWMutex class. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_RWMUTEX_H #define LLVM_SUPPORT_RWMUTEX_H #include "llvm/Support/Compiler.h" #include "llvm/Support/Threading.h" #include <cassert> namespace llvm { namespace sys { /// @brief Platform agnostic RWMutex class. class RWMutexImpl { /// @name Constructors /// @{ public: /// Initializes the lock but doesn't acquire it. /// @brief Default Constructor. explicit RWMutexImpl(); /// Releases and removes the lock /// @brief Destructor ~RWMutexImpl(); /// @} /// @name Methods /// @{ public: /// Attempts to unconditionally acquire the lock in reader mode. If the /// lock is held by a writer, this method will wait until it can acquire /// the lock. /// @returns false if any kind of error occurs, true otherwise. /// @brief Unconditionally acquire the lock in reader mode. bool reader_acquire(); /// Attempts to release the lock in reader mode. /// @returns false if any kind of error occurs, true otherwise. /// @brief Unconditionally release the lock in reader mode. bool reader_release(); /// Attempts to unconditionally acquire the lock in reader mode. If the /// lock is held by any readers, this method will wait until it can /// acquire the lock. /// @returns false if any kind of error occurs, true otherwise. /// @brief Unconditionally acquire the lock in writer mode. bool writer_acquire(); /// Attempts to release the lock in writer mode. /// @returns false if any kind of error occurs, true otherwise. /// @brief Unconditionally release the lock in write mode. bool writer_release(); //@} /// @name Platform Dependent Data /// @{ private: #if defined(LLVM_ENABLE_THREADS) && LLVM_ENABLE_THREADS != 0 void* data_; ///< We don't know what the data will be #endif /// @} /// @name Do Not Implement /// @{ private: RWMutexImpl(const RWMutexImpl & original) = delete; void operator=(const RWMutexImpl &) = delete; /// @} }; /// SmartMutex - An R/W mutex with a compile time constant parameter that /// indicates whether this mutex should become a no-op when we're not /// running in multithreaded mode. template<bool mt_only> class SmartRWMutex { RWMutexImpl impl; unsigned readers, writers; public: explicit SmartRWMutex() : impl(), readers(0), writers(0) { } bool lock_shared() { if (!mt_only || llvm_is_multithreaded()) return impl.reader_acquire(); // Single-threaded debugging code. This would be racy in multithreaded // mode, but provides not sanity checks in single threaded mode. ++readers; return true; } bool unlock_shared() { if (!mt_only || llvm_is_multithreaded()) return impl.reader_release(); // Single-threaded debugging code. This would be racy in multithreaded // mode, but provides not sanity checks in single threaded mode. assert(readers > 0 && "Reader lock not acquired before release!"); --readers; return true; } bool lock() { if (!mt_only || llvm_is_multithreaded()) return impl.writer_acquire(); // Single-threaded debugging code. This would be racy in multithreaded // mode, but provides not sanity checks in single threaded mode. assert(writers == 0 && "Writer lock already acquired!"); ++writers; return true; } bool unlock() { if (!mt_only || llvm_is_multithreaded()) return impl.writer_release(); // Single-threaded debugging code. This would be racy in multithreaded // mode, but provides not sanity checks in single threaded mode. assert(writers == 1 && "Writer lock not acquired before release!"); --writers; return true; } private: SmartRWMutex(const SmartRWMutex<mt_only> & original); void operator=(const SmartRWMutex<mt_only> &); }; typedef SmartRWMutex<false> RWMutex; /// ScopedReader - RAII acquisition of a reader lock template<bool mt_only> struct SmartScopedReader { SmartRWMutex<mt_only>& mutex; explicit SmartScopedReader(SmartRWMutex<mt_only>& m) : mutex(m) { mutex.lock_shared(); } ~SmartScopedReader() { mutex.unlock_shared(); } }; typedef SmartScopedReader<false> ScopedReader; /// ScopedWriter - RAII acquisition of a writer lock template<bool mt_only> struct SmartScopedWriter { SmartRWMutex<mt_only>& mutex; explicit SmartScopedWriter(SmartRWMutex<mt_only>& m) : mutex(m) { mutex.lock(); } ~SmartScopedWriter() { mutex.unlock(); } }; typedef SmartScopedWriter<false> ScopedWriter; } } #endif
0
repos/DirectXShaderCompiler/include/llvm
repos/DirectXShaderCompiler/include/llvm/Support/type_traits.h
//===- llvm/Support/type_traits.h - Simplfied type traits -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides useful additions to the standard type_traits library. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_TYPE_TRAITS_H #define LLVM_SUPPORT_TYPE_TRAITS_H #include <type_traits> #include <utility> #ifndef __has_feature #define LLVM_DEFINED_HAS_FEATURE #define __has_feature(x) 0 #endif namespace llvm { /// isPodLike - This is a type trait that is used to determine whether a given /// type can be copied around with memcpy instead of running ctors etc. template <typename T> struct isPodLike { // std::is_trivially_copyable is available in libc++ with clang, libstdc++ // that comes with GCC 5. #if (__has_feature(is_trivially_copyable) && defined(_LIBCPP_VERSION)) || \ (defined(__GNUC__) && __GNUC__ >= 5) || \ (_MSC_VER >= 1900) // HLSL Change // If the compiler supports the is_trivially_copyable trait use it, as it // matches the definition of isPodLike closely. static const bool value = std::is_trivially_copyable<T>::value; #elif __has_feature(is_trivially_copyable) // Use the internal name if the compiler supports is_trivially_copyable but we // don't know if the standard library does. This is the case for clang in // conjunction with libstdc++ from GCC 4.x. static const bool value = __is_trivially_copyable(T); #else // If we don't know anything else, we can (at least) assume that all non-class // types are PODs. static const bool value = !std::is_class<T>::value; #endif }; // std::pair's are pod-like if their elements are. template<typename T, typename U> struct isPodLike<std::pair<T, U> > { static const bool value = isPodLike<T>::value && isPodLike<U>::value; }; /// \brief Metafunction that determines whether the given type is either an /// integral type or an enumeration type. /// /// Note that this accepts potentially more integral types than is_integral /// because it is based on merely being convertible implicitly to an integral /// type. template <typename T> class is_integral_or_enum { typedef typename std::remove_reference<T>::type UnderlyingT; public: static const bool value = !std::is_class<UnderlyingT>::value && // Filter conversion operators. !std::is_pointer<UnderlyingT>::value && !std::is_floating_point<UnderlyingT>::value && std::is_convertible<UnderlyingT, unsigned long long>::value; }; /// \brief If T is a pointer, just return it. If it is not, return T&. template<typename T, typename Enable = void> struct add_lvalue_reference_if_not_pointer { typedef T &type; }; template <typename T> struct add_lvalue_reference_if_not_pointer< T, typename std::enable_if<std::is_pointer<T>::value>::type> { typedef T type; }; /// \brief If T is a pointer to X, return a pointer to const X. If it is not, /// return const T. template<typename T, typename Enable = void> struct add_const_past_pointer { typedef const T type; }; template <typename T> struct add_const_past_pointer< T, typename std::enable_if<std::is_pointer<T>::value>::type> { typedef const typename std::remove_pointer<T>::type *type; }; } #ifdef LLVM_DEFINED_HAS_FEATURE #undef __has_feature #endif #endif