blob: 7cf5b263667c87d3594574d1ccf3b39a683c3057 [file] [log] [blame]
Sebastian Pop082cea82012-05-07 16:20:07 +00001//===------ IslCodeGeneration.cpp - Code generate the Scops using ISL. ----===//
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// The IslCodeGeneration pass takes a Scop created by ScopInfo and translates it
11// back to LLVM-IR using the ISL code generator.
12//
13// The Scop describes the high level memory behaviour of a control flow region.
14// Transformation passes can update the schedule (execution order) of statements
15// in the Scop. ISL is used to generate an abstract syntax tree that reflects
16// the updated execution order. This clast is used to create new LLVM-IR that is
17// computationally equivalent to the original control flow region, but executes
Tobias Grosser54839312015-04-21 11:37:25 +000018// its code in the new execution order defined by the changed schedule.
Sebastian Pop082cea82012-05-07 16:20:07 +000019//
20//===----------------------------------------------------------------------===//
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000021#include "polly/Config/config.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000022#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser83628182013-05-07 08:11:54 +000023#include "polly/CodeGen/BlockGenerators.h"
24#include "polly/CodeGen/CodeGeneration.h"
25#include "polly/CodeGen/IslAst.h"
26#include "polly/CodeGen/LoopGenerators.h"
27#include "polly/CodeGen/Utils.h"
Johannes Doerfertf6557f92015-03-04 22:43:40 +000028#include "polly/DependenceInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000029#include "polly/LinkAllPasses.h"
30#include "polly/ScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000031#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000032#include "polly/Support/ScopHelper.h"
Tobias Grossere3c05582014-11-15 21:32:53 +000033#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "polly/TempScopInfo.h"
Tobias Grossere3c05582014-11-15 21:32:53 +000035
36#include "llvm/ADT/PostOrderIterator.h"
37#include "llvm/ADT/SmallPtrSet.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000038#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000039#include "llvm/Analysis/PostDominators.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000040#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser83628182013-05-07 08:11:54 +000041#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
Johannes Doerfert0b169c02015-02-27 17:37:05 +000044#include "llvm/IR/Verifier.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000045#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47
48#include "isl/union_map.h"
49#include "isl/list.h"
50#include "isl/ast.h"
51#include "isl/ast_build.h"
52#include "isl/set.h"
53#include "isl/map.h"
54#include "isl/aff.h"
55
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000056using namespace polly;
57using namespace llvm;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-codegen-isl"
60
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000061class IslNodeBuilder {
62public:
Johannes Doerfert51d1c742014-10-02 15:32:17 +000063 IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
Tobias Grossere3c05582014-11-15 21:32:53 +000064 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
65 DominatorTree &DT, Scop &S)
Tobias Grosserc9895062015-03-10 15:24:33 +000066 : S(S), Builder(Builder), Annotator(Annotator), Rewriter(SE, DL, "polly"),
Tobias Grosserbb8d1562015-03-04 19:33:31 +000067 ExprBuilder(Builder, IDToValue, Rewriter, DT, LI),
Johannes Doerfertf4af99b2015-03-08 21:38:35 +000068 BlockGen(Builder, LI, SE, DT, &ExprBuilder), RegionGen(BlockGen), P(P),
69 DL(DL), LI(LI), SE(SE), DT(DT) {}
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000070
Tobias Grosserbb8d1562015-03-04 19:33:31 +000071 ~IslNodeBuilder() {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000072
73 void addParameters(__isl_take isl_set *Context);
74 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000075 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000076
77private:
Tobias Grossere3c05582014-11-15 21:32:53 +000078 Scop &S;
Tobias Grosser5103ba72014-03-04 14:58:49 +000079 PollyIRBuilder &Builder;
Johannes Doerfert51d1c742014-10-02 15:32:17 +000080 ScopAnnotator &Annotator;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000081
82 /// @brief A SCEVExpander to create llvm values from SCEVs.
Tobias Grosserbb8d1562015-03-04 19:33:31 +000083 SCEVExpander Rewriter;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000084
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000085 IslExprBuilder ExprBuilder;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000086 BlockGenerator BlockGen;
Johannes Doerfert275a1752015-02-24 16:16:32 +000087
88 /// @brief Generator for region statements.
89 RegionGenerator RegionGen;
90
Johannes Doerfertf4af99b2015-03-08 21:38:35 +000091 Pass *const P;
Tobias Grossere3c05582014-11-15 21:32:53 +000092 const DataLayout &DL;
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000093 LoopInfo &LI;
94 ScalarEvolution &SE;
95 DominatorTree &DT;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000096
Tobias Grossere3c05582014-11-15 21:32:53 +000097 /// @brief The current iteration of out-of-scop loops
98 ///
99 /// This map provides for a given loop a llvm::Value that contains the current
100 /// loop iteration.
101 LoopToScevMapT OutsideLoopIterations;
102
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000103 // This maps an isl_id* to the Value* it has in the generated program. For now
104 // on, the only isl_ids that are stored here are the newly calculated loop
105 // ivs.
Tobias Grosser566ad582014-08-31 16:21:12 +0000106 IslExprBuilder::IDToValueTy IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000107
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000108 /// Generate code for a given SCEV*
109 ///
110 /// This function generates code for a given SCEV expression. It generated
111 /// code is emmitted at the end of the basic block our Builder currently
112 /// points to and the resulting value is returned.
113 ///
114 /// @param Expr The expression to code generate.
115 Value *generateSCEV(const SCEV *Expr);
116
Tobias Grossere3c05582014-11-15 21:32:53 +0000117 /// A set of Value -> Value remappings to apply when generating new code.
118 ///
119 /// When generating new code for a ScopStmt this map is used to map certain
120 /// llvm::Values to new llvm::Values.
121 ValueMapT ValueMap;
122
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000123 // Extract the upper bound of this loop
124 //
125 // The isl code generation can generate arbitrary expressions to check if the
126 // upper bound of a loop is reached, but it provides an option to enforce
127 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
128 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
129 //
130 // This function extracts 'atomic' upper bounds. Polly, in general, requires
131 // atomic upper bounds for the following reasons:
132 //
133 // 1. An atomic upper bound is loop invariant
134 //
135 // It must not be calculated at each loop iteration and can often even be
136 // hoisted out further by the loop invariant code motion.
137 //
138 // 2. OpenMP needs a loop invarient upper bound to calculate the number
139 // of loop iterations.
140 //
141 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000142 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
143 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000144
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000145 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
146
Tobias Grossere3c05582014-11-15 21:32:53 +0000147 /// Compute the values and loops referenced in this subtree.
148 ///
149 /// This function looks at all ScopStmts scheduled below the provided For node
150 /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
151 /// not locally defined.
152 ///
153 /// Values that can be synthesized or that are available as globals are
154 /// considered locally defined.
155 ///
156 /// Loops that contain the scop or that are part of the scop are considered
157 /// locally defined. Loops that are before the scop, but do not contain the
158 /// scop itself are considered not locally defined.
159 ///
160 /// @param For The node defining the subtree.
161 /// @param Values A vector that will be filled with the Values referenced in
162 /// this subtree.
163 /// @param Loops A vector that will be filled with the Loops referenced in
164 /// this subtree.
165 void getReferencesInSubtree(__isl_keep isl_ast_node *For,
166 SetVector<Value *> &Values,
167 SetVector<const Loop *> &Loops);
168
169 /// Change the llvm::Value(s) used for code generation.
170 ///
171 /// When generating code certain values (e.g., references to induction
172 /// variables or array base pointers) in the original code may be replaced by
173 /// new values. This function allows to (partially) update the set of values
174 /// used. A typical use case for this function is the case when we continue
175 /// code generation in a subfunction/kernel function and need to explicitly
176 /// pass down certain values.
177 ///
178 /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
179 void updateValues(ParallelLoopGenerator::ValueToValueMapTy &NewValues);
180
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000181 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000182 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
183 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000184
Tobias Grossere3c05582014-11-15 21:32:53 +0000185 /// Create LLVM-IR that executes a for node thread parallel.
186 ///
187 /// @param For The FOR isl_ast_node for which code is generated.
188 void createForParallel(__isl_take isl_ast_node *For);
189
Tobias Grosserce67a042014-07-02 16:26:47 +0000190 /// Generate LLVM-IR that computes the values of the original induction
191 /// variables in function of the newly generated loop induction variables.
192 ///
193 /// Example:
194 ///
195 /// // Original
196 /// for i
197 /// for j
198 /// S(i)
199 ///
200 /// Schedule: [i,j] -> [i+j, j]
201 ///
202 /// // New
203 /// for c0
204 /// for c1
205 /// S(c0 - c1, c1)
206 ///
207 /// Assuming the original code consists of two loops which are
208 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
209 /// ast models the original statement as a call expression where each argument
210 /// is an expression that computes the old induction variables from the new
211 /// ones, ordered such that the first argument computes the value of induction
212 /// variable that was outermost in the original code.
213 ///
214 /// @param Expr The call expression that represents the statement.
215 /// @param Stmt The statement that is called.
216 /// @param VMap The value map into which the mapping from the old induction
217 /// variable to the new one is inserted. This mapping is used
218 /// for the classical code generation (not scev-based) and
219 /// gives an explicit mapping from an original, materialized
220 /// induction variable. It consequently can only be expressed
221 /// if there was an explicit induction variable.
222 /// @param LTS The loop to SCEV map in which the mapping from the original
223 /// loop to a SCEV representing the new loop iv is added. This
224 /// mapping does not require an explicit induction variable.
225 /// Instead, we think in terms of an implicit induction variable
226 /// that counts the number of times a loop is executed. For each
227 /// original loop this count, expressed in function of the new
228 /// induction variables, is added to the LTS map.
229 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000230 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000231 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
232 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000233 std::vector<LoopToScevMapT> &VLTS,
234 std::vector<Value *> &IVS,
235 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000236 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000237 void createUserVector(__isl_take isl_ast_node *User,
238 std::vector<Value *> &IVS,
239 __isl_take isl_id *IteratorID,
240 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000241 void createUser(__isl_take isl_ast_node *User);
242 void createBlock(__isl_take isl_ast_node *Block);
243};
244
Tobias Grossere602a072013-05-07 07:30:56 +0000245__isl_give isl_ast_expr *
246IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
247 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000248 isl_id *UBID, *IteratorID;
249 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000250 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000251
252 Cond = isl_ast_node_for_get_cond(For);
253 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosser2784b082015-01-10 07:40:39 +0000254 isl_ast_expr_get_type(Cond);
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000255 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
256 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000257
Tobias Grosser2784b082015-01-10 07:40:39 +0000258 Type = isl_ast_expr_get_op_type(Cond);
259
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000260 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000261 case isl_ast_op_le:
262 Predicate = ICmpInst::ICMP_SLE;
263 break;
264 case isl_ast_op_lt:
265 Predicate = ICmpInst::ICMP_SLT;
266 break;
267 default:
268 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000269 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000270
271 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
272
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000273 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
274 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000275
276 UBID = isl_ast_expr_get_id(Arg0);
277
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000278 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
279 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000280
281 IteratorID = isl_ast_expr_get_id(Iterator);
282
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000283 assert(UBID == IteratorID &&
284 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000285
286 UB = isl_ast_expr_get_op_arg(Cond, 1);
287
288 isl_ast_expr_free(Cond);
289 isl_ast_expr_free(Iterator);
290 isl_ast_expr_free(Arg0);
291 isl_id_free(IteratorID);
292 isl_id_free(UBID);
293
294 return UB;
295}
296
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000297unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000298 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000299 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Tobias Grosserb68068b2015-04-27 10:38:45 +0000300 int Dim = isl_set_dim(LoopDomain, isl_dim_set);
301
302 // Calculate a map similar to the identity map, but with the last input
303 // and output dimension not related.
304 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
305 isl_space *Space = isl_set_get_space(LoopDomain);
306 Space = isl_space_drop_dims(Space, isl_dim_out, Dim - 1, 1);
307 Space = isl_space_map_from_set(Space);
308 isl_map *Identity = isl_map_identity(Space);
309 Identity = isl_map_add_dims(Identity, isl_dim_in, 1);
310 Identity = isl_map_add_dims(Identity, isl_dim_out, 1);
311
312 LoopDomain = isl_set_reset_tuple_id(LoopDomain);
313
314 isl_map *Map = isl_map_from_domain_and_range(isl_set_copy(LoopDomain),
315 isl_set_copy(LoopDomain));
316 isl_set_free(LoopDomain);
317 Map = isl_map_intersect(Map, Identity);
318
319 isl_map *LexMax = isl_map_lexmax(isl_map_copy(Map));
320 isl_map *LexMin = isl_map_lexmin(Map);
321 isl_map *Sub = isl_map_sum(LexMax, isl_map_neg(LexMin));
322
323 isl_set *Elements = isl_map_range(Sub);
324
325 if (!isl_set_is_singleton(Elements)) {
326 isl_set_free(Elements);
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000327 return -1;
Tobias Grosserb68068b2015-04-27 10:38:45 +0000328 }
329
330 isl_point *P = isl_set_sample_point(Elements);
331
332 isl_val *V;
333 V = isl_point_get_coordinate_val(P, isl_dim_set, Dim - 1);
334 int NumberIterations = isl_val_get_num_si(V);
335 isl_val_free(V);
336 isl_point_free(P);
337 if (NumberIterations == -1)
338 return -1;
339 return NumberIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000340}
341
Tobias Grossere3c05582014-11-15 21:32:53 +0000342struct FindValuesUser {
343 LoopInfo &LI;
344 ScalarEvolution &SE;
345 Region &R;
346 SetVector<Value *> &Values;
347 SetVector<const SCEV *> &SCEVs;
348};
349
Johannes Doerfertbbf30842015-03-02 13:41:53 +0000350/// @brief Extract the values and SCEVs needed to generate code for a block.
351static int findValuesInBlock(struct FindValuesUser &User, const ScopStmt *Stmt,
352 const BasicBlock *BB) {
Tobias Grossere3c05582014-11-15 21:32:53 +0000353 // Check all the operands of instructions in the basic block.
354 for (const Instruction &Inst : *BB) {
355 for (Value *SrcVal : Inst.operands()) {
356 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
357 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) {
358 User.SCEVs.insert(
359 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB)));
360 continue;
361 }
362 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
363 if (Stmt->getParent()->getRegion().contains(OpInst))
364 continue;
365
366 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
367 User.Values.insert(SrcVal);
368 }
369 }
Johannes Doerfertbbf30842015-03-02 13:41:53 +0000370 return 0;
371}
372
373/// Extract the values and SCEVs needed to generate code for a ScopStmt.
374///
375/// This function extracts a ScopStmt from a given isl_set and computes the
376/// Values this statement depends on as well as a set of SCEV expressions that
377/// need to be synthesized when generating code for this statment.
378static int findValuesInStmt(isl_set *Set, void *UserPtr) {
379 isl_id *Id = isl_set_get_tuple_id(Set);
380 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr);
381 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
382
383 if (Stmt->isBlockStmt())
384 findValuesInBlock(User, Stmt, Stmt->getBasicBlock());
385 else {
386 assert(Stmt->isRegionStmt() &&
387 "Stmt was neither block nor region statement");
388 for (const BasicBlock *BB : Stmt->getRegion()->blocks())
389 findValuesInBlock(User, Stmt, BB);
390 }
391
Tobias Grossere3c05582014-11-15 21:32:53 +0000392 isl_id_free(Id);
393 isl_set_free(Set);
394 return 0;
395}
396
397void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
398 SetVector<Value *> &Values,
399 SetVector<const Loop *> &Loops) {
400
401 SetVector<const SCEV *> SCEVs;
402 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs};
403
404 for (const auto &I : IDToValue)
405 Values.insert(I.second);
406
407 for (const auto &I : OutsideLoopIterations)
408 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
409
410 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For));
411
412 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues);
413 isl_union_set_free(Schedule);
414
415 for (const SCEV *Expr : SCEVs) {
416 findValues(Expr, Values);
417 findLoops(Expr, Loops);
418 }
419
420 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
421
422 /// Remove loops that contain the scop or that are part of the scop, as they
423 /// are considered local. This leaves only loops that are before the scop, but
424 /// do not contain the scop itself.
425 Loops.remove_if([this](const Loop *L) {
426 return this->S.getRegion().contains(L) ||
427 L->contains(S.getRegion().getEntry());
428 });
429}
430
431void IslNodeBuilder::updateValues(
432 ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
433 SmallPtrSet<Value *, 5> Inserted;
434
435 for (const auto &I : IDToValue) {
436 IDToValue[I.first] = NewValues[I.second];
437 Inserted.insert(I.second);
438 }
439
440 for (const auto &I : NewValues) {
441 if (Inserted.count(I.first))
442 continue;
443
444 ValueMap[I.first] = I.second;
445 }
446}
447
Tobias Grossere602a072013-05-07 07:30:56 +0000448void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
449 std::vector<Value *> &IVS,
450 __isl_take isl_id *IteratorID,
451 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000452 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
453 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
454 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
455 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000456 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000457 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000458 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000459 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000460
461 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
462 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
463 isl_map *S = isl_map_from_union_map(Schedule);
464
Tobias Grosserce67a042014-07-02 16:26:47 +0000465 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000466 VectorBlockGenerator::generate(BlockGen, *Stmt, VectorMap, VLTS, S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000467
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000468 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000469 isl_id_free(Id);
470 isl_ast_node_free(User);
471}
472
Tobias Grossere602a072013-05-07 07:30:56 +0000473void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
474 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000475 isl_ast_node *Body = isl_ast_node_for_get_body(For);
476 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
477 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
478 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
479 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000480
481 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000482 Value *ValueInc = ExprBuilder.create(Inc);
483
484 Type *MaxType = ExprBuilder.getType(Iterator);
485 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000486 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
487
488 if (MaxType != ValueLB->getType())
489 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000490 if (MaxType != ValueInc->getType())
491 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
492
Tobias Grosserc14582f2013-02-05 18:01:29 +0000493 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000494 IVS[0] = ValueLB;
495
496 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000497 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000498
Johannes Doerfert94d90822014-07-23 20:26:25 +0000499 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000500 assert(Schedule && "For statement annotation does not contain its schedule");
501
502 IDToValue[IteratorID] = ValueLB;
503
504 switch (isl_ast_node_get_type(Body)) {
505 case isl_ast_node_user:
506 createUserVector(Body, IVS, isl_id_copy(IteratorID),
507 isl_union_map_copy(Schedule));
508 break;
509 case isl_ast_node_block: {
510 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
511
512 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
513 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000514 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000515
516 isl_ast_node_free(Body);
517 isl_ast_node_list_free(List);
518 break;
519 }
520 default:
521 isl_ast_node_dump(Body);
522 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
523 }
524
Tobias Grossere3c05582014-11-15 21:32:53 +0000525 IDToValue.erase(IDToValue.find(IteratorID));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000526 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000527 isl_union_map_free(Schedule);
528
529 isl_ast_node_free(For);
530 isl_ast_expr_free(Iterator);
531}
532
533void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000534 isl_ast_node *Body;
535 isl_ast_expr *Init, *Inc, *Iterator, *UB;
536 isl_id *IteratorID;
537 Value *ValueLB, *ValueUB, *ValueInc;
538 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000539 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000540 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000541 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000542 bool Parallel;
543
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000544 Parallel =
545 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000546
547 Body = isl_ast_node_for_get_body(For);
548
549 // isl_ast_node_for_is_degenerate(For)
550 //
551 // TODO: For degenerated loops we could generate a plain assignment.
552 // However, for now we just reuse the logic for normal loops, which will
553 // create a loop with a single iteration.
554
555 Init = isl_ast_node_for_get_init(For);
556 Inc = isl_ast_node_for_get_inc(For);
557 Iterator = isl_ast_node_for_get_iterator(For);
558 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000559 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000560
561 ValueLB = ExprBuilder.create(Init);
562 ValueUB = ExprBuilder.create(UB);
563 ValueInc = ExprBuilder.create(Inc);
564
565 MaxType = ExprBuilder.getType(Iterator);
566 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
567 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
568 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
569
570 if (MaxType != ValueLB->getType())
571 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
572 if (MaxType != ValueUB->getType())
573 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
574 if (MaxType != ValueInc->getType())
575 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
576
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000577 // If we can show that LB <Predicate> UB holds at least once, we can
578 // omit the GuardBB in front of the loop.
579 bool UseGuardBB =
580 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000581 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000582 Predicate, &Annotator, Parallel, UseGuardBB);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000583 IDToValue[IteratorID] = IV;
584
585 create(Body);
586
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000587 Annotator.popLoop(Parallel);
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000588
Tobias Grossere3c05582014-11-15 21:32:53 +0000589 IDToValue.erase(IDToValue.find(IteratorID));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000590
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000591 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000592
593 isl_ast_node_free(For);
594 isl_ast_expr_free(Iterator);
595 isl_id_free(IteratorID);
596}
597
Tobias Grossere3c05582014-11-15 21:32:53 +0000598/// @brief Remove the BBs contained in a (sub)function from the dominator tree.
599///
600/// This function removes the basic blocks that are part of a subfunction from
601/// the dominator tree. Specifically, when generating code it may happen that at
602/// some point the code generation continues in a new sub-function (e.g., when
603/// generating OpenMP code). The basic blocks that are created in this
604/// sub-function are then still part of the dominator tree of the original
605/// function, such that the dominator tree reaches over function boundaries.
606/// This is not only incorrect, but also causes crashes. This function now
607/// removes from the dominator tree all basic blocks that are dominated (and
608/// consequently reachable) from the entry block of this (sub)function.
609///
610/// FIXME: A LLVM (function or region) pass should not touch anything outside of
611/// the function/region it runs on. Hence, the pure need for this function shows
612/// that we do not comply to this rule. At the moment, this does not cause any
613/// issues, but we should be aware that such issues may appear. Unfortunately
614/// the current LLVM pass infrastructure does not allow to make Polly a module
615/// or call-graph pass to solve this issue, as such a pass would not have access
616/// to the per-function analyses passes needed by Polly. A future pass manager
617/// infrastructure is supposed to enable such kind of access possibly allowing
618/// us to create a cleaner solution here.
619///
620/// FIXME: Instead of adding the dominance information and then dropping it
621/// later on, we should try to just not add it in the first place. This requires
622/// some careful testing to make sure this does not break in interaction with
623/// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
624/// which may try to update it.
625///
626/// @param F The function which contains the BBs to removed.
627/// @param DT The dominator tree from which to remove the BBs.
628static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
629 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
630 std::vector<BasicBlock *> Nodes;
631
632 // We can only remove an element from the dominator tree, if all its children
633 // have been removed. To ensure this we obtain the list of nodes to remove
634 // using a post-order tree traversal.
635 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
636 Nodes.push_back(I->getBlock());
637
638 for (BasicBlock *BB : Nodes)
639 DT.eraseNode(BB);
640}
641
642void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
643 isl_ast_node *Body;
644 isl_ast_expr *Init, *Inc, *Iterator, *UB;
645 isl_id *IteratorID;
646 Value *ValueLB, *ValueUB, *ValueInc;
647 Type *MaxType;
648 Value *IV;
649 CmpInst::Predicate Predicate;
650
651 Body = isl_ast_node_for_get_body(For);
652 Init = isl_ast_node_for_get_init(For);
653 Inc = isl_ast_node_for_get_inc(For);
654 Iterator = isl_ast_node_for_get_iterator(For);
655 IteratorID = isl_ast_expr_get_id(Iterator);
656 UB = getUpperBound(For, Predicate);
657
658 ValueLB = ExprBuilder.create(Init);
659 ValueUB = ExprBuilder.create(UB);
660 ValueInc = ExprBuilder.create(Inc);
661
662 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
663 // expression, we need to adjust the loop blound by one.
664 if (Predicate == CmpInst::ICMP_SLT)
665 ValueUB = Builder.CreateAdd(
666 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
667
668 MaxType = ExprBuilder.getType(Iterator);
669 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
670 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
671 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
672
673 if (MaxType != ValueLB->getType())
674 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
675 if (MaxType != ValueUB->getType())
676 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
677 if (MaxType != ValueInc->getType())
678 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
679
680 BasicBlock::iterator LoopBody;
681
682 SetVector<Value *> SubtreeValues;
683 SetVector<const Loop *> Loops;
684
685 getReferencesInSubtree(For, SubtreeValues, Loops);
686
687 // Create for all loops we depend on values that contain the current loop
688 // iteration. These values are necessary to generate code for SCEVs that
689 // depend on such loops. As a result we need to pass them to the subfunction.
690 for (const Loop *L : Loops) {
691 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
692 SE.getUnknown(Builder.getInt64(1)),
693 L, SCEV::FlagAnyWrap);
694 Value *V = generateSCEV(OuterLIV);
695 OutsideLoopIterations[L] = SE.getUnknown(V);
696 SubtreeValues.insert(V);
697 }
698
699 ParallelLoopGenerator::ValueToValueMapTy NewValues;
700 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
701
702 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
703 SubtreeValues, NewValues, &LoopBody);
704 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
705 Builder.SetInsertPoint(LoopBody);
706
707 // Save the current values.
708 ValueMapT ValueMapCopy = ValueMap;
709 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
710
711 updateValues(NewValues);
712 IDToValue[IteratorID] = IV;
713
714 create(Body);
715
716 // Restore the original values.
717 ValueMap = ValueMapCopy;
718 IDToValue = IDToValueCopy;
719
720 Builder.SetInsertPoint(AfterLoop);
721 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
722
723 for (const Loop *L : Loops)
724 OutsideLoopIterations.erase(L);
725
726 isl_ast_node_free(For);
727 isl_ast_expr_free(Iterator);
728 isl_id_free(IteratorID);
729}
730
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000731void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
Tobias Grosser7527e3f2015-04-05 06:53:21 +0000732 bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000733
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000734 if (Vector && IslAstInfo::isInnermostParallel(For) &&
735 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000736 int VectorWidth = getNumberOfIterations(For);
737 if (1 < VectorWidth && VectorWidth <= 16) {
738 createForVector(For, VectorWidth);
739 return;
740 }
741 }
Tobias Grossere3c05582014-11-15 21:32:53 +0000742
743 if (IslAstInfo::isExecutedInParallel(For)) {
744 createForParallel(For);
745 return;
746 }
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000747 createForSequential(For);
748}
749
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000750void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
751 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
752
753 Function *F = Builder.GetInsertBlock()->getParent();
754 LLVMContext &Context = F->getContext();
755
Tobias Grosserc14582f2013-02-05 18:01:29 +0000756 BasicBlock *CondBB =
Chandler Carruth5ec33332015-01-18 10:52:23 +0000757 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000758 CondBB->setName("polly.cond");
Chandler Carruth5ec33332015-01-18 10:52:23 +0000759 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000760 MergeBB->setName("polly.merge");
761 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
762 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
763
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000764 DT.addNewBlock(ThenBB, CondBB);
765 DT.addNewBlock(ElseBB, CondBB);
766 DT.changeImmediateDominator(MergeBB, CondBB);
767
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000768 Loop *L = LI.getLoopFor(CondBB);
769 if (L) {
Chandler Carruth6adcf562015-01-18 01:47:30 +0000770 L->addBasicBlockToLoop(ThenBB, LI);
771 L->addBasicBlockToLoop(ElseBB, LI);
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000772 }
773
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000774 CondBB->getTerminator()->eraseFromParent();
775
776 Builder.SetInsertPoint(CondBB);
777 Value *Predicate = ExprBuilder.create(Cond);
778 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
779 Builder.SetInsertPoint(ThenBB);
780 Builder.CreateBr(MergeBB);
781 Builder.SetInsertPoint(ElseBB);
782 Builder.CreateBr(MergeBB);
783 Builder.SetInsertPoint(ThenBB->begin());
784
785 create(isl_ast_node_if_get_then(If));
786
787 Builder.SetInsertPoint(ElseBB->begin());
788
789 if (isl_ast_node_if_has_else(If))
790 create(isl_ast_node_if_get_else(If));
791
792 Builder.SetInsertPoint(MergeBB->begin());
793
794 isl_ast_node_free(If);
795}
796
Tobias Grosserce67a042014-07-02 16:26:47 +0000797void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
798 ValueMapT &VMap, LoopToScevMapT &LTS) {
799 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
800 "Expression of type 'op' expected");
801 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
802 "Opertation of type 'call' expected");
803 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
804 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000805 Value *V;
806
Tobias Grosserce67a042014-07-02 16:26:47 +0000807 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
808 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000809 ScalarEvolution *SE = Stmt->getParent()->getSE();
810 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000811 }
812
Tobias Grossere3c05582014-11-15 21:32:53 +0000813 // Add the current ValueMap to our per-statement value map.
814 //
815 // This is needed e.g. to rewrite array base addresses when moving code
816 // into a parallely executed subfunction.
817 VMap.insert(ValueMap.begin(), ValueMap.end());
818
Tobias Grosserce67a042014-07-02 16:26:47 +0000819 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000820}
821
Tobias Grosserc14582f2013-02-05 18:01:29 +0000822void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000823 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
824 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
825 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000826 int i = 0;
827
828 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000829 for (Value *IV : IVS) {
830 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000831 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000832 i++;
833 }
834
835 IDToValue[IteratorID] = OldValue;
836 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000837 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000838}
839
840void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
841 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000842 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000843 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000844 ScopStmt *Stmt;
845
Tobias Grosserce67a042014-07-02 16:26:47 +0000846 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
847 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
848 Id = isl_ast_expr_get_id(StmtExpr);
849 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000850
Tobias Grossere3c05582014-11-15 21:32:53 +0000851 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
852
Tobias Grosserc14582f2013-02-05 18:01:29 +0000853 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000854 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Johannes Doerferta63b2572014-08-03 01:51:59 +0000855
Tobias Grosserce67a042014-07-02 16:26:47 +0000856 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000857 if (Stmt->isBlockStmt())
858 BlockGen.copyStmt(*Stmt, VMap, LTS);
859 else
860 RegionGen.copyStmt(*Stmt, VMap, LTS);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000861
862 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000863 isl_id_free(Id);
864}
865
866void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
867 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
868
869 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
870 create(isl_ast_node_list_get_ast_node(List, i));
871
872 isl_ast_node_free(Block);
873 isl_ast_node_list_free(List);
874}
875
876void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
877 switch (isl_ast_node_get_type(Node)) {
878 case isl_ast_node_error:
Tobias Grosser29e36dc2015-03-30 17:28:57 +0000879 llvm_unreachable("code generation error");
880 case isl_ast_node_mark:
881 llvm_unreachable("Mark node unexpected");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000882 case isl_ast_node_for:
883 createFor(Node);
884 return;
885 case isl_ast_node_if:
886 createIf(Node);
887 return;
888 case isl_ast_node_user:
889 createUser(Node);
890 return;
891 case isl_ast_node_block:
892 createBlock(Node);
893 return;
894 }
895
896 llvm_unreachable("Unknown isl_ast_node type");
897}
898
899void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000900
901 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
902 isl_id *Id;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000903
904 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000905 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000906
907 isl_id_free(Id);
908 }
909
Tobias Grossere3c05582014-11-15 21:32:53 +0000910 // Generate values for the current loop iteration for all surrounding loops.
911 //
912 // We may also reference loops outside of the scop which do not contain the
913 // scop itself, but as the number of such scops may be arbitrarily large we do
914 // not generate code for them here, but only at the point of code generation
915 // where these values are needed.
916 Region &R = S.getRegion();
917 Loop *L = LI.getLoopFor(R.getEntry());
918
919 while (L != nullptr && R.contains(L))
920 L = L->getParentLoop();
921
922 while (L != nullptr) {
923 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
924 SE.getUnknown(Builder.getInt64(1)),
925 L, SCEV::FlagAnyWrap);
926 Value *V = generateSCEV(OuterLIV);
927 OutsideLoopIterations[L] = SE.getUnknown(V);
928 L = L->getParentLoop();
929 }
930
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000931 isl_set_free(Context);
932}
933
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000934Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
935 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
Tobias Grosserbb8d1562015-03-04 19:33:31 +0000936 return Rewriter.expandCodeFor(Expr, Expr->getType(), InsertLocation);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000937}
938
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000939namespace {
940class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000941public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000942 static char ID;
943
944 IslCodeGeneration() : ScopPass(ID) {}
945
Tobias Grossere3c05582014-11-15 21:32:53 +0000946 /// @brief The datalayout used
947 const DataLayout *DL;
948
Johannes Doerfert38262242014-09-10 14:50:23 +0000949 /// @name The analysis passes we need to generate code.
950 ///
951 ///{
952 LoopInfo *LI;
953 IslAstInfo *AI;
954 DominatorTree *DT;
955 ScalarEvolution *SE;
956 ///}
957
958 /// @brief The loop annotator to generate llvm.loop metadata.
Johannes Doerfert51d1c742014-10-02 15:32:17 +0000959 ScopAnnotator Annotator;
Johannes Doerfert38262242014-09-10 14:50:23 +0000960
961 /// @brief Build the runtime condition.
962 ///
963 /// Build the condition that evaluates at run-time to true iff all
964 /// assumptions taken for the SCoP hold, and to false otherwise.
965 ///
966 /// @return A value evaluating to true/false if execution is save/unsafe.
967 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
968 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
969 Value *RTC = ExprBuilder.create(AI->getRunCondition());
Johannes Doerfertb164c792014-09-18 11:17:17 +0000970 if (!RTC->getType()->isIntegerTy(1))
971 RTC = Builder.CreateIsNotNull(RTC);
972 return RTC;
Johannes Doerfert38262242014-09-10 14:50:23 +0000973 }
974
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000975 bool verifyGeneratedFunction(Scop &S, Function &F) {
976 if (!verifyFunction(F))
977 return false;
978
979 DEBUG({
980 errs() << "== ISL Codegen created an invalid function ==\n\n== The "
981 "SCoP ==\n";
982 S.print(errs());
983 errs() << "\n== The isl AST ==\n";
Johannes Doerfert3fe584d2015-03-01 18:40:25 +0000984 AI->printScop(errs(), S);
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000985 errs() << "\n== The invalid function ==\n";
986 F.print(errs());
987 errs() << "\n== The errors ==\n";
988 verifyFunction(F, &errs());
989 });
990
991 return true;
992 }
993
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000994 bool runOnScop(Scop &S) override {
Johannes Doerfert38262242014-09-10 14:50:23 +0000995 AI = &getAnalysis<IslAstInfo>();
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000996
997 // Check if we created an isl_ast root node, otherwise exit.
998 isl_ast_node *AstRoot = AI->getAst();
999 if (!AstRoot)
1000 return false;
1001
1002 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +00001003 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1004 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser140b3942015-03-05 09:48:20 +00001005 DL = &S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001006
Tobias Grossere602a072013-05-07 07:30:56 +00001007 assert(!S.getRegion().isTopLevelRegion() &&
1008 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001009
Tobias Grosser6325cd22015-04-27 10:43:10 +00001010 Annotator.buildAliasScopes(S);
Johannes Doerfertecdf2632014-10-02 15:31:24 +00001011
Johannes Doerfert38262242014-09-10 14:50:23 +00001012 BasicBlock *EnteringBB = simplifyRegion(&S, this);
1013 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +00001014
Tobias Grossere3c05582014-11-15 21:32:53 +00001015 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
Johannes Doerfert38262242014-09-10 14:50:23 +00001016
Tobias Grosser67942382015-03-28 09:34:40 +00001017 // Only build the run-time condition and parameters _after_ having
1018 // introduced the conditional branch. This is important as the conditional
1019 // branch will guard the original scop from new induction variables that
1020 // the SCEVExpander may introduce while code generating the parameters and
1021 // which may introduce scalar dependences that prevent us from correctly
1022 // code generating this scop.
1023 BasicBlock *StartBlock =
1024 executeScopConditionally(S, this, Builder.getTrue());
1025 auto SplitBlock = StartBlock->getSinglePredecessor();
1026 Builder.SetInsertPoint(SplitBlock->getTerminator());
1027 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert38262242014-09-10 14:50:23 +00001028 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
Tobias Grosser67942382015-03-28 09:34:40 +00001029 SplitBlock->getTerminator()->setOperand(0, RTC);
Tobias Grosser28735942014-08-16 09:09:15 +00001030 Builder.SetInsertPoint(StartBlock->begin());
1031
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001032 NodeBuilder.create(AstRoot);
Johannes Doerfert0b169c02015-02-27 17:37:05 +00001033
1034 assert(!verifyGeneratedFunction(S, *EnteringBB->getParent()) &&
1035 "Verification of generated function failed");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001036 return true;
1037 }
1038
Johannes Doerfert909a3bf2015-03-01 18:42:08 +00001039 void printScop(raw_ostream &, Scop &) const override {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001040
Johannes Doerfert909a3bf2015-03-01 18:42:08 +00001041 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tobias Grosser42aff302014-01-13 22:29:56 +00001042 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001043 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001044 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001045 AU.addRequired<ScalarEvolution>();
1046 AU.addRequired<ScopDetection>();
1047 AU.addRequired<ScopInfo>();
Chandler Carruthf5579872015-01-17 14:16:56 +00001048 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001049
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001050 AU.addPreserved<DependenceInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001051
Chandler Carruthf5579872015-01-17 14:16:56 +00001052 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001053 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001054 AU.addPreserved<IslAstInfo>();
1055 AU.addPreserved<ScopDetection>();
1056 AU.addPreserved<ScalarEvolution>();
1057
1058 // FIXME: We do not yet add regions for the newly generated code to the
1059 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +00001060 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001061 AU.addPreserved<TempScopInfo>();
1062 AU.addPreserved<ScopInfo>();
1063 AU.addPreservedID(IndependentBlocksID);
1064 }
1065};
1066}
1067
1068char IslCodeGeneration::ID = 1;
1069
Tobias Grosser7242ad92013-02-22 08:07:06 +00001070Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001071
Tobias Grosser7242ad92013-02-22 08:07:06 +00001072INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1073 "Polly - Create LLVM-IR from SCoPs", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001074INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Tobias Grosser42aff302014-01-13 22:29:56 +00001075INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001076INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001077INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001078INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1079INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1080INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1081 "Polly - Create LLVM-IR from SCoPs", false, false)