4646#include " mlir/Dialect/Linalg/Utils/Utils.h"
4747#include " mlir/Dialect/SCF/SCF.h"
4848#include " mlir/Dialect/StandardOps/IR/Ops.h"
49+ #include " mlir/IR/Matchers.h"
4950
5051using namespace mlir ;
5152
@@ -301,7 +302,8 @@ struct CodeGen {
301302 indices(numTensors, std::vector<Value>(numLoops)),
302303 highs(numTensors, std::vector<Value>(numLoops)),
303304 pidxs(numTensors, std::vector<Value>(numLoops)),
304- idxs(numTensors, std::vector<Value>(numLoops)), redExp(-1u ), redVal() {}
305+ idxs(numTensors, std::vector<Value>(numLoops)), redExp(-1u ), redVal(),
306+ curVecLength(1 ), curVecMask() {}
305307 // / Sparsification options.
306308 linalg::SparsificationOptions options;
307309 // / Universal dense indices and upper bounds (by index). The loops array
@@ -327,6 +329,9 @@ struct CodeGen {
327329 // is most effective; we could generalize to more outer and while-loops.
328330 unsigned redExp;
329331 Value redVal;
332+ // Current vector length and mask.
333+ unsigned curVecLength;
334+ Value curVecMask;
330335};
331336
332337} // namespace
@@ -558,6 +563,71 @@ static void genBuffers(Merger &merger, CodeGen &codegen,
558563 }
559564}
560565
566+ // / Constructs vector type from pointer.
567+ static VectorType vectorType (CodeGen &codegen, Value ptr) {
568+ Type etp = ptr.getType ().cast <MemRefType>().getElementType ();
569+ return VectorType::get (codegen.curVecLength , etp);
570+ }
571+
572+ // / Constructs vector iteration mask.
573+ static Value genVectorMask (CodeGen &codegen, PatternRewriter &rewriter,
574+ Value iv, Value lo, Value hi, Value step) {
575+ Location loc = iv.getLoc ();
576+ VectorType mtp =
577+ VectorType::get (codegen.curVecLength , rewriter.getIntegerType (1 ));
578+ // Special case if the vector length evenly divides the trip count (for
579+ // example, "for i = 0, 128, 16"). A constant all-true mask is generated
580+ // so that all subsequent masked memory operations are immediately folded
581+ // into unconditional memory operations.
582+ IntegerAttr loInt, hiInt, stepInt;
583+ if (matchPattern (lo, m_Constant (&loInt)) &&
584+ matchPattern (hi, m_Constant (&hiInt)) &&
585+ matchPattern (step, m_Constant (&stepInt))) {
586+ if (((hiInt.getInt () - loInt.getInt ()) % stepInt.getInt ()) == 0 )
587+ return rewriter.create <vector::ConstantMaskOp>(
588+ loc, mtp, rewriter.getI64ArrayAttr (codegen.curVecLength ));
589+ }
590+ // Otherwise, generate a vector mask that avoids overrunning the upperbound
591+ // during vector execution. Here we rely on subsequent loop optimizations to
592+ // avoid executing the mask in all iterations, for example, by splitting the
593+ // loop into an unconditional vector loop and a scalar cleanup loop.
594+ Value end = rewriter.create <SubIOp>(loc, hi, iv);
595+ return rewriter.create <vector::CreateMaskOp>(loc, mtp, end);
596+ }
597+
598+ // / Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi].
599+ static Value genVectorLoad (CodeGen &codegen, PatternRewriter &rewriter,
600+ Value ptr, ArrayRef<Value> args) {
601+ Location loc = ptr.getLoc ();
602+ VectorType vtp = vectorType (codegen, ptr);
603+ Value pass = rewriter.create <ConstantOp>(loc, vtp, rewriter.getZeroAttr (vtp));
604+ if (args.back ().getType ().isa <VectorType>())
605+ return rewriter.create <vector::GatherOp>(loc, vtp, ptr, args.back (),
606+ codegen.curVecMask , pass);
607+ return rewriter.create <vector::MaskedLoadOp>(loc, vtp, ptr, args,
608+ codegen.curVecMask , pass);
609+ }
610+
611+ // / Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs.
612+ static void genVectorStore (CodeGen &codegen, PatternRewriter &rewriter,
613+ Value rhs, Value ptr, ArrayRef<Value> args) {
614+ Location loc = ptr.getLoc ();
615+ if (args.back ().getType ().isa <VectorType>())
616+ rewriter.create <vector::ScatterOp>(loc, ptr, args.back (),
617+ codegen.curVecMask , rhs);
618+ else
619+ rewriter.create <vector::MaskedStoreOp>(loc, ptr, args, codegen.curVecMask ,
620+ rhs);
621+ }
622+
623+ // / Generates a vectorized invariant. Here we rely on subsequent loop
624+ // / optimizations to hoist the invariant broadcast out of the vector loop.
625+ static Value genVectorInvariantValue (CodeGen &codegen,
626+ PatternRewriter &rewriter, Value val) {
627+ VectorType vtp = VectorType::get (codegen.curVecLength , val.getType ());
628+ return rewriter.create <vector::BroadcastOp>(val.getLoc (), vtp, val);
629+ }
630+
561631// / Generates a load on a dense or sparse tensor.
562632static Value genTensorLoad (Merger &merger, CodeGen &codegen,
563633 PatternRewriter &rewriter, linalg::GenericOp op,
@@ -582,6 +652,8 @@ static Value genTensorLoad(Merger &merger, CodeGen &codegen,
582652 }
583653 Location loc = op.getLoc ();
584654 Value ptr = codegen.buffers [tensor];
655+ if (codegen.curVecLength > 1 )
656+ return genVectorLoad (codegen, rewriter, ptr, args);
585657 return rewriter.create <LoadOp>(loc, ptr, args);
586658}
587659
@@ -595,7 +667,7 @@ static void genTensorStore(Merger &merger, CodeGen &codegen,
595667 codegen.redVal = rhs;
596668 return ;
597669 }
598- // Actual load .
670+ // Actual store .
599671 SmallVector<Value, 4 > args;
600672 auto map = op.getIndexingMap (tensor);
601673 for (unsigned i = 0 , m = map.getNumResults (); i < m; ++i) {
@@ -604,12 +676,17 @@ static void genTensorStore(Merger &merger, CodeGen &codegen,
604676 }
605677 Location loc = op.getLoc ();
606678 Value ptr = codegen.buffers [tensor];
607- rewriter.create <StoreOp>(loc, rhs, ptr, args);
679+ if (codegen.curVecLength > 1 )
680+ genVectorStore (codegen, rewriter, rhs, ptr, args);
681+ else
682+ rewriter.create <StoreOp>(loc, rhs, ptr, args);
608683}
609684
610685// / Generates a pointer/index load from the sparse storage scheme.
611- static Value genLoad (PatternRewriter &rewriter, Location loc, Value ptr,
612- Value s) {
686+ static Value genLoad (CodeGen &codegen, PatternRewriter &rewriter, Location loc,
687+ Value ptr, Value s) {
688+ if (codegen.curVecLength > 1 )
689+ return genVectorLoad (codegen, rewriter, ptr, {s});
613690 Value load = rewriter.create <LoadOp>(loc, ptr, s);
614691 return load.getType ().isa <IndexType>()
615692 ? load
@@ -619,7 +696,10 @@ static Value genLoad(PatternRewriter &rewriter, Location loc, Value ptr,
619696// / Generates an invariant value.
620697static Value genInvariantValue (Merger &merger, CodeGen &codegen,
621698 PatternRewriter &rewriter, unsigned exp) {
622- return merger.exp (exp).val ;
699+ Value val = merger.exp (exp).val ;
700+ if (codegen.curVecLength > 1 )
701+ return genVectorInvariantValue (codegen, rewriter, val);
702+ return val;
623703}
624704
625705// / Recursively generates tensor expression.
@@ -707,9 +787,9 @@ static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
707787 Value one = rewriter.create <ConstantIndexOp>(loc, 1 );
708788 Value p0 = (pat == 0 ) ? rewriter.create <ConstantIndexOp>(loc, 0 )
709789 : codegen.pidxs [tensor][topSort[pat - 1 ]];
710- codegen.pidxs [tensor][idx] = genLoad (rewriter, loc, ptr, p0);
790+ codegen.pidxs [tensor][idx] = genLoad (codegen, rewriter, loc, ptr, p0);
711791 Value p1 = rewriter.create <AddIOp>(loc, p0, one);
712- codegen.highs [tensor][idx] = genLoad (rewriter, loc, ptr, p1);
792+ codegen.highs [tensor][idx] = genLoad (codegen, rewriter, loc, ptr, p1);
713793 } else {
714794 // Dense index still in play.
715795 needsUniv = true ;
@@ -722,6 +802,39 @@ static bool genInit(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
722802 return needsUniv;
723803}
724804
805+ // / Returns vectorization strategy. Any implicit inner loop in the Linalg
806+ // / operation is a candidate. Whether it is actually converted to SIMD code
807+ // / depends on the requested strategy.
808+ static bool isVectorFor (CodeGen &codegen, bool isInner, bool isSparse) {
809+ switch (codegen.options .vectorizationStrategy ) {
810+ case linalg::SparseVectorizationStrategy::kNone :
811+ return false ;
812+ case linalg::SparseVectorizationStrategy::kDenseInnerLoop :
813+ return isInner && !isSparse;
814+ case linalg::SparseVectorizationStrategy::kAnyStorageInnerLoop :
815+ return isInner;
816+ }
817+ }
818+
819+ // / Returns parallelization strategy. Any implicit loop in the Linalg operation
820+ // / that is marked "parallel" is a candidate. Whether it is actually converted
821+ // / to a parallel operation depends on the requested strategy.
822+ static bool isParallelFor (CodeGen &codegen, bool isOuter, bool isReduction,
823+ bool isSparse, bool isVector) {
824+ switch (codegen.options .parallelizationStrategy ) {
825+ case linalg::SparseParallelizationStrategy::kNone :
826+ return false ;
827+ case linalg::SparseParallelizationStrategy::kDenseOuterLoop :
828+ return isOuter && !isSparse && !isReduction && !isVector;
829+ case linalg::SparseParallelizationStrategy::kAnyStorageOuterLoop :
830+ return isOuter && !isReduction && !isVector;
831+ case linalg::SparseParallelizationStrategy::kDenseAnyLoop :
832+ return !isSparse && !isReduction && !isVector;
833+ case linalg::SparseParallelizationStrategy::kAnyStorageAnyLoop :
834+ return !isReduction && !isVector;
835+ }
836+ }
837+
725838// / Generates a for-loop on a single index.
726839static Operation *genFor (Merger &merger, CodeGen &codegen,
727840 PatternRewriter &rewriter, linalg::GenericOp op,
@@ -730,46 +843,26 @@ static Operation *genFor(Merger &merger, CodeGen &codegen,
730843 unsigned fb = indices.find_first ();
731844 unsigned tensor = merger.tensor (fb);
732845 assert (idx == merger.index (fb));
733-
734- // Parallelization strategy. Any implicit loop in the Linalg operation that
735- // is marked "parallel" is a candidate. Whether it is actually converted to
736- // a parallel operation depends on the requested strategy.
737846 auto iteratorTypes = op.iterator_types ().getValue ();
847+ bool isReduction = linalg::isReductionIteratorType (iteratorTypes[idx]);
738848 bool isSparse = merger.isDim (fb, Dim::kSparse );
739- bool isParallel = linalg::isParallelIteratorType (iteratorTypes[idx]);
740- switch (codegen.options .parallelizationStrategy ) {
741- case linalg::SparseParallelizationStrategy::kNone :
742- isParallel = false ;
743- break ;
744- case linalg::SparseParallelizationStrategy::kDenseOuterLoop :
745- isParallel &= isOuter && !isSparse;
746- break ;
747- case linalg::SparseParallelizationStrategy::kAnyStorageOuterLoop :
748- isParallel &= isOuter;
749- break ;
750- case linalg::SparseParallelizationStrategy::kDenseAnyLoop :
751- isParallel &= !isSparse;
752- break ;
753- case linalg::SparseParallelizationStrategy::kAnyStorageAnyLoop :
754- break ;
755- }
849+ bool isVector = isVectorFor (codegen, isInner, isSparse);
850+ bool isParallel =
851+ isParallelFor (codegen, isOuter, isReduction, isSparse, isVector);
852+
853+ // Prepare vector length.
854+ if (isVector)
855+ codegen.curVecLength = codegen.options .vectorLength ;
756856
757857 // Loop bounds and increment.
758858 Location loc = op.getLoc ();
759- Value lo;
760- Value hi;
761- Value step = rewriter.create <ConstantIndexOp>(loc, 1 );
762- Value index;
763- if (isSparse) {
764- lo = codegen.pidxs [tensor][idx];
765- hi = codegen.highs [tensor][idx];
766- } else {
767- lo = codegen.loops [idx];
768- hi = codegen.sizes [idx];
769- }
859+ Value lo = isSparse ? codegen.pidxs [tensor][idx] : codegen.loops [idx];
860+ Value hi = isSparse ? codegen.highs [tensor][idx] : codegen.sizes [idx];
861+ Value step = rewriter.create <ConstantIndexOp>(loc, codegen.curVecLength );
770862
771863 // Emit a parallel loop.
772864 if (isParallel) {
865+ assert (!isVector);
773866 scf::ParallelOp parOp = rewriter.create <scf::ParallelOp>(loc, lo, hi, step);
774867 if (isSparse)
775868 codegen.pidxs [tensor][idx] = parOp.getInductionVars ()[0 ];
@@ -783,10 +876,16 @@ static Operation *genFor(Merger &merger, CodeGen &codegen,
783876 bool scalarRed = isInner && codegen.redExp != -1u ;
784877 SmallVector<Value, 4 > operands;
785878 if (scalarRed) {
786- Value load =
787- codegen.redVal
788- ? codegen.redVal // chained with previous for-loop
789- : genTensorLoad (merger, codegen, rewriter, op, codegen.redExp );
879+ Value load;
880+ if (codegen.redVal ) {
881+ load = codegen.redVal ; // chained with previous for-loop
882+ } else if (isVector) {
883+ // TODO: assumes + reductions for now
884+ VectorType vtp = vectorType (codegen, codegen.buffers [codegen.redExp ]);
885+ load = rewriter.create <ConstantOp>(loc, vtp, rewriter.getZeroAttr (vtp));
886+ } else {
887+ load = genTensorLoad (merger, codegen, rewriter, op, codegen.redExp );
888+ }
790889 operands.push_back (load);
791890 }
792891 scf::ForOp forOp = rewriter.create <scf::ForOp>(loc, lo, hi, step, operands);
@@ -795,11 +894,15 @@ static Operation *genFor(Merger &merger, CodeGen &codegen,
795894 forOp.getRegionIterArgs ().front ();
796895 }
797896 // Assign induction variable to sparse or dense index.
897+ Value iv = forOp.getInductionVar ();
798898 if (isSparse)
799- codegen.pidxs [tensor][idx] = forOp. getInductionVar () ;
899+ codegen.pidxs [tensor][idx] = iv ;
800900 else
801- codegen.loops [idx] = forOp. getInductionVar () ;
901+ codegen.loops [idx] = iv ;
802902 rewriter.setInsertionPointToStart (forOp.getBody ());
903+ // Share vector iteration mask between all subsequent loads/stores.
904+ if (isVector)
905+ codegen.curVecMask = genVectorMask (codegen, rewriter, iv, lo, hi, step);
803906 return forOp;
804907}
805908
@@ -886,7 +989,7 @@ static void genLocals(Merger &merger, CodeGen &codegen,
886989 assert (idx == merger.index (b));
887990 Value ptr = codegen.indices [tensor][idx];
888991 Value s = codegen.pidxs [tensor][idx];
889- Value load = genLoad (rewriter, loc, ptr, s);
992+ Value load = genLoad (codegen, rewriter, loc, ptr, s);
890993 codegen.idxs [tensor][idx] = load;
891994 if (!needsUniv) {
892995 if (min) {
@@ -998,7 +1101,7 @@ static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
9981101 // Then emit initialization code for the loop sequence at this level.
9991102 // We maintain the universal dense index if dense indices are still
10001103 // in play for a non-singleton loop sequence.
1001- // Location loc = op.getLoc();
1104+ Location loc = op.getLoc ();
10021105 unsigned idx = topSort[at];
10031106 unsigned lts = merger.optimizeSet (buildLattices (merger, op, exp, idx));
10041107 unsigned lsize = merger.set (lts).size ();
@@ -1015,6 +1118,7 @@ static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
10151118 unsigned li = merger.set (lts)[i];
10161119
10171120 // Emit loop.
1121+ codegen.curVecLength = 1 ;
10181122 llvm::BitVector indices = merger.lat (li).simple ;
10191123 Operation *loop =
10201124 genLoop (merger, codegen, rewriter, op, topSort, at, needsUniv, indices);
@@ -1055,7 +1159,7 @@ static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
10551159 } else {
10561160 needsUniv = false ;
10571161 if (codegen.redVal ) {
1058- rewriter.create <scf::YieldOp>(op. getLoc () , codegen.redVal );
1162+ rewriter.create <scf::YieldOp>(loc , codegen.redVal );
10591163 codegen.redVal = loop->getResult (0 );
10601164 }
10611165 }
@@ -1067,10 +1171,16 @@ static void genStmt(Merger &merger, CodeGen &codegen, PatternRewriter &rewriter,
10671171 if (red) {
10681172 codegen.redVal = merger.exp (codegen.redExp ).val = Value (); // end chain
10691173 unsigned lhs = op.getNumShapedOperands () - 1 ;
1174+ if (codegen.curVecLength > 1 ) {
1175+ codegen.curVecLength = 1 ;
1176+ Value ld = genTensorLoad (merger, codegen, rewriter, op, codegen.redExp );
1177+ red = rewriter.create <vector::ReductionOp>(
1178+ loc, ld.getType (), rewriter.getStringAttr (" add" ), red, ld);
1179+ }
10701180 genTensorStore (merger, codegen, rewriter, op, lhs, red);
10711181 }
1072- codegen.loops [idx] = Value ();
10731182 genInvariants (merger, codegen, rewriter, op, exp, ldx, /* hoist=*/ false );
1183+ codegen.loops [idx] = Value ();
10741184}
10751185
10761186namespace {
0 commit comments