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