59#define DEBUG_TYPE "lower-matrix-intrinsics"
61STATISTIC(FlattenedMatrices,
"Number of matrix flattenings");
62STATISTIC(ReshapedMatrices,
"Number of matrix reshapes");
81 return SV->isZeroEltSplat();
86template <
typename LTy,
typename RTy>
87static auto m_AnyMul(
const LTy &L,
const RTy &R) {
92template <
typename LTy,
typename RTy>
93static auto m_AnyAdd(
const LTy &L,
const RTy &R) {
138 unsigned NumElements,
Type *EltType,
143 "Stride must be >= the number of elements in the result vector.");
146 Value *VecStart = Builder.CreateMul(VecIdx, Stride,
"vec.start");
153 VecStart = Builder.CreateInBoundsGEP(EltType, BasePtr, VecStart,
"vec.gep");
163 ShapeInfo(
unsigned NumRows = 0,
unsigned NumColumns = 0)
164 : NumRows(NumRows), NumColumns(NumColumns) {}
167 : ShapeInfo(
cast<ConstantInt>(NumRows)->getZExtValue(),
168 cast<ConstantInt>(NumColumns)->getZExtValue()) {}
171 return NumRows == other.NumRows && NumColumns == other.NumColumns;
173 bool operator!=(
const ShapeInfo &other) {
return !(*
this == other); }
177 operator bool()
const {
178 assert(NumRows == 0 || NumColumns != 0);
183 ShapeInfo t()
const {
return ShapeInfo(NumColumns, NumRows); }
185 friend raw_ostream &
operator<<(raw_ostream &OS, ShapeInfo SI);
191 return OS <<
SI.NumRows <<
'x' <<
SI.NumColumns;
208 switch (Cast->getOpcode()) {
209 case llvm::Instruction::Trunc:
210 case llvm::Instruction::ZExt:
211 case llvm::Instruction::SExt:
212 case llvm::Instruction::FPToUI:
213 case llvm::Instruction::FPToSI:
214 case llvm::Instruction::UIToFP:
215 case llvm::Instruction::SIToFP:
216 case llvm::Instruction::FPTrunc:
217 case llvm::Instruction::FPExt:
219 case llvm::Instruction::AddrSpaceCast:
220 case CastInst::PtrToAddr:
221 case CastInst::PtrToInt:
222 case CastInst::IntToPtr:
224 case CastInst::BitCast: {
227 return SrcVTy->getNumElements() == DestVTy->getNumElements();
230 case llvm::Instruction::CastOpsEnd:
237 switch (
II->getIntrinsicID()) {
239 case Intrinsic::fabs:
245 switch (
I->getOpcode()) {
246 case Instruction::PHI:
247 case Instruction::FNeg:
258 "Can't retrieve shaped operands for an instruction that does not "
259 "preserve shape information");
260 auto Ops =
I->operands();
265static std::optional<ShapeInfo>
273 return ShapeInfo(M,
K);
277 return ShapeInfo(
N, M);
282 return ShapeInfo(
N, M);
285 return ShapeInfo(M,
N);
288 auto OpShape = ShapeMap.
find(MatrixA);
289 if (OpShape != ShapeMap.
end())
290 return OpShape->second;
296 for (
auto &
Op : ShapedOps) {
297 auto OpShape = ShapeMap.
find(
Op.get());
298 if (OpShape != ShapeMap.
end())
299 return OpShape->second;
330class LowerMatrixIntrinsics {
331 const ScalarOptions &Opts;
333 const DataLayout &DL;
334 const TargetTransformInfo &TTI;
337 DominatorTree *DT =
nullptr;
338 LoopInfo *LI =
nullptr;
339 OptimizationRemarkEmitter *ORE =
nullptr;
345 unsigned NumStores = 0;
347 unsigned NumLoads = 0;
349 unsigned NumComputeOps = 0;
353 unsigned NumExposedTransposes = 0;
356 NumStores +=
RHS.NumStores;
357 NumLoads +=
RHS.NumLoads;
358 NumComputeOps +=
RHS.NumComputeOps;
359 NumExposedTransposes +=
RHS.NumExposedTransposes;
367 SmallVector<Value *, 16> Vectors;
371 bool IsColumnMajor =
true;
374 MatrixTy() =
default;
375 explicit MatrixTy(
bool IsColumnMajor) : IsColumnMajor(IsColumnMajor) {}
377 : Vectors(Vectors), IsColumnMajor(IsColumnMajor) {}
378 MatrixTy(
bool IsColumnMajor,
unsigned NumRows,
unsigned NumColumns,
380 : IsColumnMajor(IsColumnMajor) {
382 unsigned D = isColumnMajor() ? NumColumns : NumRows;
383 for (
unsigned J = 0; J <
D; ++J)
385 EltTy, isColumnMajor() ? NumRows : NumColumns)));
388 Value *getVector(
unsigned i)
const {
return Vectors[i]; }
389 Value *getColumn(
unsigned i)
const {
390 assert(isColumnMajor() &&
"only supported for column-major matrixes");
393 Value *getRow(
unsigned i)
const {
394 assert(!isColumnMajor() &&
"only supported for row-major matrixes");
398 void setVector(
unsigned i,
Value *V) { Vectors[i] =
V; }
400 Type *getElementType()
const {
return getVectorTy()->getElementType(); }
402 unsigned getNumVectors()
const {
404 return getNumColumns();
408 unsigned getNumColumns()
const {
410 return Vectors.size();
412 assert(Vectors.size() > 0 &&
"Cannot call getNumRows without columns");
413 return getVectorTy()->getNumElements();
416 unsigned getNumRows()
const {
417 if (isColumnMajor()) {
418 assert(Vectors.size() > 0 &&
"Cannot call getNumRows without columns");
419 return getVectorTy()->getNumElements();
421 return Vectors.size();
424 void addVector(
Value *V) { Vectors.push_back(V); }
425 FixedVectorType *getColumnTy() {
426 assert(isColumnMajor() &&
"only supported for column-major matrixes");
427 return getVectorTy();
430 FixedVectorType *getVectorTy()
const {
434 iterator_range<SmallVector<Value *, 8>::iterator> columns() {
436 "columns() only supported for column-major matrixes");
437 return make_range(Vectors.begin(), Vectors.end());
440 iterator_range<SmallVector<Value *, 8>::iterator>
vectors() {
441 return make_range(Vectors.begin(), Vectors.end());
447 return Vectors.size() == 1 ? Vectors[0]
451 MatrixTy &addNumLoads(
unsigned N) {
452 OpInfo.NumLoads +=
N;
456 void setNumLoads(
unsigned N) { OpInfo.NumLoads =
N; }
458 MatrixTy &addNumStores(
unsigned N) {
459 OpInfo.NumStores +=
N;
463 MatrixTy &addNumExposedTransposes(
unsigned N) {
464 OpInfo.NumExposedTransposes +=
N;
468 MatrixTy &addNumComputeOps(
unsigned N) {
469 OpInfo.NumComputeOps +=
N;
473 unsigned getNumStores()
const {
return OpInfo.NumStores; }
474 unsigned getNumLoads()
const {
return OpInfo.NumLoads; }
475 unsigned getNumComputeOps()
const {
return OpInfo.NumComputeOps; }
477 const OpInfoTy &getOpInfo()
const {
return OpInfo; }
479 bool isColumnMajor()
const {
return IsColumnMajor; }
481 unsigned getStride()
const {
484 return getNumColumns();
487 ShapeInfo shape()
const {
return {getNumRows(), getNumColumns()}; }
494 Value *Vec = isColumnMajor() ? getColumn(J) : getRow(
I);
497 "Extracted vector will contain poison values");
518 DenseMap<Value *, ShapeInfo> ShapeMap;
523 SmallVector<Instruction *, 16> ToRemove;
526 MapVector<Value *, MatrixTy> Inst2ColumnMatrix;
540 bool isColumnMajor()
const {
541 return Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor;
544 unsigned getStride(
const ShapeInfo &SI)
const {
545 return isColumnMajor() ?
SI.NumRows :
SI.NumColumns;
548 unsigned getNumVectors(
const ShapeInfo &SI)
const {
549 return isColumnMajor() ?
SI.NumColumns :
SI.NumRows;
553 LowerMatrixIntrinsics(
const ScalarOptions &Opts,
Function &
F,
555 : Opts(Opts), Func(
F), DL(
F.getDataLayout()), TTI(TTI), AM(AM) {}
557 unsigned getNumOps(
Type *VT) {
564 bool isMinimal()
const {
570 unsigned getNumOps(
Type *ST,
unsigned N) {
571 return std::ceil((
ST->getPrimitiveSizeInBits() *
N).getFixedValue() /
572 double(TTI.getRegisterBitWidth(
586 unsigned getNumNativeVectorOps(
Type *EltType,
unsigned R,
unsigned M,
588 unsigned NumFMAs =
C * getNumOps(EltType, R) *
M;
589 unsigned NumALoads = getNumOps(EltType, R) *
M;
590 unsigned NumBLoads = getNumOps(EltType, M) *
C;
591 unsigned NumStores = getNumOps(EltType, R) *
C;
592 return NumFMAs + NumALoads + NumBLoads + NumStores;
600 MatrixTy getMatrix(
Value *MatrixVal,
const ShapeInfo &SI,
604 "The vector size must match the number of matrix elements");
610 auto Found = Inst2ColumnMatrix.find(MatrixVal);
611 if (Found != Inst2ColumnMatrix.end()) {
612 MatrixTy &
M = Found->second;
615 if (
SI.NumRows ==
M.getNumRows() &&
SI.NumColumns ==
M.getNumColumns())
618 MatrixVal =
M.embedInVector(Builder);
622 SmallVector<Value *, 16> SplitVecs;
624 MaskStart += getStride(SI)) {
632 if (Found != Inst2ColumnMatrix.end()) {
635 LLVM_DEBUG(
dbgs() <<
"matrix reshape from " << Found->second.shape()
636 <<
" to " << SI <<
" using at least "
637 << SplitVecs.
size() <<
" shuffles on behalf of:\n"
640 }
else if (!ShapeMap.contains(MatrixVal)) {
643 <<
"splitting a " << SI <<
" matrix with " << SplitVecs.
size()
644 <<
" shuffles beacuse we do not have a shape-aware lowering for "
656 return {isColumnMajor(), SplitVecs};
661 bool setShapeInfo(
Value *V, ShapeInfo Shape) {
662 assert(Shape &&
"Shape not set");
666 auto SIter = ShapeMap.find(V);
667 if (SIter != ShapeMap.end()) {
668 if (Opts.verify_matrix_shapes &&
669 (SIter->second.NumRows != Shape.NumRows ||
670 SIter->second.NumColumns != Shape.NumColumns)) {
671 errs() <<
"Conflicting shapes (" << SIter->second.NumRows <<
"x"
672 << SIter->second.NumColumns <<
" vs " << Shape.NumRows <<
"x"
673 << Shape.NumColumns <<
") for " << *
V <<
"\n";
675 "Matrix shape verification failed, compilation aborted!");
679 << SIter->second.NumRows <<
" "
680 << SIter->second.NumColumns <<
" for " << *V <<
"\n");
684 ShapeMap.insert({
V, Shape});
685 LLVM_DEBUG(
dbgs() <<
" " << Shape.NumRows <<
" x " << Shape.NumColumns
686 <<
" for " << *V <<
"\n");
692 bool supportsShapeInfo(
Value *V) {
699 switch (
II->getIntrinsicID()) {
700 case Intrinsic::matrix_multiply:
701 case Intrinsic::matrix_transpose:
702 case Intrinsic::matrix_column_major_load:
703 case Intrinsic::matrix_column_major_store:
716 propagateShapeForward(SmallVectorImpl<Instruction *> &WorkList) {
722 while (!WorkList.
empty()) {
726 bool Propagate =
false;
728 Propagate = setShapeInfo(Inst, *SI);
732 for (
auto *User : Inst->
users())
733 if (ShapeMap.count(User) == 0)
744 propagateShapeBackward(SmallVectorImpl<Instruction *> &WorkList) {
747 auto pushInstruction = [](
Value *
V,
748 SmallVectorImpl<Instruction *> &WorkList) {
757 while (!WorkList.
empty()) {
760 size_t BeforeProcessingV = WorkList.
size();
772 if (setShapeInfo(MatrixA, {
M,
N}))
773 pushInstruction(MatrixA, WorkList);
775 if (setShapeInfo(MatrixB, {
N,
K}))
776 pushInstruction(MatrixB, WorkList);
781 if (setShapeInfo(MatrixA, {
M,
N}))
782 pushInstruction(MatrixA, WorkList);
786 if (setShapeInfo(MatrixA, {
M,
N})) {
787 pushInstruction(MatrixA, WorkList);
798 ShapeInfo Shape = ShapeMap[
V];
799 for (Use &U : ShapedOps) {
800 if (setShapeInfo(
U.get(), Shape))
801 pushInstruction(
U.get(), WorkList);
807 for (
size_t I = BeforeProcessingV;
I != WorkList.
size();
I++)
808 for (User *U : WorkList[
I]->
users())
819 Value *Op0, ShapeInfo Shape0,
Value *Op1, ShapeInfo Shape1,
820 MatrixBuilder &Builder,
821 function_ref<Instruction *(
Value *, ShapeInfo,
Value *, ShapeInfo)>
824 Op0, Shape0.NumRows, Shape0.NumColumns, Op0->
getName() +
"_t");
827 setShapeInfo(T0, Shape0.t());
829 Op1, Shape1.NumRows, Shape1.NumColumns, Op1->
getName() +
"_t");
830 setShapeInfo(
T1, Shape1.t());
836 void eraseFromParentAndRemoveFromShapeMap(Instruction *Inst) {
837 ShapeMap.erase(Inst);
849 if (
II != BB.
rend() && Inst == &*
II)
851 eraseFromParentAndRemoveFromShapeMap(Inst);
856 void updateShapeAndReplaceAllUsesWith(Instruction &Old,
Value *New) {
860 auto S = ShapeMap.find(&Old);
861 if (S != ShapeMap.end()) {
862 ShapeInfo Shape = S->second;
864 if (supportsShapeInfo(New))
865 ShapeMap.insert({
New, Shape});
878 MatrixBuilder Builder(IB);
881 ConstantInt *
R, *
K, *
C;
890 updateShapeAndReplaceAllUsesWith(
I, TATA);
891 eraseFromParentAndMove(&
I,
II, BB);
892 eraseFromParentAndMove(TA,
II, BB);
899 updateShapeAndReplaceAllUsesWith(
I, TA);
900 eraseFromParentAndMove(&
I,
II, BB);
910 auto NewInst = distributeTransposes(
911 TAMB, {
K,
C}, TAMA, {
R,
K}, Builder,
912 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
915 Shape1.NumColumns,
"mmul");
917 updateShapeAndReplaceAllUsesWith(
I, NewInst);
918 eraseFromParentAndMove(&
I,
II, BB);
919 eraseFromParentAndMove(TA,
II, BB);
933 auto NewInst = distributeTransposes(
934 TAMA, {
R,
C}, TAMB, {
R,
C}, Builder,
935 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
936 bool IsFP =
I.getType()->isFPOrFPVectorTy();
937 auto *
Mul = IsFP ? LocalBuilder.CreateFMul(T0,
T1,
"mmul")
938 : LocalBuilder.CreateMul(T0,
T1,
"mmul");
940 setShapeInfo(Result, Shape0);
943 updateShapeAndReplaceAllUsesWith(
I, NewInst);
944 eraseFromParentAndMove(&
I,
II, BB);
945 eraseFromParentAndMove(TA,
II, BB);
954 auto NewInst = distributeTransposes(
955 TAMA, {
R,
C}, TAMB, {
R,
C}, Builder,
956 [&](
Value *T0, ShapeInfo Shape0,
Value *
T1, ShapeInfo Shape1) {
957 bool IsFP =
I.getType()->isFPOrFPVectorTy();
958 auto *
Add = IsFP ? LocalBuilder.CreateFAdd(T0,
T1,
"madd")
959 : LocalBuilder.CreateAdd(T0,
T1,
"madd");
962 setShapeInfo(Result, Shape0);
965 updateShapeAndReplaceAllUsesWith(
I, NewInst);
966 eraseFromParentAndMove(&
I,
II, BB);
967 eraseFromParentAndMove(TA,
II, BB);
975 bool liftTranspose(Instruction &
I) {
979 eraseFromParentAndRemoveFromShapeMap(&
T);
982 if (
A !=
B &&
B->use_empty())
987 ConstantInt *
R, *
K, *
C;
995 MatrixBuilder Builder(IB);
997 BT, AT,
C->getZExtValue(),
K->getZExtValue(),
R->getZExtValue());
998 setShapeInfo(M, {
C,
R});
1001 updateShapeAndReplaceAllUsesWith(
I, NewInst);
1002 CleanupBinOp(
I,
A,
B);
1014 auto *
Add = Builder.CreateFAdd(AT,
BT,
"mfadd");
1015 MatrixBuilder MBuilder(Builder);
1016 Instruction *NewInst = MBuilder.CreateMatrixTranspose(
1017 Add,
R->getZExtValue(),
C->getZExtValue(),
"mfadd_t");
1018 updateShapeAndReplaceAllUsesWith(
I, NewInst);
1021 "Shape of new instruction doesn't match original shape.");
1022 CleanupBinOp(
I,
A,
B);
1024 setShapeInfo(AddI, {
R,
C});
1028 "Shape of updated addition doesn't match cached shape.");
1036 bool optimizeTransposes() {
1040 for (BasicBlock &BB :
reverse(Func)) {
1045 if (Instruction *NewInst = sinkTranspose(
I,
II,
Changed))
1052 for (BasicBlock &BB : Func) {
1065 for (BasicBlock &BB : Func)
1066 for (Instruction &Inst : BB) {
1071 switch (
II->getIntrinsicID()) {
1072 case Intrinsic::matrix_multiply:
1073 case Intrinsic::matrix_transpose:
1074 case Intrinsic::matrix_column_major_load:
1075 case Intrinsic::matrix_column_major_store:
1084 if (WorkList.
empty())
1088 ORE = &AM->getResult<OptimizationRemarkEmitterAnalysis>(Func);
1089 AA = &AM->getResult<AAManager>(Func);
1090 DT = &AM->getResult<DominatorTreeAnalysis>(Func);
1091 LI = &AM->getResult<LoopAnalysis>(Func);
1095 while (!WorkList.
empty()) {
1096 WorkList = propagateShapeForward(WorkList);
1097 WorkList = propagateShapeBackward(WorkList);
1102 Changed |= optimizeTransposes();
1103 if (Opts.matrix_print_after_transpose_opt) {
1104 dbgs() <<
"Dump after matrix transpose optimization:\n";
1110 SmallVector<Instruction *, 16> MatrixInsts;
1115 ReversePostOrderTraversal<Function *> RPOT(&Func);
1116 for (
auto *BB : RPOT)
1117 for (Instruction &
I : *BB) {
1120 if (!ShapeMap.contains(&
I))
1128 SmallPtrSet<Instruction *, 16> FusedInsts;
1129 for (CallInst *CI : MaybeFusableInsts)
1133 for (CallInst *CI : MaybeFusableInsts)
1135 LowerMatrixMultiplyFused(CI, FusedInsts, LifetimeEnds);
1141 for (Instruction *Inst : MatrixInsts) {
1142 if (FusedInsts.
count(Inst))
1149 const ShapeInfo &
SI = ShapeMap.at(Inst);
1151 MatrixTy PhiM(isColumnMajor(),
SI.NumRows,
SI.NumColumns, EltTy);
1154 for (
unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI)
1155 PhiM.setVector(VI, Builder.CreatePHI(PhiM.getVectorTy(),
1156 PHI->getNumIncomingValues(),
1158 assert(!Inst2ColumnMatrix.contains(
PHI) &&
"map already contains phi?");
1159 Inst2ColumnMatrix[
PHI] = PhiM;
1163 for (Instruction *Inst : MatrixInsts) {
1164 if (FusedInsts.
count(Inst))
1167 const ShapeInfo &
SI = ShapeMap.at(Inst);
1174 Result = VisitBinaryOperator(BinOp, SI, Builder);
1176 Result = VisitCastInstruction(Cast, SI, Builder);
1178 Result = VisitUnaryOperator(UnOp, SI, Builder);
1180 Result = VisitIntrinsicInst(Intr, SI, Builder);
1192 finalizeLowering(Inst, Result, Builder);
1197 RemarkGenerator RemarkGen(Inst2ColumnMatrix, *ORE, Func);
1198 RemarkGen.emitRemarks();
1210 SmallPtrSet<Instruction *, 16> PoisonedInsts;
1211 for (
auto *Inst :
reverse(ToRemove)) {
1214 PoisonedInsts.
insert(Poisoned);
1218 PoisonedInsts.
erase(Inst);
1220 if (!PoisonedInsts.
empty()) {
1222 dbgs() <<
"Poisoned but present instructions:\n";
1223 for (
auto *
I : PoisonedInsts)
1224 dbgs() << *
I <<
"\n";
1232 MatrixTy VisitIntrinsicInst(IntrinsicInst *Inst,
const ShapeInfo &SI,
1238 case Intrinsic::matrix_multiply:
1239 return LowerMultiply(Inst, Builder);
1240 case Intrinsic::matrix_transpose:
1241 return LowerTranspose(Inst, Builder);
1242 case Intrinsic::matrix_column_major_load:
1243 return LowerColumnMajorLoad(Inst, Builder);
1244 case Intrinsic::matrix_column_major_store:
1245 return LowerColumnMajorStore(Inst, Builder);
1246 case Intrinsic::abs:
1247 case Intrinsic::fabs: {
1248 MatrixTy
Result(isColumnMajor());
1249 MatrixTy
M = getMatrix(Inst->
getOperand(0), SI, Builder);
1252 for (
auto *
Vector :
M.vectors()) {
1254 case Intrinsic::abs:
1258 case Intrinsic::fabs:
1267 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
1274 "only intrinsics supporting shape info should be seen here");
1282 Align getAlignForIndex(
unsigned Idx,
Value *Stride,
Type *ElementTy,
1283 MaybeAlign
A)
const {
1284 Align InitialAlign = DL.getValueOrABITypeAlignment(
A, ElementTy);
1286 return InitialAlign;
1288 TypeSize ElementSizeInBits = DL.getTypeSizeInBits(ElementTy);
1291 ConstStride->getZExtValue() * ElementSizeInBits / 8;
1307 "Attempted to cast non-integral type to integer index");
1312 V->getName() +
".cast");
1317 MatrixTy loadMatrix(
Type *Ty,
Value *Ptr, MaybeAlign MAlign,
Value *Stride,
1318 bool IsVolatile, ShapeInfo Shape,
IRBuilder<> &Builder) {
1322 Value *EltPtr = Ptr;
1323 MatrixTy
Result(isColumnMajor());
1324 Stride = castToIndexType(Ptr, Stride, Builder);
1325 for (
unsigned I = 0,
E = getNumVectors(Shape);
I <
E; ++
I) {
1328 Stride, getStride(Shape), EltTy, Builder);
1330 VecTy,
GEP, getAlignForIndex(
I, Stride, EltTy, MAlign),
1331 IsVolatile,
"col.load");
1335 return Result.addNumLoads(getNumOps(
Result.getVectorTy()) *
1341 MatrixTy loadMatrix(
Value *MatrixPtr, MaybeAlign Align,
bool IsVolatile,
1343 ShapeInfo ResultShape,
Type *EltTy,
1346 Builder.
CreateMul(J, getIndex(MatrixPtr, getStride(MatrixShape))),
I);
1350 ResultShape.NumColumns);
1352 return loadMatrix(TileTy, TileStart, Align,
1353 getIndex(MatrixPtr, getStride(MatrixShape)), IsVolatile,
1354 ResultShape, Builder);
1358 MatrixTy
LowerLoad(Instruction *Inst,
Value *Ptr, MaybeAlign Align,
1359 Value *Stride,
bool IsVolatile, ShapeInfo Shape,
1361 return loadMatrix(Inst->
getType(), Ptr, Align, Stride, IsVolatile, Shape,
1368 MatrixTy LowerColumnMajorLoad(CallInst *Inst,
IRBuilder<> &Builder) {
1369 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1370 "Intrinsic only supports column-major layout!");
1375 {Inst->getArgOperand(3), Inst->getArgOperand(4)}, Builder);
1380 void storeMatrix(
const MatrixTy &StoreVal,
Value *MatrixPtr,
1381 MaybeAlign MAlign,
bool IsVolatile, ShapeInfo MatrixShape,
1384 Builder.
CreateMul(J, getIndex(MatrixPtr, getStride(MatrixShape))),
I);
1388 StoreVal.getNumColumns());
1390 storeMatrix(TileTy, StoreVal, TileStart, MAlign,
1391 getIndex(MatrixPtr, getStride(MatrixShape)), IsVolatile,
1397 MatrixTy storeMatrix(
Type *Ty, MatrixTy StoreVal,
Value *Ptr,
1398 MaybeAlign MAlign,
Value *Stride,
bool IsVolatile,
1401 Value *EltPtr = Ptr;
1402 Stride = castToIndexType(Ptr, Stride, Builder);
1403 for (
auto Vec :
enumerate(StoreVal.vectors())) {
1410 getAlignForIndex(Vec.index(), Stride,
1415 return MatrixTy(isColumnMajor())
1416 .addNumStores(getNumOps(StoreVal.getVectorTy()) *
1417 StoreVal.getNumVectors());
1422 MaybeAlign
A,
Value *Stride,
bool IsVolatile,
1424 auto StoreVal = getMatrix(
Matrix, Shape, Builder);
1425 return storeMatrix(
Matrix->getType(), StoreVal, Ptr,
A, Stride, IsVolatile,
1432 MatrixTy LowerColumnMajorStore(CallInst *Inst,
IRBuilder<> &Builder) {
1433 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
1434 "Intrinsic only supports column-major layout!");
1440 {Inst->getArgOperand(4), Inst->getArgOperand(5)},
1449 unsigned BlockNumElts =
1452 assert(NumElts >= BlockNumElts &&
"Too few elements for current block");
1459 SmallVector<int, 16>
Mask;
1461 for (i = 0; i <
I; i++)
1464 unsigned VecNumElts =
1466 for (; i <
I + BlockNumElts; i++)
1467 Mask.push_back(i -
I + VecNumElts);
1469 for (; i < VecNumElts; i++)
1477 unsigned &NumComputeOps) {
1478 NumComputeOps += getNumOps(
A->getType());
1483 if (AllowContraction) {
1489 NumComputeOps += getNumOps(
A->getType());
1494 NumComputeOps += getNumOps(
A->getType());
1504 void finalizeLowering(Instruction *Inst, MatrixTy
Matrix,
1506 auto inserted = Inst2ColumnMatrix.insert(std::make_pair(Inst,
Matrix));
1509 "multiple matrix lowering mapping");
1511 ToRemove.push_back(Inst);
1512 Value *Flattened =
nullptr;
1514 if (ShapeMap.contains(
U.getUser()))
1518 Flattened =
Matrix.embedInVector(Builder);
1521 <<
"flattening a " <<
Matrix.shape() <<
" matrix:\n"
1523 <<
"\nbecause we do not have a shape-aware lowering for its "
1526 FlattenedMatrices++;
1535 void lowerDotProduct(CallInst *MatMul,
1536 SmallPtrSet<Instruction *, 16> &FusedInsts,
1537 FastMathFlags FMF) {
1539 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
1544 if (LShape.NumRows != 1 || RShape.NumColumns != 1)
1559 auto CanBeFlattened = [](
Value *
Op) {
1574 if (!ShapeMap.contains(
Op))
1575 return InstructionCost::getInvalid();
1583 if (!CanBeFlattened(
Op)) {
1586 for (
unsigned I = 1;
I <
N; ++
I)
1600 return NewCost - OriginalCost;
1608 for (
unsigned I = 1;
I <
N; ++
I)
1619 return TTI.getMemoryOpCost(Instruction::Load, VecTy,
Align(1), 0,
1621 N * TTI.getMemoryOpCost(Instruction::Load, EltTy,
Align(1), 0,
1628 SmallPtrSet<Value *, 4> Seen;
1633 while (!WorkList.
empty()) {
1639 if (OpCost + LHSCost >= LHSCost)
1645 WorkList.
append(
I->op_begin(),
I->op_end());
1649 int AddOpCode = IsIntVec ? Instruction::Add : Instruction::FAdd;
1650 int MulOpCode = IsIntVec ? Instruction::Mul : Instruction::FMul;
1652 TTI.getArithmeticReductionCost(
1654 IsIntVec ? std::nullopt : std::optional(FMF),
CostKind) +
1657 TTI.getArithmeticInstrCost(AddOpCode, ElementType,
CostKind) *
1658 (LShape.NumColumns - 1) +
1659 TTI.getArithmeticInstrCost(MulOpCode, ElementType,
CostKind) *
1660 (LShape.NumColumns);
1661 if ((LHSCost + ReductionCost - SequentialAddCost) >
InstructionCost(0))
1664 FusedInsts.
insert(MatMul);
1666 auto FlattenArg = [&Builder, &FusedInsts, &CanBeFlattened,
1671 if (!CanBeFlattened(
Op))
1675 auto It = ShapeMap.find(
Op);
1676 if (It != ShapeMap.end()) {
1677 It->second = It->second.t();
1691 0, MatLoad->getArgOperand(1),
1693 MatLoad->getParamAlign(0));
1696 Op->replaceAllUsesWith(NewLoad);
1702 Op->replaceAllUsesWith(Arg);
1707 for (
auto *V : ToFlatten)
1731 FusedInsts.insert(MatMul);
1732 ToRemove.push_back(MatMul);
1738 unsigned capBlockSize(
unsigned BlockSize,
unsigned Remainder,
Type *EltType) {
1744 if (TTI.isTypeLegal(VecTy))
1750 Opts.matrix_split_matmul_remainder_over_threshold)
1768 void emitMatrixMultiply(MatrixTy &Result,
const MatrixTy &
A,
1770 bool IsScalarMatrixTransposed, FastMathFlags FMF) {
1771 const unsigned VF = std::max<unsigned>(
1774 Result.getElementType()->getPrimitiveSizeInBits().getFixedValue(),
1776 unsigned R =
Result.getNumRows();
1777 unsigned C =
Result.getNumColumns();
1778 unsigned M =
A.getNumColumns();
1780 bool IsFP =
Result.getElementType()->isFloatingPointTy();
1781 assert(
A.isColumnMajor() ==
B.isColumnMajor() &&
1782 Result.isColumnMajor() ==
A.isColumnMajor() &&
1783 "operands must agree on matrix layout");
1784 unsigned NumComputeOps = 0;
1788 if (
A.isColumnMajor()) {
1792 for (
unsigned J = 0; J <
C; ++J) {
1802 for (
unsigned K = 0;
K <
M; ++
K) {
1805 B.getColumn(IsScalarMatrixTransposed ? K : J),
1806 IsScalarMatrixTransposed ? J : K);
1809 createMulAdd(isSumZero && K == 0 ?
nullptr : Sum, L,
Splat,
1820 for (
unsigned I = 0;
I <
R; ++
I) {
1823 for (
unsigned J = 0; J <
C; J +=
BlockSize) {
1827 Value *Sum =
nullptr;
1828 for (
unsigned K = 0;
K <
M; ++
K) {
1831 A.getVector(IsScalarMatrixTransposed ? K :
I),
1832 IsScalarMatrixTransposed ?
I : K);
1835 createMulAdd(isSumZero && K == 0 ?
nullptr : Sum,
Splat, R,
1843 Result.addNumComputeOps(NumComputeOps);
1849 std::pair<Value *, AllocaInst *>
1850 getNonAliasingPointer(LoadInst *
Load, StoreInst *
Store, CallInst *MatMul) {
1855 if (AA->isNoAlias(LoadLoc, StoreLoc))
1856 return {
Load->getPointerOperand(),
nullptr};
1860 IRBuilder<> AllocaBuilder(&Func.getEntryBlock().front());
1861 if (
Load->getPointerAddressSpace() !=
Store->getPointerAddressSpace()) {
1864 ArrayType::get(VT->getElementType(), VT->getNumElements());
1865 AllocaInst *Alloca =
1866 AllocaBuilder.CreateAlloca(ArrayTy,
Load->getPointerAddressSpace());
1870 Load->getPointerOperand(),
Load->getAlign(),
1872 return {Alloca, Alloca};
1885 DTUpdates.
push_back({DT->Delete, Check0, Succ});
1889 nullptr,
"alias_cont");
1895 nullptr,
"no_alias");
1903 Type *AddrTy = DL.getAddressType(
Store->getPointerOperand()->getType());
1904 Value *StoreBegin =
Store->getPointerOperand();
1906 StoreBegin, ConstantInt::get(AddrTy, StoreLoc.
Size.
getValue()),
1909 Value *LoadBegin =
Load->getPointerOperand();
1911 Builder.
CreateICmpULT(LoadBegin, StoreEnd), Check1, Fusion);
1923 auto *ArrayTy = ArrayType::get(VT->getElementType(), VT->getNumElements());
1924 AllocaInst *Alloca =
1925 AllocaBuilder.CreateAlloca(ArrayTy,
Load->getPointerAddressSpace());
1929 LoadBegin, ConstantInt::get(AddrTy, LoadLoc.
Size.
getValue()),
1943 PHI->addIncoming(
Load->getPointerOperand(), Check1);
1944 PHI->addIncoming(Alloca, Copy);
1947 DTUpdates.
push_back({DT->Insert, Check0, Check1});
1948 DTUpdates.
push_back({DT->Insert, Check0, Fusion});
1950 DTUpdates.
push_back({DT->Insert, Check1, Fusion});
1951 DT->applyUpdates(DTUpdates);
1952 return {
PHI, Alloca};
1955 bool isFusionProfitable(CallInst *MatMul) {
1956 if (Opts.force_fuse_matrix)
1962 const unsigned R = LShape.NumRows;
1963 const unsigned C = RShape.NumColumns;
1964 const unsigned M = LShape.NumColumns;
1967 const unsigned VF = std::max<unsigned>(
1979 if (R <= VF &&
C == 1)
1985 unsigned Op0Regs = (
R + VF - 1) / VF * M;
1986 unsigned Op1Regs = (
M + VF - 1) / VF *
C;
1987 return Op0Regs + Op1Regs >
1988 TTI.getNumberOfRegisters(TTI.getRegisterClassForType(
true));
1991 MatrixTy getZeroMatrix(
Type *EltType,
unsigned R,
unsigned C) {
1992 MatrixTy Res(isColumnMajor());
1994 for (
unsigned I = 0;
I <
C; ++
I)
1999 void createTiledLoops(CallInst *MatMul,
Value *LPtr, ShapeInfo LShape,
2000 Value *RPtr, ShapeInfo RShape, StoreInst *
Store) {
2004 TileInfo TI(LShape.NumRows, RShape.NumColumns, LShape.NumColumns,
2005 Opts.fuse_matrix_tile_size);
2006 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
2012 BasicBlock *InnerBody = TI.CreateTiledLoops(Start,
End, Builder, DTU, *LI);
2015 Opts.fuse_matrix_tile_size);
2016 MatrixTy TileResult(isColumnMajor());
2021 for (
unsigned I = 0;
I < Opts.fuse_matrix_tile_size;
I++) {
2022 auto *
Phi = Builder.
CreatePHI(TileVecTy, 2,
"result.vec." + Twine(
I));
2024 TI.RowLoop.Header->getSingleSuccessor());
2025 TileResult.addVector(Phi);
2034 loadMatrix(LPtr, {},
false, LShape, TI.RowLoop.Index, TI.KLoop.Index,
2035 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2038 loadMatrix(RPtr, {},
false, RShape, TI.KLoop.Index, TI.ColumnLoop.Index,
2039 {Opts.fuse_matrix_tile_size, Opts.fuse_matrix_tile_size},
2041 emitMatrixMultiply(TileResult,
A,
B, Builder,
true,
false,
2045 storeMatrix(TileResult,
Store->getPointerOperand(),
Store->getAlign(),
2046 Store->isVolatile(), {LShape.NumRows, RShape.NumColumns},
2047 TI.RowLoop.Index, TI.ColumnLoop.Index, EltType, Builder);
2049 for (
unsigned I = 0;
I < TileResult.getNumVectors();
I++)
2050 ColumnPhis[
I]->addIncoming(TileResult.getVector(
I), TI.KLoop.Latch);
2056 unsigned InnerLoopUnrollCount =
2057 std::min(10u, LShape.NumColumns / Opts.fuse_matrix_tile_size);
2059 "llvm.loop.unroll.count", InnerLoopUnrollCount);
2062 void emitSIMDTiling(CallInst *MatMul, LoadInst *LoadOp0, LoadInst *LoadOp1,
2064 SmallPtrSetImpl<Instruction *> &FusedInsts) {
2065 assert(Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor &&
2066 "Tiling only supported for column-major matrixes at the moment!");
2067 if (!isFusionProfitable(MatMul))
2073 const unsigned R = LShape.NumRows;
2074 const unsigned C = RShape.NumColumns;
2075 const unsigned M = LShape.NumColumns;
2078 auto [APtr, AAlloca] = getNonAliasingPointer(LoadOp0,
Store, MatMul);
2079 auto [BPtr, BAlloca] = getNonAliasingPointer(LoadOp1,
Store, MatMul);
2084 unsigned NumOps = getNumNativeVectorOps(EltType, R, M,
C);
2085 bool UseLoops = (
NumOps > Opts.fuse_matrix_loops_threshold) &&
2086 R % Opts.fuse_matrix_tile_size == 0 &&
2087 C % Opts.fuse_matrix_tile_size == 0;
2089 createTiledLoops(MatMul, APtr, LShape, BPtr, RShape,
Store);
2092 for (
unsigned J = 0; J <
C; J += Opts.fuse_matrix_tile_size)
2093 for (
unsigned I = 0;
I <
R;
I += Opts.fuse_matrix_tile_size) {
2094 const unsigned TileR = std::min(R -
I, Opts.fuse_matrix_tile_size);
2095 const unsigned TileC = std::min(
C - J, Opts.fuse_matrix_tile_size);
2096 MatrixTy Res = getZeroMatrix(EltType, TileR, TileC);
2098 for (
unsigned K = 0;
K <
M;
K += Opts.fuse_matrix_tile_size) {
2099 const unsigned TileM = std::min(M - K, Opts.fuse_matrix_tile_size);
2102 LShape, getIndex(APtr,
I), getIndex(APtr, K),
2103 {TileR, TileM}, EltType, Builder);
2106 RShape, getIndex(BPtr, K), getIndex(BPtr, J),
2107 {TileM, TileC}, EltType, Builder);
2108 emitMatrixMultiply(Res,
A,
B, Builder,
true,
false,
2111 storeMatrix(Res, CPtr,
Store->getAlign(),
Store->isVolatile(), {R, M},
2112 getIndex(CPtr,
I), getIndex(CPtr, J), EltType, Builder);
2127 FusedInsts.
insert(MatMul);
2128 eraseFromParentAndRemoveFromShapeMap(
Store);
2129 eraseFromParentAndRemoveFromShapeMap(MatMul);
2131 FusedInsts.
insert(LoadOp0);
2132 eraseFromParentAndRemoveFromShapeMap(LoadOp0);
2134 if (LoadOp1 != LoadOp0 && LoadOp1->
use_empty()) {
2135 FusedInsts.
insert(LoadOp1);
2136 eraseFromParentAndRemoveFromShapeMap(LoadOp1);
2145 LowerMatrixMultiplyFused(CallInst *MatMul,
2146 SmallPtrSetImpl<Instruction *> &FusedInsts,
2148 if (!Opts.fuse_matrix || !DT || Opts.fuse_matrix_tile_size == 0)
2151 assert(AA && LI &&
"Analyses should be available");
2158 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor
2166 const unsigned R = LShape.NumRows;
2167 const unsigned M = LShape.NumColumns;
2168 const unsigned C = RShape.NumColumns;
2174 if (Opts.matrix_default_layout == MatrixLayoutTy::ColumnMajor) {
2175 MA = getMatrix(
A, ShapeInfo(R, M), Builder);
2176 MB = getMatrix(
T, ShapeInfo(
C, M), Builder);
2179 MA = getMatrix(
T, ShapeInfo(R, M), Builder);
2180 MB = getMatrix(
B, ShapeInfo(
C, M), Builder);
2185 MatrixTy
Result(isColumnMajor(), R,
C, EltType);
2187 emitMatrixMultiply(Result, MA, MB, Builder,
false,
true,
2190 FusedInsts.
insert(MatMul);
2196 Inst2ColumnMatrix[Transpose] = MatrixTy(isColumnMajor(), M,
C, EltType);
2198 finalizeLowering(MatMul, Result, Builder);
2203 Opts.matrix_default_layout != MatrixLayoutTy::ColumnMajor)
2211 if (LoadOp0 && LoadOp1 &&
Store) {
2214 SetVector<Value *> WorkList;
2216 SmallVector<Instruction *> ToHoist;
2217 for (
unsigned I = 0;
I != WorkList.
size(); ++
I) {
2218 Value *Current = WorkList[
I];
2224 if (DT->dominates(CurrI, MatMul))
2226 if (CurrI->mayHaveSideEffects() || CurrI->mayReadFromMemory())
2232 sort(ToHoist, [
this](Instruction *
A, Instruction *
B) {
2233 return DT->dominates(
A,
B);
2235 for (Instruction *
I : ToHoist)
2248 bool FusableOpsInSameBlock = LoadOp0->
getParent() == StoreParent &&
2250 for (
unsigned Idx = 0;
Idx != LifetimeEnds.
size();) {
2251 IntrinsicInst *
End = LifetimeEnds[
Idx];
2255 if (DT->dominates(
End, LoadOp0) && DT->dominates(
End, LoadOp1))
2261 if (FusableOpsInSameBlock &&
End->getParent() != StoreParent)
2269 if (AA->isNoAlias(Load0Loc, EndLoc) && AA->isNoAlias(Load1Loc, EndLoc))
2275 if (
End->getParent() == StoreParent) {
2281 ToRemove.push_back(
End);
2287 emitSIMDTiling(MatMul, LoadOp0, LoadOp1,
Store, FusedInsts);
2293 MatrixTy LowerMultiply(CallInst *MatMul,
IRBuilder<> &Builder) {
2298 const MatrixTy &Lhs = getMatrix(MatMul->
getArgOperand(0), LShape, Builder);
2299 const MatrixTy &Rhs = getMatrix(MatMul->
getArgOperand(1), RShape, Builder);
2300 assert(Lhs.getElementType() == Rhs.getElementType() &&
2301 "Matrix multiply argument element types do not match.");
2303 const unsigned R = LShape.NumRows;
2304 const unsigned C = RShape.NumColumns;
2305 assert(LShape.NumColumns == RShape.NumRows);
2308 MatrixTy
Result(isColumnMajor(), R,
C, EltType);
2309 assert(Lhs.getElementType() ==
Result.getElementType() &&
2310 "Matrix multiply result element type does not match arguments.");
2312 emitMatrixMultiply(Result, Lhs, Rhs, Builder,
false,
false,
2318 MatrixTy LowerTranspose(CallInst *Inst,
IRBuilder<> &Builder) {
2319 MatrixTy
Result(isColumnMajor());
2323 MatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder);
2325 const unsigned NewNumVecs =
2326 InputMatrix.isColumnMajor() ? ArgShape.NumRows : ArgShape.NumColumns;
2327 const unsigned NewNumElts =
2328 InputMatrix.isColumnMajor() ? ArgShape.NumColumns : ArgShape.NumRows;
2330 for (
unsigned I = 0;
I < NewNumVecs; ++
I) {
2335 for (
auto J :
enumerate(InputMatrix.vectors())) {
2341 Result.addVector(ResultVector);
2347 return Result.addNumComputeOps(2 * ArgShape.NumRows * ArgShape.NumColumns)
2348 .addNumExposedTransposes(1);
2352 MatrixTy VisitLoad(LoadInst *Inst,
const ShapeInfo &SI,
Value *Ptr,
2358 MatrixTy VisitStore(StoreInst *Inst,
const ShapeInfo &SI,
Value *StoredVal,
2361 getIndex(Ptr, getStride(SI)), Inst->
isVolatile(), SI,
2365 MatrixTy VisitPHI(PHINode *Inst,
const ShapeInfo &SI,
IRBuilder<> &Builder) {
2366 auto BlockIP = Inst->
getParent()->getFirstInsertionPt();
2368 MatrixTy PhiM = getMatrix(Inst, SI, Builder);
2372 SmallDenseMap<BasicBlock *, MatrixTy> ReshapedIncoming;
2373 for (
auto [IncomingV, IncomingB] :
2380 if (
auto MaybeIP = IncomingInst->getInsertionPointAfterDef())
2385 It->second = getMatrix(IncomingV, SI, Builder);
2386 const MatrixTy &OpM = It->second;
2388 for (
unsigned VI = 0, VE = PhiM.getNumVectors(); VI != VE; ++VI) {
2390 NewPHI->
addIncoming(OpM.getVector(VI), IncomingB);
2401 MatrixTy VisitBinaryOperator(BinaryOperator *Inst,
const ShapeInfo &SI,
2406 MatrixTy
Result(isColumnMajor());
2407 MatrixTy
A = getMatrix(Lhs, SI, Builder);
2408 MatrixTy
B = getMatrix(Rhs, SI, Builder);
2409 assert(
A.isColumnMajor() ==
B.isColumnMajor() &&
2410 Result.isColumnMajor() ==
A.isColumnMajor() &&
2411 "operands must agree on matrix layout");
2418 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2423 MatrixTy VisitUnaryOperator(UnaryOperator *Inst,
const ShapeInfo &SI,
2427 MatrixTy
Result(isColumnMajor());
2428 MatrixTy
M = getMatrix(
Op, SI, Builder);
2433 auto BuildVectorOp = [&Builder, Inst](
Value *
Op) {
2435 case Instruction::FNeg:
2442 for (
auto *
Vector :
M.vectors())
2445 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2450 MatrixTy VisitCastInstruction(CastInst *Inst,
const ShapeInfo &Shape,
2454 MatrixTy
Result(isColumnMajor());
2455 MatrixTy
M = getMatrix(
Op, Shape, Builder);
2460 auto *NewVTy = VectorType::get(OrigVTy->getElementType(),
2463 for (
auto *
Vector :
M.vectors())
2466 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2471 MatrixTy VisitSelectInst(SelectInst *Inst,
const ShapeInfo &Shape,
2477 MatrixTy
Result(isColumnMajor());
2478 MatrixTy
A = getMatrix(OpA, Shape, Builder);
2479 MatrixTy
B = getMatrix(OpB, Shape, Builder);
2484 MatrixTy
C = getMatrix(
Cond, Shape, Builder);
2485 llvm::copy(
C.vectors(), std::back_inserter(CondV));
2487 CondV.
resize(
A.getNumVectors());
2495 "If we have a vector conditional, we should be propagating "
2496 "profile information.");
2500 return Result.addNumComputeOps(getNumOps(
Result.getVectorTy()) *
2507 struct ExprLinearizer {
2508 unsigned LengthToBreak = 100;
2510 raw_string_ostream Stream;
2511 unsigned LineLength = 0;
2512 const DataLayout &DL;
2516 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2520 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared;
2523 const SmallSetVector<Value *, 32> &ExprsInSubprogram;
2530 SmallPtrSet<Value *, 8> ReusedExprs;
2532 ExprLinearizer(
const DataLayout &DL,
2533 const MapVector<Value *, MatrixTy> &Inst2Matrix,
2534 const DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared,
2535 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2537 : Stream(Str), DL(DL), Inst2Matrix(Inst2Matrix), Shared(Shared),
2538 ExprsInSubprogram(ExprsInSubprogram), Leaf(Leaf) {}
2540 void indent(
unsigned N) {
2542 for (
unsigned i = 0; i <
N; i++)
2551 void maybeIndent(
unsigned Indent) {
2552 if (LineLength >= LengthToBreak)
2555 if (LineLength == 0)
2559 void write(StringRef S) {
2560 LineLength += S.
size();
2564 Value *getUnderlyingObjectThroughLoads(
Value *V) {
2566 return getUnderlyingObjectThroughLoads(Ptr);
2567 else if (
V->getType()->isPointerTy())
2573 bool isMatrix(
Value *V)
const {
return ExprsInSubprogram.count(V); }
2577 void prettyPrintMatrixType(
Value *V, raw_string_ostream &SS) {
2578 auto M = Inst2Matrix.find(V);
2579 if (M == Inst2Matrix.end())
2582 SS <<
M->second.getNumRows();
2584 SS <<
M->second.getNumColumns();
2591 void writeFnName(CallInst *CI) {
2593 write(
"<no called fn>");
2596 if (!
Name.starts_with(
"llvm.matrix")) {
2605 raw_string_ostream
SS(Tmp);
2607 switch (
II->getIntrinsicID()) {
2608 case Intrinsic::matrix_multiply:
2609 prettyPrintMatrixType(
II->getOperand(0), SS);
2611 prettyPrintMatrixType(
II->getOperand(1), SS);
2612 SS <<
"." << *
II->getType()->getScalarType();
2614 case Intrinsic::matrix_transpose:
2615 prettyPrintMatrixType(
II->getOperand(0), SS);
2616 SS <<
"." << *
II->getType()->getScalarType();
2618 case Intrinsic::matrix_column_major_load:
2619 prettyPrintMatrixType(
II, SS);
2620 SS <<
"." << *
II->getType()->getScalarType();
2622 case Intrinsic::matrix_column_major_store:
2623 prettyPrintMatrixType(
II->getOperand(0), SS);
2624 SS <<
"." << *
II->getOperand(0)->getType()->getScalarType();
2633 unsigned getNumShapeArgs(CallInst *CI)
const {
2635 switch (
II->getIntrinsicID()) {
2636 case Intrinsic::matrix_multiply:
2638 case Intrinsic::matrix_transpose:
2640 case Intrinsic::matrix_column_major_load:
2641 case Intrinsic::matrix_column_major_store:
2654 V = getUnderlyingObjectThroughLoads(V);
2655 if (
V->getType()->isPointerTy()) {
2657 Stream <<
"stack addr";
2658 LineLength += StringRef(
"stack addr").size();
2661 LineLength += StringRef(
"addr").size();
2663 if (!
V->getName().empty()) {
2664 Stream <<
" %" <<
V->getName() <<
"";
2665 LineLength +=
V->getName().size() + 2;
2671 raw_string_ostream TmpStream(Tmp);
2674 TmpStream << CI->getValue();
2676 TmpStream <<
"constant";
2679 TmpStream <<
"matrix";
2681 TmpStream <<
"scalar";
2683 Tmp = std::string(StringRef(Tmp).trim());
2684 LineLength += Tmp.size();
2691 void linearizeExpr(
Value *Expr,
unsigned Indent,
bool ParentReused,
2692 bool ParentShared) {
2694 maybeIndent(Indent);
2695 SmallVector<Value *, 8>
Ops;
2698 bool ExprShared =
false;
2701 if (!ParentShared) {
2702 auto SI = Shared.find(Expr);
2703 assert(SI != Shared.end() &&
SI->second.count(Leaf));
2709 write(
"shared with remark at line " + std::to_string(DL.getLine()) +
2710 " column " + std::to_string(DL.getCol()) +
" (");
2712 ExprShared =
SI->second.size() > 1;
2715 bool Reused = !ReusedExprs.insert(Expr).second;
2716 if (Reused && !ParentReused)
2729 Ops.append(
I->value_op_begin(),
I->value_op_end());
2730 write(
I->getOpcodeName());
2735 unsigned NumOpsToBreak = 1;
2740 if (
Ops.size() > NumOpsToBreak)
2743 maybeIndent(Indent + 1);
2745 linearizeExpr(
Op, Indent + 1, Reused, ExprShared);
2748 if (
Op !=
Ops.back())
2755 const std::string &getResult() {
2773 struct RemarkGenerator {
2774 const MapVector<Value *, MatrixTy> &Inst2Matrix;
2775 OptimizationRemarkEmitter &ORE;
2777 const DataLayout &DL;
2779 RemarkGenerator(
const MapVector<Value *, MatrixTy> &Inst2Matrix,
2780 OptimizationRemarkEmitter &ORE,
Function &Func)
2781 : Inst2Matrix(Inst2Matrix), ORE(ORE), Func(Func),
2782 DL(Func.getDataLayout()) {}
2787 SmallVector<Value *, 4>
2788 getExpressionLeaves(
const SmallSetVector<Value *, 32> &ExprsInSubprogram) {
2789 SmallVector<Value *, 4> Leaves;
2790 for (
auto *Expr : ExprsInSubprogram)
2792 !
any_of(Expr->
users(), [&ExprsInSubprogram](User *U) {
2793 return ExprsInSubprogram.count(U);
2802 void collectSharedInfo(
Value *Leaf,
Value *V,
2803 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2804 DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared) {
2806 if (!ExprsInSubprogram.
count(V))
2812 collectSharedInfo(Leaf,
Op, ExprsInSubprogram, Shared);
2818 std::pair<OpInfoTy, OpInfoTy>
2819 sumOpInfos(
Value *Root, SmallPtrSetImpl<Value *> &ReusedExprs,
2820 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2821 DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared)
const {
2822 if (!ExprsInSubprogram.
count(Root))
2826 if (!ReusedExprs.
insert(Root).second)
2829 OpInfoTy SharedCount;
2833 auto CM = Inst2Matrix.find(Root);
2834 if (
I->second.size() == 1)
2835 Count = CM->second.getOpInfo();
2837 SharedCount = CM->second.getOpInfo();
2840 auto C = sumOpInfos(
Op, ReusedExprs, ExprsInSubprogram, Shared);
2842 SharedCount +=
C.second;
2844 return {
Count, SharedCount};
2847 void emitRemarks() {
2854 MapVector<DISubprogram *, SmallVector<Value *, 8>> Subprog2Exprs;
2855 for (
const auto &KV : Inst2Matrix) {
2856 if (Func.getSubprogram()) {
2858 DILocation *
Context =
I->getDebugLoc();
2865 Subprog2Exprs[
nullptr].push_back(KV.first);
2868 for (
auto &KV : Subprog2Exprs) {
2869 SmallSetVector<Value *, 32> ExprsInSubprogram(KV.second.begin(),
2871 auto Leaves = getExpressionLeaves(ExprsInSubprogram);
2873 DenseMap<Value *, SmallPtrSet<Value *, 2>>
Shared;
2874 for (
Value *Leaf : Leaves)
2875 collectSharedInfo(Leaf, Leaf, ExprsInSubprogram, Shared);
2878 for (
auto *L : Leaves) {
2890 SmallPtrSet<Value *, 8> ReusedExprs;
2891 OpInfoTy Counts, SharedCounts;
2892 std::tie(Counts, SharedCounts) =
2893 sumOpInfos(L, ReusedExprs, ExprsInSubprogram, Shared);
2895 OptimizationRemark Rem(
DEBUG_TYPE,
"matrix-lowered", Loc,
2898 Rem <<
"Lowered with ";
2899 Rem <<
ore::NV(
"NumStores", Counts.NumStores) <<
" stores, "
2900 <<
ore::NV(
"NumLoads", Counts.NumLoads) <<
" loads, "
2901 <<
ore::NV(
"NumComputeOps", Counts.NumComputeOps)
2903 <<
ore::NV(
"NumExposedTransposes", Counts.NumExposedTransposes)
2904 <<
" exposed transposes";
2906 if (SharedCounts.NumStores > 0 || SharedCounts.NumLoads > 0 ||
2907 SharedCounts.NumComputeOps > 0) {
2908 Rem <<
",\nadditionally "
2909 <<
ore::NV(
"NumStores", SharedCounts.NumStores) <<
" stores, "
2910 <<
ore::NV(
"NumLoads", SharedCounts.NumLoads) <<
" loads, "
2911 <<
ore::NV(
"NumFPOps", SharedCounts.NumComputeOps)
2913 <<
" are shared with other expressions";
2916 Rem << (
"\n" + linearize(L, Shared, ExprsInSubprogram, DL));
2924 const DenseMap<
Value *, SmallPtrSet<Value *, 2>> &Shared,
2925 const SmallSetVector<Value *, 32> &ExprsInSubprogram,
2926 const DataLayout &DL) {
2927 ExprLinearizer Lin(DL, Inst2Matrix, Shared, ExprsInSubprogram, L);
2928 Lin.linearizeExpr(L, 0,
false,
false);
2929 return Lin.getResult();
2939 const ScalarOptions &Opts =
2940 F.getContext().getLibraryOptions().get<ScalarOptions>();
2941 LowerMatrixIntrinsics LMT(Opts,
F,
TTI, Minimal ?
nullptr : &AM);
2955 static_cast<PassInfoMixin<LowerMatrixIntrinsicsPass> *
>(
this)->
printPipeline(
2956 OS, MapClassName2PassName);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static Type * getIndexType(Value *In)
hexagon Hexagon specific predictive commoning for HVX vectors
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
static DISubprogram * getSubprogram(DIScope *Scope)
Helper function to either return Scope, if it is a subprogram or the attached subprogram for a local ...
static auto m_AnyAdd(const LTy &L, const RTy &R)
Match any add operation (fp or integer).
static bool isShapePreserving(Value *V)
static auto m_AnyMul(const LTy &L, const RTy &R)
Match any mul operation (fp or integer).
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
static std::optional< ShapeInfo > computeShapeInfoForInst(Instruction *I, const DenseMap< Value *, ShapeInfo > &ShapeMap)
Return the ShapeInfo for the result of I, it it can be determined.
static iterator_range< Use * > getShapedOperandsForInst(Instruction *I)
Return an iterator over the operands of I that should share shape information with I.
static Value * computeVectorAddr(Value *BasePtr, Value *VecIdx, Value *Stride, unsigned NumElements, Type *EltType, IRBuilder<> &Builder)
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getFastMathFlags(const MachineInstr &I, const SPIRVSubtarget &ST)
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static const int BlockSize
static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget, SelectionDAG &DAG)
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator begin()
Instruction iterator methods.
const Function * getParent() const
Return the enclosing method, or null if none.
reverse_iterator rbegin()
InstListType::reverse_iterator reverse_iterator
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
static constexpr ElementCount getFixed(ScalarTy MinVal)
void setAllowContract(bool B=true)
bool allowReassoc() const
Flag queries.
bool allowContract() const
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
LLVM_ABI CallInst * CreateLifetimeStart(Value *Ptr)
Create a lifetime.start intrinsic.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
LLVM_ABI CallInst * CreateLifetimeEnd(Value *Ptr)
Create a lifetime.end intrinsic.
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Value * CreateFAdd(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
LLVM_ABI Value * CreateAddReduce(Value *Src)
Create a vector int add reduction intrinsic of the source vector.
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
LLVM_ABI Value * CreateFAddReduce(Value *Acc, Value *Src)
Create a sequential vector fadd reduction intrinsic of the source vector.
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Align getAlign() const
Return the alignment of the access that is being performed.
TypeSize getValue() const
Analysis pass that exposes the LoopInfo for a function.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
CallInst * CreateMatrixTranspose(Value *Matrix, unsigned Rows, unsigned Columns, const Twine &Name="")
Create a llvm.matrix.transpose call, transposing Matrix with Rows rows and Columns columns.
CallInst * CreateMatrixMultiply(Value *LHS, Value *RHS, unsigned LHSRows, unsigned LHSColumns, unsigned RHSColumns, const Twine &Name="")
Create a llvm.matrix.multiply call, multiplying matrixes LHS and RHS.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
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.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
size_type size() const
Determine the number of elements in the SetVector.
void insert_range(Range &&R)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Represent a constant reference to a string, i.e.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
constexpr size_t size() const
Get the string size.
Analysis pass providing the TargetTransformInfo.
The instances of the Type class are immutable: once they are created, they are never changed.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isVoidTy() const
Return true if this is 'void'.
UnaryOps getOpcode() const
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use 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()
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
TwoOps_match< ValueOpTy, PointerOpTy, Instruction::Store > m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp)
Matches StoreInst.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
ElementType
The element type of an SRV or UAV resource.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool operator!=(uint64_t V1, const APInt &V2)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI Value * concatenateVectors(IRBuilderBase &Builder, ArrayRef< Value * > Vecs)
Concatenate a list of vectors.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mul
Product of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
LLVM_ABI llvm::SmallVector< int, 16 > createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs)
Create a sequential shuffle mask.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.