1 //===- LoopPipelining.cpp - Code to perform loop software pipelining-------===//
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 // This file implements loop software pipelining
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15 #include "mlir/Dialect/SCF/SCF.h"
16 #include "mlir/Dialect/SCF/Transforms.h"
17 #include "mlir/Dialect/SCF/Utils.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/BlockAndValueMapping.h"
20 #include "mlir/IR/PatternMatch.h"
21 #include "mlir/Support/MathExtras.h"
22 
23 using namespace mlir;
24 using namespace mlir::scf;
25 
26 namespace {
27 
28 /// Helper to keep internal information during pipelining transformation.
29 struct LoopPipelinerInternal {
30   /// Coarse liverange information for ops used across stages.
31   struct LiverangeInfo {
32     unsigned lastUseStage = 0;
33     unsigned defStage = 0;
34   };
35 
36 protected:
37   ForOp forOp;
38   unsigned maxStage = 0;
39   DenseMap<Operation *, unsigned> stages;
40   std::vector<Operation *> opOrder;
41   int64_t ub;
42   int64_t lb;
43   int64_t step;
44 
45   // When peeling the kernel we generate several version of each value for
46   // different stage of the prologue. This map tracks the mapping between
47   // original Values in the loop and the different versions
48   // peeled from the loop.
49   DenseMap<Value, llvm::SmallVector<Value>> valueMapping;
50 
51   /// Assign a value to `valueMapping`, this means `val` represents the version
52   /// `idx` of `key` in the epilogue.
53   void setValueMapping(Value key, Value el, int64_t idx);
54 
55 public:
56   /// Initalize the information for the given `op`, return true if it
57   /// satisfies the pre-condition to apply pipelining.
58   bool initializeLoopInfo(ForOp op, const PipeliningOption &options);
59   /// Emits the prologue, this creates `maxStage - 1` part which will contain
60   /// operations from stages [0; i], where i is the part index.
61   void emitPrologue(PatternRewriter &rewriter);
62   /// Gather liverange information for Values that are used in a different stage
63   /// than its definition.
64   llvm::MapVector<Value, LiverangeInfo> analyzeCrossStageValues();
65   scf::ForOp createKernelLoop(
66       const llvm::MapVector<Value, LiverangeInfo> &crossStageValues,
67       PatternRewriter &rewriter,
68       llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap);
69   /// Emits the pipelined kernel. This clones loop operations following user
70   /// order and remaps operands defined in a different stage as their use.
71   void createKernel(
72       scf::ForOp newForOp,
73       const llvm::MapVector<Value, LiverangeInfo> &crossStageValues,
74       const llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap,
75       PatternRewriter &rewriter);
76   /// Emits the epilogue, this creates `maxStage - 1` part which will contain
77   /// operations from stages [i; maxStage], where i is the part index.
78   llvm::SmallVector<Value> emitEpilogue(PatternRewriter &rewriter);
79 };
80 
81 bool LoopPipelinerInternal::initializeLoopInfo(
82     ForOp op, const PipeliningOption &options) {
83   forOp = op;
84   auto upperBoundCst =
85       forOp.upperBound().getDefiningOp<arith::ConstantIndexOp>();
86   auto lowerBoundCst =
87       forOp.lowerBound().getDefiningOp<arith::ConstantIndexOp>();
88   auto stepCst = forOp.step().getDefiningOp<arith::ConstantIndexOp>();
89   if (!upperBoundCst || !lowerBoundCst || !stepCst)
90     return false;
91   ub = upperBoundCst.value();
92   lb = lowerBoundCst.value();
93   step = stepCst.value();
94   int64_t numIteration = ceilDiv(ub - lb, step);
95   std::vector<std::pair<Operation *, unsigned>> schedule;
96   options.getScheduleFn(forOp, schedule);
97   if (schedule.empty())
98     return false;
99 
100   opOrder.reserve(schedule.size());
101   for (auto &opSchedule : schedule) {
102     maxStage = std::max(maxStage, opSchedule.second);
103     stages[opSchedule.first] = opSchedule.second;
104     opOrder.push_back(opSchedule.first);
105   }
106   if (numIteration <= maxStage)
107     return false;
108 
109   // All operations need to have a stage.
110   if (forOp
111           .walk([this](Operation *op) {
112             if (op != forOp.getOperation() && !isa<scf::YieldOp>(op) &&
113                 stages.find(op) == stages.end())
114               return WalkResult::interrupt();
115             return WalkResult::advance();
116           })
117           .wasInterrupted())
118     return false;
119 
120   // Only support loop carried dependency with a distance of 1. This means the
121   // source of all the scf.yield operands needs to be defined by operations in
122   // the loop.
123   if (llvm::any_of(forOp.getBody()->getTerminator()->getOperands(),
124                    [this](Value operand) {
125                      Operation *def = operand.getDefiningOp();
126                      return !def || stages.find(def) == stages.end();
127                    }))
128     return false;
129   return true;
130 }
131 
132 void LoopPipelinerInternal::emitPrologue(PatternRewriter &rewriter) {
133   // Initialize the iteration argument to the loop initiale values.
134   for (BlockArgument &arg : forOp.getRegionIterArgs()) {
135     OpOperand &operand = forOp.getOpOperandForRegionIterArg(arg);
136     setValueMapping(arg, operand.get(), 0);
137   }
138   auto yield = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
139   for (int64_t i = 0; i < maxStage; i++) {
140     // special handling for induction variable as the increment is implicit.
141     Value iv = rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(), lb + i);
142     setValueMapping(forOp.getInductionVar(), iv, i);
143     for (Operation *op : opOrder) {
144       if (stages[op] > i)
145         continue;
146       Operation *newOp = rewriter.clone(*op);
147       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
148         auto it = valueMapping.find(op->getOperand(opIdx));
149         if (it != valueMapping.end())
150           newOp->setOperand(opIdx, it->second[i - stages[op]]);
151       }
152       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
153         setValueMapping(op->getResult(destId), newOp->getResult(destId),
154                         i - stages[op]);
155         // If the value is a loop carried dependency update the loop argument
156         // mapping.
157         for (OpOperand &operand : yield->getOpOperands()) {
158           if (operand.get() != op->getResult(destId))
159             continue;
160           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
161                           newOp->getResult(destId), i - stages[op] + 1);
162         }
163       }
164     }
165   }
166 }
167 
168 llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
169 LoopPipelinerInternal::analyzeCrossStageValues() {
170   llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo> crossStageValues;
171   for (Operation *op : opOrder) {
172     unsigned stage = stages[op];
173     for (OpOperand &operand : op->getOpOperands()) {
174       Operation *def = operand.get().getDefiningOp();
175       if (!def)
176         continue;
177       auto defStage = stages.find(def);
178       if (defStage == stages.end() || defStage->second == stage)
179         continue;
180       assert(stage > defStage->second);
181       LiverangeInfo &info = crossStageValues[operand.get()];
182       info.defStage = defStage->second;
183       info.lastUseStage = std::max(info.lastUseStage, stage);
184     }
185   }
186   return crossStageValues;
187 }
188 
189 scf::ForOp LoopPipelinerInternal::createKernelLoop(
190     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
191         &crossStageValues,
192     PatternRewriter &rewriter,
193     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap) {
194   // Creates the list of initial values associated to values used across
195   // stages. The initial values come from the prologue created above.
196   // Keep track of the kernel argument associated to each version of the
197   // values passed to the kernel.
198   llvm::SmallVector<Value> newLoopArg;
199   // For existing loop argument initialize them with the right version from the
200   // prologue.
201   for (auto retVal :
202        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
203     Operation *def = retVal.value().getDefiningOp();
204     assert(def && "Only support loop carried dependencies of distance 1");
205     unsigned defStage = stages[def];
206     Value valueVersion = valueMapping[forOp.getRegionIterArgs()[retVal.index()]]
207                                      [maxStage - defStage];
208     assert(valueVersion);
209     newLoopArg.push_back(valueVersion);
210   }
211   for (auto escape : crossStageValues) {
212     LiverangeInfo &info = escape.second;
213     Value value = escape.first;
214     for (unsigned stageIdx = 0; stageIdx < info.lastUseStage - info.defStage;
215          stageIdx++) {
216       Value valueVersion =
217           valueMapping[value][maxStage - info.lastUseStage + stageIdx];
218       assert(valueVersion);
219       newLoopArg.push_back(valueVersion);
220       loopArgMap[std::make_pair(value, info.lastUseStage - info.defStage -
221                                            stageIdx)] = newLoopArg.size() - 1;
222     }
223   }
224 
225   // Create the new kernel loop. Since we need to peel `numStages - 1`
226   // iteration we change the upper bound to remove those iterations.
227   Value newUb = rewriter.create<arith::ConstantIndexOp>(forOp.getLoc(),
228                                                         ub - maxStage * step);
229   auto newForOp = rewriter.create<scf::ForOp>(
230       forOp.getLoc(), forOp.lowerBound(), newUb, forOp.step(), newLoopArg);
231   return newForOp;
232 }
233 
234 void LoopPipelinerInternal::createKernel(
235     scf::ForOp newForOp,
236     const llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
237         &crossStageValues,
238     const llvm::DenseMap<std::pair<Value, unsigned>, unsigned> &loopArgMap,
239     PatternRewriter &rewriter) {
240   valueMapping.clear();
241 
242   // Create the kernel, we clone instruction based on the order given by
243   // user and remap operands coming from a previous stages.
244   rewriter.setInsertionPoint(newForOp.getBody(), newForOp.getBody()->begin());
245   BlockAndValueMapping mapping;
246   mapping.map(forOp.getInductionVar(), newForOp.getInductionVar());
247   for (auto arg : llvm::enumerate(forOp.getRegionIterArgs())) {
248     mapping.map(arg.value(), newForOp.getRegionIterArgs()[arg.index()]);
249   }
250   for (Operation *op : opOrder) {
251     int64_t useStage = stages[op];
252     auto *newOp = rewriter.clone(*op, mapping);
253     for (OpOperand &operand : op->getOpOperands()) {
254       // Special case for the induction variable uses. We replace it with a
255       // version incremented based on the stage where it is used.
256       if (operand.get() == forOp.getInductionVar()) {
257         rewriter.setInsertionPoint(newOp);
258         Value offset = rewriter.create<arith::ConstantIndexOp>(
259             forOp.getLoc(), (maxStage - stages[op]) * step);
260         Value iv = rewriter.create<arith::AddIOp>(
261             forOp.getLoc(), newForOp.getInductionVar(), offset);
262         newOp->setOperand(operand.getOperandNumber(), iv);
263         rewriter.setInsertionPointAfter(newOp);
264         continue;
265       }
266       auto arg = operand.get().dyn_cast<BlockArgument>();
267       if (arg && arg.getOwner() == forOp.getBody()) {
268         // If the value is a loop carried value coming from stage N + 1 remap,
269         // it will become a direct use.
270         Value ret = forOp.getBody()->getTerminator()->getOperand(
271             arg.getArgNumber() - 1);
272         Operation *dep = ret.getDefiningOp();
273         if (!dep)
274           continue;
275         auto stageDep = stages.find(dep);
276         if (stageDep == stages.end() || stageDep->second == useStage)
277           continue;
278         assert(stageDep->second == useStage + 1);
279         newOp->setOperand(operand.getOperandNumber(),
280                           mapping.lookupOrDefault(ret));
281         continue;
282       }
283       // For operands defined in a previous stage we need to remap it to use
284       // the correct region argument. We look for the right version of the
285       // Value based on the stage where it is used.
286       Operation *def = operand.get().getDefiningOp();
287       if (!def)
288         continue;
289       auto stageDef = stages.find(def);
290       if (stageDef == stages.end() || stageDef->second == useStage)
291         continue;
292       auto remap = loopArgMap.find(
293           std::make_pair(operand.get(), useStage - stageDef->second));
294       assert(remap != loopArgMap.end());
295       newOp->setOperand(operand.getOperandNumber(),
296                         newForOp.getRegionIterArgs()[remap->second]);
297     }
298   }
299 
300   // Collect the Values that need to be returned by the forOp. For each
301   // value we need to have `LastUseStage - DefStage` number of versions
302   // returned.
303   // We create a mapping between original values and the associated loop
304   // returned values that will be needed by the epilogue.
305   llvm::SmallVector<Value> yieldOperands;
306   for (Value retVal : forOp.getBody()->getTerminator()->getOperands()) {
307     yieldOperands.push_back(mapping.lookupOrDefault(retVal));
308   }
309   for (auto &it : crossStageValues) {
310     int64_t version = maxStage - it.second.lastUseStage + 1;
311     unsigned numVersionReturned = it.second.lastUseStage - it.second.defStage;
312     // add the original verstion to yield ops.
313     // If there is a liverange spanning across more than 2 stages we need to add
314     // extra arg.
315     for (unsigned i = 1; i < numVersionReturned; i++) {
316       setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
317                       version++);
318       yieldOperands.push_back(
319           newForOp.getBody()->getArguments()[yieldOperands.size() + 1 +
320                                              newForOp.getNumInductionVars()]);
321     }
322     setValueMapping(it.first, newForOp->getResult(yieldOperands.size()),
323                     version++);
324     yieldOperands.push_back(mapping.lookupOrDefault(it.first));
325   }
326   // Map the yield operand to the forOp returned value.
327   for (auto retVal :
328        llvm::enumerate(forOp.getBody()->getTerminator()->getOperands())) {
329     Operation *def = retVal.value().getDefiningOp();
330     assert(def && "Only support loop carried dependencies of distance 1");
331     unsigned defStage = stages[def];
332     setValueMapping(forOp.getRegionIterArgs()[retVal.index()],
333                     newForOp->getResult(retVal.index()),
334                     maxStage - defStage + 1);
335   }
336   rewriter.create<scf::YieldOp>(forOp.getLoc(), yieldOperands);
337 }
338 
339 llvm::SmallVector<Value>
340 LoopPipelinerInternal::emitEpilogue(PatternRewriter &rewriter) {
341   llvm::SmallVector<Value> returnValues(forOp->getNumResults());
342   // Emit different versions of the induction variable. They will be
343   // removed by dead code if not used.
344   for (int64_t i = 0; i < maxStage; i++) {
345     Value newlastIter = rewriter.create<arith::ConstantIndexOp>(
346         forOp.getLoc(), lb + step * ((((ub - 1) - lb) / step) - i));
347     setValueMapping(forOp.getInductionVar(), newlastIter, maxStage - i);
348   }
349   // Emit `maxStage - 1` epilogue part that includes operations fro stages
350   // [i; maxStage].
351   for (int64_t i = 1; i <= maxStage; i++) {
352     for (Operation *op : opOrder) {
353       if (stages[op] < i)
354         continue;
355       Operation *newOp = rewriter.clone(*op);
356       for (unsigned opIdx = 0; opIdx < op->getNumOperands(); opIdx++) {
357         auto it = valueMapping.find(op->getOperand(opIdx));
358         if (it != valueMapping.end()) {
359           Value v = it->second[maxStage - stages[op] + i];
360           assert(v);
361           newOp->setOperand(opIdx, v);
362         }
363       }
364       for (unsigned destId : llvm::seq(unsigned(0), op->getNumResults())) {
365         setValueMapping(op->getResult(destId), newOp->getResult(destId),
366                         maxStage - stages[op] + i);
367         // If the value is a loop carried dependency update the loop argument
368         // mapping and keep track of the last version to replace the original
369         // forOp uses.
370         for (OpOperand &operand :
371              forOp.getBody()->getTerminator()->getOpOperands()) {
372           if (operand.get() != op->getResult(destId))
373             continue;
374           unsigned version = maxStage - stages[op] + i + 1;
375           // If the version is greater than maxStage it means it maps to the
376           // original forOp returned value.
377           if (version > maxStage) {
378             returnValues[operand.getOperandNumber()] = newOp->getResult(destId);
379             continue;
380           }
381           setValueMapping(forOp.getRegionIterArgs()[operand.getOperandNumber()],
382                           newOp->getResult(destId), version);
383         }
384       }
385     }
386   }
387   return returnValues;
388 }
389 
390 void LoopPipelinerInternal::setValueMapping(Value key, Value el, int64_t idx) {
391   auto it = valueMapping.find(key);
392   // If the value is not in the map yet add a vector big enough to store all
393   // versions.
394   if (it == valueMapping.end())
395     it =
396         valueMapping
397             .insert(std::make_pair(key, llvm::SmallVector<Value>(maxStage + 1)))
398             .first;
399   it->second[idx] = el;
400 }
401 
402 /// Generate a pipelined version of the scf.for loop based on the schedule given
403 /// as option. This applies the mechanical transformation of changing the loop
404 /// and generating the prologue/epilogue for the pipelining and doesn't make any
405 /// decision regarding the schedule.
406 /// Based on the option the loop is split into several stages.
407 /// The transformation assumes that the scheduling given by user is valid.
408 /// For example if we break a loop into 3 stages named S0, S1, S2 we would
409 /// generate the following code with the number in parenthesis the iteration
410 /// index:
411 /// S0(0)                        // Prologue
412 /// S0(1) S1(0)                  // Prologue
413 /// scf.for %I = %C0 to %N - 2 {
414 ///  S0(I+2) S1(I+1) S2(I)       // Pipelined kernel
415 /// }
416 /// S1(N) S2(N-1)                // Epilogue
417 /// S2(N)                        // Epilogue
418 struct ForLoopPipelining : public OpRewritePattern<ForOp> {
419   ForLoopPipelining(const PipeliningOption &options, MLIRContext *context)
420       : OpRewritePattern<ForOp>(context), options(options) {}
421   LogicalResult matchAndRewrite(ForOp forOp,
422                                 PatternRewriter &rewriter) const override {
423 
424     LoopPipelinerInternal pipeliner;
425     if (!pipeliner.initializeLoopInfo(forOp, options))
426       return failure();
427 
428     // 1. Emit prologue.
429     pipeliner.emitPrologue(rewriter);
430 
431     // 2. Track values used across stages. When a value cross stages it will
432     // need to be passed as loop iteration arguments.
433     // We first collect the values that are used in a different stage than where
434     // they are defined.
435     llvm::MapVector<Value, LoopPipelinerInternal::LiverangeInfo>
436         crossStageValues = pipeliner.analyzeCrossStageValues();
437 
438     // Mapping between original loop values used cross stage and the block
439     // arguments associated after pipelining. A Value may map to several
440     // arguments if its liverange spans across more than 2 stages.
441     llvm::DenseMap<std::pair<Value, unsigned>, unsigned> loopArgMap;
442     // 3. Create the new kernel loop and return the block arguments mapping.
443     ForOp newForOp =
444         pipeliner.createKernelLoop(crossStageValues, rewriter, loopArgMap);
445     // Create the kernel block, order ops based on user choice and remap
446     // operands.
447     pipeliner.createKernel(newForOp, crossStageValues, loopArgMap, rewriter);
448 
449     // 4. Emit the epilogue after the new forOp.
450     rewriter.setInsertionPointAfter(newForOp);
451     llvm::SmallVector<Value> returnValues = pipeliner.emitEpilogue(rewriter);
452 
453     // 5. Erase the original loop and replace the uses with the epilogue output.
454     if (forOp->getNumResults() > 0)
455       rewriter.replaceOp(forOp, returnValues);
456     else
457       rewriter.eraseOp(forOp);
458 
459     return success();
460   }
461 
462 protected:
463   PipeliningOption options;
464 };
465 
466 } // namespace
467 
468 void mlir::scf::populateSCFLoopPipeliningPatterns(
469     RewritePatternSet &patterns, const PipeliningOption &options) {
470   patterns.add<ForLoopPipelining>(options, patterns.getContext());
471 }
472