Coverage Report

Created: 2017-06-23 12:40

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