diff --git a/llvm/include/llvm/ADT/Bitfields.h b/llvm/include/llvm/ADT/Bitfields.h new file mode 100644 --- /dev/null +++ b/llvm/include/llvm/ADT/Bitfields.h @@ -0,0 +1,120 @@ +//===-- llvm/ADT/Bitfield.h - Get and Set bits in an integer ---*- C++ -*--===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file implements methods to test, set and extract typed bits from packed +/// unsigned integers. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_BITFIELDS_H +#define LLVM_ADT_BITFIELDS_H + +#include +#include +#include + +/// Helpers to pack / unpack typed bitfields into an unsigned scalar. +/// e.g. +/// +/// uint8_t storage = 0; +/// +/// // Store and retrieve a single bit as bool. +/// using Volatile = Bitfield; +/// setField(storage, true); +/// EXPECT_EQ(storage, 0b00000001); +/// EXPECT_EQ(getField(storage), true); +/// +/// // Store and retrieve a 2 bit typed enum. +/// enum class SuitEnum { CLUBS, DIAMONDS, HEARTS, SPADES }; +/// using Suit = Bitfield; +/// setField(storage, SuitEnum::HEARTS); +/// EXPECT_EQ(storage, 0b00000101); +/// EXPECT_EQ(getField(storage), SuitEnum::HEARTS); +/// +/// // Store and retrieve a 5 bit value as unsigned. +/// using Value = Bitfield; +/// setField(storage, 10); +/// EXPECT_EQ(storage, 0b01010101); +/// EXPECT_EQ(getField(storage), 10U); +/// +/// // Alter storage changes value. +/// storage = 0; +/// EXPECT_EQ(getField(storage), false); +/// EXPECT_EQ(getField(storage), SuitEnum::CLUBS); +/// EXPECT_EQ(getField(storage), 0U); +/// +/// storage = 255; +/// EXPECT_EQ(getField(storage), true); +/// EXPECT_EQ(getField(storage), SuitEnum::SPADES); +/// EXPECT_EQ(getField(storage), 31U); +/// +/// // Ability to efficiently test if a field is non zero. +/// EXPECT_NE(testField(storage), 0U); + +namespace llvm { + +/// A struct to hold the bitfield informations. +/// \param Type, the type of the field once in unpacked form, +/// \param Offset, the position of the first bit, +/// \param Size, the size of the field. +template struct Bitfield { + using type = Type; + static_assert(std::is_unsigned::value || std::is_enum::value, + "Type must be unsigned or enum"); + static constexpr unsigned offset = Offset; + static constexpr unsigned size = Size; + static constexpr unsigned firstBit = offset; + static constexpr unsigned lastBit = offset + size; + static_assert(size > 0, "Size must be non zero"); + static_assert(lastBit <= 64, "Data must fit in 64 bits"); + static constexpr uint64_t max_value = (1ULL << size) - 1ULL; + static constexpr uint64_t mask = max_value << offset; +}; + +template static constexpr bool IsOverlapping() { + return A::lastBit > B::firstBit && B::lastBit > A::firstBit; +} + +/// Unpacks the field from the packed value. +template +static typename Bitfield::type getField(T packed) { + static_assert(std::is_unsigned(), "storage must be unsigned"); + static_assert(sizeof(T) <= sizeof(uint64_t), + "T must not exceed uint64_t size"); + const T masked = packed & Bitfield::mask; + const T shifted = masked >> Bitfield::offset; + return static_cast(shifted); +} + +/// Return a non zero value if the field is non zero. +/// It saves a shift operation compared to `getField`. +template static T testField(T packed) { + static_assert(std::is_unsigned(), "storage must be unsigned"); + static_assert(sizeof(T) <= sizeof(uint64_t), + "T must not exceed uint64_t size"); + return packed & Bitfield::mask; +} + +/// Sets the typed value in the provided packed value. +/// The method will asserts if the provided value is too big to fit in the +/// packed field. +template +static void setField(T &packed, typename Bitfield::type value) { + static_assert(std::is_unsigned(), "storage must be unsigned"); + static_assert(sizeof(T) <= sizeof(uint64_t), + "T must not exceed uint64_t size"); + assert(static_cast(value) <= Bitfield::max_value && + "value is too big"); + packed &= ~Bitfield::mask; + packed |= T(value) << Bitfield::offset; +} + +} // namespace llvm + +#endif // LLVM_ADT_BITFIELDS_H \ No newline at end of file diff --git a/llvm/include/llvm/IR/InstrTypes.h b/llvm/include/llvm/IR/InstrTypes.h --- a/llvm/include/llvm/IR/InstrTypes.h +++ b/llvm/include/llvm/IR/InstrTypes.h @@ -757,6 +757,7 @@ LAST_ICMP_PREDICATE = ICMP_SLE, BAD_ICMP_PREDICATE = ICMP_SLE + 1 }; + using PredicateField = Bitfield; // Next bit:6 protected: CmpInst(Type *ty, Instruction::OtherOps op, Predicate pred, @@ -797,12 +798,10 @@ } /// Return the predicate for this instruction. - Predicate getPredicate() const { - return Predicate(getSubclassDataFromInstruction()); - } + Predicate getPredicate() const { return getSubclassData(); } /// Set the predicate for this instruction to the specified value. - void setPredicate(Predicate P) { setInstructionSubclassData(P); } + void setPredicate(Predicate P) { setSubclassData(P); } static bool isFPPredicate(Predicate P) { return P >= FIRST_FCMP_PREDICATE && P <= LAST_FCMP_PREDICATE; @@ -1096,6 +1095,8 @@ /// subclass requires. Note that accessing the end of the argument list isn't /// as cheap as most other operations on the base class. class CallBase : public Instruction { + using CallingConvField = Bitfield; // Next bit:12 + protected: /// The last operand is the called operand. static constexpr int CalledOperandOpEndIdx = -1; @@ -1349,14 +1350,13 @@ } CallingConv::ID getCallingConv() const { - return static_cast(getSubclassDataFromInstruction() >> 2); + return getSubclassData(); } void setCallingConv(CallingConv::ID CC) { - auto ID = static_cast(CC); - assert(!(ID & ~CallingConv::MaxID) && "Unsupported calling convention"); - setInstructionSubclassData((getSubclassDataFromInstruction() & 3) | - (ID << 2)); + assert(!(unsigned(CC) & ~CallingConv::MaxID) && + "Unsupported calling convention"); + setSubclassData(CC); } /// Check if this call is an inline asm statement. diff --git a/llvm/include/llvm/IR/Instruction.h b/llvm/include/llvm/IR/Instruction.h --- a/llvm/include/llvm/IR/Instruction.h +++ b/llvm/include/llvm/IR/Instruction.h @@ -15,6 +15,7 @@ #define LLVM_IR_INSTRUCTION_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Bitfields.h" #include "llvm/ADT/None.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/ilist_node.h" @@ -49,11 +50,14 @@ /// O(1) local dominance checks between instructions. mutable unsigned Order = 0; - enum { - /// This is a bit stored in the SubClassData field which indicates whether - /// this instruction has metadata attached to it or not. - HasMetadataBit = 1 << 15 - }; +protected: + // The 15 first bits of `Value::SubclassData` are available for subclasses of + // `Instruction` to use. + using OpaqueField = Bitfield; // Next bit:15 +private: + // The last bit is used to store whether the instruction has metadata attached + // or not. + using HasMetadataField = Bitfield; protected: ~Instruction(); // Use deleteValue() to delete a generic Instruction. @@ -471,7 +475,7 @@ private: /// Return true if we have an entry in the on-the-side metadata hash. bool hasMetadataHashEntry() const { - return (getSubclassDataFromValue() & HasMetadataBit) != 0; + return getSubclassData(); } // These are all implemented in Metadata.cpp. @@ -763,10 +767,7 @@ return Value::getSubclassDataFromValue(); } - void setHasMetadataHashEntry(bool V) { - setValueSubclassData((getSubclassDataFromValue() & ~HasMetadataBit) | - (V ? HasMetadataBit : 0)); - } + void setHasMetadataHashEntry(bool V) { setSubclassData(V); } void setParent(BasicBlock *P); @@ -774,14 +775,21 @@ // Instruction subclasses can stick up to 15 bits of stuff into the // SubclassData field of instruction with these members. - // Verify that only the low 15 bits are used. - void setInstructionSubclassData(unsigned short D) { - assert((D & HasMetadataBit) == 0 && "Out of range value put into field"); - setValueSubclassData((getSubclassDataFromValue() & HasMetadataBit) | D); - } - - unsigned getSubclassDataFromInstruction() const { - return getSubclassDataFromValue() & ~HasMetadataBit; + template typename Bitfield::type getSubclassData() const { + static_assert(std::is_same::value || + !IsOverlapping(), + "Must not override the metadat bit"); + return getField(getSubclassDataFromValue()); + } + + template + void setSubclassData(typename Bitfield::type value) { + static_assert(std::is_same::value || + !IsOverlapping(), + "Must not override the metadat bit"); + auto storage = getSubclassDataFromValue(); + setField(storage, value); + setValueSubclassData(storage); } Instruction(Type *Ty, unsigned iType, Use *Ops, unsigned NumOps, diff --git a/llvm/include/llvm/IR/Instructions.h b/llvm/include/llvm/IR/Instructions.h --- a/llvm/include/llvm/IR/Instructions.h +++ b/llvm/include/llvm/IR/Instructions.h @@ -16,6 +16,7 @@ #define LLVM_IR_INSTRUCTIONS_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Bitfields.h" #include "llvm/ADT/None.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" @@ -59,6 +60,10 @@ class AllocaInst : public UnaryInstruction { Type *AllocatedType; + using AlignmentField = Bitfield; // Next bit:5 + using UsedWithInAllocaField = Bitfield; // Next bit:6 + using SwiftErrorField = Bitfield; // Next bit:7 + protected: // Note: Instruction needs to be a friend here to call cloneImpl. friend class Instruction; @@ -108,7 +113,7 @@ /// Return the alignment of the memory that is being allocated by the /// instruction. Align getAlign() const { - return *decodeMaybeAlign(getSubclassDataFromInstruction() & 31); + return *decodeMaybeAlign(getSubclassData()); } // FIXME: Remove this one transition to Align is over. unsigned getAlignment() const { return getAlign().value(); } @@ -122,25 +127,18 @@ /// Return true if this alloca is used as an inalloca argument to a call. Such /// allocas are never considered static even if they are in the entry block. bool isUsedWithInAlloca() const { - return getSubclassDataFromInstruction() & 32; + return getSubclassData(); } /// Specify whether this alloca is used to represent the arguments to a call. void setUsedWithInAlloca(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) | - (V ? 32 : 0)); + setSubclassData(V); } /// Return true if this alloca is used as a swifterror argument to a call. - bool isSwiftError() const { - return getSubclassDataFromInstruction() & 64; - } - + bool isSwiftError() const { return getSubclassData(); } /// Specify whether this alloca is used to represent a swifterror. - void setSwiftError(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) | - (V ? 64 : 0)); - } + void setSwiftError(bool V) { setSubclassData(V); } // Methods for support type inquiry through isa, cast, and dyn_cast: static bool classof(const Instruction *I) { @@ -153,8 +151,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } }; @@ -165,6 +164,10 @@ /// An instruction for reading from memory. This uses the SubclassData field in /// Value to store whether or not the load is volatile. class LoadInst : public UnaryInstruction { + using VolatileField = Bitfield; // Next bit:1 + using AlignmentField = Bitfield; // Next bit:7 + using OrderingField = Bitfield; // Next bit:10 + void AssertOK(); protected: @@ -194,13 +197,10 @@ BasicBlock *InsertAtEnd); /// Return true if this is a load from a volatile memory location. - bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } + bool isVolatile() const { return getSubclassData(); } /// Specify whether this is a volatile load or not. - void setVolatile(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | - (V ? 1 : 0)); - } + void setVolatile(bool V) { setSubclassData(V); } /// Return the alignment of the access that is being performed. /// FIXME: Remove this function once transition to Align is over. @@ -209,21 +209,19 @@ /// Return the alignment of the access that is being performed. Align getAlign() const { - return *decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31); + return *decodeMaybeAlign(getSubclassData()); } void setAlignment(Align Alignment); /// Returns the ordering constraint of this load instruction. AtomicOrdering getOrdering() const { - return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7); + return getSubclassData(); } - /// Sets the ordering constraint of this load instruction. May not be Release /// or AcquireRelease. void setOrdering(AtomicOrdering Ordering) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) | - ((unsigned)Ordering << 7)); + setSubclassData(Ordering); } /// Returns the synchronization scope ID of this load instruction. @@ -273,8 +271,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } /// The synchronization scope ID of this load instruction. Not quite enough @@ -289,6 +288,10 @@ /// An instruction for storing to memory. class StoreInst : public Instruction { + using VolatileField = Bitfield; // Next bit:1 + using AlignmentField = Bitfield; // Next bit:7 + using OrderingField = Bitfield; // Next bit:10 + void AssertOK(); protected: @@ -318,13 +321,10 @@ } /// Return true if this is a store to a volatile memory location. - bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } + bool isVolatile() const { return getSubclassData(); } /// Specify whether this is a volatile store or not. - void setVolatile(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | - (V ? 1 : 0)); - } + void setVolatile(bool V) { setSubclassData(V); } /// Transparently provide more efficient getOperand methods. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); @@ -335,21 +335,20 @@ unsigned getAlignment() const { return getAlign().value(); } Align getAlign() const { - return *decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31); + return *decodeMaybeAlign(getSubclassData()); } void setAlignment(Align Alignment); /// Returns the ordering constraint of this store instruction. AtomicOrdering getOrdering() const { - return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7); + return getSubclassData(); } /// Sets the ordering constraint of this store instruction. May not be /// Acquire or AcquireRelease. void setOrdering(AtomicOrdering Ordering) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) | - ((unsigned)Ordering << 7)); + setSubclassData(Ordering); } /// Returns the synchronization scope ID of this store instruction. @@ -402,8 +401,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } /// The synchronization scope ID of this store instruction. Not quite enough @@ -424,6 +424,8 @@ /// An instruction for ordering other memory operations. class FenceInst : public Instruction { + using OrderingField = Bitfield; // Next bit:4 + void Init(AtomicOrdering Ordering, SyncScope::ID SSID); protected: @@ -448,14 +450,13 @@ /// Returns the ordering constraint of this fence instruction. AtomicOrdering getOrdering() const { - return AtomicOrdering(getSubclassDataFromInstruction() >> 1); + return getSubclassData(); } /// Sets the ordering constraint of this fence instruction. May only be /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. void setOrdering(AtomicOrdering Ordering) { - setInstructionSubclassData((getSubclassDataFromInstruction() & 1) | - ((unsigned)Ordering << 1)); + setSubclassData(Ordering); } /// Returns the synchronization scope ID of this fence instruction. @@ -479,8 +480,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } /// The synchronization scope ID of this fence instruction. Not quite enough @@ -525,57 +527,49 @@ return User::operator new(s, 3); } + using VolatileField = Bitfield; // Next bit:1 + using SuccessOrderingField = Bitfield; // Next bit:5 + using FailureOrderingField = Bitfield; // Next bit:8 + using WeakField = Bitfield; // Next bit:9 /// Return true if this is a cmpxchg from a volatile memory /// location. /// - bool isVolatile() const { - return getSubclassDataFromInstruction() & 1; - } + bool isVolatile() const { return getSubclassData(); } /// Specify whether this is a volatile cmpxchg. /// - void setVolatile(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | - (unsigned)V); - } + void setVolatile(bool V) { setSubclassData(V); } /// Return true if this cmpxchg may spuriously fail. - bool isWeak() const { - return getSubclassDataFromInstruction() & 0x100; - } + bool isWeak() const { return getSubclassData(); } - void setWeak(bool IsWeak) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) | - (IsWeak << 8)); - } + void setWeak(bool IsWeak) { setSubclassData(IsWeak); } /// Transparently provide more efficient getOperand methods. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); /// Returns the success ordering constraint of this cmpxchg instruction. AtomicOrdering getSuccessOrdering() const { - return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7); + return getSubclassData(); } /// Sets the success ordering constraint of this cmpxchg instruction. void setSuccessOrdering(AtomicOrdering Ordering) { assert(Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) | - ((unsigned)Ordering << 2)); + setSubclassData(Ordering); } /// Returns the failure ordering constraint of this cmpxchg instruction. AtomicOrdering getFailureOrdering() const { - return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7); + return getSubclassData(); } /// Sets the failure ordering constraint of this cmpxchg instruction. void setFailureOrdering(AtomicOrdering Ordering) { assert(Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) | - ((unsigned)Ordering << 5)); + setSubclassData(Ordering); } /// Returns the synchronization scope ID of this cmpxchg instruction. @@ -637,8 +631,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } /// The synchronization scope ID of this cmpxchg instruction. Not quite @@ -721,9 +716,11 @@ return User::operator new(s, 2); } - BinOp getOperation() const { - return static_cast(getSubclassDataFromInstruction() >> 5); - } + using VolatileField = Bitfield; + using AtomicOrderingField = Bitfield; + using OperationField = Bitfield; + + BinOp getOperation() const { return getSubclassData(); } static StringRef getOperationName(BinOp Op); @@ -738,38 +735,30 @@ } void setOperation(BinOp Operation) { - unsigned short SubclassData = getSubclassDataFromInstruction(); - setInstructionSubclassData((SubclassData & 31) | - (Operation << 5)); + setSubclassData(Operation); } /// Return true if this is a RMW on a volatile memory location. /// - bool isVolatile() const { - return getSubclassDataFromInstruction() & 1; - } + bool isVolatile() const { return getSubclassData(); } /// Specify whether this is a volatile RMW or not. /// - void setVolatile(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | - (unsigned)V); - } + void setVolatile(bool V) { setSubclassData(V); } /// Transparently provide more efficient getOperand methods. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); /// Returns the ordering constraint of this rmw instruction. AtomicOrdering getOrdering() const { - return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7); + return getSubclassData(); } /// Sets the ordering constraint of this rmw instruction. void setOrdering(AtomicOrdering Ordering) { assert(Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) | - ((unsigned)Ordering << 2)); + setSubclassData(Ordering); } /// Returns the synchronization scope ID of this rmw instruction. @@ -812,8 +801,9 @@ // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } /// The synchronization scope ID of this rmw instruction. Not quite enough @@ -1548,31 +1538,28 @@ TCK_MustTail = 2, TCK_NoTail = 3 }; + + using TailCallKindField = Bitfield; + TailCallKind getTailCallKind() const { - return TailCallKind(getSubclassDataFromInstruction() & 3); + return getSubclassData(); } bool isTailCall() const { - unsigned Kind = getSubclassDataFromInstruction() & 3; + unsigned Kind = getTailCallKind(); return Kind == TCK_Tail || Kind == TCK_MustTail; } - bool isMustTailCall() const { - return (getSubclassDataFromInstruction() & 3) == TCK_MustTail; - } + bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } - bool isNoTailCall() const { - return (getSubclassDataFromInstruction() & 3) == TCK_NoTail; - } + bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } - void setTailCall(bool isTC = true) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) | - unsigned(isTC ? TCK_Tail : TCK_None)); + void setTailCallKind(TailCallKind TCK) { + setSubclassData(TCK); } - void setTailCallKind(TailCallKind TCK) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) | - unsigned(TCK)); + void setTailCall(bool isTC = true) { + setTailCallKind(isTC ? TCK_Tail : TCK_None); } /// Return true if the call can return twice @@ -1595,8 +1582,9 @@ private: // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } }; @@ -2715,6 +2703,8 @@ /// cleanup. /// class LandingPadInst : public Instruction { + using CleanupField = Bitfield; + /// The number of operands actually allocated. NumOperands is /// the number actually in use. unsigned ReservedSpace; @@ -2759,13 +2749,10 @@ /// Return 'true' if this landingpad instruction is a /// cleanup. I.e., it should be run when unwinding even if its landing pad /// doesn't catch the exception. - bool isCleanup() const { return getSubclassDataFromInstruction() & 1; } + bool isCleanup() const { return getSubclassData(); } /// Indicate that this landingpad instruction is a cleanup. - void setCleanup(bool V) { - setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | - (V ? 1 : 0)); - } + void setCleanup(bool V) { setSubclassData(V); } /// Add a catch or filter clause to the landing pad. void addClause(Constant *ClauseVal); @@ -3752,11 +3739,11 @@ } private: - // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } }; @@ -3992,11 +3979,11 @@ } private: - // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } }; @@ -4087,6 +4074,8 @@ // CatchSwitchInst Class //===----------------------------------------------------------------------===// class CatchSwitchInst : public Instruction { + using UnwindDestField = Bitfield; // Next bit:1 + /// The number of operands actually allocated. NumOperands is /// the number actually in use. unsigned ReservedSpace; @@ -4148,7 +4137,7 @@ void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } // Accessor Methods for CatchSwitch stmt - bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; } + bool hasUnwindDest() const { return getSubclassData(); } bool unwindsToCaller() const { return !hasUnwindDest(); } BasicBlock *getUnwindDest() const { if (hasUnwindDest()) @@ -4434,6 +4423,7 @@ //===----------------------------------------------------------------------===// class CleanupReturnInst : public Instruction { + using UnwindDestField = Bitfield; // Next bit:1 private: CleanupReturnInst(const CleanupReturnInst &RI); CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, @@ -4474,7 +4464,7 @@ /// Provide fast operand accessors DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); - bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; } + bool hasUnwindDest() const { return getSubclassData(); } bool unwindsToCaller() const { return !hasUnwindDest(); } /// Convenience accessor. @@ -4518,8 +4508,9 @@ // Shadow Instruction::setInstructionSubclassData with a private forwarding // method so that subclasses cannot accidentally use it. - void setInstructionSubclassData(unsigned short D) { - Instruction::setInstructionSubclassData(D); + template + void setSubclassData(typename Bitfield::type value) { + Instruction::setSubclassData(value); } }; diff --git a/llvm/lib/IR/Instructions.cpp b/llvm/lib/IR/Instructions.cpp --- a/llvm/lib/IR/Instructions.cpp +++ b/llvm/lib/IR/Instructions.cpp @@ -960,7 +960,8 @@ OperandTraits::op_end(this) - CRI.getNumOperands(), CRI.getNumOperands()) { - setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); + setSubclassData( + CRI.getSubclassData()); Op<0>() = CRI.Op<0>(); if (CRI.hasUnwindDest()) Op<1>() = CRI.Op<1>(); @@ -968,7 +969,7 @@ void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { if (UnwindBB) - setInstructionSubclassData(getSubclassDataFromInstruction() | 1); + setSubclassData(true); Op<0>() = CleanupPad; if (UnwindBB) @@ -1072,7 +1073,7 @@ Op<0>() = ParentPad; if (UnwindDest) { - setInstructionSubclassData(getSubclassDataFromInstruction() | 1); + setSubclassData(true); setUnwindDest(UnwindDest); } } @@ -1299,9 +1300,7 @@ void AllocaInst::setAlignment(Align Align) { assert(Align <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | - encode(Align)); - assert(getAlignment() == Align.value() && "Alignment representation error!"); + setSubclassData(encode(Align)); } bool AllocaInst::isArrayAllocation() const { @@ -1397,9 +1396,7 @@ void LoadInst::setAlignment(Align Align) { assert(Align <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | - (encode(Align) << 1)); - assert(getAlign() == Align && "Alignment representation error!"); + setSubclassData(encode(Align)); } //===----------------------------------------------------------------------===// @@ -1476,9 +1473,7 @@ void StoreInst::setAlignment(Align Alignment) { assert(Alignment <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); - setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | - (encode(Alignment) << 1)); - assert(getAlign() == Alignment && "Alignment representation error!"); + setSubclassData(encode(Alignment)); } //===----------------------------------------------------------------------===// diff --git a/llvm/unittests/ADT/BitFieldsTest.cpp b/llvm/unittests/ADT/BitFieldsTest.cpp new file mode 100644 --- /dev/null +++ b/llvm/unittests/ADT/BitFieldsTest.cpp @@ -0,0 +1,141 @@ +//===- llvm/unittests/ADT/BitFieldsTest.cpp - BitFields unit tests --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/ADT/Bitfields.h" +#include "gtest/gtest.h" + +using namespace llvm; + +namespace { + +TEST(BitfieldsTest, Example) { + uint8_t storage = 0; + + // Store and retrieve a single bit as bool. + using Volatile = Bitfield; + setField(storage, true); + EXPECT_EQ(storage, 0b00000001); + EXPECT_EQ(getField(storage), true); + + // Store and retrieve a 2 bit typed enum. + enum class SuitEnum { CLUBS, DIAMONDS, HEARTS, SPADES }; + using Suit = Bitfield; + setField(storage, SuitEnum::HEARTS); + EXPECT_EQ(storage, 0b00000101); + EXPECT_EQ(getField(storage), SuitEnum::HEARTS); + + // Store and retrieve a 5 bit value as unsigned. + using Value = Bitfield; + setField(storage, 10); + EXPECT_EQ(storage, 0b01010101); + EXPECT_EQ(getField(storage), 10U); + + // Alter storage changes value. + storage = 0; + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(getField(storage), SuitEnum::CLUBS); + EXPECT_EQ(getField(storage), 0U); + + storage = 255; + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(getField(storage), SuitEnum::SPADES); + EXPECT_EQ(getField(storage), 31U); + + // Ability to efficiently test if a field is non zero. + EXPECT_NE(testField(storage), 0U); +} + +TEST(BitfieldsTest, FirstBit) { + uint8_t storage = 0; + using FirstBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x1ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, SecondBit) { + uint8_t storage = 0; + using SecondBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x2ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBit) { + uint8_t storage = 0; + using LastBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x80ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +TEST(BitfieldsTest, LastBitUint64) { + uint64_t storage = 0; + using LastBit = Bitfield; + // Set true + setField(storage, true); + EXPECT_EQ(getField(storage), true); + EXPECT_EQ(storage, 0x8000000000000000ULL); + // Set false + setField(storage, false); + EXPECT_EQ(getField(storage), false); + EXPECT_EQ(storage, 0x0ULL); +} + +enum class Ordering { + Not = 0, + Unordered = 1, + Monotonic = 2, +}; + +TEST(BitfieldsTest, EnumClass) { + uint8_t storage = 0; + using OrderingField = Bitfield; + EXPECT_EQ(getField(storage), Ordering::Not); + setField(storage, Ordering::Monotonic); + EXPECT_EQ(getField(storage), Ordering::Monotonic); + EXPECT_EQ(storage, 0b00000100); + // value 2 in ^^ +} + +#ifdef EXPECT_DEBUG_DEATH + +TEST(BitfieldsTest, ValueTooBigBool) { + uint64_t storage = 0; + using A = Bitfield; + setField(storage, true); + setField(storage, false); + EXPECT_DEBUG_DEATH(setField(storage, 2), "value is too big"); +} + +TEST(BitfieldsTest, ValueTooBigInt) { + uint64_t storage = 0; + using A = Bitfield; + setField(storage, 3); + EXPECT_DEBUG_DEATH(setField(storage, 4), "value is too big"); + EXPECT_DEBUG_DEATH(setField(storage, -1), "value is too big"); +} + +#endif + +} // namespace \ No newline at end of file diff --git a/llvm/unittests/ADT/CMakeLists.txt b/llvm/unittests/ADT/CMakeLists.txt --- a/llvm/unittests/ADT/CMakeLists.txt +++ b/llvm/unittests/ADT/CMakeLists.txt @@ -8,6 +8,7 @@ APIntTest.cpp APSIntTest.cpp ArrayRefTest.cpp + BitFieldsTest.cpp BitmaskEnumTest.cpp BitVectorTest.cpp BreadthFirstIteratorTest.cpp