Coverage Report

Created: 2017-11-23 03:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/include/polly/CodeGen/BlockGenerators.h
Line
Count
Source (jump to first uncovered line)
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 "polly/Support/GICHelper.h"
21
#include "polly/Support/ScopHelper.h"
22
#include "llvm/ADT/MapVector.h"
23
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
24
#include "isl/map.h"
25
26
struct isl_ast_build;
27
struct isl_id_to_ast_expr;
28
29
namespace llvm {
30
class Pass;
31
class Region;
32
class ScalarEvolution;
33
} // namespace llvm
34
35
namespace polly {
36
using namespace llvm;
37
class ScopStmt;
38
class MemoryAccess;
39
class ScopArrayInfo;
40
class IslExprBuilder;
41
42
/// Generate a new basic block for a polyhedral statement.
43
class BlockGenerator {
44
public:
45
  typedef llvm::SmallVector<ValueMapT, 8> VectorValueMapT;
46
47
  /// Map types to resolve scalar dependences.
48
  ///
49
  ///@{
50
  using AllocaMapTy = DenseMap<const ScopArrayInfo *, AssertingVH<AllocaInst>>;
51
52
  /// Simple vector of instructions to store escape users.
53
  using EscapeUserVectorTy = SmallVector<Instruction *, 4>;
54
55
  /// Map type to resolve escaping users for scalar instructions.
56
  ///
57
  /// @see The EscapeMap member.
58
  using EscapeUsersAllocaMapTy =
59
      MapVector<Instruction *,
60
                std::pair<AssertingVH<Value>, EscapeUserVectorTy>>;
61
62
  ///@}
63
64
  /// Create a generator for basic blocks.
65
  ///
66
  /// @param Builder     The LLVM-IR Builder used to generate the statement. The
67
  ///                    code is generated at the location, the Builder points
68
  ///                    to.
69
  /// @param LI          The loop info for the current function
70
  /// @param SE          The scalar evolution info for the current function
71
  /// @param DT          The dominator tree of this function.
72
  /// @param ScalarMap   Map from scalars to their demoted location.
73
  /// @param EscapeMap   Map from scalars to their escape users and locations.
74
  /// @param GlobalMap   A mapping from llvm::Values used in the original scop
75
  ///                    region to a new set of llvm::Values. Each reference to
76
  ///                    an original value appearing in this mapping is replaced
77
  ///                    with the new value it is mapped to.
78
  /// @param ExprBuilder An expression builder to generate new access functions.
79
  /// @param StartBlock  The first basic block after the RTC.
80
  BlockGenerator(PollyIRBuilder &Builder, LoopInfo &LI, ScalarEvolution &SE,
81
                 DominatorTree &DT, AllocaMapTy &ScalarMap,
82
                 EscapeUsersAllocaMapTy &EscapeMap, ValueMapT &GlobalMap,
83
                 IslExprBuilder *ExprBuilder, BasicBlock *StartBlock);
84
85
  /// Copy the basic block.
86
  ///
87
  /// This copies the entire basic block and updates references to old values
88
  /// with references to new values, as defined by GlobalMap.
89
  ///
90
  /// @param Stmt        The block statement to code generate.
91
  /// @param LTS         A map from old loops to new induction variables as
92
  ///                    SCEVs.
93
  /// @param NewAccesses A map from memory access ids to new ast expressions,
94
  ///                    which may contain new access expressions for certain
95
  ///                    memory accesses.
96
  void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
97
                isl_id_to_ast_expr *NewAccesses);
98
99
  /// Remove a ScopArrayInfo's allocation from the ScalarMap.
100
  ///
101
  /// This function allows to remove values from the ScalarMap. This is useful
102
  /// if the corresponding alloca instruction will be deleted (or moved into
103
  /// another module), as without removing these values the underlying
104
  /// AssertingVH will trigger due to us still keeping reference to this
105
  /// scalar.
106
  ///
107
  /// @param Array The array for which the alloca was generated.
108
0
  void freeScalarAlloc(ScopArrayInfo *Array) { ScalarMap.erase(Array); }
109
110
  /// Return the alloca for @p Access.
111
  ///
112
  /// If no alloca was mapped for @p Access a new one is created.
113
  ///
114
  /// @param Access    The memory access for which to generate the alloca.
115
  ///
116
  /// @returns The alloca for @p Access or a replacement value taken from
117
  ///          GlobalMap.
118
  Value *getOrCreateAlloca(const MemoryAccess &Access);
119
120
  /// Return the alloca for @p Array.
121
  ///
122
  /// If no alloca was mapped for @p Array a new one is created.
123
  ///
124
  /// @param Array The array for which to generate the alloca.
125
  ///
126
  /// @returns The alloca for @p Array or a replacement value taken from
127
  ///          GlobalMap.
128
  Value *getOrCreateAlloca(const ScopArrayInfo *Array);
129
130
  /// Finalize the code generation for the SCoP @p S.
131
  ///
132
  /// This will initialize and finalize the scalar variables we demoted during
133
  /// the code generation.
134
  ///
135
  /// @see createScalarInitialization(Scop &)
136
  /// @see createScalarFinalization(Region &)
137
  void finalizeSCoP(Scop &S);
138
139
  /// An empty destructor
140
600
  virtual ~BlockGenerator() {}
141
142
310
  BlockGenerator(const BlockGenerator &) = default;
143
144
protected:
145
  PollyIRBuilder &Builder;
146
  LoopInfo &LI;
147
  ScalarEvolution &SE;
148
  IslExprBuilder *ExprBuilder;
149
150
  /// The dominator tree of this function.
151
  DominatorTree &DT;
152
153
  /// The entry block of the current function.
154
  BasicBlock *EntryBB;
155
156
  /// Map to resolve scalar dependences for PHI operands and scalars.
157
  ///
158
  /// When translating code that contains scalar dependences as they result from
159
  /// inter-block scalar dependences (including the use of data carrying PHI
160
  /// nodes), we do not directly regenerate in-register SSA code, but instead
161
  /// allocate some stack memory through which these scalar values are passed.
162
  /// Only a later pass of -mem2reg will then (re)introduce in-register
163
  /// computations.
164
  ///
165
  /// To keep track of the memory location(s) used to store the data computed by
166
  /// a given SSA instruction, we use the map 'ScalarMap'. ScalarMap maps a
167
  /// given ScopArrayInfo to the junk of stack allocated memory, that is
168
  /// used for code generation.
169
  ///
170
  /// Up to two different ScopArrayInfo objects are associated with each
171
  /// llvm::Value:
172
  ///
173
  /// MemoryType::Value objects are used for normal scalar dependences that go
174
  /// from a scalar definition to its use. Such dependences are lowered by
175
  /// directly writing the value an instruction computes into the corresponding
176
  /// chunk of memory and reading it back from this chunk of memory right before
177
  /// every use of this original scalar value. The memory allocations for
178
  /// MemoryType::Value objects end with '.s2a'.
179
  ///
180
  /// MemoryType::PHI (and MemoryType::ExitPHI) objects are used to model PHI
181
  /// nodes. For each PHI nodes we introduce, besides the Array of type
182
  /// MemoryType::Value, a second chunk of memory into which we write at the end
183
  /// of each basic block preceding the PHI instruction the value passed
184
  /// through this basic block. At the place where the PHI node is executed, we
185
  /// replace the PHI node with a load from the corresponding MemoryType::PHI
186
  /// memory location. The memory allocations for MemoryType::PHI end with
187
  /// '.phiops'.
188
  ///
189
  /// Example:
190
  ///
191
  ///                              Input C Code
192
  ///                              ============
193
  ///
194
  ///                 S1:      x1 = ...
195
  ///                          for (i=0...N) {
196
  ///                 S2:           x2 = phi(x1, add)
197
  ///                 S3:           add = x2 + 42;
198
  ///                          }
199
  ///                 S4:      print(x1)
200
  ///                          print(x2)
201
  ///                          print(add)
202
  ///
203
  ///
204
  ///        Unmodified IR                         IR After expansion
205
  ///        =============                         ==================
206
  ///
207
  /// S1:   x1 = ...                     S1:    x1 = ...
208
  ///                                           x1.s2a = s1
209
  ///                                           x2.phiops = s1
210
  ///        |                                    |
211
  ///        |   <--<--<--<--<                    |   <--<--<--<--<
212
  ///        | /              \                   | /              \     .
213
  ///        V V               \                  V V               \    .
214
  /// S2:  x2 = phi (x1, add)   |        S2:    x2 = x2.phiops       |
215
  ///                           |               x2.s2a = x2          |
216
  ///                           |                                    |
217
  /// S3:  add = x2 + 42        |        S3:    add = x2 + 42        |
218
  ///                           |               add.s2a = add        |
219
  ///                           |               x2.phiops = add      |
220
  ///        | \               /                  | \               /
221
  ///        |  \             /                   |  \             /
222
  ///        |   >-->-->-->-->                    |   >-->-->-->-->
223
  ///        V                                    V
224
  ///
225
  ///                                    S4:    x1 = x1.s2a
226
  /// S4:  ... = x1                             ... = x1
227
  ///                                           x2 = x2.s2a
228
  ///      ... = x2                             ... = x2
229
  ///                                           add = add.s2a
230
  ///      ... = add                            ... = add
231
  ///
232
  ///      ScalarMap = { x1:Value -> x1.s2a, x2:Value -> x2.s2a,
233
  ///                    add:Value -> add.s2a, x2:PHI -> x2.phiops }
234
  ///
235
  ///  ??? Why does a PHI-node require two memory chunks ???
236
  ///
237
  ///  One may wonder why a PHI node requires two memory chunks and not just
238
  ///  all data is stored in a single location. The following example tries
239
  ///  to store all data in .s2a and drops the .phiops location:
240
  ///
241
  ///      S1:    x1 = ...
242
  ///             x1.s2a = s1
243
  ///             x2.s2a = s1             // use .s2a instead of .phiops
244
  ///               |
245
  ///               |   <--<--<--<--<
246
  ///               | /              \    .
247
  ///               V V               \   .
248
  ///      S2:    x2 = x2.s2a          |  // value is same as above, but read
249
  ///                                  |  // from .s2a
250
  ///                                  |
251
  ///             x2.s2a = x2          |  // store into .s2a as normal
252
  ///                                  |
253
  ///      S3:    add = x2 + 42        |
254
  ///             add.s2a = add        |
255
  ///             x2.s2a = add         |  // use s2a instead of .phiops
256
  ///               | \               /   // !!! This is wrong, as x2.s2a now
257
  ///               |   >-->-->-->-->     // contains add instead of x2.
258
  ///               V
259
  ///
260
  ///      S4:    x1 = x1.s2a
261
  ///             ... = x1
262
  ///             x2 = x2.s2a             // !!! We now read 'add' instead of
263
  ///             ... = x2                // 'x2'
264
  ///             add = add.s2a
265
  ///             ... = add
266
  ///
267
  ///  As visible in the example, the SSA value of the PHI node may still be
268
  ///  needed _after_ the basic block, which could conceptually branch to the
269
  ///  PHI node, has been run and has overwritten the PHI's old value. Hence, a
270
  ///  single memory location is not enough to code-generate a PHI node.
271
  ///
272
  /// Memory locations used for the special PHI node modeling.
273
  AllocaMapTy &ScalarMap;
274
275
  /// Map from instructions to their escape users as well as the alloca.
276
  EscapeUsersAllocaMapTy &EscapeMap;
277
278
  /// A map from llvm::Values referenced in the old code to a new set of
279
  ///        llvm::Values, which is used to replace these old values during
280
  ///        code generation.
281
  ValueMapT &GlobalMap;
282
283
  /// The first basic block after the RTC.
284
  BasicBlock *StartBlock;
285
286
  /// Split @p BB to create a new one we can use to clone @p BB in.
287
  BasicBlock *splitBB(BasicBlock *BB);
288
289
  /// Copy the given basic block.
290
  ///
291
  /// @param Stmt      The statement to code generate.
292
  /// @param BB        The basic block to code generate.
293
  /// @param BBMap     A mapping from old values to their new values in this
294
  /// block.
295
  /// @param LTS         A map from old loops to new induction variables as
296
  ///                    SCEVs.
297
  /// @param NewAccesses A map from memory access ids to new ast expressions,
298
  ///                    which may contain new access expressions for certain
299
  ///                    memory accesses.
300
  ///
301
  /// @returns The copy of the basic block.
302
  BasicBlock *copyBB(ScopStmt &Stmt, BasicBlock *BB, ValueMapT &BBMap,
303
                     LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses);
304
305
  /// Copy the given basic block.
306
  ///
307
  /// @param Stmt      The statement to code generate.
308
  /// @param BB        The basic block to code generate.
309
  /// @param BBCopy    The new basic block to generate code in.
310
  /// @param BBMap     A mapping from old values to their new values in this
311
  /// block.
312
  /// @param LTS         A map from old loops to new induction variables as
313
  ///                    SCEVs.
314
  /// @param NewAccesses A map from memory access ids to new ast expressions,
315
  ///                    which may contain new access expressions for certain
316
  ///                    memory accesses.
317
  void copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *BBCopy,
318
              ValueMapT &BBMap, LoopToScevMapT &LTS,
319
              isl_id_to_ast_expr *NewAccesses);
320
321
  /// Generate reload of scalars demoted to memory and needed by @p Stmt.
322
  ///
323
  /// @param Stmt  The statement we generate code for.
324
  /// @param LTS   A mapping from loops virtual canonical induction
325
  ///              variable to their new values.
326
  /// @param BBMap A mapping from old values to their new values in this block.
327
  /// @param NewAccesses A map from memory access ids to new ast expressions.
328
  void generateScalarLoads(ScopStmt &Stmt, LoopToScevMapT &LTS,
329
                           ValueMapT &BBMap,
330
                           __isl_keep isl_id_to_ast_expr *NewAccesses);
331
332
  /// Generate instructions that compute whether one instance of @p Set is
333
  /// executed.
334
  ///
335
  /// @param Stmt      The statement we generate code for.
336
  /// @param Subdomain A set in the space of @p Stmt's domain. Elements not in
337
  ///                  @p Stmt's domain are ignored.
338
  ///
339
  /// @return An expression of type i1, generated into the current builder
340
  ///         position, that evaluates to 1 if the executed instance is part of
341
  ///         @p Set.
342
  Value *buildContainsCondition(ScopStmt &Stmt, const isl::set &Subdomain);
343
344
  /// Generate code that executes in a subset of @p Stmt's domain.
345
  ///
346
  /// @param Stmt        The statement we generate code for.
347
  /// @param Subdomain   The condition for some code to be executed.
348
  /// @param Subject     A name for the code that is executed
349
  ///                    conditionally. Used to name new basic blocks and
350
  ///                    instructions.
351
  /// @param GenThenFunc Callback which generates the code to be executed
352
  ///                    when the current executed instance is in @p Set. The
353
  ///                    IRBuilder's position is moved to within the block that
354
  ///                    executes conditionally for this callback.
355
  void generateConditionalExecution(ScopStmt &Stmt, const isl::set &Subdomain,
356
                                    StringRef Subject,
357
                                    const std::function<void()> &GenThenFunc);
358
359
  /// Generate the scalar stores for the given statement.
360
  ///
361
  /// After the statement @p Stmt was copied all inner-SCoP scalar dependences
362
  /// starting in @p Stmt (hence all scalar write accesses in @p Stmt) need to
363
  /// be demoted to memory.
364
  ///
365
  /// @param Stmt  The statement we generate code for.
366
  /// @param LTS   A mapping from loops virtual canonical induction
367
  ///              variable to their new values
368
  ///              (for values recalculated in the new ScoP, but not
369
  ///               within this basic block)
370
  /// @param BBMap A mapping from old values to their new values in this block.
371
  /// @param NewAccesses A map from memory access ids to new ast expressions.
372
  virtual void generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
373
                                    ValueMapT &BBMap,
374
                                    __isl_keep isl_id_to_ast_expr *NewAccesses);
375
376
  /// Handle users of @p Array outside the SCoP.
377
  ///
378
  /// @param S         The current SCoP.
379
  /// @param Inst      The ScopArrayInfo to handle.
380
  void handleOutsideUsers(const Scop &S, ScopArrayInfo *Array);
381
382
  /// Find scalar statements that have outside users.
383
  ///
384
  /// We register these scalar values to later update subsequent scalar uses of
385
  /// these values to either use the newly computed value from within the scop
386
  /// (if the scop was executed) or the unchanged original code (if the run-time
387
  /// check failed).
388
  ///
389
  /// @param S The scop for which to find the outside users.
390
  void findOutsideUsers(Scop &S);
391
392
  /// Initialize the memory of demoted scalars.
393
  ///
394
  /// @param S The scop for which to generate the scalar initializers.
395
  void createScalarInitialization(Scop &S);
396
397
  /// Create exit PHI node merges for PHI nodes with more than two edges
398
  ///        from inside the scop.
399
  ///
400
  /// For scops which have a PHI node in the exit block that has more than two
401
  /// incoming edges from inside the scop region, we require some special
402
  /// handling to understand which of the possible values will be passed to the
403
  /// PHI node from inside the optimized version of the scop. To do so ScopInfo
404
  /// models the possible incoming values as write accesses of the ScopStmts.
405
  ///
406
  /// This function creates corresponding code to reload the computed outgoing
407
  /// value from the stack slot it has been stored into and to pass it on to the
408
  /// PHI node in the original exit block.
409
  ///
410
  /// @param S The scop for which to generate the exiting PHI nodes.
411
  void createExitPHINodeMerges(Scop &S);
412
413
  /// Promote the values of demoted scalars after the SCoP.
414
  ///
415
  /// If a scalar value was used outside the SCoP we need to promote the value
416
  /// stored in the memory cell allocated for that scalar and combine it with
417
  /// the original value in the non-optimized SCoP.
418
  void createScalarFinalization(Scop &S);
419
420
  /// Try to synthesize a new value
421
  ///
422
  /// Given an old value, we try to synthesize it in a new context from its
423
  /// original SCEV expression. We start from the original SCEV expression,
424
  /// then replace outdated parameter and loop references, and finally
425
  /// expand it to code that computes this updated expression.
426
  ///
427
  /// @param Stmt      The statement to code generate
428
  /// @param Old       The old Value
429
  /// @param BBMap     A mapping from old values to their new values
430
  ///                  (for values recalculated within this basic block)
431
  /// @param LTS       A mapping from loops virtual canonical induction
432
  ///                  variable to their new values
433
  ///                  (for values recalculated in the new ScoP, but not
434
  ///                   within this basic block)
435
  /// @param L         The loop that surrounded the instruction that referenced
436
  ///                  this value in the original code. This loop is used to
437
  ///                  evaluate the scalar evolution at the right scope.
438
  ///
439
  /// @returns  o A newly synthesized value.
440
  ///           o NULL, if synthesizing the value failed.
441
  Value *trySynthesizeNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
442
                               LoopToScevMapT &LTS, Loop *L) const;
443
444
  /// Get the new version of a value.
445
  ///
446
  /// Given an old value, we first check if a new version of this value is
447
  /// available in the BBMap or GlobalMap. In case it is not and the value can
448
  /// be recomputed using SCEV, we do so. If we can not recompute a value
449
  /// using SCEV, but we understand that the value is constant within the scop,
450
  /// we return the old value.  If the value can still not be derived, this
451
  /// function will assert.
452
  ///
453
  /// @param Stmt      The statement to code generate.
454
  /// @param Old       The old Value.
455
  /// @param BBMap     A mapping from old values to their new values
456
  ///                  (for values recalculated within this basic block).
457
  /// @param LTS       A mapping from loops virtual canonical induction
458
  ///                  variable to their new values
459
  ///                  (for values recalculated in the new ScoP, but not
460
  ///                   within this basic block).
461
  /// @param L         The loop that surrounded the instruction that referenced
462
  ///                  this value in the original code. This loop is used to
463
  ///                  evaluate the scalar evolution at the right scope.
464
  ///
465
  /// @returns  o The old value, if it is still valid.
466
  ///           o The new value, if available.
467
  ///           o NULL, if no value is found.
468
  Value *getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
469
                     LoopToScevMapT &LTS, Loop *L) const;
470
471
  void copyInstScalar(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap,
472
                      LoopToScevMapT &LTS);
473
474
  /// Get the innermost loop that surrounds the statement @p Stmt.
475
  Loop *getLoopForStmt(const ScopStmt &Stmt) const;
476
477
  /// Generate the operand address
478
  /// @param NewAccesses A map from memory access ids to new ast expressions,
479
  ///                    which may contain new access expressions for certain
480
  ///                    memory accesses.
481
  Value *generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
482
                                  ValueMapT &BBMap, LoopToScevMapT &LTS,
483
                                  isl_id_to_ast_expr *NewAccesses);
484
485
  /// Generate the operand address.
486
  ///
487
  /// @param Stmt         The statement to generate code for.
488
  /// @param L            The innermost loop that surrounds the statement.
489
  /// @param Pointer      If the access expression is not changed (ie. not found
490
  ///                     in @p LTS), use this Pointer from the original code
491
  ///                     instead.
492
  /// @param BBMap        A mapping from old values to their new values.
493
  /// @param LTS          A mapping from loops virtual canonical induction
494
  ///                     variable to their new values.
495
  /// @param NewAccesses  Ahead-of-time generated access expressions.
496
  /// @param Id           Identifier of the MemoryAccess to generate.
497
  /// @param ExpectedType The type the returned value should have.
498
  ///
499
  /// @return The generated address.
500
  Value *generateLocationAccessed(ScopStmt &Stmt, Loop *L, Value *Pointer,
501
                                  ValueMapT &BBMap, LoopToScevMapT &LTS,
502
                                  isl_id_to_ast_expr *NewAccesses,
503
                                  __isl_take isl_id *Id, Type *ExpectedType);
504
505
  /// Generate the pointer value that is accesses by @p Access.
506
  ///
507
  /// For write accesses, generate the target address. For read accesses,
508
  /// generate the source address.
509
  /// The access can be either an array access or a scalar access. In the first
510
  /// case, the returned address will point to an element into that array. In
511
  /// the scalar case, an alloca is used.
512
  /// If a new AccessRelation is set for the MemoryAccess, the new relation will
513
  /// be used.
514
  ///
515
  /// @param Access      The access to generate a pointer for.
516
  /// @param L           The innermost loop that surrounds the statement.
517
  /// @param LTS         A mapping from loops virtual canonical induction
518
  ///                    variable to their new values.
519
  /// @param BBMap       A mapping from old values to their new values.
520
  /// @param NewAccesses A map from memory access ids to new ast expressions.
521
  ///
522
  /// @return The generated address.
523
  Value *getImplicitAddress(MemoryAccess &Access, Loop *L, LoopToScevMapT &LTS,
524
                            ValueMapT &BBMap,
525
                            __isl_keep isl_id_to_ast_expr *NewAccesses);
526
527
  /// @param NewAccesses A map from memory access ids to new ast expressions,
528
  ///                    which may contain new access expressions for certain
529
  ///                    memory accesses.
530
  Value *generateArrayLoad(ScopStmt &Stmt, LoadInst *load, ValueMapT &BBMap,
531
                           LoopToScevMapT &LTS,
532
                           isl_id_to_ast_expr *NewAccesses);
533
534
  /// @param NewAccesses A map from memory access ids to new ast expressions,
535
  ///                    which may contain new access expressions for certain
536
  ///                    memory accesses.
537
  void generateArrayStore(ScopStmt &Stmt, StoreInst *store, ValueMapT &BBMap,
538
                          LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses);
539
540
  /// Copy a single PHI instruction.
541
  ///
542
  /// The implementation in the BlockGenerator is trivial, however it allows
543
  /// subclasses to handle PHIs different.
544
  virtual void copyPHIInstruction(ScopStmt &, PHINode *, ValueMapT &,
545
37
                                  LoopToScevMapT &) {}
546
547
  /// Copy a single Instruction.
548
  ///
549
  /// This copies a single Instruction and updates references to old values
550
  /// with references to new values, as defined by GlobalMap and BBMap.
551
  ///
552
  /// @param Stmt        The statement to code generate.
553
  /// @param Inst        The instruction to copy.
554
  /// @param BBMap       A mapping from old values to their new values
555
  ///                    (for values recalculated within this basic block).
556
  /// @param GlobalMap   A mapping from old values to their new values
557
  ///                    (for values recalculated in the new ScoP, but not
558
  ///                    within this basic block).
559
  /// @param LTS         A mapping from loops virtual canonical induction
560
  ///                    variable to their new values
561
  ///                    (for values recalculated in the new ScoP, but not
562
  ///                     within this basic block).
563
  /// @param NewAccesses A map from memory access ids to new ast expressions,
564
  ///                    which may contain new access expressions for certain
565
  ///                    memory accesses.
566
  void copyInstruction(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap,
567
                       LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses);
568
569
  /// Helper to determine if @p Inst can be synthesized in @p Stmt.
570
  ///
571
  /// @returns false, iff @p Inst can be synthesized in @p Stmt.
572
  bool canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst);
573
574
  /// Remove dead instructions generated for BB
575
  ///
576
  /// @param BB The basic block code for which code has been generated.
577
  /// @param BBMap A local map from old to new instructions.
578
  void removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap);
579
580
  /// Invalidate the scalar evolution expressions for a scop.
581
  ///
582
  /// This function invalidates the scalar evolution results for all
583
  /// instructions that are part of a given scop, and the loops
584
  /// surrounding the users of merge blocks. This is necessary to ensure that
585
  /// later scops do not obtain scalar evolution expressions that reference
586
  /// values that earlier dominated the later scop, but have been moved in the
587
  /// conditional part of an earlier scop and consequently do not any more
588
  /// dominate the later scop.
589
  ///
590
  /// @param S The scop to invalidate.
591
  void invalidateScalarEvolution(Scop &S);
592
};
593
594
/// Generate a new vector basic block for a polyhedral statement.
595
///
596
/// The only public function exposed is generate().
597
class VectorBlockGenerator : BlockGenerator {
598
public:
599
  /// Generate a new vector basic block for a ScoPStmt.
600
  ///
601
  /// This code generation is similar to the normal, scalar code generation,
602
  /// except that each instruction is code generated for several vector lanes
603
  /// at a time. If possible instructions are issued as actual vector
604
  /// instructions, but e.g. for address calculation instructions we currently
605
  /// generate scalar instructions for each vector lane.
606
  ///
607
  /// @param BlockGen    A block generator object used as parent.
608
  /// @param Stmt        The statement to code generate.
609
  /// @param VLTS        A mapping from loops virtual canonical induction
610
  ///                    variable to their new values
611
  ///                    (for values recalculated in the new ScoP, but not
612
  ///                     within this basic block), one for each lane.
613
  /// @param Schedule    A map from the statement to a schedule where the
614
  ///                    innermost dimension is the dimension of the innermost
615
  ///                    loop containing the statement.
616
  /// @param NewAccesses A map from memory access ids to new ast expressions,
617
  ///                    which may contain new access expressions for certain
618
  ///                    memory accesses.
619
  static void generate(BlockGenerator &BlockGen, ScopStmt &Stmt,
620
                       std::vector<LoopToScevMapT> &VLTS,
621
                       __isl_keep isl_map *Schedule,
622
20
                       __isl_keep isl_id_to_ast_expr *NewAccesses) {
623
20
    VectorBlockGenerator Generator(BlockGen, VLTS, Schedule);
624
20
    Generator.copyStmt(Stmt, NewAccesses);
625
20
  }
626
627
private:
628
  // This is a vector of loop->scev maps.  The first map is used for the first
629
  // vector lane, ...
630
  // Each map, contains information about Instructions in the old ScoP, which
631
  // are recalculated in the new SCoP. When copying the basic block, we replace
632
  // all references to the old instructions with their recalculated values.
633
  //
634
  // For example, when the code generator produces this AST:
635
  //
636
  //   for (int c1 = 0; c1 <= 1023; c1 += 1)
637
  //     for (int c2 = 0; c2 <= 1023; c2 += VF)
638
  //       for (int lane = 0; lane <= VF; lane += 1)
639
  //         Stmt(c2 + lane + 3, c1);
640
  //
641
  // VLTS[lane] contains a map:
642
  //   "outer loop in the old loop nest" -> SCEV("c2 + lane + 3"),
643
  //   "inner loop in the old loop nest" -> SCEV("c1").
644
  std::vector<LoopToScevMapT> &VLTS;
645
646
  // A map from the statement to a schedule where the innermost dimension is the
647
  // dimension of the innermost loop containing the statement.
648
  isl_map *Schedule;
649
650
  VectorBlockGenerator(BlockGenerator &BlockGen,
651
                       std::vector<LoopToScevMapT> &VLTS,
652
                       __isl_keep isl_map *Schedule);
653
654
  int getVectorWidth();
655
656
  Value *getVectorValue(ScopStmt &Stmt, Value *Old, ValueMapT &VectorMap,
657
                        VectorValueMapT &ScalarMaps, Loop *L);
658
659
  Type *getVectorPtrTy(const Value *V, int Width);
660
661
  /// Load a vector from a set of adjacent scalars
662
  ///
663
  /// In case a set of scalars is known to be next to each other in memory,
664
  /// create a vector load that loads those scalars
665
  ///
666
  /// %vector_ptr= bitcast double* %p to <4 x double>*
667
  /// %vec_full = load <4 x double>* %vector_ptr
668
  ///
669
  /// @param Stmt           The statement to code generate.
670
  /// @param NegativeStride This is used to indicate a -1 stride. In such
671
  ///                       a case we load the end of a base address and
672
  ///                       shuffle the accesses in reverse order into the
673
  ///                       vector. By default we would do only positive
674
  ///                       strides.
675
  ///
676
  /// @param NewAccesses    A map from memory access ids to new ast
677
  ///                       expressions, which may contain new access
678
  ///                       expressions for certain memory accesses.
679
  Value *generateStrideOneLoad(ScopStmt &Stmt, LoadInst *Load,
680
                               VectorValueMapT &ScalarMaps,
681
                               __isl_keep isl_id_to_ast_expr *NewAccesses,
682
                               bool NegativeStride);
683
684
  /// Load a vector initialized from a single scalar in memory
685
  ///
686
  /// In case all elements of a vector are initialized to the same
687
  /// scalar value, this value is loaded and shuffled into all elements
688
  /// of the vector.
689
  ///
690
  /// %splat_one = load <1 x double>* %p
691
  /// %splat = shufflevector <1 x double> %splat_one, <1 x
692
  ///       double> %splat_one, <4 x i32> zeroinitializer
693
  ///
694
  /// @param NewAccesses A map from memory access ids to new ast expressions,
695
  ///                    which may contain new access expressions for certain
696
  ///                    memory accesses.
697
  Value *generateStrideZeroLoad(ScopStmt &Stmt, LoadInst *Load,
698
                                ValueMapT &BBMap,
699
                                __isl_keep isl_id_to_ast_expr *NewAccesses);
700
701
  /// Load a vector from scalars distributed in memory
702
  ///
703
  /// In case some scalars a distributed randomly in memory. Create a vector
704
  /// by loading each scalar and by inserting one after the other into the
705
  /// vector.
706
  ///
707
  /// %scalar_1= load double* %p_1
708
  /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
709
  /// %scalar 2 = load double* %p_2
710
  /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
711
  ///
712
  /// @param NewAccesses A map from memory access ids to new ast expressions,
713
  ///                    which may contain new access expressions for certain
714
  ///                    memory accesses.
715
  Value *generateUnknownStrideLoad(ScopStmt &Stmt, LoadInst *Load,
716
                                   VectorValueMapT &ScalarMaps,
717
                                   __isl_keep isl_id_to_ast_expr *NewAccesses);
718
719
  /// @param NewAccesses A map from memory access ids to new ast expressions,
720
  ///                    which may contain new access expressions for certain
721
  ///                    memory accesses.
722
  void generateLoad(ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
723
                    VectorValueMapT &ScalarMaps,
724
                    __isl_keep isl_id_to_ast_expr *NewAccesses);
725
726
  void copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
727
                     ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
728
729
  void copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
730
                      ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
731
732
  /// @param NewAccesses A map from memory access ids to new ast expressions,
733
  ///                    which may contain new access expressions for certain
734
  ///                    memory accesses.
735
  void copyStore(ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
736
                 VectorValueMapT &ScalarMaps,
737
                 __isl_keep isl_id_to_ast_expr *NewAccesses);
738
739
  /// @param NewAccesses A map from memory access ids to new ast expressions,
740
  ///                    which may contain new access expressions for certain
741
  ///                    memory accesses.
742
  void copyInstScalarized(ScopStmt &Stmt, Instruction *Inst,
743
                          ValueMapT &VectorMap, VectorValueMapT &ScalarMaps,
744
                          __isl_keep isl_id_to_ast_expr *NewAccesses);
745
746
  bool extractScalarValues(const Instruction *Inst, ValueMapT &VectorMap,
747
                           VectorValueMapT &ScalarMaps);
748
749
  bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
750
751
  /// Generate vector loads for scalars.
752
  ///
753
  /// @param Stmt           The scop statement for which to generate the loads.
754
  /// @param VectorBlockMap A map that will be updated to relate the original
755
  ///                       values with the newly generated vector loads.
756
  void generateScalarVectorLoads(ScopStmt &Stmt, ValueMapT &VectorBlockMap);
757
758
  /// Verify absence of scalar stores.
759
  ///
760
  /// @param Stmt The scop statement to check for scalar stores.
761
  void verifyNoScalarStores(ScopStmt &Stmt);
762
763
  /// @param NewAccesses A map from memory access ids to new ast expressions,
764
  ///                    which may contain new access expressions for certain
765
  ///                    memory accesses.
766
  void copyInstruction(ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
767
                       VectorValueMapT &ScalarMaps,
768
                       __isl_keep isl_id_to_ast_expr *NewAccesses);
769
770
  /// @param NewAccesses A map from memory access ids to new ast expressions,
771
  ///                    which may contain new access expressions for certain
772
  ///                    memory accesses.
773
  void copyStmt(ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses);
774
};
775
776
/// Generator for new versions of polyhedral region statements.
777
class RegionGenerator : public BlockGenerator {
778
public:
779
  /// Create a generator for regions.
780
  ///
781
  /// @param BlockGen A generator for basic blocks.
782
290
  RegionGenerator(BlockGenerator &BlockGen) : BlockGenerator(BlockGen) {}
783
784
290
  virtual ~RegionGenerator() {}
785
786
  /// Copy the region statement @p Stmt.
787
  ///
788
  /// This copies the entire region represented by @p Stmt and updates
789
  /// references to old values with references to new values, as defined by
790
  /// GlobalMap.
791
  ///
792
  /// @param Stmt      The statement to code generate.
793
  /// @param LTS       A map from old loops to new induction variables as SCEVs.
794
  void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
795
                __isl_keep isl_id_to_ast_expr *IdToAstExp);
796
797
private:
798
  /// A map from old to the first new block in the region, that was created to
799
  /// model the old basic block.
800
  DenseMap<BasicBlock *, BasicBlock *> StartBlockMap;
801
802
  /// A map from old to the last new block in the region, that was created to
803
  /// model the old basic block.
804
  DenseMap<BasicBlock *, BasicBlock *> EndBlockMap;
805
806
  /// The "BBMaps" for the whole region (one for each block). In case a basic
807
  /// block is code generated to multiple basic blocks (e.g., for partial
808
  /// writes), the StartBasic is used as index for the RegionMap.
809
  DenseMap<BasicBlock *, ValueMapT> RegionMaps;
810
811
  /// Mapping to remember PHI nodes that still need incoming values.
812
  using PHINodePairTy = std::pair<PHINode *, PHINode *>;
813
  DenseMap<BasicBlock *, SmallVector<PHINodePairTy, 4>> IncompletePHINodeMap;
814
815
  /// Repair the dominance tree after we created a copy block for @p BB.
816
  ///
817
  /// @returns The immediate dominator in the DT for @p BBCopy if in the region.
818
  BasicBlock *repairDominance(BasicBlock *BB, BasicBlock *BBCopy);
819
820
  /// Add the new operand from the copy of @p IncomingBB to @p PHICopy.
821
  ///
822
  /// PHI nodes, which may have (multiple) edges that enter from outside the
823
  /// non-affine subregion and even from outside the scop, are code generated as
824
  /// follows:
825
  ///
826
  /// # Original
827
  ///
828
  ///   Region: %A-> %exit
829
  ///   NonAffine Stmt: %nonaffB -> %D (includes %nonaffB, %nonaffC)
830
  ///
831
  ///     pre:
832
  ///       %val = add i64 1, 1
833
  ///
834
  ///     A:
835
  ///      br label %nonaff
836
  ///
837
  ///     nonaffB:
838
  ///       %phi = phi i64 [%val, %A], [%valC, %nonAffC], [%valD, %D]
839
  ///       %cmp = <nonaff>
840
  ///       br i1 %cmp, label %C, label %nonaffC
841
  ///
842
  ///     nonaffC:
843
  ///       %valC = add i64 1, 1
844
  ///       br i1 undef, label %D, label %nonaffB
845
  ///
846
  ///     D:
847
  ///       %valD = ...
848
  ///       %exit_cond = <loopexit>
849
  ///       br i1 %exit_cond, label %nonaffB, label %exit
850
  ///
851
  ///     exit:
852
  ///       ...
853
  ///
854
  ///  - %start and %C enter from outside the non-affine region.
855
  ///  - %nonaffC enters from within the non-affine region.
856
  ///
857
  ///  # New
858
  ///
859
  ///    polly.A:
860
  ///       store i64 %val, i64* %phi.phiops
861
  ///       br label %polly.nonaffA.entry
862
  ///
863
  ///    polly.nonaffB.entry:
864
  ///       %phi.phiops.reload = load i64, i64* %phi.phiops
865
  ///       br label %nonaffB
866
  ///
867
  ///    polly.nonaffB:
868
  ///       %polly.phi = [%phi.phiops.reload, %nonaffB.entry],
869
  ///                    [%p.valC, %polly.nonaffC]
870
  ///
871
  ///    polly.nonaffC:
872
  ///       %p.valC = add i64 1, 1
873
  ///       br i1 undef, label %polly.D, label %polly.nonaffB
874
  ///
875
  ///    polly.D:
876
  ///        %p.valD = ...
877
  ///        store i64 %p.valD, i64* %phi.phiops
878
  ///        %p.exit_cond = <loopexit>
879
  ///        br i1 %p.exit_cond, label %polly.nonaffB, label %exit
880
  ///
881
  /// Values that enter the PHI from outside the non-affine region are stored
882
  /// into the stack slot %phi.phiops by statements %polly.A and %polly.D and
883
  /// reloaded in %polly.nonaffB.entry, a basic block generated before the
884
  /// actual non-affine region.
885
  ///
886
  /// When generating the PHI node of the non-affine region in %polly.nonaffB,
887
  /// incoming edges from outside the region are combined into a single branch
888
  /// from %polly.nonaffB.entry which has as incoming value the value reloaded
889
  /// from the %phi.phiops stack slot. Incoming edges from within the region
890
  /// refer to the copied instructions (%p.valC) and basic blocks
891
  /// (%polly.nonaffC) of the non-affine region.
892
  ///
893
  /// @param Stmt       The statement to code generate.
894
  /// @param PHI        The original PHI we copy.
895
  /// @param PHICopy    The copy of @p PHI.
896
  /// @param IncomingBB An incoming block of @p PHI.
897
  /// @param LTS        A map from old loops to new induction variables as
898
  /// SCEVs.
899
  void addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, PHINode *PHICopy,
900
                       BasicBlock *IncomingBB, LoopToScevMapT &LTS);
901
902
  /// Create a PHI that combines the incoming values from all incoming blocks
903
  /// that are in the subregion.
904
  ///
905
  /// PHIs in the subregion's exit block can have incoming edges from within and
906
  /// outside the subregion. This function combines the incoming values from
907
  /// within the subregion to appear as if there is only one incoming edge from
908
  /// the subregion (an additional exit block is created by RegionGenerator).
909
  /// This is to avoid that a value is written to the .phiops location without
910
  /// leaving the subregion because the exiting block as an edge back into the
911
  /// subregion.
912
  ///
913
  /// @param MA    The WRITE of MemoryKind::PHI/MemoryKind::ExitPHI for a PHI in
914
  ///              the subregion's exit block.
915
  /// @param LTS   Virtual induction variable mapping.
916
  /// @param BBMap A mapping from old values to their new values in this block.
917
  /// @param L     Loop surrounding this region statement.
918
  ///
919
  /// @returns The constructed PHI node.
920
  PHINode *buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap,
921
                        Loop *L);
922
923
  /// @param Return the new value of a scalar write, creating a PHINode if
924
  ///        necessary.
925
  ///
926
  /// @param MA    A scalar WRITE MemoryAccess.
927
  /// @param LTS   Virtual induction variable mapping.
928
  /// @param BBMap A mapping from old values to their new values in this block.
929
  ///
930
  /// @returns The effective value of @p MA's written value when leaving the
931
  ///          subregion.
932
  /// @see buildExitPHI
933
  Value *getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap);
934
935
  /// Generate the scalar stores for the given statement.
936
  ///
937
  /// After the statement @p Stmt was copied all inner-SCoP scalar dependences
938
  /// starting in @p Stmt (hence all scalar write accesses in @p Stmt) need to
939
  /// be demoted to memory.
940
  ///
941
  /// @param Stmt  The statement we generate code for.
942
  /// @param LTS   A mapping from loops virtual canonical induction variable to
943
  ///              their new values (for values recalculated in the new ScoP,
944
  ///              but not within this basic block)
945
  /// @param BBMap A mapping from old values to their new values in this block.
946
  /// @param LTS   A mapping from loops virtual canonical induction variable to
947
  /// their new values.
948
  virtual void
949
  generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMAp,
950
                       __isl_keep isl_id_to_ast_expr *NewAccesses) override;
951
952
  /// Copy a single PHI instruction.
953
  ///
954
  /// This copies a single PHI instruction and updates references to old values
955
  /// with references to new values, as defined by GlobalMap and BBMap.
956
  ///
957
  /// @param Stmt      The statement to code generate.
958
  /// @param PHI       The PHI instruction to copy.
959
  /// @param BBMap     A mapping from old values to their new values
960
  ///                  (for values recalculated within this basic block).
961
  /// @param LTS       A map from old loops to new induction variables as SCEVs.
962
  virtual void copyPHIInstruction(ScopStmt &Stmt, PHINode *Inst,
963
                                  ValueMapT &BBMap,
964
                                  LoopToScevMapT &LTS) override;
965
};
966
} // namespace polly
967
#endif