Coverage Report

Created: 2017-04-29 12:21

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/include/polly/CodeGen/IslNodeBuilder.h
Line
Count
Source
1
//===------ IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST---===//
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
// This file contains the IslNodeBuilder, a class to translate an isl AST into
10
// a LLVM-IR AST.
11
//===----------------------------------------------------------------------===//
12
13
#ifndef POLLY_ISL_NODE_BUILDER_H
14
#define POLLY_ISL_NODE_BUILDER_H
15
16
#include "polly/CodeGen/BlockGenerators.h"
17
#include "polly/CodeGen/IslExprBuilder.h"
18
#include "polly/CodeGen/LoopGenerators.h"
19
#include "polly/ScopInfo.h"
20
#include "llvm/ADT/ArrayRef.h"
21
#include "llvm/ADT/SetVector.h"
22
#include "llvm/ADT/SmallSet.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "isl/ctx.h"
25
#include "isl/union_map.h"
26
#include <utility>
27
#include <vector>
28
29
using namespace polly;
30
using namespace llvm;
31
32
struct isl_ast_node;
33
struct isl_ast_build;
34
struct isl_union_map;
35
36
struct SubtreeReferences {
37
  LoopInfo &LI;
38
  ScalarEvolution &SE;
39
  Scop &S;
40
  ValueMapT &GlobalMap;
41
  SetVector<Value *> &Values;
42
  SetVector<const SCEV *> &SCEVs;
43
  BlockGenerator &BlockGen;
44
};
45
46
/// Extract the out-of-scop values and SCEVs referenced from a ScopStmt.
47
///
48
/// This includes the SCEVUnknowns referenced by the SCEVs used in the
49
/// statement and the base pointers of the memory accesses. For scalar
50
/// statements we force the generation of alloca memory locations and list
51
/// these locations in the set of out-of-scop values as well.
52
///
53
/// @param Stmt             The statement for which to extract the information.
54
/// @param UserPtr          A void pointer that can be casted to a
55
///                         SubtreeReferences structure.
56
/// @param CreateScalarRefs Should the result include allocas of scalar
57
///                         references?
58
isl_stat addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr,
59
                               bool CreateScalarRefs = true);
60
61
class IslNodeBuilder {
62
public:
63
  IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
64
                 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
65
                 DominatorTree &DT, Scop &S, BasicBlock *StartBlock)
66
      : S(S), Builder(Builder), Annotator(Annotator),
67
        ExprBuilder(S, Builder, IDToValue, ValueMap, DL, SE, DT, LI,
68
                    StartBlock),
69
        BlockGen(Builder, LI, SE, DT, ScalarMap, EscapeMap, ValueMap,
70
                 &ExprBuilder, StartBlock),
71
        RegionGen(BlockGen), DL(DL), LI(LI), SE(SE), DT(DT),
72
262
        StartBlock(StartBlock) {}
73
74
262
  virtual ~IslNodeBuilder() = default;
75
76
  void addParameters(__isl_take isl_set *Context);
77
78
  /// Generate code that evaluates @p Condition at run-time.
79
  ///
80
  /// This function is typically called to generate the LLVM-IR for the
81
  /// run-time condition of the scop, that verifies that all the optimistic
82
  /// assumptions we have taken during scop modeling and transformation
83
  /// hold at run-time.
84
  ///
85
  /// @param Condition The condition to evaluate
86
  ///
87
  /// @result An llvm::Value that is true if the condition holds and false
88
  ///         otherwise.
89
  Value *createRTC(isl_ast_expr *Condition);
90
91
  void create(__isl_take isl_ast_node *Node);
92
93
  /// Allocate memory for all new arrays created by Polly.
94
  void allocateNewArrays();
95
96
  /// Preload all memory loads that are invariant.
97
  bool preloadInvariantLoads();
98
99
  /// Finalize code generation.
100
  ///
101
  /// @see BlockGenerator::finalizeSCoP(Scop &S)
102
257
  virtual void finalize() { BlockGen.finalizeSCoP(S); }
103
104
257
  IslExprBuilder &getExprBuilder() { return ExprBuilder; }
105
106
  /// Get the associated block generator.
107
  ///
108
  /// @return A referecne to the associated block generator.
109
26
  BlockGenerator &getBlockGenerator() { return BlockGen; }
110
111
  /// Return the parallel subfunctions that have been created.
112
262
  const ArrayRef<Function *> getParallelSubfunctions() const {
113
262
    return ParallelSubfunctions;
114
262
  }
115
116
protected:
117
  Scop &S;
118
  PollyIRBuilder &Builder;
119
  ScopAnnotator &Annotator;
120
121
  IslExprBuilder ExprBuilder;
122
123
  /// Maps used by the block and region generator to demote scalars.
124
  ///
125
  ///@{
126
127
  /// See BlockGenerator::ScalarMap.
128
  BlockGenerator::AllocaMapTy ScalarMap;
129
130
  /// See BlockGenerator::EscapeMap.
131
  BlockGenerator::EscapeUsersAllocaMapTy EscapeMap;
132
133
  ///@}
134
135
  /// The generator used to copy a basic block.
136
  BlockGenerator BlockGen;
137
138
  /// The generator used to copy a non-affine region.
139
  RegionGenerator RegionGen;
140
141
  const DataLayout &DL;
142
  LoopInfo &LI;
143
  ScalarEvolution &SE;
144
  DominatorTree &DT;
145
  BasicBlock *StartBlock;
146
147
  /// The current iteration of out-of-scop loops
148
  ///
149
  /// This map provides for a given loop a llvm::Value that contains the current
150
  /// loop iteration.
151
  LoopToScevMapT OutsideLoopIterations;
152
153
  // This maps an isl_id* to the Value* it has in the generated program. For now
154
  // on, the only isl_ids that are stored here are the newly calculated loop
155
  // ivs.
156
  IslExprBuilder::IDToValueTy IDToValue;
157
158
  /// A collection of all parallel subfunctions that have been created.
159
  SmallVector<Function *, 8> ParallelSubfunctions;
160
161
  /// Generate code for a given SCEV*
162
  ///
163
  /// This function generates code for a given SCEV expression. It generated
164
  /// code is emitted at the end of the basic block our Builder currently
165
  /// points to and the resulting value is returned.
166
  ///
167
  /// @param Expr The expression to code generate.
168
  llvm::Value *generateSCEV(const SCEV *Expr);
169
170
  /// A set of Value -> Value remappings to apply when generating new code.
171
  ///
172
  /// When generating new code for a ScopStmt this map is used to map certain
173
  /// llvm::Values to new llvm::Values.
174
  ValueMapT ValueMap;
175
176
  /// Materialize code for @p Id if it was not done before.
177
  ///
178
  /// @returns False, iff a problem occured and the value was not materialized.
179
  bool materializeValue(__isl_take isl_id *Id);
180
181
  /// Materialize parameters of @p Set.
182
  ///
183
  /// @returns False, iff a problem occurred and the value was not materialized.
184
  bool materializeParameters(__isl_take isl_set *Set);
185
186
  /// Materialize all parameters in the current scop.
187
  ///
188
  /// @returns False, iff a problem occurred and the value was not materialized.
189
  bool materializeParameters();
190
191
  // Extract the upper bound of this loop
192
  //
193
  // The isl code generation can generate arbitrary expressions to check if the
194
  // upper bound of a loop is reached, but it provides an option to enforce
195
  // 'atomic' upper bounds. An 'atomic upper bound is always of the form
196
  // iv <= expr, where expr is an (arbitrary) expression not containing iv.
197
  //
198
  // This function extracts 'atomic' upper bounds. Polly, in general, requires
199
  // atomic upper bounds for the following reasons:
200
  //
201
  // 1. An atomic upper bound is loop invariant
202
  //
203
  //    It must not be calculated at each loop iteration and can often even be
204
  //    hoisted out further by the loop invariant code motion.
205
  //
206
  // 2. OpenMP needs a loop invariant upper bound to calculate the number
207
  //    of loop iterations.
208
  //
209
  // 3. With the existing code, upper bounds have been easier to implement.
210
  __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
211
                                         CmpInst::Predicate &Predicate);
212
213
  /// Return non-negative number of iterations in case of the following form
214
  /// of a loop and -1 otherwise.
215
  ///
216
  /// for (i = 0; i <= NumIter; i++) {
217
  ///   loop body;
218
  /// }
219
  ///
220
  /// NumIter is a non-negative integer value. Condition can have
221
  /// isl_ast_op_lt type.
222
  int getNumberOfIterations(__isl_keep isl_ast_node *For);
223
224
  /// Compute the values and loops referenced in this subtree.
225
  ///
226
  /// This function looks at all ScopStmts scheduled below the provided For node
227
  /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
228
  /// not locally defined.
229
  ///
230
  /// Values that can be synthesized or that are available as globals are
231
  /// considered locally defined.
232
  ///
233
  /// Loops that contain the scop or that are part of the scop are considered
234
  /// locally defined. Loops that are before the scop, but do not contain the
235
  /// scop itself are considered not locally defined.
236
  ///
237
  /// @param For    The node defining the subtree.
238
  /// @param Values A vector that will be filled with the Values referenced in
239
  ///               this subtree.
240
  /// @param Loops  A vector that will be filled with the Loops referenced in
241
  ///               this subtree.
242
  void getReferencesInSubtree(__isl_keep isl_ast_node *For,
243
                              SetVector<Value *> &Values,
244
                              SetVector<const Loop *> &Loops);
245
246
  /// Change the llvm::Value(s) used for code generation.
247
  ///
248
  /// When generating code certain values (e.g., references to induction
249
  /// variables or array base pointers) in the original code may be replaced by
250
  /// new values. This function allows to (partially) update the set of values
251
  /// used. A typical use case for this function is the case when we continue
252
  /// code generation in a subfunction/kernel function and need to explicitly
253
  /// pass down certain values.
254
  ///
255
  /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
256
  void updateValues(ValueMapT &NewValues);
257
258
  /// Generate code for a marker now.
259
  ///
260
  /// For mark nodes with an unknown name, we just forward the code generation
261
  /// to its child. This is currently the only behavior implemented, as there is
262
  /// currently not special handling for marker nodes implemented.
263
  ///
264
  /// @param Mark The node we generate code for.
265
  virtual void createMark(__isl_take isl_ast_node *Marker);
266
  virtual void createFor(__isl_take isl_ast_node *For);
267
268
  /// Set to remember materialized invariant loads.
269
  ///
270
  /// An invariant load is identified by its pointer (the SCEV) and its type.
271
  SmallSet<std::pair<const SCEV *, Type *>, 16> PreloadedPtrs;
272
273
  /// Preload the memory access at @p AccessRange with @p Build.
274
  ///
275
  /// @returns The preloaded value casted to type @p Ty
276
  Value *preloadUnconditionally(__isl_take isl_set *AccessRange,
277
                                isl_ast_build *Build, Instruction *AccInst);
278
279
  /// Preload the memory load access @p MA.
280
  ///
281
  /// If @p MA is not always executed it will be conditionally loaded and
282
  /// merged with undef from the same type. Hence, if @p MA is executed only
283
  /// under condition C then the preload code will look like this:
284
  ///
285
  /// MA_preload = undef;
286
  /// if (C)
287
  ///   MA_preload = load MA;
288
  /// use MA_preload
289
  Value *preloadInvariantLoad(const MemoryAccess &MA,
290
                              __isl_take isl_set *Domain);
291
292
  /// Preload the invariant access equivalence class @p IAClass
293
  ///
294
  /// This function will preload the representing load from @p IAClass and
295
  /// map all members of @p IAClass to that preloaded value, potentially casted
296
  /// to the required type.
297
  ///
298
  /// @returns False, iff a problem occurred and the load was not preloaded.
299
  bool preloadInvariantEquivClass(InvariantEquivClassTy &IAClass);
300
301
  void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
302
  void createForSequential(__isl_take isl_ast_node *For, bool KnownParallel);
303
304
  /// Create LLVM-IR that executes a for node thread parallel.
305
  ///
306
  /// @param For The FOR isl_ast_node for which code is generated.
307
  void createForParallel(__isl_take isl_ast_node *For);
308
309
  /// Create new access functions for modified memory accesses.
310
  ///
311
  /// In case the access function of one of the memory references in the Stmt
312
  /// has been modified, we generate a new isl_ast_expr that reflects the
313
  /// newly modified access function and return a map that maps from the
314
  /// individual memory references in the statement (identified by their id)
315
  /// to these newly generated ast expressions.
316
  ///
317
  /// @param Stmt  The statement for which to (possibly) generate new access
318
  ///              functions.
319
  /// @param Node  The ast node corresponding to the statement for us to extract
320
  ///              the local schedule from.
321
  /// @return A new hash table that contains remappings from memory ids to new
322
  ///         access expressions.
323
  __isl_give isl_id_to_ast_expr *
324
  createNewAccesses(ScopStmt *Stmt, __isl_keep isl_ast_node *Node);
325
326
  /// Generate LLVM-IR that computes the values of the original induction
327
  /// variables in function of the newly generated loop induction variables.
328
  ///
329
  /// Example:
330
  ///
331
  ///   // Original
332
  ///   for i
333
  ///     for j
334
  ///       S(i)
335
  ///
336
  ///   Schedule: [i,j] -> [i+j, j]
337
  ///
338
  ///   // New
339
  ///   for c0
340
  ///     for c1
341
  ///       S(c0 - c1, c1)
342
  ///
343
  /// Assuming the original code consists of two loops which are
344
  /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
345
  /// ast models the original statement as a call expression where each argument
346
  /// is an expression that computes the old induction variables from the new
347
  /// ones, ordered such that the first argument computes the value of induction
348
  /// variable that was outermost in the original code.
349
  ///
350
  /// @param Expr The call expression that represents the statement.
351
  /// @param Stmt The statement that is called.
352
  /// @param LTS  The loop to SCEV map in which the mapping from the original
353
  ///             loop to a SCEV representing the new loop iv is added. This
354
  ///             mapping does not require an explicit induction variable.
355
  ///             Instead, we think in terms of an implicit induction variable
356
  ///             that counts the number of times a loop is executed. For each
357
  ///             original loop this count, expressed in function of the new
358
  ///             induction variables, is added to the LTS map.
359
  void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
360
                           LoopToScevMapT &LTS);
361
  void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
362
                                 std::vector<LoopToScevMapT> &VLTS,
363
                                 std::vector<Value *> &IVS,
364
                                 __isl_take isl_id *IteratorID);
365
  virtual void createIf(__isl_take isl_ast_node *If);
366
  void createUserVector(__isl_take isl_ast_node *User,
367
                        std::vector<Value *> &IVS,
368
                        __isl_take isl_id *IteratorID,
369
                        __isl_take isl_union_map *Schedule);
370
  virtual void createUser(__isl_take isl_ast_node *User);
371
  virtual void createBlock(__isl_take isl_ast_node *Block);
372
373
  /// Get the schedule for a given AST node.
374
  ///
375
  /// This information is used to reason about parallelism of loops or the
376
  /// locality of memory accesses under a given schedule.
377
  ///
378
  /// @param Node The node we want to obtain the schedule for.
379
  /// @return Return an isl_union_map that maps from the statements executed
380
  ///         below this ast node to the scheduling vectors used to enumerate
381
  ///         them.
382
  ///
383
  virtual __isl_give isl_union_map *
384
  getScheduleForAstNode(__isl_take isl_ast_node *Node);
385
386
private:
387
  /// Create code for a copy statement.
388
  ///
389
  /// A copy statement is expected to have one read memory access and one write
390
  /// memory access (in this very order). Data is loaded from the location
391
  /// described by the read memory access and written to the location described
392
  /// by the write memory access. @p NewAccesses contains for each access
393
  /// the isl ast expression that describes the location accessed.
394
  ///
395
  /// @param Stmt The copy statement that contains the accesses.
396
  /// @param NewAccesses The hash table that contains remappings from memory
397
  ///                    ids to new access expressions.
398
  void generateCopyStmt(ScopStmt *Stmt,
399
                        __isl_keep isl_id_to_ast_expr *NewAccesses);
400
};
401
402
#endif // POLLY_ISL_NODE_BUILDER_H