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