52 #define DEBUG_TYPE "scalarizer" 59 cl::desc(
"Allow the scalarizer pass to scalarize loads and store"));
69 using ScatterMap = std::map<Value *, ValueVector>;
79 Scatterer() =
default;
85 ValueVector *cachePtr =
nullptr);
88 Value *operator[](
unsigned I);
91 unsigned size()
const {
return Size; }
97 ValueVector *CachePtr;
105 struct FCmpSplitter {
106 FCmpSplitter(
FCmpInst &fci) : FCI(fci) {}
118 struct ICmpSplitter {
119 ICmpSplitter(
ICmpInst &ici) : ICI(ici) {}
131 struct UnarySplitter {
143 struct BinarySplitter {
159 uint64_t getElemAlign(
unsigned I) {
160 return MinAlign(VecAlign, I * ElemSize);
167 Type *ElemTy =
nullptr;
170 uint64_t VecAlign = 0;
173 uint64_t ElemSize = 0;
176 class ScalarizerVisitor :
public InstVisitor<ScalarizerVisitor, bool> {
178 ScalarizerVisitor(
unsigned ParallelLoopAccessMDKind,
DominatorTree *DT)
179 : ParallelLoopAccessMDKind(ParallelLoopAccessMDKind), DT(DT) {
196 bool visitPHINode(
PHINode &PHI);
204 bool canTransferMetadata(
unsigned Kind);
205 void transferMetadataAndIRFlags(
Instruction *
Op,
const ValueVector &CV);
210 template<
typename T>
bool splitUnary(
Instruction &,
const T &);
211 template<
typename T>
bool splitBinary(
Instruction &,
const T &);
215 ScatterMap Scattered;
218 unsigned ParallelLoopAccessMDKind;
243 "Scalarize vector operations",
false,
false)
249 ValueVector *cachePtr)
250 : BB(bb), BBI(bbi), V(v), CachePtr(cachePtr) {
251 Type *Ty = V->getType();
254 Ty = PtrTy->getElementType();
257 Tmp.resize(
Size,
nullptr);
258 else if (CachePtr->empty())
259 CachePtr->resize(
Size,
nullptr);
261 assert(
Size == CachePtr->size() &&
"Inconsistent vector sizes");
265 Value *Scatterer::operator[](
unsigned I) {
266 ValueVector &CV = (CachePtr ? *CachePtr : Tmp);
275 CV[0] = Builder.
CreateBitCast(V, NewPtrTy, V->getName() +
".i0");
279 V->getName() +
".i" +
Twine(I));
314 unsigned ParallelLoopAccessMDKind =
316 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
317 ScalarizerVisitor Impl(ParallelLoopAccessMDKind, DT);
318 return Impl.visit(F);
322 return new ScalarizerLegacyPass();
325 bool ScalarizerVisitor::visit(
Function &F) {
326 assert(Gathered.empty() && Scattered.empty());
346 if (
Argument *VArg = dyn_cast<Argument>(V)) {
351 return Scatterer(BB, BB->
begin(), V, &Scattered[V]);
360 if (!DT->isReachableFromEntry(VOp->getParent()))
378 void ScalarizerVisitor::gather(
Instruction *
Op,
const ValueVector &CV) {
384 transferMetadataAndIRFlags(Op, CV);
388 ValueVector &SV = Scattered[
Op];
390 for (
unsigned I = 0,
E = SV.size(); I !=
E; ++
I) {
402 Gathered.
push_back(GatherList::value_type(Op, &SV));
407 bool ScalarizerVisitor::canTransferMetadata(
unsigned Tag) {
408 return (Tag == LLVMContext::MD_tbaa
409 || Tag == LLVMContext::MD_fpmath
410 || Tag == LLVMContext::MD_tbaa_struct
411 || Tag == LLVMContext::MD_invariant_load
412 || Tag == LLVMContext::MD_alias_scope
413 || Tag == LLVMContext::MD_noalias
414 || Tag == ParallelLoopAccessMDKind
415 || Tag == LLVMContext::MD_access_group);
420 void ScalarizerVisitor::transferMetadataAndIRFlags(
Instruction *Op,
421 const ValueVector &CV) {
424 for (
unsigned I = 0,
E = CV.size(); I !=
E; ++
I) {
425 if (
Instruction *New = dyn_cast<Instruction>(CV[I])) {
426 for (
const auto &MD : MDs)
427 if (canTransferMetadata(MD.first))
428 New->setMetadata(MD.first, MD.second);
429 New->copyIRFlags(Op);
438 bool ScalarizerVisitor::getVectorLayout(
Type *Ty,
unsigned Alignment,
446 Layout.ElemTy = Layout.VecTy->getElementType();
451 Layout.VecAlign = Alignment;
460 template<
typename Splitter>
461 bool ScalarizerVisitor::splitUnary(
Instruction &I,
const Splitter &Split) {
469 assert(Op.size() == NumElems &&
"Mismatched unary operation");
471 Res.resize(NumElems);
472 for (
unsigned Elem = 0; Elem < NumElems; ++Elem)
473 Res[Elem] = Split(Builder, Op[Elem], I.
getName() +
".i" +
Twine(Elem));
480 template<
typename Splitter>
481 bool ScalarizerVisitor::splitBinary(
Instruction &I,
const Splitter &Split) {
490 assert(Op0.size() == NumElems &&
"Mismatched binary operation");
491 assert(Op1.size() == NumElems &&
"Mismatched binary operation");
493 Res.resize(NumElems);
494 for (
unsigned Elem = 0; Elem < NumElems; ++Elem)
495 Res[Elem] = Split(Builder, Op0[Elem], Op1[Elem],
514 bool ScalarizerVisitor::splitCall(
CallInst &CI) {
530 ValueVector ScalarOperands(NumArgs);
533 Scattered.
resize(NumArgs);
537 for (
unsigned I = 0; I != NumArgs; ++
I) {
540 Scattered[
I] = scatter(&CI, OpI);
541 assert(Scattered[I].
size() == NumElems &&
"mismatched call operands");
543 ScalarOperands[
I] = OpI;
547 ValueVector Res(NumElems);
548 ValueVector ScalarCallOps(NumArgs);
554 for (
unsigned Elem = 0; Elem < NumElems; ++Elem) {
555 ScalarCallOps.clear();
557 for (
unsigned J = 0; J != NumArgs; ++J) {
559 ScalarCallOps.push_back(ScalarOperands[J]);
561 ScalarCallOps.push_back(Scattered[J][Elem]);
564 Res[Elem] = Builder.CreateCall(NewIntrin, ScalarCallOps,
572 bool ScalarizerVisitor::visitSelectInst(
SelectInst &
SI) {
579 Scatterer Op1 = scatter(&SI, SI.
getOperand(1));
580 Scatterer Op2 = scatter(&SI, SI.
getOperand(2));
581 assert(Op1.size() == NumElems &&
"Mismatched select");
582 assert(Op2.size() == NumElems &&
"Mismatched select");
584 Res.resize(NumElems);
587 Scatterer Op0 = scatter(&SI, SI.
getOperand(0));
588 assert(Op0.size() == NumElems &&
"Mismatched select");
589 for (
unsigned I = 0; I < NumElems; ++
I)
594 for (
unsigned I = 0; I < NumElems; ++
I)
602 bool ScalarizerVisitor::visitICmpInst(
ICmpInst &ICI) {
603 return splitBinary(ICI, ICmpSplitter(ICI));
606 bool ScalarizerVisitor::visitFCmpInst(
FCmpInst &FCI) {
607 return splitBinary(FCI, FCmpSplitter(FCI));
610 bool ScalarizerVisitor::visitUnaryOperator(
UnaryOperator &UO) {
611 return splitUnary(UO, UnarySplitter(UO));
615 return splitBinary(BO, BinarySplitter(BO));
632 Scatterer
Base = scatter(&GEPI, Op0);
636 for (
unsigned I = 0; I < NumIndices; ++
I) {
644 Ops[
I] = scatter(&GEPI, Op);
648 Res.resize(NumElems);
649 for (
unsigned I = 0; I < NumElems; ++
I) {
651 Indices.
resize(NumIndices);
652 for (
unsigned J = 0; J < NumIndices; ++J)
653 Indices[J] = Ops[J][I];
658 NewGEPI->setIsInBounds();
664 bool ScalarizerVisitor::visitCastInst(
CastInst &CI) {
671 Scatterer Op0 = scatter(&CI, CI.
getOperand(0));
672 assert(Op0.size() == NumElems &&
"Mismatched cast");
674 Res.resize(NumElems);
675 for (
unsigned I = 0; I < NumElems; ++
I)
682 bool ScalarizerVisitor::visitBitCastInst(
BitCastInst &BCI) {
685 if (!DstVT || !SrcVT)
689 unsigned SrcNumElems = SrcVT->getNumElements();
691 Scatterer Op0 = scatter(&BCI, BCI.
getOperand(0));
693 Res.resize(DstNumElems);
695 if (DstNumElems == SrcNumElems) {
696 for (
unsigned I = 0; I < DstNumElems; ++
I)
699 }
else if (DstNumElems > SrcNumElems) {
702 unsigned FanOut = DstNumElems / SrcNumElems;
705 for (
unsigned Op0I = 0; Op0I < SrcNumElems; ++Op0I) {
706 Value *V = Op0[Op0I];
710 while ((VI = dyn_cast<Instruction>(V)) &&
714 Scatterer Mid = scatter(&BCI, V);
715 for (
unsigned MidI = 0; MidI < FanOut; ++MidI)
716 Res[ResI++] = Mid[MidI];
720 unsigned FanIn = SrcNumElems / DstNumElems;
723 for (
unsigned ResI = 0; ResI < DstNumElems; ++ResI) {
725 for (
unsigned MidI = 0; MidI < FanIn; ++MidI)
728 +
".upto" +
Twine(MidI));
743 Scatterer Op0 = scatter(&SVI, SVI.
getOperand(0));
744 Scatterer Op1 = scatter(&SVI, SVI.
getOperand(1));
746 Res.resize(NumElems);
748 for (
unsigned I = 0; I < NumElems; ++
I) {
752 else if (
unsigned(Selector) < Op0.size())
753 Res[I] = Op0[Selector];
755 Res[
I] = Op1[Selector - Op0.size()];
761 bool ScalarizerVisitor::visitPHINode(
PHINode &PHI) {
769 Res.resize(NumElems);
772 for (
unsigned I = 0; I < NumElems; ++
I)
776 for (
unsigned I = 0; I < NumOps; ++
I) {
779 for (
unsigned J = 0; J < NumElems; ++J)
780 cast<PHINode>(Res[J])->addIncoming(Op[J], IncomingBlock);
786 bool ScalarizerVisitor::visitLoadInst(
LoadInst &LI) {
797 unsigned NumElems = Layout.VecTy->getNumElements();
801 Res.resize(NumElems);
803 for (
unsigned I = 0; I < NumElems; ++
I)
805 Layout.getElemAlign(I),
811 bool ScalarizerVisitor::visitStoreInst(
StoreInst &SI) {
823 unsigned NumElems = Layout.VecTy->getNumElements();
826 Scatterer Val = scatter(&SI, FullValue);
829 Stores.resize(NumElems);
830 for (
unsigned I = 0; I < NumElems; ++
I) {
831 unsigned Align = Layout.getElemAlign(I);
834 transferMetadataAndIRFlags(&SI, Stores);
838 bool ScalarizerVisitor::visitCallInst(
CallInst &CI) {
839 return splitCall(CI);
844 bool ScalarizerVisitor::finish() {
847 if (Gathered.empty() && Scattered.empty())
849 for (
const auto &GMI : Gathered) {
851 ValueVector &CV = *GMI.second;
860 if (isa<PHINode>(Op))
862 for (
unsigned I = 0; I < Count; ++
I)
877 unsigned ParallelLoopAccessMDKind =
880 ScalarizerVisitor Impl(ParallelLoopAccessMDKind, DT);
881 bool Changed = Impl.visit(F);
void getAllMetadataOtherThanDebugLoc(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
This does the same thing as getAllMetadata, except that it filters out the debug location.
Type * getVectorElementType() const
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name="")
Type * getSrcTy() const
Return the source type, as a convenience.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
This instruction constructs a fixed permutation of two input vectors.
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
bool isVectorTy() const
True if this is an instance of VectorType.
bool typeSizeEqualsStoreSize(Type *Ty) const
Returns true if no extra padding bits are needed when storing the specified type. ...
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
iterator begin()
Instruction iterator methods.
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
INITIALIZE_PASS_BEGIN(ScalarizerLegacyPass, "scalarizer", "Scalarize vector operations", false, false) INITIALIZE_PASS_END(ScalarizerLegacyPass
void initializeScalarizerLegacyPassPass(PassRegistry &)
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
This is the base class for all instructions that perform data casts.
LLVMContext & getContext() const
Get the global data context.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Type * getSourceElementType() const
void visit(Iterator Start, Iterator End)
unsigned getNumIndices() const
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
This instruction compares its operands according to the predicate given to the constructor.
This class represents a no-op cast from one type to another.
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Value * getOperand(unsigned i) const
Class to represent pointers.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
This instruction inserts a single (scalar) element into a VectorType value.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static Function * getScalarIntrinsicDeclaration(Module *M, Intrinsic::ID ID, VectorType *Ty)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
static bool isTriviallyScalariable(Intrinsic::ID ID)
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Scalarize vector operations
Value * getPointerOperand()
self_iterator getIterator()
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static int getMaskValue(const Constant *Mask, unsigned Elt)
Return the shuffle mask value for the specified element of the mask.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This struct is a compact representation of a valid (non-zero power of two) alignment.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Module.h This file contains the declarations for the Module class.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Type * getDestTy() const
Return the destination type, as a convenience.
bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx)
Identifies if the vector form of the intrinsic has a scalar operand.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
void setOperand(unsigned i, Value *Val)
unsigned getVectorNumElements() const
This pass converts vector operations into scalar operations, in order to expose optimization opportun...
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
void push_back(pointer val)
static cl::opt< bool > ScalarizeLoadStore("scalarize-load-store", cl::init(false), cl::Hidden, cl::desc("Allow the scalarizer pass to scalarize loads and store"))
unsigned getNumArgOperands() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Type * getElementType() const
FunctionPass * createScalarizerPass()
Create a legacy pass manager instance of the Scalarizer pass.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
VectorType * getType() const
Overload to return most specific vector type.
Value * getPointerOperand()
const BasicBlock * getParent() const
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.