23#include "llvm/IR/IntrinsicsSPIRV.h"
26#define DEBUG_TYPE "spirv-prelegalizer"
51 cast<Constant>(cast<ConstantAsMetadata>(
52 MI.getOperand(3).getMetadata()->getOperand(0))
54 if (
auto *GV = dyn_cast<GlobalValue>(Const)) {
57 GR->
add(GV, &MF,
MI.getOperand(2).getReg());
59 RegsAlreadyAddedToDT[&
MI] = Reg;
63 if (
auto *ConstVec = dyn_cast<ConstantDataVector>(Const)) {
64 auto *BuildVec =
MRI.getVRegDef(
MI.getOperand(2).getReg());
66 BuildVec->getOpcode() == TargetOpcode::G_BUILD_VECTOR);
67 for (
unsigned i = 0; i < ConstVec->getNumElements(); ++i) {
70 Constant *ElemConst = ConstVec->getElementAsConstant(i);
73 GR->
add(ElemConst, &MF, BuildVec->getOperand(1 + i).getReg());
75 BuildVec->getOperand(1 + i).setReg(ElemReg);
78 GR->
add(Const, &MF,
MI.getOperand(2).getReg());
80 RegsAlreadyAddedToDT[&
MI] = Reg;
83 assert(
MI.getOperand(2).isReg() &&
"Reg operand is expected");
85 if (SrcMI &&
isSpvIntrinsic(*SrcMI, Intrinsic::spv_const_composite))
94 Reg = RegsAlreadyAddedToDT[
MI];
95 auto *RC =
MRI.getRegClassOrNull(
MI->getOperand(0).getReg());
96 if (!
MRI.getRegClassOrNull(Reg) && RC)
97 MRI.setRegClass(Reg, RC);
98 MRI.replaceRegWith(
MI->getOperand(0).getReg(), Reg);
99 MI->eraseFromParent();
102 MI->eraseFromParent();
108 const unsigned AssignNameOperandShift = 2;
113 unsigned NumOp =
MI.getNumExplicitDefs() + AssignNameOperandShift;
114 while (
MI.getOperand(NumOp).isReg()) {
118 MI.removeOperand(NumOp);
127 MI->eraseFromParent();
167 MI->eraseFromParent();
188 assert(
MI &&
"Machine instr is expected");
189 if (
MI->getOperand(0).isReg()) {
193 switch (
MI->getOpcode()) {
194 case TargetOpcode::G_CONSTANT: {
196 Type *Ty =
MI->getOperand(1).getCImm()->getType();
200 case TargetOpcode::G_GLOBAL_VALUE: {
205 Global->getType()->getAddressSpace());
209 case TargetOpcode::G_ZEXT: {
210 if (
MI->getOperand(1).isReg()) {
212 MRI.getVRegDef(
MI->getOperand(1).getReg())) {
215 unsigned ExpectedBW =
216 std::max(
MRI.getType(Reg).getScalarSizeInBits(), CurrentBW);
227 case TargetOpcode::G_PTRTOINT:
229 MRI.getType(Reg).getScalarSizeInBits(), MIB);
231 case TargetOpcode::G_TRUNC:
232 case TargetOpcode::G_ADDRSPACE_CAST:
233 case TargetOpcode::G_PTR_ADD:
234 case TargetOpcode::COPY: {
246 if (!
MRI.getRegClassOrNull(Reg))
247 MRI.setRegClass(Reg, &SPIRV::IDRegClass);
253static std::pair<Register, unsigned>
258 assert(SpvType &&
"VReg is expected to have SPIRV type");
259 LLT SrcLLT =
MRI.getType(SrcReg);
261 bool IsFloat = SpvType->
getOpcode() == SPIRV::OpTypeFloat;
263 SpvType->
getOpcode() == SPIRV::OpTypeVector &&
266 IsFloat |= IsVectorFloat;
267 auto GetIdOp = IsFloat ? SPIRV::GET_fID : SPIRV::GET_ID;
268 auto DstClass = IsFloat ? &SPIRV::fIDRegClass : &SPIRV::IDRegClass;
277 GetIdOp = SPIRV::GET_vpID64;
278 DstClass = &SPIRV::vpID64RegClass;
280 GetIdOp = SPIRV::GET_pID64;
281 DstClass = &SPIRV::pID64RegClass;
285 GetIdOp = SPIRV::GET_vpID32;
286 DstClass = &SPIRV::vpID32RegClass;
288 GetIdOp = SPIRV::GET_pID32;
289 DstClass = &SPIRV::pID32RegClass;
295 GetIdOp = SPIRV::GET_vfID;
296 DstClass = &SPIRV::vfIDRegClass;
298 GetIdOp = SPIRV::GET_vID;
299 DstClass = &SPIRV::vIDRegClass;
302 Register IdReg =
MRI.createGenericVirtualRegister(NewT);
303 MRI.setRegClass(IdReg, DstClass);
304 return {IdReg, GetIdOp};
317 assert((Ty || SpirvTy) &&
"Either LLVM or SPIRV type is expected.");
319 (Def->getNextNode() ? Def->getNextNode()->getIterator()
320 : Def->getParent()->end()));
322 Register NewReg =
MRI.createGenericVirtualRegister(
MRI.getType(Reg));
323 if (
auto *RC =
MRI.getRegClassOrNull(Reg)) {
324 MRI.setRegClass(NewReg, RC);
326 MRI.setRegClass(NewReg, &SPIRV::IDRegClass);
327 MRI.setRegClass(Reg, &SPIRV::IDRegClass);
335 const uint32_t Flags = Def->getFlags();
341 Def->getOperand(0).setReg(NewReg);
347 assert(
MI.getNumDefs() > 0 &&
MRI.hasOneUse(
MI.getOperand(0).getReg()));
349 *(
MRI.use_instr_begin(
MI.getOperand(0).getReg()));
353 MI.getOperand(0).setReg(NewReg);
355 (
MI.getNextNode() ?
MI.getNextNode()->getIterator()
356 :
MI.getParent()->end()));
357 for (
auto &
Op :
MI.operands()) {
358 if (!
Op.isReg() ||
Op.isDef())
362 Op.setReg(IdOpInfo.first);
380 bool ReachedBegin =
false;
394 assert(Def &&
"Expecting an instruction that defines the register");
396 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
404 assert(Def &&
"Expecting an instruction that defines the register");
406 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
409 }
else if (
MI.getOpcode() == TargetOpcode::G_CONSTANT ||
410 MI.getOpcode() == TargetOpcode::G_FCONSTANT ||
411 MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
418 if (
MRI.hasOneUse(Reg)) {
425 if (
MI.getOpcode() == TargetOpcode::G_CONSTANT)
426 Ty =
MI.getOperand(1).getCImm()->getType();
427 else if (
MI.getOpcode() == TargetOpcode::G_FCONSTANT)
428 Ty =
MI.getOperand(1).getFPImm()->getType();
430 assert(
MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
431 Type *ElemTy =
nullptr;
435 if (ElemMI->
getOpcode() == TargetOpcode::G_CONSTANT)
437 else if (ElemMI->
getOpcode() == TargetOpcode::G_FCONSTANT)
442 MI.getNumExplicitOperands() -
MI.getNumExplicitDefs();
443 Ty = VectorType::get(ElemTy, NumElts,
false);
446 }
else if (
MI.getOpcode() == TargetOpcode::G_TRUNC ||
447 MI.getOpcode() == TargetOpcode::G_ZEXT ||
448 MI.getOpcode() == TargetOpcode::G_PTRTOINT ||
449 MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE ||
450 MI.getOpcode() == TargetOpcode::COPY ||
451 MI.getOpcode() == TargetOpcode::G_ADDRSPACE_CAST) {
462 MI->eraseFromParent();
484 if (
MI.getOpcode() != SPIRV::ASSIGN_TYPE)
487 unsigned Opcode =
MRI.getVRegDef(SrcReg)->getOpcode();
491 bool IsDstPtr =
MRI.getType(DstReg).isPointer();
492 bool isDstVec =
MRI.getType(DstReg).isVector();
493 if (IsDstPtr || isDstVec)
494 MRI.setRegClass(DstReg, &SPIRV::IDRegClass);
497 if (Opcode == TargetOpcode::G_CONSTANT &&
MRI.hasOneUse(DstReg)) {
499 if (
UseMI.getOpcode() == TargetOpcode::G_ADDRSPACE_CAST)
523 for (
unsigned i = 2; i <
MI.getNumOperands(); ++i) {
531 BuildMBB->
getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
542 for (
auto &SwIt : Switches) {
546 for (
unsigned i = 0; i < Ins.size(); ++i) {
547 if (Ins[i]->
getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
549 Ins[i]->getOperand(1).getBlockAddress()->getBasicBlock();
550 auto It = BB2MBB.
find(CaseBB);
551 if (It == BB2MBB.
end())
553 "block in a switch statement");
555 MI.getParent()->addSuccessor(It->second);
562 for (
unsigned i =
MI.getNumOperands() - 1; i > 1; --i)
564 for (
auto &MO : NewOps)
569 Next =
MI.getNextNode();
571 if (Next && Next->getOpcode() == TargetOpcode::G_BRINDIRECT)
576 BlockAddrI->eraseFromParent();
617 GR->setCurrentFunc(MF);
633char SPIRVPreLegalizer::
ID = 0;
636 return new SPIRVPreLegalizer();
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void removeImplicitFallthroughs(MachineFunction &MF, MachineIRBuilder MIB)
static bool isImplicitFallthrough(MachineBasicBlock &MBB)
bool isTypeFoldingSupported(unsigned Opcode)
static void insertBitcasts(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void processInstrsWithTypeFolding(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static SPIRVType * propagateSPIRVType(MachineInstr *MI, SPIRVGlobalRegistry *GR, MachineRegisterInfo &MRI, MachineIRBuilder &MIB)
static void processSwitches(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void generateAssignInstrs(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void addConstantsToTrack(MachineFunction &MF, SPIRVGlobalRegistry *GR)
static std::pair< Register, unsigned > createNewIdReg(SPIRVType *SpvType, Register SrcReg, MachineRegisterInfo &MRI, const SPIRVGlobalRegistry &GR)
static void foldConstantsIntoIntrinsics(MachineFunction &MF)
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
LLVM Basic Block Representation.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
This class represents an Operation in the Expression.
iterator find(const_arg_type_t< KeyT > Val)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
FunctionPass class - This class is used to implement most global optimizations.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr bool isPointer() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Helper class to build MachineInstr.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildBitcast(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_BITCAST Src.
MachineRegisterInfo * getMRI()
Getter for MRI.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i....
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
static MachineOperand CreateCImm(const ConstantInt *CI)
void setReg(Register Reg)
Change the register this operand corresponds to.
const BlockAddress * getBlockAddress() const
static MachineOperand CreateImm(int64_t Val)
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
SPIRVType * getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
void add(const Constant *C, MachineFunction *MF, Register R)
unsigned getScalarOrVectorComponentCount(Register VReg) const
unsigned getPointerSize() const
Register getSPIRVTypeID(const SPIRVType *SpirvType) const
SPIRVType * getOrCreateSPIRVType(const Type *Type, MachineIRBuilder &MIRBuilder, SPIRV::AccessQualifier::AccessQualifier AQ=SPIRV::AccessQualifier::ReadWrite, bool EmitIR=true)
void assignSPIRVTypeToVReg(SPIRVType *Type, Register VReg, MachineFunction &MF)
Register find(const MachineInstr *MI, MachineFunction *MF)
SPIRVType * getOrCreateSPIRVPointerType(SPIRVType *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SClass=SPIRV::StorageClass::Function)
SPIRVType * getOrCreateSPIRVVectorType(SPIRVType *BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder)
SPIRVType * getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
Type * getDeducedGlobalValueType(const GlobalValue *Global)
unsigned getScalarOrVectorBitWidth(const SPIRVType *Type) const
const SPIRVInstrInfo * getInstrInfo() const override
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
static TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Type * getType() const
All values are typed, get the type of this value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createSPIRVPreLegalizerPass()
Register insertAssignInstr(Register Reg, Type *Ty, SPIRVType *SpirvTy, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
Helper external function for inserting ASSIGN_TYPE instuction between Reg and its definition,...
iterator_range< po_iterator< T > > post_order(const T &G)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
@ Global
Append to llvm.global_dtors.
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
void processInstr(MachineInstr &MI, MachineIRBuilder &MIB, MachineRegisterInfo &MRI, SPIRVGlobalRegistry *GR)
MachineInstr * getDefInstrMaybeConstant(Register &ConstReg, const MachineRegisterInfo *MRI)
Type * getMDOperandAsType(const MDNode *N, unsigned I)
void initializeSPIRVPreLegalizerPass(PassRegistry &)
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)