25#define DEBUG_TYPE "dxil-legalize"
36 FI->replaceAllUsesWith(FI->getOperand(0));
48 for (
unsigned OpIdx = 0; OpIdx <
I.getNumOperands(); ++OpIdx) {
51 ReplacedValues[
Op]->getType()->isIntegerTy())
52 InstrType = ReplacedValues[
Op]->getType();
55 for (
unsigned OpIdx = 0; OpIdx <
I.getNumOperands(); ++OpIdx) {
58 NewOperands.push_back(ReplacedValues[
Op]);
61 unsigned NewBitWidth = InstrType->getIntegerBitWidth();
66 "Replacement's BitWidth should be larger than Current.");
68 NewOperands.push_back(ConstantInt::get(InstrType, NewValue));
70 assert(!
Op->getType()->isIntegerTy(8));
71 NewOperands.push_back(
Op);
77 if (Trunc->getDestTy()->isIntegerTy(8)) {
78 ReplacedValues[Trunc] = Trunc->getOperand(0);
85 if (!
Store->getValueOperand()->getType()->isIntegerTy(8))
88 ProcessOperands(NewOperands);
89 Value *NewStore = Builder.CreateStore(NewOperands[0], NewOperands[1]);
90 ReplacedValues[
Store] = NewStore;
96 Load &&
I.getType()->isIntegerTy(8)) {
98 ProcessOperands(NewOperands);
99 Type *ElementType = NewOperands[0]->getType();
101 ElementType = AI->getAllocatedType();
103 ElementType =
GEP->getSourceElementType();
105 if (ElementType->isArrayTy())
106 ElementType = ElementType->getArrayElementType();
107 LoadInst *NewLoad = Builder.CreateLoad(ElementType, NewOperands[0]);
108 ReplacedValues[
Load] = NewLoad;
116 if (!(CE->getOpcode() == Instruction::GetElementPtr))
119 if (!
GEP->getSourceElementType()->isIntegerTy(8))
122 Type *ElementType =
Load->getType();
125 uint32_t ElemSize =
Load->getDataLayout().getTypeAllocSize(ElementType);
126 uint32_t Index = ByteOffset / ElemSize;
128 Value *PtrOperand =
GEP->getPointerOperand();
129 Type *GEPType =
GEP->getPointerOperandType();
132 GEPType = GV->getValueType();
134 GEPType = AI->getAllocatedType();
141 Value *NewGEP = Builder.CreateGEP(
142 GEPType, PtrOperand, {Builder.getInt32(0), Builder.getInt32(Index)},
143 GEP->getName(),
GEP->getNoWrapFlags());
145 LoadInst *NewLoad = Builder.CreateLoad(ElementType, NewGEP);
146 ReplacedValues[
Load] = NewLoad;
147 Load->replaceAllUsesWith(NewLoad);
153 if (!
I.getType()->isIntegerTy(8))
156 ProcessOperands(NewOperands);
158 Builder.CreateBinOp(BO->getOpcode(), NewOperands[0], NewOperands[1]);
161 if (NewBO && OBO->hasNoSignedWrap())
162 NewBO->setHasNoSignedWrap();
163 if (NewBO && OBO->hasNoUnsignedWrap())
164 NewBO->setHasNoUnsignedWrap();
166 ReplacedValues[BO] = NewInst;
172 if (!
I.getType()->isIntegerTy(8))
175 ProcessOperands(NewOperands);
176 Value *NewInst = Builder.CreateSelect(Sel->getCondition(), NewOperands[1],
178 ReplacedValues[Sel] = NewInst;
184 if (!Cmp->getOperand(0)->getType()->isIntegerTy(8))
187 ProcessOperands(NewOperands);
189 Builder.CreateCmp(Cmp->getPredicate(), NewOperands[0], NewOperands[1]);
190 Cmp->replaceAllUsesWith(NewInst);
191 ReplacedValues[Cmp] = NewInst;
197 if (!Cast->getSrcTy()->isIntegerTy(8))
201 auto *Replacement = ReplacedValues[Cast->getOperand(0)];
202 if (Cast->getType() == Replacement->getType()) {
203 Cast->replaceAllUsesWith(Replacement);
207 Value *AdjustedCast =
nullptr;
208 if (Cast->getOpcode() == Instruction::ZExt)
209 AdjustedCast = Builder.CreateZExtOrTrunc(Replacement, Cast->getType());
210 if (Cast->getOpcode() == Instruction::SExt)
211 AdjustedCast = Builder.CreateSExtOrTrunc(Replacement, Cast->getType());
217 if (!
GEP->getType()->isPointerTy() ||
218 !
GEP->getSourceElementType()->isIntegerTy(8))
221 Value *BasePtr =
GEP->getPointerOperand();
222 if (ReplacedValues.
count(BasePtr))
223 BasePtr = ReplacedValues[BasePtr];
225 Type *ElementType = BasePtr->getType();
228 ElementType = AI->getAllocatedType();
230 ElementType = GV->getValueType();
232 Type *GEPType = ElementType;
243 assert(
Offset &&
"Offset is expected to be a ConstantInt");
245 uint32_t ElemSize =
GEP->getDataLayout().getTypeAllocSize(ElementType);
246 assert(ElemSize > 0 &&
"ElementSize must be set");
247 uint32_t Index = ByteOffset / ElemSize;
248 Value *NewGEP = Builder.CreateGEP(
249 GEPType, BasePtr, {Builder.getInt32(0), Builder.getInt32(Index)},
250 GEP->getName(),
GEP->getNoWrapFlags());
251 ReplacedValues[
GEP] = NewGEP;
252 GEP->replaceAllUsesWith(NewGEP);
263 if (!AI || !AI->getAllocatedType()->isIntegerTy(8))
266 Type *SmallestType =
nullptr;
285 for (
User *GU :
GEP->users()) {
297 auto *NewAlloca = Builder.CreateAlloca(SmallestType);
298 ReplacedValues[AI] = NewAlloca;
309 Value *Idx = Extract->getIndexOperand();
311 if (CI && CI->getBitWidth() == 64) {
313 int64_t IndexValue = CI->getSExtValue();
316 Value *NewExtract = Builder.CreateExtractElement(
317 Extract->getVectorOperand(), Idx32, Extract->getName());
326 Value *Idx = Insert->getOperand(2);
328 if (CI && CI->getBitWidth() == 64) {
329 int64_t IndexValue = CI->getSExtValue();
333 Value *Insert32Index = Builder.CreateInsertElement(
334 Insert->getOperand(0), Insert->getOperand(1), Idx32,
337 Insert->replaceAllUsesWith(Insert32Index);
349 if (ID != Instruction::FNeg)
353 Value *In =
I.getOperand(0);
354 Value *Zero = ConstantFP::get(In->getType(), -0.0);
355 I.replaceAllUsesWith(Builder.CreateFSub(Zero, In));
372 Type *ValTy = AI->getValOperand()->getType();
379 if (Width != 32 && Width != 64)
381 "floating-point value");
385 Value *Val = Builder.CreateBitCast(AI->getValOperand(), IntTy);
388 AI->getOrdering(), AI->getSyncScopeID());
390 AI->replaceAllUsesWith(Builder.CreateBitCast(NewAI, ValTy));
400 if (!
SI ||
SI->getNumCases() == 0)
406 if (DefaultBB->
size() == 0 ||
416 for (
auto &Case :
SI->cases()) {
420 CommonSuccessor =
nullptr;
424 if (!CommonSuccessor)
425 CommonSuccessor = Succ;
426 else if (CommonSuccessor != Succ) {
427 CommonSuccessor =
nullptr;
433 CommonSuccessor ? CommonSuccessor :
SI->case_begin()->getCaseSuccessor();
436 SI->setDefaultDest(NewDefault);
453 [[maybe_unused]]
Type *LoadStoreTy;
455 PtrOp = LI->getPointerOperand();
456 PtrOpIndex = LI->getPointerOperandIndex();
457 LoadStoreTy = LI->getType();
459 PtrOp =
SI->getPointerOperand();
460 PtrOpIndex =
SI->getPointerOperandIndex();
461 LoadStoreTy =
SI->getValueOperand()->getType();
474 ArrayTy = GlobalVarPtrOp->getValueType();
476 ArrayTy = AllocaPtrOp->getAllocatedType();
484 "Expected array element type to be the same as to the scalar load or "
490 I.setOperand(PtrOpIndex,
GEP);
495class DXILLegalizationPipeline {
498 DXILLegalizationPipeline() { initializeLegalizationPipeline(); }
500 bool runLegalizationPipeline(
Function &
F) {
501 bool MadeChange =
false;
502 SmallVector<Instruction *>
ToRemove;
503 DenseMap<Value *, Value *> ReplacedValues;
504 for (
int Stage = 0; Stage < NumStages; ++Stage) {
506 ReplacedValues.
clear();
508 for (
auto &LegalizationFn : LegalizationPipeline[Stage])
509 MadeChange |= LegalizationFn(
I,
ToRemove, ReplacedValues);
513 Inst->eraseFromParent();
522 enum LegalizationStage { Stage1 = 0, Stage2 = 1, NumStages };
524 using LegalizationFnTy =
525 std::function<bool(Instruction &, SmallVectorImpl<Instruction *> &,
526 DenseMap<Value *, Value *> &)>;
530 void initializeLegalizationPipeline() {
536 LegalizationPipeline[Stage1].push_back(
547 DXILLegalizeLegacy() : FunctionPass(ID) {}
555 DXILLegalizationPipeline DXLegalize;
556 bool MadeChanges = DXLegalize.runLegalizationPipeline(
F);
563bool DXILLegalizeLegacy::runOnFunction(
Function &
F) {
564 DXILLegalizationPipeline DXLegalize;
565 return DXLegalize.runLegalizationPipeline(
F);
568char DXILLegalizeLegacy::ID = 0;
576 return new DXILLegalizeLegacy();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
Expand Atomic instructions
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool fixI8UseChain(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &ReplacedValues)
static bool downcastI64toI32InsertExtractElements(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &)
static bool legalizeFloatAtomicExchange(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &)
static bool upcastI8AllocasAndUses(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &ReplacedValues)
static bool resolveUnreachableSwitchDefault(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &)
static bool legalizeScalarLoadStoreOnArrays(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &)
static bool legalizeFreeze(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * >)
static bool updateFnegToFsub(Instruction &I, SmallVectorImpl< Instruction * > &ToRemove, DenseMap< Value *, Value * > &)
static bool runOnFunction(Function &F, bool PostInlining)
Module.h This file contains the declarations for the Module class.
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Class for arbitrary precision integers.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
an instruction that atomically reads a memory location, combines it with another value,...
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This is the base class for all instructions that perform data casts.
This is the shared class of boolean and integer constants.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
FunctionPass class - This class is used to implement most global optimizations.
static GEPNoWrapFlags all()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
An instruction for reading from memory.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Type * getArrayElementType() const
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
This is an optimization pass for GlobalISel generic memory operations.
FunctionPass * createDXILLegalizeLegacyPass()
Pass to Legalize DXIL by remove i8 truncations and i64 insert/extract elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
auto reverse(ContainerTy &&C)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
DWARFExpression::Operation Op
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.