1 //===-BlockGenerators.h - Helper to generate code for statements-*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the BlockGenerator and VectorBlockGenerator classes, which
11 // generate sequential code and vectorized code for a polyhedral statement,
12 // respectively.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef POLLY_BLOCK_GENERATORS_H
17 #define POLLY_BLOCK_GENERATORS_H
18 
19 #include "polly/CodeGen/IRBuilder.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
22 #include "isl/map.h"
23 #include <vector>
24 
25 struct isl_ast_build;
26 
27 namespace llvm {
28 class Pass;
29 class Region;
30 class ScalarEvolution;
31 }
32 
33 namespace polly {
34 using namespace llvm;
35 class ScopStmt;
36 class MemoryAccess;
37 class IslExprBuilder;
38 
39 typedef DenseMap<const Value *, Value *> ValueMapT;
40 typedef std::vector<ValueMapT> VectorValueMapT;
41 
42 /// @brief Check whether an instruction can be synthesized by the code
43 ///        generator.
44 ///
45 /// Some instructions will be recalculated only from information that is code
46 /// generated from the polyhedral representation. For such instructions we do
47 /// not need to ensure that their operands are available during code generation.
48 ///
49 /// @param I The instruction to check.
50 /// @param LI The LoopInfo analysis.
51 /// @param SE The scalar evolution database.
52 /// @param R The region out of which SSA names are parameters.
53 /// @return If the instruction I can be regenerated from its
54 ///         scalar evolution representation, return true,
55 ///         otherwise return false.
56 bool canSynthesize(const llvm::Instruction *I, const llvm::LoopInfo *LI,
57                    llvm::ScalarEvolution *SE, const llvm::Region *R);
58 
59 /// @brief Return true iff @p V is an intrinsic that we ignore during code
60 ///        generation.
61 bool isIgnoredIntrinsic(const llvm::Value *V);
62 
63 /// @brief Generate a new basic block for a polyhedral statement.
64 class BlockGenerator {
65 public:
66   /// @brief Map types to resolve scalar dependences.
67   ///
68   ///@{
69 
70   /// @see The ScalarMap and PHIOpMap member.
71   using ScalarAllocaMapTy = DenseMap<Instruction *, AllocaInst *>;
72 
73   /// @brief Simple vector of instructions to store escape users.
74   using EscapeUserVectorTy = SmallVector<Instruction *, 4>;
75 
76   /// @brief Map type to resolve escaping users for scalar instructions.
77   ///
78   /// @see The EscapeMap member.
79   using EscapeUsersAllocaMapTy =
80       DenseMap<Instruction *, std::pair<AllocaInst *, EscapeUserVectorTy>>;
81 
82   ///@}
83 
84   /// @brief Create a generator for basic blocks.
85   ///
86   /// @param Builder     The LLVM-IR Builder used to generate the statement. The
87   ///                    code is generated at the location, the Builder points
88   ///                    to.
89   /// @param LI          The loop info for the current function
90   /// @param SE          The scalar evolution info for the current function
91   /// @param DT          The dominator tree of this function.
92   /// @param ScalarMap   Map from scalars to their demoted location.
93   /// @param PHIOpMap    Map from PHIs to their demoted operand location.
94   /// @param EscapeMap   Map from scalars to their escape users and locations.
95   /// @param ExprBuilder An expression builder to generate new access functions.
96   BlockGenerator(PollyIRBuilder &Builder, LoopInfo &LI, ScalarEvolution &SE,
97                  DominatorTree &DT, ScalarAllocaMapTy &ScalarMap,
98                  ScalarAllocaMapTy &PHIOpMap, EscapeUsersAllocaMapTy &EscapeMap,
99                  IslExprBuilder *ExprBuilder = nullptr);
100 
101   /// @brief Copy the basic block.
102   ///
103   /// This copies the entire basic block and updates references to old values
104   /// with references to new values, as defined by GlobalMap.
105   ///
106   /// @param Stmt      The block statement to code generate.
107   /// @param GlobalMap A mapping from old values to their new values
108   ///                  (for values recalculated in the new ScoP, but not
109   ///                  within this basic block).
110   /// @param LTS       A map from old loops to new induction variables as SCEVs.
111   void copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap, LoopToScevMapT &LTS);
112 
113   /// @brief Finalize the code generation for the SCoP @p S.
114   ///
115   /// This will initialize and finalize the scalar variables we demoted during
116   /// the code generation.
117   ///
118   /// @see createScalarInitialization(Region &, ValueMapT &)
119   /// @see createScalarFinalization(Region &)
120   void finalizeSCoP(Scop &S, ValueMapT &VMap);
121 
122   /// @brief An empty destructor
123   virtual ~BlockGenerator(){};
124 
125 protected:
126   PollyIRBuilder &Builder;
127   LoopInfo &LI;
128   ScalarEvolution &SE;
129   IslExprBuilder *ExprBuilder;
130 
131   /// @brief The dominator tree of this function.
132   DominatorTree &DT;
133 
134   /// @brief The entry block of the current function.
135   BasicBlock *EntryBB;
136 
137   /// @brief Maps to resolve scalar dependences for PHI operands and scalars.
138   ///
139   /// When translating code that contains scalar dependences as they result from
140   /// inter-block scalar dependences (including the use of data carrying
141   /// PHI nodes), we do not directly regenerate in-register SSA code, but
142   /// instead allocate some stack memory through which these scalar values are
143   /// passed. Only a later pass of -mem2reg will then (re)introduce in-register
144   /// computations.
145   ///
146   /// To keep track of the memory location(s) used to store the data computed by
147   /// a given SSA instruction, we use the maps 'ScalarMap' and 'PHIOpMap'. Each
148   /// maps a given scalar value to a junk of stack allocated memory.
149   ///
150   /// 'ScalarMap' is used for normal scalar dependences that go from a scalar
151   /// definition to its use. Such dependences are lowered by directly writing
152   /// the value an instruction computes into the corresponding chunk of memory
153   /// and reading it back from this chunk of memory right before every use of
154   /// this original scalar value. The memory locations in 'ScalarMap' end with
155   /// '.s2a'.
156   ///
157   /// 'PHIOpMap' is used to model PHI nodes. For each PHI nodes we introduce,
158   /// besides the memory in 'ScalarMap', a second chunk of memory into which we
159   /// write at the end of each basic block preceeding the PHI instruction the
160   /// value passed through this basic block. At the place where the PHI node is
161   /// executed, we replace the PHI node with a load from the corresponding
162   /// memory location in the 'PHIOpMap' table. The memory locations in
163   /// 'PHIOpMap' end with '.phiops'.
164   ///
165   /// The ScopArrayInfo objects of accesses that belong to a PHI node may have
166   /// identical base pointers, even though they refer to two different memory
167   /// locations, the normal '.s2a' locations and the special '.phiops'
168   /// locations. For historic reasons we keep such accesses in two maps
169   /// 'ScalarMap' and 'PHIOpMap', index by the BasePointer. An alternative
170   /// implemenation, could use a single map that uses the ScopArrayInfo object
171   /// as index.
172   ///
173   /// Example:
174   ///
175   ///                              Input C Code
176   ///                              ============
177   ///
178   ///                 S1:      x1 = ...
179   ///                          for (i=0...N) {
180   ///                 S2:           x2 = phi(x1, add)
181   ///                 S3:           add = x2 + 42;
182   ///                          }
183   ///                 S4:      print(x1)
184   ///                          print(x2)
185   ///                          print(add)
186   ///
187   ///
188   ///        Unmodified IR                         IR After expansion
189   ///        =============                         ==================
190   ///
191   /// S1:   x1 = ...                     S1:    x1 = ...
192   ///                                           x1.s2a = s1
193   ///                                           x2.phiops = s1
194   ///        |                                    |
195   ///        |   <--<--<--<--<                    |   <--<--<--<--<
196   ///        | /              \                   | /              \
197   ///        V V               \                  V V               \
198   /// S2:  x2 = phi (x1, add)   |        S2:    x2 = x2.phiops       |
199   ///                           |               x2.s2a = x2          |
200   ///                           |                                    |
201   /// S3:  add = x2 + 42        |        S3:    add = x2 + 42        |
202   ///                           |               add.s2a = add        |
203   ///                           |               x2.phiops = add      |
204   ///        | \               /                  | \               /
205   ///        |  \             /                   |  \             /
206   ///        |   >-->-->-->-->                    |   >-->-->-->-->
207   ///        V                                    V
208   ///
209   ///                                    S4:    x1 = x1.s2a
210   /// S4:  ... = x1                             ... = x1
211   ///                                           x2 = x2.s2a
212   ///      ... = x2                             ... = x2
213   ///                                           add = add.s2a
214   ///      ... = add                            ... = add
215   ///
216   ///      ScalarMap = { x1 -> x1.s2a, x2 -> x2.s2a, add -> add.s2a }
217   ///      PHIOpMap =  { x2 -> x2.phiops }
218   ///
219   ///
220   ///  ??? Why does a PHI-node require two memory chunks ???
221   ///
222   ///  One may wonder why a PHI node requires two memory chunks and not just
223   ///  all data is stored in a single location. The following example tries
224   ///  to store all data in .s2a and drops the .phiops location:
225   ///
226   ///      S1:    x1 = ...
227   ///             x1.s2a = s1
228   ///             x2.s2a = s1             // use .s2a instead of .phiops
229   ///               |
230   ///               |   <--<--<--<--<
231   ///               | /              \
232   ///               V V               \
233   ///      S2:    x2 = x2.s2a          |  // value is same as above, but read
234   ///                                  |  // from .s2a
235   ///                                  |
236   ///             x2.s2a = x2          |  // store into .s2a as normal
237   ///                                  |
238   ///      S3:    add = x2 + 42        |
239   ///             add.s2a = add        |
240   ///             x2.s2a = add         |  // use s2a instead of .phiops
241   ///               | \               /   // !!! This is wrong, as x2.s2a now
242   ///               |   >-->-->-->-->     // contains add instead of x2.
243   ///               V
244   ///
245   ///      S4:    x1 = x1.s2a
246   ///             ... = x1
247   ///             x2 = x2.s2a             // !!! We now read 'add' instead of
248   ///             ... = x2                // 'x2'
249   ///             add = add.s2a
250   ///             ... = add
251   ///
252   ///  As visible in the example, the SSA value of the PHI node may still be
253   ///  needed _after_ the basic block, which could conceptually branch to the
254   ///  PHI node, has been run and has overwritten the PHI's old value. Hence, a
255   ///  single memory location is not enough to code-generate a PHI node.
256   ///
257   ///{
258   ///
259   /// @brief Memory locations used for the special PHI node modeling.
260   ScalarAllocaMapTy &PHIOpMap;
261 
262   /// @brief Memory locations used to model scalar dependences.
263   ScalarAllocaMapTy &ScalarMap;
264   ///}
265 
266   /// @brief Map from instructions to their escape users as well as the alloca.
267   EscapeUsersAllocaMapTy &EscapeMap;
268 
269   /// @brief Split @p BB to create a new one we can use to clone @p BB in.
270   BasicBlock *splitBB(BasicBlock *BB);
271 
272   /// @brief Copy the given basic block.
273   ///
274   /// @param Stmt      The statement to code generate.
275   /// @param BB        The basic block to code generate.
276   /// @param BBMap     A mapping from old values to their new values in this
277   /// block.
278   /// @param GlobalMap A mapping from old values to their new values
279   ///                  (for values recalculated in the new ScoP, but not
280   ///                  within this basic block).
281   /// @param LTS       A map from old loops to new induction variables as SCEVs.
282   ///
283   /// @returns The copy of the basic block.
284   BasicBlock *copyBB(ScopStmt &Stmt, BasicBlock *BB, ValueMapT &BBMap,
285                      ValueMapT &GlobalMap, LoopToScevMapT &LTS);
286 
287   /// @brief Copy the given basic block.
288   ///
289   /// @param Stmt      The statement to code generate.
290   /// @param BB        The basic block to code generate.
291   /// @param BBCopy    The new basic block to generate code in.
292   /// @param BBMap     A mapping from old values to their new values in this
293   /// block.
294   /// @param GlobalMap A mapping from old values to their new values
295   ///                  (for values recalculated in the new ScoP, but not
296   ///                  within this basic block).
297   /// @param LTS       A map from old loops to new induction variables as SCEVs.
298   void copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *BBCopy,
299               ValueMapT &BBMap, ValueMapT &GlobalMap, LoopToScevMapT &LTS);
300 
301   /// @brief Return the alloca for @p ScalarBase in @p Map.
302   ///
303   /// If no alloca was mapped to @p ScalarBase in @p Map a new one is created
304   /// and named after @p ScalarBase with the suffix @p NameExt.
305   ///
306   /// @param ScalarBase The demoted scalar instruction.
307   /// @param Map        The map we should look for a mapped alloca instruction.
308   /// @param NameExt    The suffix we add to the name of a new created alloca.
309   /// @param IsNew      If set it will hold true iff the alloca was created.
310   ///
311   /// @returns The alloca for @p ScalarBase in @p Map.
312   AllocaInst *getOrCreateAlloca(Instruction *ScalarBase, ScalarAllocaMapTy &Map,
313                                 const char *NameExt = ".s2a",
314                                 bool *IsNew = nullptr);
315 
316   /// @brief Generate reload of scalars demoted to memory and needed by @p Inst.
317   ///
318   /// @param Stmt  The statement we generate code for.
319   /// @param Inst  The instruction that might need reloaded values.
320   /// @param BBMap A mapping from old values to their new values in this block.
321   virtual void generateScalarLoads(ScopStmt &Stmt, const Instruction *Inst,
322                                    ValueMapT &BBMap);
323 
324   /// @brief Generate the scalar stores for the given statement.
325   ///
326   /// After the statement @p Stmt was copied all inner-SCoP scalar dependences
327   /// starting in @p Stmt (hence all scalar write accesses in @p Stmt) need to
328   /// be demoted to memory.
329   ///
330   /// @param Stmt  The statement we generate code for.
331   /// @param BB    The basic block we generate code for.
332   /// @param BBMap A mapping from old values to their new values in this block.
333   /// @param GlobalMap A mapping for globally replaced values.
334   virtual void generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
335                                     ValueMapT &BBMAp, ValueMapT &GlobalMap);
336 
337   /// @brief Handle users of @p Inst outside the SCoP.
338   ///
339   /// @param R        The current SCoP region.
340   /// @param Inst     The current instruction we check.
341   /// @param InstCopy The copy of the instruction @p Inst in the optimized SCoP.
342   void handleOutsideUsers(const Region &R, Instruction *Inst, Value *InstCopy);
343 
344   /// @brief Initialize the memory of demoted scalars.
345   ///
346   /// If a PHI node was demoted and one of its predecessor blocks was outside
347   /// the SCoP we need to initialize the memory cell we demoted the PHI into
348   /// with the value corresponding to that predecessor. As a SCoP is a
349   /// __single__ entry region there is at most one such predecessor.
350   void createScalarInitialization(Region &R, ValueMapT &VMap);
351 
352   /// @brief Promote the values of demoted scalars after the SCoP.
353   ///
354   /// If a scalar value was used outside the SCoP we need to promote the value
355   /// stored in the memory cell allocated for that scalar and combine it with
356   /// the original value in the non-optimized SCoP.
357   void createScalarFinalization(Region &R);
358 
359   /// @brief Get the new version of a value.
360   ///
361   /// Given an old value, we first check if a new version of this value is
362   /// available in the BBMap or GlobalMap. In case it is not and the value can
363   /// be recomputed using SCEV, we do so. If we can not recompute a value
364   /// using SCEV, but we understand that the value is constant within the scop,
365   /// we return the old value.  If the value can still not be derived, this
366   /// function will assert.
367   ///
368   /// @param Stmt      The statement to code generate.
369   /// @param Old       The old Value.
370   /// @param BBMap     A mapping from old values to their new values
371   ///                  (for values recalculated within this basic block).
372   /// @param GlobalMap A mapping from old values to their new values
373   ///                  (for values recalculated in the new ScoP, but not
374   ///                   within this basic block).
375   /// @param LTS       A mapping from loops virtual canonical induction
376   ///                  variable to their new values
377   ///                  (for values recalculated in the new ScoP, but not
378   ///                   within this basic block).
379   /// @param L         The loop that surrounded the instruction that referenced
380   ///                  this value in the original code. This loop is used to
381   ///                  evaluate the scalar evolution at the right scope.
382   ///
383   /// @returns  o The old value, if it is still valid.
384   ///           o The new value, if available.
385   ///           o NULL, if no value is found.
386   Value *getNewValue(ScopStmt &Stmt, const Value *Old, ValueMapT &BBMap,
387                      ValueMapT &GlobalMap, LoopToScevMapT &LTS, Loop *L) const;
388 
389   void copyInstScalar(ScopStmt &Stmt, const Instruction *Inst, ValueMapT &BBMap,
390                       ValueMapT &GlobalMap, LoopToScevMapT &LTS);
391 
392   /// @brief Get the innermost loop that surrounds an instruction.
393   ///
394   /// @param Inst The instruction for which we get the loop.
395   /// @return The innermost loop that surrounds the instruction.
396   Loop *getLoopForInst(const Instruction *Inst);
397 
398   /// @brief Get the new operand address according to access relation of @p MA.
399   Value *getNewAccessOperand(ScopStmt &Stmt, const MemoryAccess &MA);
400 
401   /// @brief Generate the operand address
402   Value *generateLocationAccessed(ScopStmt &Stmt, const Instruction *Inst,
403                                   const Value *Pointer, ValueMapT &BBMap,
404                                   ValueMapT &GlobalMap, LoopToScevMapT &LTS);
405 
406   Value *generateScalarLoad(ScopStmt &Stmt, const LoadInst *load,
407                             ValueMapT &BBMap, ValueMapT &GlobalMap,
408                             LoopToScevMapT &LTS);
409 
410   Value *generateScalarStore(ScopStmt &Stmt, const StoreInst *store,
411                              ValueMapT &BBMap, ValueMapT &GlobalMap,
412                              LoopToScevMapT &LTS);
413 
414   /// @brief Copy a single PHI instruction.
415   ///
416   /// The implementation in the BlockGenerator is trivial, however it allows
417   /// subclasses to handle PHIs different.
418   ///
419   /// @returns The nullptr as the BlockGenerator does not copy PHIs.
420   virtual Value *copyPHIInstruction(ScopStmt &, const PHINode *, ValueMapT &,
421                                     ValueMapT &, LoopToScevMapT &) {
422     return nullptr;
423   }
424 
425   /// @brief Copy a single Instruction.
426   ///
427   /// This copies a single Instruction and updates references to old values
428   /// with references to new values, as defined by GlobalMap and BBMap.
429   ///
430   /// @param Stmt      The statement to code generate.
431   /// @param Inst      The instruction to copy.
432   /// @param BBMap     A mapping from old values to their new values
433   ///                  (for values recalculated within this basic block).
434   /// @param GlobalMap A mapping from old values to their new values
435   ///                  (for values recalculated in the new ScoP, but not
436   ///                  within this basic block).
437   /// @param LTS       A mapping from loops virtual canonical induction
438   ///                  variable to their new values
439   ///                  (for values recalculated in the new ScoP, but not
440   ///                   within this basic block).
441   void copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
442                        ValueMapT &BBMap, ValueMapT &GlobalMap,
443                        LoopToScevMapT &LTS);
444 
445   /// @brief Helper to get the newest version of @p ScalarValue.
446   ///
447   /// @param ScalarValue The original value needed.
448   /// @param R           The current SCoP region.
449   /// @param ReloadMap   The scalar map for demoted values.
450   /// @param BBMap       A mapping from old values to their new values
451   ///                    (for values recalculated within this basic block).
452   /// @param GlobalMap   A mapping from old values to their new values
453   ///                    (for values recalculated in the new ScoP, but not
454   ///                    within this basic block).
455   ///
456   /// @returns The newest version (e.g., reloaded) of the scalar value.
457   Value *getNewScalarValue(Value *ScalarValue, const Region &R,
458                            ScalarAllocaMapTy &ReloadMap, ValueMapT &BBMap,
459                            ValueMapT &GlobalMap);
460 };
461 
462 /// @brief Generate a new vector basic block for a polyhedral statement.
463 ///
464 /// The only public function exposed is generate().
465 class VectorBlockGenerator : BlockGenerator {
466 public:
467   /// @brief Generate a new vector basic block for a ScoPStmt.
468   ///
469   /// This code generation is similar to the normal, scalar code generation,
470   /// except that each instruction is code generated for several vector lanes
471   /// at a time. If possible instructions are issued as actual vector
472   /// instructions, but e.g. for address calculation instructions we currently
473   /// generate scalar instructions for each vector lane.
474   ///
475   /// @param BlockGen   A block generator object used as parent.
476   /// @param Stmt       The statement to code generate.
477   /// @param GlobalMaps A vector of maps that define for certain Values
478   ///                   referenced from the original code new Values they should
479   ///                   be replaced with. Each map in the vector of maps is
480   ///                   used for one vector lane. The number of elements in the
481   ///                   vector defines the width of the generated vector
482   ///                   instructions.
483   /// @param VLTS       A mapping from loops virtual canonical induction
484   ///                   variable to their new values
485   ///                   (for values recalculated in the new ScoP, but not
486   ///                    within this basic block), one for each lane.
487   /// @param Schedule   A map from the statement to a schedule where the
488   ///                   innermost dimension is the dimension of the innermost
489   ///                   loop containing the statemenet.
490   static void generate(BlockGenerator &BlockGen, ScopStmt &Stmt,
491                        VectorValueMapT &GlobalMaps,
492                        std::vector<LoopToScevMapT> &VLTS,
493                        __isl_keep isl_map *Schedule) {
494     VectorBlockGenerator Generator(BlockGen, GlobalMaps, VLTS, Schedule);
495     Generator.copyStmt(Stmt);
496   }
497 
498 private:
499   // This is a vector of global value maps.  The first map is used for the first
500   // vector lane, ...
501   // Each map, contains information about Instructions in the old ScoP, which
502   // are recalculated in the new SCoP. When copying the basic block, we replace
503   // all referenes to the old instructions with their recalculated values.
504   VectorValueMapT &GlobalMaps;
505 
506   // This is a vector of loop->scev maps.  The first map is used for the first
507   // vector lane, ...
508   // Each map, contains information about Instructions in the old ScoP, which
509   // are recalculated in the new SCoP. When copying the basic block, we replace
510   // all referenes to the old instructions with their recalculated values.
511   //
512   // For example, when the code generator produces this AST:
513   //
514   //   for (int c1 = 0; c1 <= 1023; c1 += 1)
515   //     for (int c2 = 0; c2 <= 1023; c2 += VF)
516   //       for (int lane = 0; lane <= VF; lane += 1)
517   //         Stmt(c2 + lane + 3, c1);
518   //
519   // VLTS[lane] contains a map:
520   //   "outer loop in the old loop nest" -> SCEV("c2 + lane + 3"),
521   //   "inner loop in the old loop nest" -> SCEV("c1").
522   std::vector<LoopToScevMapT> &VLTS;
523 
524   // A map from the statement to a schedule where the innermost dimension is the
525   // dimension of the innermost loop containing the statemenet.
526   isl_map *Schedule;
527 
528   VectorBlockGenerator(BlockGenerator &BlockGen, VectorValueMapT &GlobalMaps,
529                        std::vector<LoopToScevMapT> &VLTS,
530                        __isl_keep isl_map *Schedule);
531 
532   int getVectorWidth();
533 
534   Value *getVectorValue(ScopStmt &Stmt, const Value *Old, ValueMapT &VectorMap,
535                         VectorValueMapT &ScalarMaps, Loop *L);
536 
537   Type *getVectorPtrTy(const Value *V, int Width);
538 
539   /// @brief Load a vector from a set of adjacent scalars
540   ///
541   /// In case a set of scalars is known to be next to each other in memory,
542   /// create a vector load that loads those scalars
543   ///
544   /// %vector_ptr= bitcast double* %p to <4 x double>*
545   /// %vec_full = load <4 x double>* %vector_ptr
546   ///
547   /// @param Stmt           The statement to code generate.
548   /// @param NegativeStride This is used to indicate a -1 stride. In such
549   ///                       a case we load the end of a base address and
550   ///                       shuffle the accesses in reverse order into the
551   ///                       vector. By default we would do only positive
552   ///                       strides.
553   ///
554   Value *generateStrideOneLoad(ScopStmt &Stmt, const LoadInst *Load,
555                                VectorValueMapT &ScalarMaps,
556                                bool NegativeStride);
557 
558   /// @brief Load a vector initialized from a single scalar in memory
559   ///
560   /// In case all elements of a vector are initialized to the same
561   /// scalar value, this value is loaded and shuffeled into all elements
562   /// of the vector.
563   ///
564   /// %splat_one = load <1 x double>* %p
565   /// %splat = shufflevector <1 x double> %splat_one, <1 x
566   ///       double> %splat_one, <4 x i32> zeroinitializer
567   ///
568   Value *generateStrideZeroLoad(ScopStmt &Stmt, const LoadInst *Load,
569                                 ValueMapT &BBMap);
570 
571   /// @brief Load a vector from scalars distributed in memory
572   ///
573   /// In case some scalars a distributed randomly in memory. Create a vector
574   /// by loading each scalar and by inserting one after the other into the
575   /// vector.
576   ///
577   /// %scalar_1= load double* %p_1
578   /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
579   /// %scalar 2 = load double* %p_2
580   /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
581   ///
582   Value *generateUnknownStrideLoad(ScopStmt &Stmt, const LoadInst *Load,
583                                    VectorValueMapT &ScalarMaps);
584 
585   void generateLoad(ScopStmt &Stmt, const LoadInst *Load, ValueMapT &VectorMap,
586                     VectorValueMapT &ScalarMaps);
587 
588   void copyUnaryInst(ScopStmt &Stmt, const UnaryInstruction *Inst,
589                      ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
590 
591   void copyBinaryInst(ScopStmt &Stmt, const BinaryOperator *Inst,
592                       ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
593 
594   void copyStore(ScopStmt &Stmt, const StoreInst *Store, ValueMapT &VectorMap,
595                  VectorValueMapT &ScalarMaps);
596 
597   void copyInstScalarized(ScopStmt &Stmt, const Instruction *Inst,
598                           ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
599 
600   bool extractScalarValues(const Instruction *Inst, ValueMapT &VectorMap,
601                            VectorValueMapT &ScalarMaps);
602 
603   bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
604 
605   void copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
606                        ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
607 
608   void copyStmt(ScopStmt &Stmt);
609 };
610 
611 /// @brief Generator for new versions of polyhedral region statements.
612 class RegionGenerator : public BlockGenerator {
613 public:
614   /// @brief Create a generator for regions.
615   ///
616   /// @param BlockGen A generator for basic blocks.
617   RegionGenerator(BlockGenerator &BlockGen) : BlockGenerator(BlockGen) {}
618 
619   /// @brief Copy the region statement @p Stmt.
620   ///
621   /// This copies the entire region represented by @p Stmt and updates
622   /// references to old values with references to new values, as defined by
623   /// GlobalMap.
624   ///
625   /// @param Stmt      The statement to code generate.
626   /// @param GlobalMap A mapping from old values to their new values
627   ///                  (for values recalculated in the new ScoP, but not
628   ///                  within this basic block).
629   /// @param LTS       A map from old loops to new induction variables as SCEVs.
630   void copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap, LoopToScevMapT &LTS);
631 
632   /// @brief An empty destructor
633   virtual ~RegionGenerator(){};
634 
635 private:
636   /// @brief A map from old to new blocks in the region.
637   DenseMap<BasicBlock *, BasicBlock *> BlockMap;
638 
639   /// @brief The "BBMaps" for the whole region (one for each block).
640   DenseMap<BasicBlock *, ValueMapT> RegionMaps;
641 
642   /// @brief Mapping to remember PHI nodes that still need incoming values.
643   using PHINodePairTy = std::pair<const PHINode *, PHINode *>;
644   DenseMap<BasicBlock *, SmallVector<PHINodePairTy, 4>> IncompletePHINodeMap;
645 
646   /// @brief Repair the dominance tree after we created a copy block for @p BB.
647   ///
648   /// @returns The immediate dominator in the DT for @p BBCopy if in the region.
649   BasicBlock *repairDominance(BasicBlock *BB, BasicBlock *BBCopy);
650 
651   /// @brief Add the new operand from the copy of @p IncomingBB to @p PHICopy.
652   ///
653   /// @param Stmt       The statement to code generate.
654   /// @param PHI        The original PHI we copy.
655   /// @param PHICopy    The copy of @p PHI.
656   /// @param IncomingBB An incoming block of @p PHI.
657   /// @param GlobalMap  A mapping from old values to their new values
658   ///                   (for values recalculated in the new ScoP, but not
659   ///                   within this basic block).
660   /// @param LTS        A map from old loops to new induction variables as
661   /// SCEVs.
662   void addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI, PHINode *PHICopy,
663                        BasicBlock *IncomingBB, ValueMapT &GlobalMap,
664                        LoopToScevMapT &LTS);
665 
666   /// @brief Generate reload of scalars demoted to memory and needed by @p Inst.
667   ///
668   /// @param Stmt  The statement we generate code for.
669   /// @param Inst  The instruction that might need reloaded values.
670   /// @param BBMap A mapping from old values to their new values in this block.
671   virtual void generateScalarLoads(ScopStmt &Stmt, const Instruction *Inst,
672                                    ValueMapT &BBMap) override;
673 
674   /// @brief Generate the scalar stores for the given statement.
675   ///
676   /// After the statement @p Stmt was copied all inner-SCoP scalar dependences
677   /// starting in @p Stmt (hence all scalar write accesses in @p Stmt) need to
678   /// be demoted to memory.
679   ///
680   /// @param Stmt  The statement we generate code for.
681   /// @param BB    The basic block we generate code for.
682   /// @param BBMap A mapping from old values to their new values in this block.
683   /// @param GlobalMap  A mapping from old values to their new values
684   ///                   (for values recalculated in the new ScoP, but not
685   ///                   within this basic block).
686   virtual void generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
687                                     ValueMapT &BBMAp,
688                                     ValueMapT &GlobalMap) override;
689 
690   /// @brief Copy a single PHI instruction.
691   ///
692   /// This copies a single PHI instruction and updates references to old values
693   /// with references to new values, as defined by GlobalMap and BBMap.
694   ///
695   /// @param Stmt      The statement to code generate.
696   /// @param PHI       The PHI instruction to copy.
697   /// @param BBMap     A mapping from old values to their new values
698   ///                  (for values recalculated within this basic block).
699   /// @param GlobalMap A mapping from old values to their new values
700   ///                  (for values recalculated in the new ScoP, but not
701   ///                  within this basic block).
702   /// @param LTS       A map from old loops to new induction variables as SCEVs.
703   ///
704   /// @returns The copied instruction or nullptr if no copy was made.
705   virtual Value *copyPHIInstruction(ScopStmt &Stmt, const PHINode *Inst,
706                                     ValueMapT &BBMap, ValueMapT &GlobalMap,
707                                     LoopToScevMapT &LTS) override;
708 };
709 }
710 #endif
711