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