1 //===- LowerMatrixIntrinsics.cpp - Lower matrix intrinsics -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Lower matrix intrinsics to vector operations. 10 // 11 // TODO: 12 // * Improve fusion: 13 // * Support more cases, e.g. multiply-add, multiply-sub, operands/results 14 // transposed. 15 // * Improve cost-modeling, e.g. choose different number of rows/columns 16 // columns for tiles, consider cost of copies on alias. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 21 #include "llvm/ADT/GraphTraits.h" 22 #include "llvm/ADT/PostOrderIterator.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/DomTreeUpdater.h" 26 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Analysis/VectorUtils.h" 30 #include "llvm/IR/CFG.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DebugInfoMetadata.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/IRBuilder.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/MatrixBuilder.h" 38 #include "llvm/IR/PatternMatch.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/Alignment.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Transforms/Scalar.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/LoopUtils.h" 47 #include "llvm/Transforms/Utils/MatrixUtils.h" 48 49 using namespace llvm; 50 using namespace PatternMatch; 51 52 #define DEBUG_TYPE "lower-matrix-intrinsics" 53 54 static cl::opt<bool> 55 FuseMatrix("fuse-matrix", cl::init(true), cl::Hidden, 56 cl::desc("Enable/disable fusing matrix instructions.")); 57 // TODO: Allow and use non-square tiles. 58 static cl::opt<unsigned> TileSize( 59 "fuse-matrix-tile-size", cl::init(4), cl::Hidden, 60 cl::desc( 61 "Tile size for matrix instruction fusion using square-shaped tiles.")); 62 static cl::opt<bool> TileUseLoops("fuse-matrix-use-loops", cl::init(false), 63 cl::Hidden, 64 cl::desc("Generate loop nest for tiling.")); 65 static cl::opt<bool> ForceFusion( 66 "force-fuse-matrix", cl::init(false), cl::Hidden, 67 cl::desc("Force matrix instruction fusion even if not profitable.")); 68 static cl::opt<bool> AllowContractEnabled( 69 "matrix-allow-contract", cl::init(false), cl::Hidden, 70 cl::desc("Allow the use of FMAs if available and profitable. This may " 71 "result in different results, due to less rounding error.")); 72 73 enum class MatrixLayoutTy { ColumnMajor, RowMajor }; 74 75 static cl::opt<MatrixLayoutTy> MatrixLayout( 76 "matrix-default-layout", cl::init(MatrixLayoutTy::ColumnMajor), 77 cl::desc("Sets the default matrix layout"), 78 cl::values(clEnumValN(MatrixLayoutTy::ColumnMajor, "column-major", 79 "Use column-major layout"), 80 clEnumValN(MatrixLayoutTy::RowMajor, "row-major", 81 "Use row-major layout"))); 82 83 /// Helper function to either return Scope, if it is a subprogram or the 84 /// attached subprogram for a local scope. 85 static DISubprogram *getSubprogram(DIScope *Scope) { 86 if (auto *Subprogram = dyn_cast<DISubprogram>(Scope)) 87 return Subprogram; 88 return cast<DILocalScope>(Scope)->getSubprogram(); 89 } 90 91 namespace { 92 93 // Given an element pointer \p BasePtr to the start of a (sub) matrix, compute 94 // the start address of vector \p VecIdx with type (\p EltType x \p NumElements) 95 // assuming \p Stride elements between start two consecutive vectors. 96 // \p Stride must be >= \p NumElements. 97 // For column-major matrixes, the function computes the address of a column 98 // vectors and \p NumElements must be set to the number of elements in a column 99 // (= number of rows of the matrix). For row-major matrixes, the function 100 // computes the address of a row vector and \p NumElements must be set to the 101 // number of elements in a column (= number of columns of the matrix). 102 // 103 // Consider a 4x4 matrix in column-mjaor layout like below 104 // 105 // 0 1 2 3 106 // 0 v_0_0 v_0_1 v_0_2 v_0_3 107 // 1 v_1_0 v_1_1 v_1_2 v_1_3 108 // 2 v_2_0 v_2_1 v_2_2 v_2_3 109 // 3 v_3_0 v_3_1 v_3_2 v_3_3 110 111 // To compute the column addresses for a 2x3 sub-matrix at row 1 and column 1, 112 // we need a pointer to the first element of the submatrix as base pointer. 113 // Then we can use computeVectorAddr to compute the addresses for the columns 114 // of the sub-matrix. 115 // 116 // Column 0: computeVectorAddr(Base, 0 (column), 4 (stride), 2 (num rows), ..) 117 // -> just returns Base 118 // Column 1: computeVectorAddr(Base, 1 (column), 4 (stride), 2 (num rows), ..) 119 // -> returns Base + (1 * 4) 120 // Column 2: computeVectorAddr(Base, 2 (column), 4 (stride), 2 (num rows), ..) 121 // -> returns Base + (2 * 4) 122 // 123 // The graphic below illustrates the number of elements in a column (marked 124 // with |) and the number of skipped elements (marked with }). 125 // 126 // v_0_0 v_0_1 {v_0_2 {v_0_3 127 // Base Col 1 Col 2 128 // | | | 129 // v_1_0 |v_1_1 |v_1_2 |v_1_3 130 // v_2_0 |v_2_1 |v_2_2 |v_2_3 131 // v_3_0 {v_3_1 {v_3_2 v_3_3 132 // 133 Value *computeVectorAddr(Value *BasePtr, Value *VecIdx, Value *Stride, 134 unsigned NumElements, Type *EltType, 135 IRBuilder<> &Builder) { 136 137 assert((!isa<ConstantInt>(Stride) || 138 cast<ConstantInt>(Stride)->getZExtValue() >= NumElements) && 139 "Stride must be >= the number of elements in the result vector."); 140 unsigned AS = cast<PointerType>(BasePtr->getType())->getAddressSpace(); 141 142 // Compute the start of the vector with index VecIdx as VecIdx * Stride. 143 Value *VecStart = Builder.CreateMul(VecIdx, Stride, "vec.start"); 144 145 // Get pointer to the start of the selected vector. Skip GEP creation, 146 // if we select vector 0. 147 if (isa<ConstantInt>(VecStart) && cast<ConstantInt>(VecStart)->isZero()) 148 VecStart = BasePtr; 149 else 150 VecStart = Builder.CreateGEP(EltType, BasePtr, VecStart, "vec.gep"); 151 152 // Cast elementwise vector start pointer to a pointer to a vector 153 // (EltType x NumElements)*. 154 auto *VecType = FixedVectorType::get(EltType, NumElements); 155 Type *VecPtrType = PointerType::get(VecType, AS); 156 return Builder.CreatePointerCast(VecStart, VecPtrType, "vec.cast"); 157 } 158 159 /// LowerMatrixIntrinsics contains the methods used to lower matrix intrinsics. 160 /// 161 /// Currently, the lowering for each matrix intrinsic is done as follows: 162 /// 1. Propagate the shape information from intrinsics to connected 163 /// instructions. 164 /// 2. Lower instructions with shape information (assuming column-major layout). 165 /// The lowering works similarly using row-major layout. 166 /// 2.1. Get column vectors for each argument. If we already lowered the 167 /// definition of an argument, use the produced column vectors directly. 168 /// If not, split the operand vector containing an embedded matrix into 169 /// a set of column vectors, 170 /// 2.2. Lower the instruction in terms of column major operations, which 171 /// yields a set of column vectors containing result matrix. Note that we 172 /// lower all instructions that have shape information. Besides the 173 /// intrinsics, this includes stores for example. 174 /// 2.3. Update uses of the lowered instruction. If we have shape information 175 /// for a user, there is nothing to do, as we will look up the result 176 /// column matrix when lowering the user. For other uses, we embed the 177 /// result matrix in a flat vector and update the use. 178 /// 2.4. Cache the result column matrix for the instruction we lowered 179 /// 3. After we lowered all instructions in a function, remove the now 180 /// obsolete instructions. 181 /// 182 class LowerMatrixIntrinsics { 183 Function &Func; 184 const DataLayout &DL; 185 const TargetTransformInfo &TTI; 186 AliasAnalysis *AA; 187 DominatorTree *DT; 188 LoopInfo *LI; 189 OptimizationRemarkEmitter *ORE; 190 191 /// Contains estimates of the number of operations (loads, stores, compute) required to lower a matrix operation. 192 struct OpInfoTy { 193 /// Number of stores emitted to generate this matrix. 194 unsigned NumStores = 0; 195 /// Number of loads emitted to generate this matrix. 196 unsigned NumLoads = 0; 197 /// Number of compute operations emitted to generate this matrix. 198 unsigned NumComputeOps = 0; 199 /// Most of the time transposes can be fused with matrix multiplies or can 200 /// be folded away via algebraic simplifications. This is the number of 201 /// transposes that we failed to make "free" via such optimizations. 202 unsigned NumExposedTransposes = 0; 203 204 OpInfoTy &operator+=(const OpInfoTy &RHS) { 205 NumStores += RHS.NumStores; 206 NumLoads += RHS.NumLoads; 207 NumComputeOps += RHS.NumComputeOps; 208 NumExposedTransposes += RHS.NumExposedTransposes; 209 return *this; 210 } 211 }; 212 213 /// Wrapper class representing a matrix as a set of vectors, either in row or 214 /// column major layout. All vectors must have the same vector type. 215 class MatrixTy { 216 SmallVector<Value *, 16> Vectors; 217 218 OpInfoTy OpInfo; 219 220 bool IsColumnMajor = true; 221 222 public: 223 MatrixTy() 224 : Vectors(), 225 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 226 MatrixTy(ArrayRef<Value *> Vectors) 227 : Vectors(Vectors.begin(), Vectors.end()), 228 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 229 MatrixTy(unsigned NumRows, unsigned NumColumns, Type *EltTy) 230 : IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) { 231 232 unsigned D = isColumnMajor() ? NumColumns : NumRows; 233 for (unsigned J = 0; J < D; ++J) 234 addVector(UndefValue::get(FixedVectorType::get( 235 EltTy, isColumnMajor() ? NumRows : NumColumns))); 236 } 237 238 Value *getVector(unsigned i) const { return Vectors[i]; } 239 Value *getColumn(unsigned i) const { 240 assert(isColumnMajor() && "only supported for column-major matrixes"); 241 return Vectors[i]; 242 } 243 Value *getRow(unsigned i) const { 244 assert(!isColumnMajor() && "only supported for row-major matrixes"); 245 return Vectors[i]; 246 } 247 248 void setVector(unsigned i, Value *V) { Vectors[i] = V; } 249 250 Type *getElementType() const { return getVectorTy()->getElementType(); } 251 252 unsigned getNumVectors() const { 253 if (isColumnMajor()) 254 return getNumColumns(); 255 return getNumRows(); 256 } 257 258 unsigned getNumColumns() const { 259 if (isColumnMajor()) 260 return Vectors.size(); 261 else { 262 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns"); 263 return cast<FixedVectorType>(Vectors[0]->getType())->getNumElements(); 264 } 265 } 266 unsigned getNumRows() const { 267 if (isColumnMajor()) { 268 assert(Vectors.size() > 0 && "Cannot call getNumRows without columns"); 269 return cast<FixedVectorType>(Vectors[0]->getType())->getNumElements(); 270 } else 271 return Vectors.size(); 272 } 273 274 void addVector(Value *V) { Vectors.push_back(V); } 275 VectorType *getColumnTy() { 276 assert(isColumnMajor() && "only supported for column-major matrixes"); 277 return getVectorTy(); 278 } 279 280 VectorType *getVectorTy() const { 281 return cast<VectorType>(Vectors[0]->getType()); 282 } 283 284 iterator_range<SmallVector<Value *, 8>::iterator> columns() { 285 assert(isColumnMajor() && 286 "columns() only supported for column-major matrixes"); 287 return make_range(Vectors.begin(), Vectors.end()); 288 } 289 290 iterator_range<SmallVector<Value *, 8>::iterator> vectors() { 291 return make_range(Vectors.begin(), Vectors.end()); 292 } 293 294 /// Embed the vectors of the matrix into a flat vector by concatenating 295 /// them. 296 Value *embedInVector(IRBuilder<> &Builder) const { 297 return Vectors.size() == 1 ? Vectors[0] 298 : concatenateVectors(Builder, Vectors); 299 } 300 301 MatrixTy &addNumLoads(unsigned N) { 302 OpInfo.NumLoads += N; 303 return *this; 304 } 305 306 void setNumLoads(unsigned N) { OpInfo.NumLoads = N; } 307 308 MatrixTy &addNumStores(unsigned N) { 309 OpInfo.NumStores += N; 310 return *this; 311 } 312 313 MatrixTy &addNumExposedTransposes(unsigned N) { 314 OpInfo.NumExposedTransposes += N; 315 return *this; 316 } 317 318 MatrixTy &addNumComputeOps(unsigned N) { 319 OpInfo.NumComputeOps += N; 320 return *this; 321 } 322 323 unsigned getNumStores() const { return OpInfo.NumStores; } 324 unsigned getNumLoads() const { return OpInfo.NumLoads; } 325 unsigned getNumComputeOps() const { return OpInfo.NumComputeOps; } 326 327 const OpInfoTy &getOpInfo() const { return OpInfo; } 328 329 bool isColumnMajor() const { return IsColumnMajor; } 330 331 unsigned getStride() const { 332 if (isColumnMajor()) 333 return getNumRows(); 334 return getNumColumns(); 335 } 336 337 /// Extract a vector of \p NumElts starting at index (\p I, \p J). If the 338 /// matrix is column-major, the result vector is extracted from a column 339 /// vector, otherwise from a row vector. 340 Value *extractVector(unsigned I, unsigned J, unsigned NumElts, 341 IRBuilder<> &Builder) const { 342 Value *Vec = isColumnMajor() ? getColumn(J) : getRow(I); 343 return Builder.CreateShuffleVector( 344 Vec, createSequentialMask(isColumnMajor() ? I : J, NumElts, 0), 345 "block"); 346 } 347 }; 348 349 struct ShapeInfo { 350 unsigned NumRows; 351 unsigned NumColumns; 352 353 bool IsColumnMajor; 354 355 ShapeInfo(unsigned NumRows = 0, unsigned NumColumns = 0) 356 : NumRows(NumRows), NumColumns(NumColumns), 357 IsColumnMajor(MatrixLayout == MatrixLayoutTy::ColumnMajor) {} 358 359 ShapeInfo(Value *NumRows, Value *NumColumns) 360 : ShapeInfo(cast<ConstantInt>(NumRows)->getZExtValue(), 361 cast<ConstantInt>(NumColumns)->getZExtValue()) {} 362 363 bool operator==(const ShapeInfo &other) { 364 return NumRows == other.NumRows && NumColumns == other.NumColumns; 365 } 366 bool operator!=(const ShapeInfo &other) { return !(*this == other); } 367 368 /// Returns true if shape-information is defined, meaning both dimensions 369 /// are != 0. 370 operator bool() const { 371 assert(NumRows == 0 || NumColumns != 0); 372 return NumRows != 0; 373 } 374 375 unsigned getStride() const { 376 if (IsColumnMajor) 377 return NumRows; 378 return NumColumns; 379 } 380 381 unsigned getNumVectors() const { 382 if (IsColumnMajor) 383 return NumColumns; 384 return NumRows; 385 } 386 }; 387 388 /// Maps instructions to their shape information. The shape information 389 /// describes the shape to be used while lowering. This matches the shape of 390 /// the result value of the instruction, with the only exceptions being store 391 /// instructions and the matrix_column_major_store intrinsics. For those, the 392 /// shape information indicates that those instructions should be lowered 393 /// using shape information as well. A ValueMap is used so that when 394 /// sub-passes like optimizeTransposes performs RAUW the map stays 395 /// up-to-date. 396 ValueMap<Value *, ShapeInfo> ShapeMap; 397 398 /// List of instructions to remove. While lowering, we are not replacing all 399 /// users of a lowered instruction, if shape information is available and 400 /// those need to be removed after we finished lowering. 401 SmallVector<Instruction *, 16> ToRemove; 402 403 /// Map from instructions to their produced column matrix. 404 MapVector<Value *, MatrixTy> Inst2ColumnMatrix; 405 406 private: 407 static FastMathFlags getFastMathFlags(Instruction *Inst) { 408 FastMathFlags FMF; 409 410 if (isa<FPMathOperator>(*Inst)) 411 FMF = Inst->getFastMathFlags(); 412 413 FMF.setAllowContract(AllowContractEnabled || FMF.allowContract()); 414 415 return FMF; 416 } 417 418 public: 419 LowerMatrixIntrinsics(Function &F, TargetTransformInfo &TTI, 420 AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, 421 OptimizationRemarkEmitter *ORE) 422 : Func(F), DL(F.getParent()->getDataLayout()), TTI(TTI), AA(AA), DT(DT), 423 LI(LI), ORE(ORE) {} 424 425 unsigned getNumOps(Type *VT) { 426 assert(isa<VectorType>(VT) && "Expected vector type"); 427 return getNumOps(VT->getScalarType(), 428 cast<FixedVectorType>(VT)->getNumElements()); 429 } 430 431 /// Is this the minimal version executed in the backend pipelines. 432 bool isMinimal() const { 433 return !DT; 434 } 435 436 /// Return the estimated number of vector ops required for an operation on 437 /// \p VT * N. 438 unsigned getNumOps(Type *ST, unsigned N) { 439 return std::ceil((ST->getPrimitiveSizeInBits() * N).getFixedSize() / 440 double(TTI.getRegisterBitWidth( 441 TargetTransformInfo::RGK_FixedWidthVector) 442 .getFixedSize())); 443 } 444 445 /// Return the set of vectors that a matrix value is lowered to. 446 /// 447 /// If we lowered \p MatrixVal, just return the cache result matrix. Otherwise 448 /// split the flat vector \p MatrixVal containing a matrix with shape \p SI 449 /// into vectors. 450 MatrixTy getMatrix(Value *MatrixVal, const ShapeInfo &SI, 451 IRBuilder<> &Builder) { 452 VectorType *VType = dyn_cast<VectorType>(MatrixVal->getType()); 453 assert(VType && "MatrixVal must be a vector type"); 454 assert(cast<FixedVectorType>(VType)->getNumElements() == 455 SI.NumRows * SI.NumColumns && 456 "The vector size must match the number of matrix elements"); 457 458 // Check if we lowered MatrixVal using shape information. In that case, 459 // return the existing matrix, if it matches the requested shape 460 // information. If there is a mis-match, embed the result in a flat 461 // vector and split it later. 462 auto Found = Inst2ColumnMatrix.find(MatrixVal); 463 if (Found != Inst2ColumnMatrix.end()) { 464 MatrixTy &M = Found->second; 465 // Return the found matrix, if its shape matches the requested shape 466 // information 467 if (SI.NumRows == M.getNumRows() && SI.NumColumns == M.getNumColumns()) 468 return M; 469 470 MatrixVal = M.embedInVector(Builder); 471 } 472 473 // Otherwise split MatrixVal. 474 SmallVector<Value *, 16> SplitVecs; 475 for (unsigned MaskStart = 0; 476 MaskStart < cast<FixedVectorType>(VType)->getNumElements(); 477 MaskStart += SI.getStride()) { 478 Value *V = Builder.CreateShuffleVector( 479 MatrixVal, createSequentialMask(MaskStart, SI.getStride(), 0), 480 "split"); 481 SplitVecs.push_back(V); 482 } 483 484 return {SplitVecs}; 485 } 486 487 /// If \p V already has a known shape return false. Otherwise set the shape 488 /// for instructions that support it. 489 bool setShapeInfo(Value *V, ShapeInfo Shape) { 490 assert(Shape && "Shape not set"); 491 if (isa<UndefValue>(V) || !supportsShapeInfo(V)) 492 return false; 493 494 auto SIter = ShapeMap.find(V); 495 if (SIter != ShapeMap.end()) { 496 LLVM_DEBUG(dbgs() << " not overriding existing shape: " 497 << SIter->second.NumRows << " " 498 << SIter->second.NumColumns << " for " << *V << "\n"); 499 return false; 500 } 501 502 ShapeMap.insert({V, Shape}); 503 LLVM_DEBUG(dbgs() << " " << Shape.NumRows << " x " << Shape.NumColumns 504 << " for " << *V << "\n"); 505 return true; 506 } 507 508 bool isUniformShape(Value *V) { 509 Instruction *I = dyn_cast<Instruction>(V); 510 if (!I) 511 return true; 512 513 switch (I->getOpcode()) { 514 case Instruction::FAdd: 515 case Instruction::FSub: 516 case Instruction::FMul: // Scalar multiply. 517 case Instruction::FNeg: 518 case Instruction::Add: 519 case Instruction::Mul: 520 case Instruction::Sub: 521 return true; 522 default: 523 return false; 524 } 525 } 526 527 /// Returns true if shape information can be used for \p V. The supported 528 /// instructions must match the instructions that can be lowered by this pass. 529 bool supportsShapeInfo(Value *V) { 530 Instruction *Inst = dyn_cast<Instruction>(V); 531 if (!Inst) 532 return false; 533 534 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst); 535 if (II) 536 switch (II->getIntrinsicID()) { 537 case Intrinsic::matrix_multiply: 538 case Intrinsic::matrix_transpose: 539 case Intrinsic::matrix_column_major_load: 540 case Intrinsic::matrix_column_major_store: 541 return true; 542 default: 543 return false; 544 } 545 return isUniformShape(V) || isa<StoreInst>(V) || isa<LoadInst>(V); 546 } 547 548 /// Propagate the shape information of instructions to their users. 549 /// The work list contains instructions for which we can compute the shape, 550 /// either based on the information provided by matrix intrinsics or known 551 /// shapes of operands. 552 SmallVector<Instruction *, 32> 553 propagateShapeForward(SmallVectorImpl<Instruction *> &WorkList) { 554 SmallVector<Instruction *, 32> NewWorkList; 555 // Pop an element for which we guaranteed to have at least one of the 556 // operand shapes. Add the shape for this and then add users to the work 557 // list. 558 LLVM_DEBUG(dbgs() << "Forward-propagate shapes:\n"); 559 while (!WorkList.empty()) { 560 Instruction *Inst = WorkList.pop_back_val(); 561 562 // New entry, set the value and insert operands 563 bool Propagate = false; 564 565 Value *MatrixA; 566 Value *MatrixB; 567 Value *M; 568 Value *N; 569 Value *K; 570 if (match(Inst, m_Intrinsic<Intrinsic::matrix_multiply>( 571 m_Value(MatrixA), m_Value(MatrixB), m_Value(M), 572 m_Value(N), m_Value(K)))) { 573 Propagate = setShapeInfo(Inst, {M, K}); 574 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_transpose>( 575 m_Value(MatrixA), m_Value(M), m_Value(N)))) { 576 // Flip dimensions. 577 Propagate = setShapeInfo(Inst, {N, M}); 578 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_column_major_store>( 579 m_Value(MatrixA), m_Value(), m_Value(), 580 m_Value(), m_Value(M), m_Value(N)))) { 581 Propagate = setShapeInfo(Inst, {N, M}); 582 } else if (match(Inst, m_Intrinsic<Intrinsic::matrix_column_major_load>( 583 m_Value(), m_Value(), m_Value(), m_Value(M), 584 m_Value(N)))) { 585 Propagate = setShapeInfo(Inst, {M, N}); 586 } else if (match(Inst, m_Store(m_Value(MatrixA), m_Value()))) { 587 auto OpShape = ShapeMap.find(MatrixA); 588 if (OpShape != ShapeMap.end()) 589 setShapeInfo(Inst, OpShape->second); 590 continue; 591 } else if (isUniformShape(Inst)) { 592 // Find the first operand that has a known shape and use that. 593 for (auto &Op : Inst->operands()) { 594 auto OpShape = ShapeMap.find(Op.get()); 595 if (OpShape != ShapeMap.end()) { 596 Propagate |= setShapeInfo(Inst, OpShape->second); 597 break; 598 } 599 } 600 } 601 602 if (Propagate) { 603 NewWorkList.push_back(Inst); 604 for (auto *User : Inst->users()) 605 if (ShapeMap.count(User) == 0) 606 WorkList.push_back(cast<Instruction>(User)); 607 } 608 } 609 610 return NewWorkList; 611 } 612 613 /// Propagate the shape to operands of instructions with shape information. 614 /// \p Worklist contains the instruction for which we already know the shape. 615 SmallVector<Instruction *, 32> 616 propagateShapeBackward(SmallVectorImpl<Instruction *> &WorkList) { 617 SmallVector<Instruction *, 32> NewWorkList; 618 619 auto pushInstruction = [](Value *V, 620 SmallVectorImpl<Instruction *> &WorkList) { 621 Instruction *I = dyn_cast<Instruction>(V); 622 if (I) 623 WorkList.push_back(I); 624 }; 625 // Pop an element with known shape. Traverse the operands, if their shape 626 // derives from the result shape and is unknown, add it and add them to the 627 // worklist. 628 LLVM_DEBUG(dbgs() << "Backward-propagate shapes:\n"); 629 while (!WorkList.empty()) { 630 Value *V = WorkList.pop_back_val(); 631 632 size_t BeforeProcessingV = WorkList.size(); 633 if (!isa<Instruction>(V)) 634 continue; 635 636 Value *MatrixA; 637 Value *MatrixB; 638 Value *M; 639 Value *N; 640 Value *K; 641 if (match(V, m_Intrinsic<Intrinsic::matrix_multiply>( 642 m_Value(MatrixA), m_Value(MatrixB), m_Value(M), 643 m_Value(N), m_Value(K)))) { 644 if (setShapeInfo(MatrixA, {M, N})) 645 pushInstruction(MatrixA, WorkList); 646 647 if (setShapeInfo(MatrixB, {N, K})) 648 pushInstruction(MatrixB, WorkList); 649 650 } else if (match(V, m_Intrinsic<Intrinsic::matrix_transpose>( 651 m_Value(MatrixA), m_Value(M), m_Value(N)))) { 652 // Flip dimensions. 653 if (setShapeInfo(MatrixA, {M, N})) 654 pushInstruction(MatrixA, WorkList); 655 } else if (match(V, m_Intrinsic<Intrinsic::matrix_column_major_store>( 656 m_Value(MatrixA), m_Value(), m_Value(), m_Value(), 657 m_Value(M), m_Value(N)))) { 658 if (setShapeInfo(MatrixA, {M, N})) { 659 pushInstruction(MatrixA, WorkList); 660 } 661 } else if (isa<LoadInst>(V) || 662 match(V, m_Intrinsic<Intrinsic::matrix_column_major_load>())) { 663 // Nothing to do, no matrix input. 664 } else if (isa<StoreInst>(V)) { 665 // Nothing to do. We forward-propagated to this so we would just 666 // backward propagate to an instruction with an already known shape. 667 } else if (isUniformShape(V)) { 668 // Propagate to all operands. 669 ShapeInfo Shape = ShapeMap[V]; 670 for (Use &U : cast<Instruction>(V)->operands()) { 671 if (setShapeInfo(U.get(), Shape)) 672 pushInstruction(U.get(), WorkList); 673 } 674 } 675 // After we discovered new shape info for new instructions in the 676 // worklist, we use their users as seeds for the next round of forward 677 // propagation. 678 for (size_t I = BeforeProcessingV; I != WorkList.size(); I++) 679 for (User *U : WorkList[I]->users()) 680 if (isa<Instruction>(U) && V != U) 681 NewWorkList.push_back(cast<Instruction>(U)); 682 } 683 return NewWorkList; 684 } 685 686 /// Try moving transposes in order to fold them away or into multiplies. 687 void optimizeTransposes() { 688 auto ReplaceAllUsesWith = [this](Instruction &Old, Value *New) { 689 // We need to remove Old from the ShapeMap otherwise RAUW will replace it 690 // with New. We should only add New it it supportsShapeInfo so we insert 691 // it conditionally instead. 692 auto S = ShapeMap.find(&Old); 693 if (S != ShapeMap.end()) { 694 ShapeMap.erase(S); 695 if (supportsShapeInfo(New)) 696 ShapeMap.insert({New, S->second}); 697 } 698 Old.replaceAllUsesWith(New); 699 }; 700 701 // First sink all transposes inside matmuls, hoping that we end up with NN, 702 // NT or TN variants. 703 for (BasicBlock &BB : reverse(Func)) { 704 for (auto II = BB.rbegin(); II != BB.rend();) { 705 Instruction &I = *II; 706 // We may remove II. By default continue on the next/prev instruction. 707 ++II; 708 // If we were to erase II, move again. 709 auto EraseFromParent = [&II](Value *V) { 710 auto *Inst = cast<Instruction>(V); 711 if (Inst->use_empty()) { 712 if (Inst == &*II) { 713 ++II; 714 } 715 Inst->eraseFromParent(); 716 } 717 }; 718 719 // If we're creating a new instruction, continue from there. 720 Instruction *NewInst = nullptr; 721 722 IRBuilder<> IB(&I); 723 MatrixBuilder<IRBuilder<>> Builder(IB); 724 725 Value *TA, *TAMA, *TAMB; 726 ConstantInt *R, *K, *C; 727 if (match(&I, m_Intrinsic<Intrinsic::matrix_transpose>(m_Value(TA)))) { 728 729 // Transpose of a transpose is a nop 730 Value *TATA; 731 if (match(TA, 732 m_Intrinsic<Intrinsic::matrix_transpose>(m_Value(TATA)))) { 733 ReplaceAllUsesWith(I, TATA); 734 EraseFromParent(&I); 735 EraseFromParent(TA); 736 } 737 738 // (A * B)^t -> B^t * A^t 739 // RxK KxC CxK KxR 740 else if (match(TA, m_Intrinsic<Intrinsic::matrix_multiply>( 741 m_Value(TAMA), m_Value(TAMB), m_ConstantInt(R), 742 m_ConstantInt(K), m_ConstantInt(C)))) { 743 Value *T0 = Builder.CreateMatrixTranspose(TAMB, K->getZExtValue(), 744 C->getZExtValue(), 745 TAMB->getName() + "_t"); 746 // We are being run after shape prop, add shape for newly created 747 // instructions so that we lower them later. 748 setShapeInfo(T0, {C, K}); 749 Value *T1 = Builder.CreateMatrixTranspose(TAMA, R->getZExtValue(), 750 K->getZExtValue(), 751 TAMA->getName() + "_t"); 752 setShapeInfo(T1, {K, R}); 753 NewInst = Builder.CreateMatrixMultiply(T0, T1, C->getZExtValue(), 754 K->getZExtValue(), 755 R->getZExtValue(), "mmul"); 756 ReplaceAllUsesWith(I, NewInst); 757 EraseFromParent(&I); 758 EraseFromParent(TA); 759 } 760 } 761 762 // If we replaced I with a new instruction, continue from there. 763 if (NewInst) 764 II = std::next(BasicBlock::reverse_iterator(NewInst)); 765 } 766 } 767 768 // If we have a TT matmul, lift the transpose. We may be able to fold into 769 // consuming multiply. 770 for (BasicBlock &BB : Func) { 771 for (BasicBlock::iterator II = BB.begin(); II != BB.end();) { 772 Instruction *I = &*II; 773 // We may remove I. 774 ++II; 775 Value *A, *B, *AT, *BT; 776 ConstantInt *R, *K, *C; 777 if (match(&*I, m_Intrinsic<Intrinsic::matrix_multiply>( 778 m_Value(A), m_Value(B), m_ConstantInt(R), 779 m_ConstantInt(K), m_ConstantInt(C))) && 780 match(A, m_Intrinsic<Intrinsic::matrix_transpose>(m_Value(AT))) && 781 match(B, m_Intrinsic<Intrinsic::matrix_transpose>(m_Value((BT))))) { 782 IRBuilder<> IB(&*I); 783 MatrixBuilder<IRBuilder<>> Builder(IB); 784 Value *M = Builder.CreateMatrixMultiply( 785 BT, AT, C->getZExtValue(), K->getZExtValue(), R->getZExtValue()); 786 setShapeInfo(M, {C, R}); 787 Value *NewInst = Builder.CreateMatrixTranspose(M, R->getZExtValue(), 788 C->getZExtValue()); 789 ReplaceAllUsesWith(*I, NewInst); 790 if (I->use_empty()) 791 I->eraseFromParent(); 792 if (A->use_empty()) 793 cast<Instruction>(A)->eraseFromParent(); 794 if (A != B && B->use_empty()) 795 cast<Instruction>(B)->eraseFromParent(); 796 } 797 } 798 } 799 } 800 801 bool Visit() { 802 SmallVector<Instruction *, 32> WorkList; 803 804 // Initially only the shape of matrix intrinsics is known. 805 // Initialize the work list with ops carrying shape information. 806 for (BasicBlock &BB : Func) 807 for (Instruction &Inst : BB) { 808 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst); 809 if (!II) 810 continue; 811 812 switch (II->getIntrinsicID()) { 813 case Intrinsic::matrix_multiply: 814 case Intrinsic::matrix_transpose: 815 case Intrinsic::matrix_column_major_load: 816 case Intrinsic::matrix_column_major_store: 817 WorkList.push_back(&Inst); 818 break; 819 default: 820 break; 821 } 822 } 823 824 // Avoid unnecessary work if there are no matrix intrinsics in the function. 825 if (WorkList.empty()) 826 return false; 827 828 // Propagate shapes until nothing changes any longer. 829 while (!WorkList.empty()) { 830 WorkList = propagateShapeForward(WorkList); 831 WorkList = propagateShapeBackward(WorkList); 832 } 833 834 if (!isMinimal()) { 835 optimizeTransposes(); 836 LLVM_DEBUG({ 837 dbgs() << "Dump after matrix transpose optimization:\n"; 838 Func.dump(); 839 }); 840 } 841 842 bool Changed = false; 843 SmallVector<CallInst *, 16> MaybeFusableInsts; 844 SmallVector<Instruction *, 16> MatrixInsts; 845 846 // First, collect all instructions with shape information and candidates for 847 // fusion (currently only matrix multiplies). 848 ReversePostOrderTraversal<Function *> RPOT(&Func); 849 for (auto *BB : RPOT) 850 for (Instruction &I : *BB) { 851 if (ShapeMap.find(&I) == ShapeMap.end()) 852 continue; 853 if (match(&I, m_Intrinsic<Intrinsic::matrix_multiply>())) 854 MaybeFusableInsts.push_back(cast<CallInst>(&I)); 855 MatrixInsts.push_back(&I); 856 } 857 858 // Second, try to fuse candidates. 859 SmallPtrSet<Instruction *, 16> FusedInsts; 860 for (CallInst *CI : MaybeFusableInsts) 861 LowerMatrixMultiplyFused(CI, FusedInsts); 862 Changed = !FusedInsts.empty(); 863 864 // Third, lower remaining instructions with shape information. 865 for (Instruction *Inst : MatrixInsts) { 866 if (FusedInsts.count(Inst)) 867 continue; 868 869 IRBuilder<> Builder(Inst); 870 871 if (CallInst *CInst = dyn_cast<CallInst>(Inst)) 872 Changed |= VisitCallInst(CInst); 873 874 Value *Op1; 875 Value *Op2; 876 if (auto *BinOp = dyn_cast<BinaryOperator>(Inst)) 877 Changed |= VisitBinaryOperator(BinOp); 878 if (auto *UnOp = dyn_cast<UnaryOperator>(Inst)) 879 Changed |= VisitUnaryOperator(UnOp); 880 if (match(Inst, m_Load(m_Value(Op1)))) 881 Changed |= VisitLoad(cast<LoadInst>(Inst), Op1, Builder); 882 else if (match(Inst, m_Store(m_Value(Op1), m_Value(Op2)))) 883 Changed |= VisitStore(cast<StoreInst>(Inst), Op1, Op2, Builder); 884 } 885 886 if (ORE) { 887 RemarkGenerator RemarkGen(Inst2ColumnMatrix, *ORE, Func); 888 RemarkGen.emitRemarks(); 889 } 890 891 // Delete the instructions backwards, as it has a reduced likelihood of 892 // having to update as many def-use and use-def chains. 893 // 894 // Because we add to ToRemove during fusion we can't guarantee that defs 895 // are before uses. Change uses to undef temporarily as these should get 896 // removed as well. 897 // 898 // For verification, we keep track of where we changed uses to undefs in 899 // UndefedInsts and then check that we in fact remove them. 900 SmallSet<Instruction *, 16> UndefedInsts; 901 for (auto *Inst : reverse(ToRemove)) { 902 for (auto I = Inst->use_begin(), E = Inst->use_end(); I != E;) { 903 Use &U = *I++; 904 if (auto *Undefed = dyn_cast<Instruction>(U.getUser())) 905 UndefedInsts.insert(Undefed); 906 U.set(UndefValue::get(Inst->getType())); 907 } 908 Inst->eraseFromParent(); 909 UndefedInsts.erase(Inst); 910 } 911 if (!UndefedInsts.empty()) { 912 // If we didn't remove all undefed instructions, it's a hard error. 913 dbgs() << "Undefed but present instructions:\n"; 914 for (auto *I : UndefedInsts) 915 dbgs() << *I << "\n"; 916 llvm_unreachable("Undefed but instruction not removed"); 917 } 918 919 return Changed; 920 } 921 922 /// Turns \p BasePtr into an elementwise pointer to \p EltType. 923 Value *createElementPtr(Value *BasePtr, Type *EltType, IRBuilder<> &Builder) { 924 unsigned AS = cast<PointerType>(BasePtr->getType())->getAddressSpace(); 925 Type *EltPtrType = PointerType::get(EltType, AS); 926 return Builder.CreatePointerCast(BasePtr, EltPtrType); 927 } 928 929 /// Replace intrinsic calls 930 bool VisitCallInst(CallInst *Inst) { 931 if (!Inst->getCalledFunction() || !Inst->getCalledFunction()->isIntrinsic()) 932 return false; 933 934 switch (Inst->getCalledFunction()->getIntrinsicID()) { 935 case Intrinsic::matrix_multiply: 936 LowerMultiply(Inst); 937 break; 938 case Intrinsic::matrix_transpose: 939 LowerTranspose(Inst); 940 break; 941 case Intrinsic::matrix_column_major_load: 942 LowerColumnMajorLoad(Inst); 943 break; 944 case Intrinsic::matrix_column_major_store: 945 LowerColumnMajorStore(Inst); 946 break; 947 default: 948 return false; 949 } 950 return true; 951 } 952 953 /// Compute the alignment for a column/row \p Idx with \p Stride between them. 954 /// The address at \p Idx == 0 has alignment \p A. If \p Stride is a 955 /// ConstantInt, reduce the initial alignment based on the byte offset. For 956 /// non-ConstantInt strides, return the common alignment of the initial 957 /// alignment and the element size in bytes. 958 Align getAlignForIndex(unsigned Idx, Value *Stride, Type *ElementTy, 959 MaybeAlign A) const { 960 Align InitialAlign = DL.getValueOrABITypeAlignment(A, ElementTy); 961 if (Idx == 0) 962 return InitialAlign; 963 964 TypeSize ElementSizeInBits = DL.getTypeSizeInBits(ElementTy); 965 if (auto *ConstStride = dyn_cast<ConstantInt>(Stride)) { 966 uint64_t StrideInBytes = 967 ConstStride->getZExtValue() * ElementSizeInBits / 8; 968 return commonAlignment(InitialAlign, Idx * StrideInBytes); 969 } 970 return commonAlignment(InitialAlign, ElementSizeInBits / 8); 971 } 972 973 /// Load a matrix with \p Shape starting at \p Ptr and using \p Stride between 974 /// vectors. 975 MatrixTy loadMatrix(Type *Ty, Value *Ptr, MaybeAlign MAlign, Value *Stride, 976 bool IsVolatile, ShapeInfo Shape, IRBuilder<> &Builder) { 977 auto *VType = cast<VectorType>(Ty); 978 Type *EltTy = VType->getElementType(); 979 Type *VecTy = FixedVectorType::get(EltTy, Shape.getStride()); 980 Value *EltPtr = createElementPtr(Ptr, EltTy, Builder); 981 MatrixTy Result; 982 for (unsigned I = 0, E = Shape.getNumVectors(); I < E; ++I) { 983 Value *GEP = computeVectorAddr(EltPtr, Builder.getInt64(I), Stride, 984 Shape.getStride(), EltTy, Builder); 985 Value *Vector = Builder.CreateAlignedLoad( 986 VecTy, GEP, getAlignForIndex(I, Stride, EltTy, MAlign), 987 IsVolatile, "col.load"); 988 989 Result.addVector(Vector); 990 } 991 return Result.addNumLoads(getNumOps(Result.getVectorTy()) * 992 Result.getNumVectors()); 993 } 994 995 /// Loads a sub-matrix with shape \p ResultShape from a \p R x \p C matrix, 996 /// starting at \p MatrixPtr[I][J]. 997 MatrixTy loadMatrix(Value *MatrixPtr, MaybeAlign Align, bool IsVolatile, 998 ShapeInfo MatrixShape, Value *I, Value *J, 999 ShapeInfo ResultShape, Type *EltTy, 1000 IRBuilder<> &Builder) { 1001 1002 Value *Offset = Builder.CreateAdd( 1003 Builder.CreateMul(J, Builder.getInt64(MatrixShape.getStride())), I); 1004 1005 unsigned AS = cast<PointerType>(MatrixPtr->getType())->getAddressSpace(); 1006 Value *EltPtr = 1007 Builder.CreatePointerCast(MatrixPtr, PointerType::get(EltTy, AS)); 1008 Value *TileStart = Builder.CreateGEP(EltTy, EltPtr, Offset); 1009 auto *TileTy = FixedVectorType::get(EltTy, ResultShape.NumRows * 1010 ResultShape.NumColumns); 1011 Type *TilePtrTy = PointerType::get(TileTy, AS); 1012 Value *TilePtr = 1013 Builder.CreatePointerCast(TileStart, TilePtrTy, "col.cast"); 1014 1015 return loadMatrix(TileTy, TilePtr, Align, 1016 Builder.getInt64(MatrixShape.getStride()), IsVolatile, 1017 ResultShape, Builder); 1018 } 1019 1020 /// Lower a load instruction with shape information. 1021 void LowerLoad(Instruction *Inst, Value *Ptr, MaybeAlign Align, Value *Stride, 1022 bool IsVolatile, ShapeInfo Shape) { 1023 IRBuilder<> Builder(Inst); 1024 finalizeLowering(Inst, 1025 loadMatrix(Inst->getType(), Ptr, Align, Stride, IsVolatile, 1026 Shape, Builder), 1027 Builder); 1028 } 1029 1030 /// Lowers llvm.matrix.column.major.load. 1031 /// 1032 /// The intrinsic loads a matrix from memory using a stride between columns. 1033 void LowerColumnMajorLoad(CallInst *Inst) { 1034 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 1035 "Intrinsic only supports column-major layout!"); 1036 Value *Ptr = Inst->getArgOperand(0); 1037 Value *Stride = Inst->getArgOperand(1); 1038 LowerLoad(Inst, Ptr, Inst->getParamAlign(0), Stride, 1039 cast<ConstantInt>(Inst->getArgOperand(2))->isOne(), 1040 {Inst->getArgOperand(3), Inst->getArgOperand(4)}); 1041 } 1042 1043 /// Stores a sub-matrix \p StoreVal into the \p R x \p C matrix starting at \p 1044 /// MatrixPtr[I][J]. 1045 void storeMatrix(const MatrixTy &StoreVal, Value *MatrixPtr, 1046 MaybeAlign MAlign, bool IsVolatile, ShapeInfo MatrixShape, 1047 Value *I, Value *J, Type *EltTy, IRBuilder<> &Builder) { 1048 Value *Offset = Builder.CreateAdd( 1049 Builder.CreateMul(J, Builder.getInt64(MatrixShape.getStride())), I); 1050 1051 unsigned AS = cast<PointerType>(MatrixPtr->getType())->getAddressSpace(); 1052 Value *EltPtr = 1053 Builder.CreatePointerCast(MatrixPtr, PointerType::get(EltTy, AS)); 1054 Value *TileStart = Builder.CreateGEP(EltTy, EltPtr, Offset); 1055 auto *TileTy = FixedVectorType::get(EltTy, StoreVal.getNumRows() * 1056 StoreVal.getNumColumns()); 1057 Type *TilePtrTy = PointerType::get(TileTy, AS); 1058 Value *TilePtr = 1059 Builder.CreatePointerCast(TileStart, TilePtrTy, "col.cast"); 1060 1061 storeMatrix(TileTy, StoreVal, TilePtr, MAlign, 1062 Builder.getInt64(MatrixShape.getStride()), IsVolatile, Builder); 1063 } 1064 1065 /// Store matrix \p StoreVal starting at \p Ptr and using \p Stride between 1066 /// vectors. 1067 MatrixTy storeMatrix(Type *Ty, MatrixTy StoreVal, Value *Ptr, 1068 MaybeAlign MAlign, Value *Stride, bool IsVolatile, 1069 IRBuilder<> &Builder) { 1070 auto VType = cast<VectorType>(Ty); 1071 Value *EltPtr = createElementPtr(Ptr, VType->getElementType(), Builder); 1072 for (auto Vec : enumerate(StoreVal.vectors())) { 1073 Value *GEP = computeVectorAddr(EltPtr, Builder.getInt64(Vec.index()), 1074 Stride, StoreVal.getStride(), 1075 VType->getElementType(), Builder); 1076 Builder.CreateAlignedStore(Vec.value(), GEP, 1077 getAlignForIndex(Vec.index(), Stride, 1078 VType->getElementType(), 1079 MAlign), 1080 IsVolatile); 1081 } 1082 return MatrixTy().addNumStores(getNumOps(StoreVal.getVectorTy()) * 1083 StoreVal.getNumVectors()); 1084 } 1085 1086 /// Lower a store instruction with shape information. 1087 void LowerStore(Instruction *Inst, Value *Matrix, Value *Ptr, MaybeAlign A, 1088 Value *Stride, bool IsVolatile, ShapeInfo Shape) { 1089 IRBuilder<> Builder(Inst); 1090 auto StoreVal = getMatrix(Matrix, Shape, Builder); 1091 finalizeLowering(Inst, 1092 storeMatrix(Matrix->getType(), StoreVal, Ptr, A, Stride, 1093 IsVolatile, Builder), 1094 Builder); 1095 } 1096 1097 /// Lowers llvm.matrix.column.major.store. 1098 /// 1099 /// The intrinsic store a matrix back memory using a stride between columns. 1100 void LowerColumnMajorStore(CallInst *Inst) { 1101 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 1102 "Intrinsic only supports column-major layout!"); 1103 Value *Matrix = Inst->getArgOperand(0); 1104 Value *Ptr = Inst->getArgOperand(1); 1105 Value *Stride = Inst->getArgOperand(2); 1106 LowerStore(Inst, Matrix, Ptr, Inst->getParamAlign(1), Stride, 1107 cast<ConstantInt>(Inst->getArgOperand(3))->isOne(), 1108 {Inst->getArgOperand(4), Inst->getArgOperand(5)}); 1109 } 1110 1111 // Set elements I..I+NumElts-1 to Block 1112 Value *insertVector(Value *Col, unsigned I, Value *Block, 1113 IRBuilder<> &Builder) { 1114 1115 // First, bring Block to the same size as Col 1116 unsigned BlockNumElts = 1117 cast<FixedVectorType>(Block->getType())->getNumElements(); 1118 unsigned NumElts = cast<FixedVectorType>(Col->getType())->getNumElements(); 1119 assert(NumElts >= BlockNumElts && "Too few elements for current block"); 1120 1121 Block = Builder.CreateShuffleVector( 1122 Block, createSequentialMask(0, BlockNumElts, NumElts - BlockNumElts)); 1123 1124 // If Col is 7 long and I is 2 and BlockNumElts is 2 the mask is: 0, 1, 7, 1125 // 8, 4, 5, 6 1126 SmallVector<int, 16> Mask; 1127 unsigned i; 1128 for (i = 0; i < I; i++) 1129 Mask.push_back(i); 1130 1131 unsigned VecNumElts = 1132 cast<FixedVectorType>(Col->getType())->getNumElements(); 1133 for (; i < I + BlockNumElts; i++) 1134 Mask.push_back(i - I + VecNumElts); 1135 1136 for (; i < VecNumElts; i++) 1137 Mask.push_back(i); 1138 1139 return Builder.CreateShuffleVector(Col, Block, Mask); 1140 } 1141 1142 Value *createMulAdd(Value *Sum, Value *A, Value *B, bool UseFPOp, 1143 IRBuilder<> &Builder, bool AllowContraction, 1144 unsigned &NumComputeOps) { 1145 NumComputeOps += getNumOps(A->getType()); 1146 if (!Sum) 1147 return UseFPOp ? Builder.CreateFMul(A, B) : Builder.CreateMul(A, B); 1148 1149 if (UseFPOp) { 1150 if (AllowContraction) { 1151 // Use fmuladd for floating point operations and let the backend decide 1152 // if that's profitable. 1153 Function *FMulAdd = Intrinsic::getDeclaration( 1154 Func.getParent(), Intrinsic::fmuladd, A->getType()); 1155 return Builder.CreateCall(FMulAdd, {A, B, Sum}); 1156 } 1157 NumComputeOps += getNumOps(A->getType()); 1158 Value *Mul = Builder.CreateFMul(A, B); 1159 return Builder.CreateFAdd(Sum, Mul); 1160 } 1161 1162 NumComputeOps += getNumOps(A->getType()); 1163 Value *Mul = Builder.CreateMul(A, B); 1164 return Builder.CreateAdd(Sum, Mul); 1165 } 1166 1167 /// Cache \p Matrix as result of \p Inst and update the uses of \p Inst. For 1168 /// users with shape information, there's nothing to do: they will use the 1169 /// cached value when they are lowered. For other users, \p Matrix is 1170 /// flattened and the uses are updated to use it. Also marks \p Inst for 1171 /// deletion. 1172 void finalizeLowering(Instruction *Inst, MatrixTy Matrix, 1173 IRBuilder<> &Builder) { 1174 auto inserted = Inst2ColumnMatrix.insert(std::make_pair(Inst, Matrix)); 1175 (void)inserted; 1176 assert(inserted.second && "multiple matrix lowering mapping"); 1177 1178 ToRemove.push_back(Inst); 1179 Value *Flattened = nullptr; 1180 for (Use &U : llvm::make_early_inc_range(Inst->uses())) { 1181 if (ShapeMap.find(U.getUser()) == ShapeMap.end()) { 1182 if (!Flattened) 1183 Flattened = Matrix.embedInVector(Builder); 1184 U.set(Flattened); 1185 } 1186 } 1187 } 1188 1189 /// Compute \p Result += \p A * \p B for input matrices with left-associating 1190 /// addition. 1191 /// 1192 /// We can fold a transpose into the operand that is used to extract scalars. 1193 /// This is the first operands with row-major and the second with 1194 /// column-major. If \p IsScalarMatrixTransposed we assume the appropriate 1195 /// operand is transposed. 1196 void emitMatrixMultiply(MatrixTy &Result, const MatrixTy &A, 1197 const MatrixTy &B, IRBuilder<> &Builder, bool IsTiled, 1198 bool IsScalarMatrixTransposed, FastMathFlags FMF) { 1199 const unsigned VF = std::max<unsigned>( 1200 TTI.getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 1201 .getFixedSize() / 1202 Result.getElementType()->getPrimitiveSizeInBits().getFixedSize(), 1203 1U); 1204 unsigned R = Result.getNumRows(); 1205 unsigned C = Result.getNumColumns(); 1206 unsigned M = A.getNumColumns(); 1207 1208 bool IsFP = Result.getElementType()->isFloatingPointTy(); 1209 assert(A.isColumnMajor() == B.isColumnMajor() && 1210 Result.isColumnMajor() == A.isColumnMajor() && 1211 "operands must agree on matrix layout"); 1212 unsigned NumComputeOps = 0; 1213 1214 Builder.setFastMathFlags(FMF); 1215 1216 if (A.isColumnMajor()) { 1217 // Multiply columns from the first operand with scalars from the second 1218 // operand. Then move along the K axes and accumulate the columns. With 1219 // this the adds can be vectorized without reassociation. 1220 for (unsigned J = 0; J < C; ++J) { 1221 unsigned BlockSize = VF; 1222 // If Result is zero, we don't need to accumulate in the K==0 iteration. 1223 bool isSumZero = isa<ConstantAggregateZero>(Result.getColumn(J)); 1224 1225 for (unsigned I = 0; I < R; I += BlockSize) { 1226 // Gradually lower the vectorization factor to cover the remainder. 1227 while (I + BlockSize > R) 1228 BlockSize /= 2; 1229 1230 Value *Sum = IsTiled ? Result.extractVector(I, J, BlockSize, Builder) 1231 : nullptr; 1232 for (unsigned K = 0; K < M; ++K) { 1233 Value *L = A.extractVector(I, K, BlockSize, Builder); 1234 Value *RH = Builder.CreateExtractElement( 1235 B.getColumn(IsScalarMatrixTransposed ? K : J), 1236 IsScalarMatrixTransposed ? J : K); 1237 Value *Splat = Builder.CreateVectorSplat(BlockSize, RH, "splat"); 1238 Sum = 1239 createMulAdd(isSumZero && K == 0 ? nullptr : Sum, L, Splat, 1240 IsFP, Builder, FMF.allowContract(), NumComputeOps); 1241 } 1242 Result.setVector(J, 1243 insertVector(Result.getVector(J), I, Sum, Builder)); 1244 } 1245 } 1246 } else { 1247 // Multiply rows from the second operand with scalars from the first 1248 // operand. Then move along the K axes and accumulate the rows. With this 1249 // the adds can be vectorized without reassociation. 1250 for (unsigned I = 0; I < R; ++I) { 1251 unsigned BlockSize = VF; 1252 bool isSumZero = isa<ConstantAggregateZero>(Result.getRow(I)); 1253 for (unsigned J = 0; J < C; J += BlockSize) { 1254 // Gradually lower the vectorization factor to cover the remainder. 1255 while (J + BlockSize > C) 1256 BlockSize /= 2; 1257 1258 Value *Sum = nullptr; 1259 for (unsigned K = 0; K < M; ++K) { 1260 Value *R = B.extractVector(K, J, BlockSize, Builder); 1261 Value *LH = Builder.CreateExtractElement( 1262 A.getVector(IsScalarMatrixTransposed ? K : I), 1263 IsScalarMatrixTransposed ? I : K); 1264 Value *Splat = Builder.CreateVectorSplat(BlockSize, LH, "splat"); 1265 Sum = 1266 createMulAdd(isSumZero && K == 0 ? nullptr : Sum, Splat, R, 1267 IsFP, Builder, FMF.allowContract(), NumComputeOps); 1268 } 1269 Result.setVector(I, 1270 insertVector(Result.getVector(I), J, Sum, Builder)); 1271 } 1272 } 1273 } 1274 Result.addNumComputeOps(NumComputeOps); 1275 } 1276 1277 /// Ensure that the memory in \p Load does not alias \p Store by potentially 1278 /// copying it to a new location. This new or otherwise the original location 1279 /// is returned. 1280 Value *getNonAliasingPointer(LoadInst *Load, StoreInst *Store, 1281 CallInst *MatMul) { 1282 MemoryLocation StoreLoc = MemoryLocation::get(Store); 1283 MemoryLocation LoadLoc = MemoryLocation::get(Load); 1284 1285 // If we can statically determine noalias we're good. 1286 if (AA->isNoAlias(LoadLoc, StoreLoc)) 1287 return Load->getPointerOperand(); 1288 1289 // Create code to check if the memory locations of the Load and Store 1290 // overlap and if they do, copy Load's operand to a new buffer. 1291 1292 // First, create new blocks for 2n part of the check and the copy. 1293 BasicBlock *Check0 = MatMul->getParent(); 1294 // FIXME: Use lazy DTU and update SplitBlock to accept a DTU instead of a 1295 // DT. Manually collect dominator tree updates, to avoid unnecessary work, 1296 // as we adjust Check0 and Check1's branches. 1297 SmallVector<DominatorTree::UpdateType, 4> DTUpdates; 1298 for (BasicBlock *Succ : successors(Check0)) 1299 DTUpdates.push_back({DT->Delete, Check0, Succ}); 1300 1301 BasicBlock *Check1 = 1302 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1303 nullptr, "alias_cont"); 1304 BasicBlock *Copy = 1305 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1306 nullptr, "copy"); 1307 BasicBlock *Fusion = 1308 SplitBlock(MatMul->getParent(), MatMul, (DomTreeUpdater *)nullptr, LI, 1309 nullptr, "no_alias"); 1310 1311 // Check if the loaded memory location begins before the end of the store 1312 // location. If the condition holds, they might overlap, otherwise they are 1313 // guaranteed to not overlap. 1314 IRBuilder<> Builder(MatMul); 1315 Check0->getTerminator()->eraseFromParent(); 1316 Builder.SetInsertPoint(Check0); 1317 Type *IntPtrTy = Builder.getIntPtrTy(Load->getModule()->getDataLayout()); 1318 Value *StoreBegin = Builder.CreatePtrToInt( 1319 const_cast<Value *>(StoreLoc.Ptr), IntPtrTy, "store.begin"); 1320 Value *StoreEnd = Builder.CreateAdd( 1321 StoreBegin, ConstantInt::get(IntPtrTy, StoreLoc.Size.getValue()), 1322 "store.end", true, true); 1323 Value *LoadBegin = Builder.CreatePtrToInt(const_cast<Value *>(LoadLoc.Ptr), 1324 IntPtrTy, "load.begin"); 1325 Builder.CreateCondBr(Builder.CreateICmpULT(LoadBegin, StoreEnd), Check1, 1326 Fusion); 1327 1328 // Check if the store begins before the end of the load location. If the 1329 // condition holds, they alias, otherwise they are guaranteed to not 1330 // overlap. 1331 Check1->getTerminator()->eraseFromParent(); 1332 Builder.SetInsertPoint(Check1, Check1->begin()); 1333 Value *LoadEnd = Builder.CreateAdd( 1334 LoadBegin, ConstantInt::get(IntPtrTy, LoadLoc.Size.getValue()), 1335 "load.end", true, true); 1336 Builder.CreateCondBr(Builder.CreateICmpULT(StoreBegin, LoadEnd), Copy, 1337 Fusion); 1338 1339 // Copy load operand to new alloca. 1340 Builder.SetInsertPoint(Copy, Copy->begin()); 1341 AllocaInst *NewLd = 1342 Builder.CreateAlloca(Load->getType(), Load->getPointerAddressSpace()); 1343 Builder.CreateMemCpy(NewLd, NewLd->getAlign(), 1344 Load->getPointerOperand(), Load->getAlign(), 1345 LoadLoc.Size.getValue()); 1346 Builder.SetInsertPoint(Fusion, Fusion->begin()); 1347 PHINode *PHI = Builder.CreatePHI(Load->getPointerOperandType(), 3); 1348 PHI->addIncoming(Load->getPointerOperand(), Check0); 1349 PHI->addIncoming(Load->getPointerOperand(), Check1); 1350 PHI->addIncoming(NewLd, Copy); 1351 1352 // Adjust DT. 1353 DTUpdates.push_back({DT->Insert, Check0, Check1}); 1354 DTUpdates.push_back({DT->Insert, Check0, Fusion}); 1355 DTUpdates.push_back({DT->Insert, Check1, Copy}); 1356 DTUpdates.push_back({DT->Insert, Check1, Fusion}); 1357 DT->applyUpdates(DTUpdates); 1358 return PHI; 1359 } 1360 1361 bool isFusionProfitable(CallInst *MatMul) { 1362 if (ForceFusion) 1363 return true; 1364 1365 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1366 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1367 1368 const unsigned R = LShape.NumRows; 1369 const unsigned C = RShape.NumColumns; 1370 const unsigned M = LShape.NumColumns; 1371 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1372 1373 const unsigned VF = std::max<unsigned>( 1374 TTI.getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 1375 .getFixedSize() / 1376 EltType->getPrimitiveSizeInBits().getFixedSize(), 1377 1U); 1378 1379 // Cost model for tiling 1380 // 1381 // For tiling to be beneficial, we need reuse either along the R or 1382 // the C axis. We vectorize along the R axis so that means at least 1383 // 3 elements. 1384 // TODO: Also consider cost of copying if operands alias. 1385 if (R <= VF && C == 1) 1386 return false; 1387 // Then we need enough elements to exceed the number of vector 1388 // registers we have. Note that this is an oversimplification since 1389 // fusing also takes some extra loads which may exceed the number of 1390 // reloads necessary. 1391 unsigned Op0Regs = (R + VF - 1) / VF * M; 1392 unsigned Op1Regs = (M + VF - 1) / VF * C; 1393 return Op0Regs + Op1Regs > TTI.getNumberOfRegisters(true); 1394 } 1395 1396 MatrixTy getZeroMatrix(Type *EltType, unsigned R, unsigned C) { 1397 MatrixTy Res; 1398 auto *ColumType = FixedVectorType::get(EltType, R); 1399 for (unsigned I = 0; I < C; ++I) 1400 Res.addVector(ConstantAggregateZero::get(ColumType)); 1401 return Res; 1402 } 1403 1404 void createTiledLoops(CallInst *MatMul, Value *LPtr, ShapeInfo LShape, 1405 Value *RPtr, ShapeInfo RShape, StoreInst *Store) { 1406 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1407 1408 // Create the main tiling loop nest. 1409 TileInfo TI(LShape.NumRows, RShape.NumColumns, LShape.NumColumns, TileSize); 1410 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 1411 Instruction *InsertI = cast<Instruction>(MatMul); 1412 BasicBlock *Start = InsertI->getParent(); 1413 BasicBlock *End = 1414 SplitBlock(InsertI->getParent(), InsertI, DT, LI, nullptr, "continue"); 1415 IRBuilder<> Builder(MatMul); 1416 BasicBlock *InnerBody = TI.CreateTiledLoops(Start, End, Builder, DTU, *LI); 1417 1418 Type *TileVecTy = 1419 FixedVectorType::get(MatMul->getType()->getScalarType(), TileSize); 1420 MatrixTy TileResult; 1421 // Insert in the inner loop header. 1422 Builder.SetInsertPoint(TI.InnerLoopHeader->getTerminator()); 1423 // Create PHI nodes for the result columns to accumulate across iterations. 1424 SmallVector<PHINode *, 4> ColumnPhis; 1425 for (unsigned I = 0; I < TileSize; I++) { 1426 auto *Phi = Builder.CreatePHI(TileVecTy, 2, "result.vec." + Twine(I)); 1427 Phi->addIncoming(ConstantAggregateZero::get(TileVecTy), 1428 TI.RowLoopHeader->getSingleSuccessor()); 1429 TileResult.addVector(Phi); 1430 ColumnPhis.push_back(Phi); 1431 } 1432 1433 // Insert in the inner loop body, which computes 1434 // Res += Load(CurrentRow, K) * Load(K, CurrentColumn) 1435 Builder.SetInsertPoint(InnerBody->getTerminator()); 1436 // Load tiles of the operands. 1437 MatrixTy A = loadMatrix(LPtr, {}, false, LShape, TI.CurrentRow, TI.CurrentK, 1438 {TileSize, TileSize}, EltType, Builder); 1439 MatrixTy B = loadMatrix(RPtr, {}, false, RShape, TI.CurrentK, TI.CurrentCol, 1440 {TileSize, TileSize}, EltType, Builder); 1441 emitMatrixMultiply(TileResult, A, B, Builder, true, false, 1442 getFastMathFlags(MatMul)); 1443 // Store result after the inner loop is done. 1444 Builder.SetInsertPoint(TI.RowLoopLatch->getTerminator()); 1445 storeMatrix(TileResult, Store->getPointerOperand(), Store->getAlign(), 1446 Store->isVolatile(), {LShape.NumRows, RShape.NumColumns}, 1447 TI.CurrentRow, TI.CurrentCol, EltType, Builder); 1448 1449 for (unsigned I = 0; I < TileResult.getNumVectors(); I++) 1450 ColumnPhis[I]->addIncoming(TileResult.getVector(I), TI.InnerLoopLatch); 1451 1452 // Force unrolling of a few iterations of the inner loop, to make sure there 1453 // is enough work per iteration. 1454 // FIXME: The unroller should make this decision directly instead, but 1455 // currently the cost-model is not up to the task. 1456 unsigned InnerLoopUnrollCount = std::min(10u, LShape.NumColumns / TileSize); 1457 addStringMetadataToLoop(LI->getLoopFor(TI.InnerLoopHeader), 1458 "llvm.loop.unroll.count", InnerLoopUnrollCount); 1459 } 1460 1461 void emitSIMDTiling(CallInst *MatMul, LoadInst *LoadOp0, LoadInst *LoadOp1, 1462 StoreInst *Store, 1463 SmallPtrSetImpl<Instruction *> &FusedInsts) { 1464 assert(MatrixLayout == MatrixLayoutTy::ColumnMajor && 1465 "Tiling only supported for column-major matrixes at the moment!"); 1466 if (!isFusionProfitable(MatMul)) 1467 return; 1468 1469 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1470 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1471 1472 const unsigned R = LShape.NumRows; 1473 const unsigned C = RShape.NumColumns; 1474 const unsigned M = LShape.NumColumns; 1475 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1476 1477 Value *APtr = getNonAliasingPointer(LoadOp0, Store, MatMul); 1478 Value *BPtr = getNonAliasingPointer(LoadOp1, Store, MatMul); 1479 Value *CPtr = Store->getPointerOperand(); 1480 1481 if (TileUseLoops && (R % TileSize == 0 && C % TileSize == 0)) 1482 createTiledLoops(MatMul, APtr, LShape, BPtr, RShape, Store); 1483 else { 1484 IRBuilder<> Builder(Store); 1485 for (unsigned J = 0; J < C; J += TileSize) 1486 for (unsigned I = 0; I < R; I += TileSize) { 1487 const unsigned TileR = std::min(R - I, unsigned(TileSize)); 1488 const unsigned TileC = std::min(C - J, unsigned(TileSize)); 1489 MatrixTy Res = getZeroMatrix(EltType, TileR, TileC); 1490 1491 for (unsigned K = 0; K < M; K += TileSize) { 1492 const unsigned TileM = std::min(M - K, unsigned(TileSize)); 1493 MatrixTy A = 1494 loadMatrix(APtr, LoadOp0->getAlign(), LoadOp0->isVolatile(), 1495 LShape, Builder.getInt64(I), Builder.getInt64(K), 1496 {TileR, TileM}, EltType, Builder); 1497 MatrixTy B = 1498 loadMatrix(BPtr, LoadOp1->getAlign(), LoadOp1->isVolatile(), 1499 RShape, Builder.getInt64(K), Builder.getInt64(J), 1500 {TileM, TileC}, EltType, Builder); 1501 emitMatrixMultiply(Res, A, B, Builder, true, false, 1502 getFastMathFlags(MatMul)); 1503 } 1504 storeMatrix(Res, CPtr, Store->getAlign(), Store->isVolatile(), {R, M}, 1505 Builder.getInt64(I), Builder.getInt64(J), EltType, 1506 Builder); 1507 } 1508 } 1509 1510 // Mark eliminated instructions as fused and remove them. 1511 FusedInsts.insert(Store); 1512 FusedInsts.insert(MatMul); 1513 Store->eraseFromParent(); 1514 MatMul->eraseFromParent(); 1515 if (LoadOp0->hasNUses(0)) { 1516 FusedInsts.insert(LoadOp0); 1517 LoadOp0->eraseFromParent(); 1518 } 1519 if (LoadOp1 != LoadOp0 && LoadOp1->hasNUses(0)) { 1520 FusedInsts.insert(LoadOp1); 1521 LoadOp1->eraseFromParent(); 1522 } 1523 } 1524 1525 /// Try to lower matrix multiply chains by fusing operations. 1526 /// 1527 /// Call finalizeLowering on lowered instructions. Instructions that are 1528 /// completely eliminated by fusion are added to \p FusedInsts. 1529 void LowerMatrixMultiplyFused(CallInst *MatMul, 1530 SmallPtrSetImpl<Instruction *> &FusedInsts) { 1531 if (!FuseMatrix || !DT) 1532 return; 1533 1534 assert(AA && LI && "Analyses should be available"); 1535 1536 Value *A = MatMul->getArgOperand(0); 1537 Value *B = MatMul->getArgOperand(1); 1538 1539 // We can fold the transpose into the operand that is used to fetch scalars. 1540 Value *T; 1541 if (MatrixLayout == MatrixLayoutTy::ColumnMajor 1542 ? match(B, m_Intrinsic<Intrinsic::matrix_transpose>(m_Value(T))) 1543 : match(A, m_Intrinsic<Intrinsic::matrix_transpose>(m_Value(T)))) { 1544 IRBuilder<> Builder(MatMul); 1545 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1546 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1547 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1548 const unsigned R = LShape.NumRows; 1549 const unsigned M = LShape.NumColumns; 1550 const unsigned C = RShape.NumColumns; 1551 1552 MatrixTy MA; 1553 MatrixTy MB; 1554 1555 Value *Transpose; 1556 if (MatrixLayout == MatrixLayoutTy::ColumnMajor) { 1557 MA = getMatrix(A, ShapeInfo(R, M), Builder); 1558 MB = getMatrix(T, ShapeInfo(C, M), Builder); 1559 Transpose = B; 1560 } else { 1561 MA = getMatrix(T, ShapeInfo(R, M), Builder); 1562 MB = getMatrix(B, ShapeInfo(C, M), Builder); 1563 Transpose = A; 1564 } 1565 1566 // Initialize the output 1567 MatrixTy Result(R, C, EltType); 1568 1569 emitMatrixMultiply(Result, MA, MB, Builder, false, true, 1570 getFastMathFlags(MatMul)); 1571 1572 FusedInsts.insert(MatMul); 1573 if (Transpose->hasOneUse()) { 1574 FusedInsts.insert(cast<Instruction>(Transpose)); 1575 ToRemove.push_back(cast<Instruction>(Transpose)); 1576 // TODO: add a fake entry for the folded instruction so that this is 1577 // included in the expression in the remark. 1578 Inst2ColumnMatrix[Transpose] = MatrixTy(M, C, EltType); 1579 } 1580 finalizeLowering(MatMul, Result, Builder); 1581 return; 1582 } 1583 1584 if (!MatMul->hasOneUse() || MatrixLayout != MatrixLayoutTy::ColumnMajor) 1585 return; 1586 1587 // Lower {ld, ld} -> matmul -> st chains. No need to call finalizeLowering 1588 // since the single store user will be lowered as part of this. 1589 auto *LoadOp0 = dyn_cast<LoadInst>(A); 1590 auto *LoadOp1 = dyn_cast<LoadInst>(B); 1591 auto *Store = dyn_cast<StoreInst>(*MatMul->user_begin()); 1592 if (LoadOp0 && LoadOp1 && Store) { 1593 // The store address must dominate the MatMul instruction, otherwise 1594 // we create invalid IR. 1595 SetVector<Value *> WorkList; 1596 WorkList.insert(Store->getOperand(1)); 1597 SmallVector<Instruction *> ToHoist; 1598 for (unsigned I = 0; I != WorkList.size(); ++I) { 1599 Value *Current = WorkList[I]; 1600 auto *CurrI = dyn_cast<Instruction>(Current); 1601 if (!CurrI) 1602 continue; 1603 if (isa<PHINode>(CurrI)) 1604 return; 1605 if (DT->dominates(CurrI, MatMul)) 1606 continue; 1607 if (CurrI->mayHaveSideEffects() || CurrI->mayReadFromMemory()) 1608 return; 1609 ToHoist.push_back(CurrI); 1610 WorkList.insert(CurrI->op_begin(), CurrI->op_end()); 1611 } 1612 1613 sort(ToHoist, [this](Instruction *A, Instruction *B) { 1614 return DT->dominates(A, B); 1615 }); 1616 for (Instruction *I : ToHoist) 1617 I->moveBefore(MatMul); 1618 1619 emitSIMDTiling(MatMul, LoadOp0, LoadOp1, Store, FusedInsts); 1620 return; 1621 } 1622 } 1623 1624 /// Lowers llvm.matrix.multiply. 1625 void LowerMultiply(CallInst *MatMul) { 1626 IRBuilder<> Builder(MatMul); 1627 auto *EltType = cast<VectorType>(MatMul->getType())->getElementType(); 1628 ShapeInfo LShape(MatMul->getArgOperand(2), MatMul->getArgOperand(3)); 1629 ShapeInfo RShape(MatMul->getArgOperand(3), MatMul->getArgOperand(4)); 1630 1631 const MatrixTy &Lhs = getMatrix(MatMul->getArgOperand(0), LShape, Builder); 1632 const MatrixTy &Rhs = getMatrix(MatMul->getArgOperand(1), RShape, Builder); 1633 assert(Lhs.getElementType() == Rhs.getElementType() && 1634 "Matrix multiply argument element types do not match."); 1635 1636 const unsigned R = LShape.NumRows; 1637 const unsigned C = RShape.NumColumns; 1638 assert(LShape.NumColumns == RShape.NumRows); 1639 1640 // Initialize the output 1641 MatrixTy Result(R, C, EltType); 1642 assert(Lhs.getElementType() == Result.getElementType() && 1643 "Matrix multiply result element type does not match arguments."); 1644 1645 emitMatrixMultiply(Result, Lhs, Rhs, Builder, false, false, 1646 getFastMathFlags(MatMul)); 1647 finalizeLowering(MatMul, Result, Builder); 1648 } 1649 1650 /// Lowers llvm.matrix.transpose. 1651 void LowerTranspose(CallInst *Inst) { 1652 MatrixTy Result; 1653 IRBuilder<> Builder(Inst); 1654 Value *InputVal = Inst->getArgOperand(0); 1655 VectorType *VectorTy = cast<VectorType>(InputVal->getType()); 1656 ShapeInfo ArgShape(Inst->getArgOperand(1), Inst->getArgOperand(2)); 1657 MatrixTy InputMatrix = getMatrix(InputVal, ArgShape, Builder); 1658 1659 const unsigned NewNumVecs = 1660 InputMatrix.isColumnMajor() ? ArgShape.NumRows : ArgShape.NumColumns; 1661 const unsigned NewNumElts = 1662 InputMatrix.isColumnMajor() ? ArgShape.NumColumns : ArgShape.NumRows; 1663 1664 for (unsigned I = 0; I < NewNumVecs; ++I) { 1665 // Build a single result vector. First initialize it. 1666 Value *ResultVector = UndefValue::get( 1667 FixedVectorType::get(VectorTy->getElementType(), NewNumElts)); 1668 // Go through the old elements and insert it into the resulting vector. 1669 for (auto J : enumerate(InputMatrix.vectors())) { 1670 Value *Elt = Builder.CreateExtractElement(J.value(), I); 1671 // Row and column indices are transposed. 1672 ResultVector = 1673 Builder.CreateInsertElement(ResultVector, Elt, J.index()); 1674 } 1675 Result.addVector(ResultVector); 1676 } 1677 1678 // TODO: Improve estimate of operations needed for transposes. Currently we 1679 // just count the insertelement/extractelement instructions, but do not 1680 // account for later simplifications/combines. 1681 finalizeLowering( 1682 Inst, 1683 Result.addNumComputeOps(2 * ArgShape.NumRows * ArgShape.NumColumns) 1684 .addNumExposedTransposes(1), 1685 Builder); 1686 } 1687 1688 /// Lower load instructions, if shape information is available. 1689 bool VisitLoad(LoadInst *Inst, Value *Ptr, IRBuilder<> &Builder) { 1690 auto I = ShapeMap.find(Inst); 1691 if (I == ShapeMap.end()) 1692 return false; 1693 1694 LowerLoad(Inst, Ptr, Inst->getAlign(), 1695 Builder.getInt64(I->second.getStride()), Inst->isVolatile(), 1696 I->second); 1697 return true; 1698 } 1699 1700 bool VisitStore(StoreInst *Inst, Value *StoredVal, Value *Ptr, 1701 IRBuilder<> &Builder) { 1702 auto I = ShapeMap.find(StoredVal); 1703 if (I == ShapeMap.end()) 1704 return false; 1705 1706 LowerStore(Inst, StoredVal, Ptr, Inst->getAlign(), 1707 Builder.getInt64(I->second.getStride()), Inst->isVolatile(), 1708 I->second); 1709 return true; 1710 } 1711 1712 /// Lower binary operators, if shape information is available. 1713 bool VisitBinaryOperator(BinaryOperator *Inst) { 1714 auto I = ShapeMap.find(Inst); 1715 if (I == ShapeMap.end()) 1716 return false; 1717 1718 Value *Lhs = Inst->getOperand(0); 1719 Value *Rhs = Inst->getOperand(1); 1720 1721 IRBuilder<> Builder(Inst); 1722 ShapeInfo &Shape = I->second; 1723 1724 MatrixTy Result; 1725 MatrixTy A = getMatrix(Lhs, Shape, Builder); 1726 MatrixTy B = getMatrix(Rhs, Shape, Builder); 1727 assert(A.isColumnMajor() == B.isColumnMajor() && 1728 Result.isColumnMajor() == A.isColumnMajor() && 1729 "operands must agree on matrix layout"); 1730 1731 Builder.setFastMathFlags(getFastMathFlags(Inst)); 1732 1733 // Helper to perform binary op on vectors. 1734 auto BuildVectorOp = [&Builder, Inst](Value *LHS, Value *RHS) { 1735 switch (Inst->getOpcode()) { 1736 case Instruction::Add: 1737 return Builder.CreateAdd(LHS, RHS); 1738 case Instruction::Mul: 1739 return Builder.CreateMul(LHS, RHS); 1740 case Instruction::Sub: 1741 return Builder.CreateSub(LHS, RHS); 1742 case Instruction::FAdd: 1743 return Builder.CreateFAdd(LHS, RHS); 1744 case Instruction::FMul: 1745 return Builder.CreateFMul(LHS, RHS); 1746 case Instruction::FSub: 1747 return Builder.CreateFSub(LHS, RHS); 1748 default: 1749 llvm_unreachable("Unsupported binary operator for matrix"); 1750 } 1751 }; 1752 1753 for (unsigned I = 0; I < Shape.getNumVectors(); ++I) 1754 Result.addVector(BuildVectorOp(A.getVector(I), B.getVector(I))); 1755 1756 finalizeLowering(Inst, 1757 Result.addNumComputeOps(getNumOps(Result.getVectorTy()) * 1758 Result.getNumVectors()), 1759 Builder); 1760 return true; 1761 } 1762 1763 /// Lower unary operators, if shape information is available. 1764 bool VisitUnaryOperator(UnaryOperator *Inst) { 1765 auto I = ShapeMap.find(Inst); 1766 if (I == ShapeMap.end()) 1767 return false; 1768 1769 Value *Op = Inst->getOperand(0); 1770 1771 IRBuilder<> Builder(Inst); 1772 ShapeInfo &Shape = I->second; 1773 1774 MatrixTy Result; 1775 MatrixTy M = getMatrix(Op, Shape, Builder); 1776 1777 Builder.setFastMathFlags(getFastMathFlags(Inst)); 1778 1779 // Helper to perform unary op on vectors. 1780 auto BuildVectorOp = [&Builder, Inst](Value *Op) { 1781 switch (Inst->getOpcode()) { 1782 case Instruction::FNeg: 1783 return Builder.CreateFNeg(Op); 1784 default: 1785 llvm_unreachable("Unsupported unary operator for matrix"); 1786 } 1787 }; 1788 1789 for (unsigned I = 0; I < Shape.getNumVectors(); ++I) 1790 Result.addVector(BuildVectorOp(M.getVector(I))); 1791 1792 finalizeLowering(Inst, 1793 Result.addNumComputeOps(getNumOps(Result.getVectorTy()) * 1794 Result.getNumVectors()), 1795 Builder); 1796 return true; 1797 } 1798 1799 /// Helper to linearize a matrix expression tree into a string. Currently 1800 /// matrix expressions are linarized by starting at an expression leaf and 1801 /// linearizing bottom up. 1802 struct ExprLinearizer { 1803 unsigned LengthToBreak = 100; 1804 std::string Str; 1805 raw_string_ostream Stream; 1806 unsigned LineLength = 0; 1807 const DataLayout &DL; 1808 1809 /// Mapping from instructions to matrixes. It is used to identify 1810 /// matrix instructions. 1811 const MapVector<Value *, MatrixTy> &Inst2Matrix; 1812 1813 /// Mapping from values to the leaves of all expressions that the value is 1814 /// part of. 1815 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared; 1816 1817 /// Set of matrix expressions in the scope of a given DISubprogram. 1818 const SmallSetVector<Value *, 32> &ExprsInSubprogram; 1819 1820 /// Leaf node of the expression to linearize. 1821 Value *Leaf; 1822 1823 /// Used to keep track of sub-expressions that get reused while linearizing 1824 /// the expression. Re-used sub-expressions are marked as (reused). 1825 SmallPtrSet<Value *, 8> ReusedExprs; 1826 1827 ExprLinearizer(const DataLayout &DL, 1828 const MapVector<Value *, MatrixTy> &Inst2Matrix, 1829 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared, 1830 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 1831 Value *Leaf) 1832 : Str(), Stream(Str), DL(DL), Inst2Matrix(Inst2Matrix), Shared(Shared), 1833 ExprsInSubprogram(ExprsInSubprogram), Leaf(Leaf) {} 1834 1835 void indent(unsigned N) { 1836 LineLength += N; 1837 for (unsigned i = 0; i < N; i++) 1838 Stream << " "; 1839 } 1840 1841 void lineBreak() { 1842 Stream << "\n"; 1843 LineLength = 0; 1844 } 1845 1846 void maybeIndent(unsigned Indent) { 1847 if (LineLength >= LengthToBreak) 1848 lineBreak(); 1849 1850 if (LineLength == 0) 1851 indent(Indent); 1852 } 1853 1854 void write(StringRef S) { 1855 LineLength += S.size(); 1856 Stream << S; 1857 } 1858 1859 Value *getUnderlyingObjectThroughLoads(Value *V) { 1860 if (Value *Ptr = getPointerOperand(V)) 1861 return getUnderlyingObjectThroughLoads(Ptr); 1862 else if (V->getType()->isPointerTy()) 1863 return getUnderlyingObject(V); 1864 return V; 1865 } 1866 1867 /// Returns true if \p V is a matrix value in the given subprogram. 1868 bool isMatrix(Value *V) const { return ExprsInSubprogram.count(V); } 1869 1870 /// If \p V is a matrix value, print its shape as as NumRows x NumColumns to 1871 /// \p SS. 1872 void prettyPrintMatrixType(Value *V, raw_string_ostream &SS) { 1873 auto M = Inst2Matrix.find(V); 1874 if (M == Inst2Matrix.end()) 1875 SS << "unknown"; 1876 else { 1877 SS << M->second.getNumRows(); 1878 SS << "x"; 1879 SS << M->second.getNumColumns(); 1880 } 1881 } 1882 1883 /// Write the called function name. Handles calls to llvm.matrix.* 1884 /// specially: we write the name, followed by the dimensions of the input 1885 /// matrixes, followed by the scalar type name. 1886 void writeFnName(CallInst *CI) { 1887 if (!CI->getCalledFunction()) 1888 write("<no called fn>"); 1889 else { 1890 StringRef Name = CI->getCalledFunction()->getName(); 1891 if (!Name.startswith("llvm.matrix")) { 1892 write(Name); 1893 return; 1894 } 1895 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); 1896 write(Intrinsic::getBaseName(II->getIntrinsicID()) 1897 .drop_front(StringRef("llvm.matrix.").size())); 1898 write("."); 1899 std::string Tmp; 1900 raw_string_ostream SS(Tmp); 1901 1902 switch (II->getIntrinsicID()) { 1903 case Intrinsic::matrix_multiply: 1904 prettyPrintMatrixType(II->getOperand(0), SS); 1905 SS << "."; 1906 prettyPrintMatrixType(II->getOperand(1), SS); 1907 SS << "." << *II->getType()->getScalarType(); 1908 break; 1909 case Intrinsic::matrix_transpose: 1910 prettyPrintMatrixType(II->getOperand(0), SS); 1911 SS << "." << *II->getType()->getScalarType(); 1912 break; 1913 case Intrinsic::matrix_column_major_load: 1914 prettyPrintMatrixType(II, SS); 1915 SS << "." << *II->getType()->getScalarType(); 1916 break; 1917 case Intrinsic::matrix_column_major_store: 1918 prettyPrintMatrixType(II->getOperand(0), SS); 1919 SS << "." << *II->getOperand(0)->getType()->getScalarType(); 1920 break; 1921 default: 1922 llvm_unreachable("Unhandled case"); 1923 } 1924 SS.flush(); 1925 write(Tmp); 1926 } 1927 } 1928 1929 unsigned getNumShapeArgs(CallInst *CI) const { 1930 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 1931 switch (II->getIntrinsicID()) { 1932 case Intrinsic::matrix_multiply: 1933 return 3; 1934 case Intrinsic::matrix_transpose: 1935 return 2; 1936 case Intrinsic::matrix_column_major_load: 1937 case Intrinsic::matrix_column_major_store: 1938 return 3; 1939 default: 1940 return 0; 1941 } 1942 } 1943 return 0; 1944 } 1945 1946 /// Special printing for values: for pointers, we print if they refer to an 1947 /// (function) external address or a stack address, for other values we 1948 /// either print the constant or "scalar"/"matrix" for other values. 1949 void write(Value *V) { 1950 V = getUnderlyingObjectThroughLoads(V); 1951 if (V->getType()->isPointerTy()) { 1952 if (isa<AllocaInst>(V)) { 1953 Stream << "stack addr"; 1954 LineLength += StringRef("stack addr").size(); 1955 } else { 1956 Stream << "addr"; 1957 LineLength += StringRef("addr").size(); 1958 } 1959 if (!V->getName().empty()) { 1960 Stream << " %" << V->getName() << ""; 1961 LineLength += V->getName().size() + 2; 1962 } 1963 return; 1964 } 1965 1966 std::string Tmp; 1967 raw_string_ostream TmpStream(Tmp); 1968 1969 if (auto *CI = dyn_cast<ConstantInt>(V)) 1970 TmpStream << CI->getValue(); 1971 else if (isa<Constant>(V)) 1972 TmpStream << "constant"; 1973 else { 1974 if (isMatrix(V)) 1975 TmpStream << "matrix"; 1976 else 1977 TmpStream << "scalar"; 1978 } 1979 TmpStream.flush(); 1980 Tmp = std::string(StringRef(Tmp).trim()); 1981 LineLength += Tmp.size(); 1982 Stream << Tmp; 1983 } 1984 1985 /// Linearize expression \p Expr starting at an indentation of \p Indent. 1986 /// Expressions that are re-used multiple times are prefixed with (reused) 1987 /// at the re-used root instruction. 1988 void linearizeExpr(Value *Expr, unsigned Indent, bool ParentReused, 1989 bool ParentShared) { 1990 auto *I = cast<Instruction>(Expr); 1991 maybeIndent(Indent); 1992 SmallVector<Value *, 8> Ops; 1993 1994 // Is Expr shared with other expression leaves? 1995 bool ExprShared = false; 1996 1997 // Deal with shared subtrees. Mark them as shared, if required. 1998 if (!ParentShared) { 1999 auto SI = Shared.find(Expr); 2000 assert(SI != Shared.end() && SI->second.count(Leaf)); 2001 2002 for (Value *S : SI->second) { 2003 if (S == Leaf) 2004 continue; 2005 DebugLoc DL = cast<Instruction>(S)->getDebugLoc(); 2006 write("shared with remark at line " + std::to_string(DL.getLine()) + 2007 " column " + std::to_string(DL.getCol()) + " ("); 2008 } 2009 ExprShared = SI->second.size() > 1; 2010 } 2011 2012 bool Reused = !ReusedExprs.insert(Expr).second; 2013 if (Reused && !ParentReused) 2014 write("(reused) "); 2015 2016 if (auto *CI = dyn_cast<CallInst>(I)) { 2017 writeFnName(CI); 2018 2019 Ops.append(CI->arg_begin(), CI->arg_end() - getNumShapeArgs(CI)); 2020 } else if (isa<BitCastInst>(Expr)) { 2021 // Special case bitcasts, which are used to materialize matrixes from 2022 // non-matrix ops. 2023 write("matrix"); 2024 return; 2025 } else { 2026 Ops.append(I->value_op_begin(), I->value_op_end()); 2027 write(std::string(I->getOpcodeName())); 2028 } 2029 2030 write(std::string("(")); 2031 2032 unsigned NumOpsToBreak = 1; 2033 if (match(Expr, m_Intrinsic<Intrinsic::matrix_column_major_load>())) 2034 NumOpsToBreak = 2; 2035 2036 for (Value *Op : Ops) { 2037 if (Ops.size() > NumOpsToBreak) 2038 lineBreak(); 2039 2040 maybeIndent(Indent + 1); 2041 if (isMatrix(Op)) 2042 linearizeExpr(Op, Indent + 1, Reused, ExprShared); 2043 else 2044 write(Op); 2045 if (Op != Ops.back()) 2046 write(", "); 2047 } 2048 2049 write(")"); 2050 } 2051 2052 const std::string &getResult() { 2053 Stream.flush(); 2054 return Str; 2055 } 2056 }; 2057 2058 /// Generate remarks for matrix operations in a function. To generate remarks 2059 /// for matrix expressions, the following approach is used: 2060 /// 1. Use the inlined-at debug information to group matrix operations to the 2061 /// DISubprograms they are contained in. 2062 /// 2. Collect leaves of matrix expressions (done in 2063 /// RemarkGenerator::getExpressionLeaves) for each subprogram - expression 2064 // mapping. Leaves are lowered matrix instructions without other matrix 2065 // users (like stores) in the current subprogram. 2066 /// 3. For each leaf, create a remark containing a linearizied version of the 2067 /// matrix expression. The expression is linearized by a recursive 2068 /// bottom-up traversal of the matrix operands, starting at a leaf. Note 2069 /// that multiple leaves can share sub-expressions. Shared subexpressions 2070 /// are explicitly marked as shared(). 2071 struct RemarkGenerator { 2072 const MapVector<Value *, MatrixTy> &Inst2Matrix; 2073 OptimizationRemarkEmitter &ORE; 2074 Function &Func; 2075 const DataLayout &DL; 2076 2077 RemarkGenerator(const MapVector<Value *, MatrixTy> &Inst2Matrix, 2078 OptimizationRemarkEmitter &ORE, Function &Func) 2079 : Inst2Matrix(Inst2Matrix), ORE(ORE), Func(Func), 2080 DL(Func.getParent()->getDataLayout()) {} 2081 2082 /// Return all leaves of the expressions in \p ExprsInSubprogram. Those are 2083 /// instructions in Inst2Matrix returning void or without any users in 2084 /// \p ExprsInSubprogram. Currently that should only include stores. 2085 SmallVector<Value *, 4> 2086 getExpressionLeaves(const SmallSetVector<Value *, 32> &ExprsInSubprogram) { 2087 SmallVector<Value *, 4> Leaves; 2088 for (auto *Expr : ExprsInSubprogram) 2089 if (Expr->getType()->isVoidTy() || 2090 !any_of(Expr->users(), [&ExprsInSubprogram](User *U) { 2091 return ExprsInSubprogram.count(U); 2092 })) 2093 Leaves.push_back(Expr); 2094 return Leaves; 2095 } 2096 2097 /// Recursively traverse expression \p V starting at \p Leaf and add \p Leaf 2098 /// to all visited expressions in \p Shared. Limit the matrix operations to 2099 /// the ones in \p ExprsInSubprogram. 2100 void collectSharedInfo(Value *Leaf, Value *V, 2101 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 2102 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) { 2103 2104 if (!ExprsInSubprogram.count(V)) 2105 return; 2106 2107 auto I = Shared.insert({V, {}}); 2108 I.first->second.insert(Leaf); 2109 2110 for (Value *Op : cast<Instruction>(V)->operand_values()) 2111 collectSharedInfo(Leaf, Op, ExprsInSubprogram, Shared); 2112 } 2113 2114 /// Calculate the number of exclusive and shared op counts for expression 2115 /// starting at \p V. Expressions used multiple times are counted once. 2116 /// Limit the matrix operations to the ones in \p ExprsInSubprogram. 2117 std::pair<OpInfoTy, OpInfoTy> 2118 sumOpInfos(Value *Root, SmallPtrSetImpl<Value *> &ReusedExprs, 2119 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 2120 DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared) const { 2121 if (!ExprsInSubprogram.count(Root)) 2122 return {}; 2123 2124 // Already counted this expression. Stop. 2125 if (!ReusedExprs.insert(Root).second) 2126 return {}; 2127 2128 OpInfoTy SharedCount; 2129 OpInfoTy Count; 2130 2131 auto I = Shared.find(Root); 2132 auto CM = Inst2Matrix.find(Root); 2133 if (I->second.size() == 1) 2134 Count = CM->second.getOpInfo(); 2135 else 2136 SharedCount = CM->second.getOpInfo(); 2137 2138 for (Value *Op : cast<Instruction>(Root)->operand_values()) { 2139 auto C = sumOpInfos(Op, ReusedExprs, ExprsInSubprogram, Shared); 2140 Count += C.first; 2141 SharedCount += C.second; 2142 } 2143 return {Count, SharedCount}; 2144 } 2145 2146 void emitRemarks() { 2147 if (!ORE.allowExtraAnalysis(DEBUG_TYPE)) 2148 return; 2149 2150 // Map matrix operations to their containting subprograms, by traversing 2151 // the inlinedAt chain. If the function does not have a DISubprogram, we 2152 // only map them to the containing function. 2153 MapVector<DISubprogram *, SmallVector<Value *, 8>> Subprog2Exprs; 2154 for (auto &KV : Inst2Matrix) { 2155 if (Func.getSubprogram()) { 2156 auto *I = cast<Instruction>(KV.first); 2157 DILocation *Context = I->getDebugLoc(); 2158 while (Context) { 2159 auto I = 2160 Subprog2Exprs.insert({getSubprogram(Context->getScope()), {}}); 2161 I.first->second.push_back(KV.first); 2162 Context = DebugLoc(Context).getInlinedAt(); 2163 } 2164 } else { 2165 auto I = Subprog2Exprs.insert({nullptr, {}}); 2166 I.first->second.push_back(KV.first); 2167 } 2168 } 2169 for (auto &KV : Subprog2Exprs) { 2170 SmallSetVector<Value *, 32> ExprsInSubprogram(KV.second.begin(), 2171 KV.second.end()); 2172 auto Leaves = getExpressionLeaves(ExprsInSubprogram); 2173 2174 DenseMap<Value *, SmallPtrSet<Value *, 2>> Shared; 2175 for (Value *Leaf : Leaves) 2176 collectSharedInfo(Leaf, Leaf, ExprsInSubprogram, Shared); 2177 2178 // Generate remarks for each leaf. 2179 for (auto *L : Leaves) { 2180 2181 DebugLoc Loc = cast<Instruction>(L)->getDebugLoc(); 2182 DILocation *Context = cast<Instruction>(L)->getDebugLoc(); 2183 while (Context) { 2184 if (getSubprogram(Context->getScope()) == KV.first) { 2185 Loc = Context; 2186 break; 2187 } 2188 Context = DebugLoc(Context).getInlinedAt(); 2189 } 2190 2191 SmallPtrSet<Value *, 8> ReusedExprs; 2192 OpInfoTy Counts, SharedCounts; 2193 std::tie(Counts, SharedCounts) = 2194 sumOpInfos(L, ReusedExprs, ExprsInSubprogram, Shared); 2195 2196 OptimizationRemark Rem(DEBUG_TYPE, "matrix-lowered", Loc, 2197 cast<Instruction>(L)->getParent()); 2198 2199 Rem << "Lowered with "; 2200 Rem << ore::NV("NumStores", Counts.NumStores) << " stores, " 2201 << ore::NV("NumLoads", Counts.NumLoads) << " loads, " 2202 << ore::NV("NumComputeOps", Counts.NumComputeOps) 2203 << " compute ops, " 2204 << ore::NV("NumExposedTransposes", Counts.NumExposedTransposes) 2205 << " exposed transposes"; 2206 2207 if (SharedCounts.NumStores > 0 || SharedCounts.NumLoads > 0 || 2208 SharedCounts.NumComputeOps > 0) { 2209 Rem << ",\nadditionally " 2210 << ore::NV("NumStores", SharedCounts.NumStores) << " stores, " 2211 << ore::NV("NumLoads", SharedCounts.NumLoads) << " loads, " 2212 << ore::NV("NumFPOps", SharedCounts.NumComputeOps) 2213 << " compute ops" 2214 << " are shared with other expressions"; 2215 } 2216 2217 Rem << ("\n" + linearize(L, Shared, ExprsInSubprogram, DL)); 2218 ORE.emit(Rem); 2219 } 2220 } 2221 } 2222 2223 std::string 2224 linearize(Value *L, 2225 const DenseMap<Value *, SmallPtrSet<Value *, 2>> &Shared, 2226 const SmallSetVector<Value *, 32> &ExprsInSubprogram, 2227 const DataLayout &DL) { 2228 ExprLinearizer Lin(DL, Inst2Matrix, Shared, ExprsInSubprogram, L); 2229 Lin.linearizeExpr(L, 0, false, false); 2230 return Lin.getResult(); 2231 } 2232 }; 2233 }; 2234 } // namespace 2235 2236 PreservedAnalyses LowerMatrixIntrinsicsPass::run(Function &F, 2237 FunctionAnalysisManager &AM) { 2238 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 2239 OptimizationRemarkEmitter *ORE = nullptr; 2240 AAResults *AA = nullptr; 2241 DominatorTree *DT = nullptr; 2242 LoopInfo *LI = nullptr; 2243 2244 if (!Minimal) { 2245 ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 2246 AA = &AM.getResult<AAManager>(F); 2247 DT = &AM.getResult<DominatorTreeAnalysis>(F); 2248 LI = &AM.getResult<LoopAnalysis>(F); 2249 } 2250 2251 LowerMatrixIntrinsics LMT(F, TTI, AA, DT, LI, ORE); 2252 if (LMT.Visit()) { 2253 PreservedAnalyses PA; 2254 if (!Minimal) { 2255 PA.preserve<LoopAnalysis>(); 2256 PA.preserve<DominatorTreeAnalysis>(); 2257 } 2258 return PA; 2259 } 2260 return PreservedAnalyses::all(); 2261 } 2262 2263 namespace { 2264 2265 class LowerMatrixIntrinsicsLegacyPass : public FunctionPass { 2266 public: 2267 static char ID; 2268 2269 LowerMatrixIntrinsicsLegacyPass() : FunctionPass(ID) { 2270 initializeLowerMatrixIntrinsicsLegacyPassPass( 2271 *PassRegistry::getPassRegistry()); 2272 } 2273 2274 bool runOnFunction(Function &F) override { 2275 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2276 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 2277 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2278 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2279 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2280 LowerMatrixIntrinsics LMT(F, TTI, &AA, &DT, &LI, &ORE); 2281 bool C = LMT.Visit(); 2282 return C; 2283 } 2284 2285 void getAnalysisUsage(AnalysisUsage &AU) const override { 2286 AU.addRequired<TargetTransformInfoWrapperPass>(); 2287 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2288 AU.addRequired<AAResultsWrapperPass>(); 2289 AU.addRequired<DominatorTreeWrapperPass>(); 2290 AU.addPreserved<DominatorTreeWrapperPass>(); 2291 AU.addRequired<LoopInfoWrapperPass>(); 2292 AU.addPreserved<LoopInfoWrapperPass>(); 2293 } 2294 }; 2295 } // namespace 2296 2297 static const char pass_name[] = "Lower the matrix intrinsics"; 2298 char LowerMatrixIntrinsicsLegacyPass::ID = 0; 2299 INITIALIZE_PASS_BEGIN(LowerMatrixIntrinsicsLegacyPass, DEBUG_TYPE, pass_name, 2300 false, false) 2301 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 2302 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2303 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2304 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2305 INITIALIZE_PASS_END(LowerMatrixIntrinsicsLegacyPass, DEBUG_TYPE, pass_name, 2306 false, false) 2307 2308 Pass *llvm::createLowerMatrixIntrinsicsPass() { 2309 return new LowerMatrixIntrinsicsLegacyPass(); 2310 } 2311 2312 namespace { 2313 2314 /// A lightweight version of the matrix lowering pass that only requires TTI. 2315 /// Advanced features that require DT, AA or ORE like tiling are disabled. This 2316 /// is used to lower matrix intrinsics if the main lowering pass is not run, for 2317 /// example with -O0. 2318 class LowerMatrixIntrinsicsMinimalLegacyPass : public FunctionPass { 2319 public: 2320 static char ID; 2321 2322 LowerMatrixIntrinsicsMinimalLegacyPass() : FunctionPass(ID) { 2323 initializeLowerMatrixIntrinsicsMinimalLegacyPassPass( 2324 *PassRegistry::getPassRegistry()); 2325 } 2326 2327 bool runOnFunction(Function &F) override { 2328 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2329 LowerMatrixIntrinsics LMT(F, TTI, nullptr, nullptr, nullptr, nullptr); 2330 bool C = LMT.Visit(); 2331 return C; 2332 } 2333 2334 void getAnalysisUsage(AnalysisUsage &AU) const override { 2335 AU.addRequired<TargetTransformInfoWrapperPass>(); 2336 AU.setPreservesCFG(); 2337 } 2338 }; 2339 } // namespace 2340 2341 static const char pass_name_minimal[] = "Lower the matrix intrinsics (minimal)"; 2342 char LowerMatrixIntrinsicsMinimalLegacyPass::ID = 0; 2343 INITIALIZE_PASS_BEGIN(LowerMatrixIntrinsicsMinimalLegacyPass, 2344 "lower-matrix-intrinsics-minimal", pass_name_minimal, 2345 false, false) 2346 INITIALIZE_PASS_END(LowerMatrixIntrinsicsMinimalLegacyPass, 2347 "lower-matrix-intrinsics-minimal", pass_name_minimal, false, 2348 false) 2349 2350 Pass *llvm::createLowerMatrixIntrinsicsMinimalPass() { 2351 return new LowerMatrixIntrinsicsMinimalLegacyPass(); 2352 } 2353