blob: 361ef8ac5a5dc0bec7c29eee7117f5d50c5f7509 [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
18// its code in the new execution order defined by the changed scattering.
19//
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"
Johannes Doerfert48cf6ec2014-07-29 20:50:09 +000026#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser83628182013-05-07 08:11:54 +000027#include "polly/CodeGen/LoopGenerators.h"
28#include "polly/CodeGen/Utils.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000029#include "polly/Dependences.h"
30#include "polly/LinkAllPasses.h"
31#include "polly/ScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000032#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000033#include "polly/Support/ScopHelper.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "polly/TempScopInfo.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000035#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000036#include "llvm/Analysis/PostDominators.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000037#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser83628182013-05-07 08:11:54 +000038#include "llvm/IR/Module.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000041#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43
44#include "isl/union_map.h"
45#include "isl/list.h"
46#include "isl/ast.h"
47#include "isl/ast_build.h"
48#include "isl/set.h"
49#include "isl/map.h"
50#include "isl/aff.h"
51
52#include <map>
53
54using namespace polly;
55using namespace llvm;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-codegen-isl"
58
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000059class IslNodeBuilder {
60public:
Tobias Grosser37c9b8e2014-03-04 14:59:00 +000061 IslNodeBuilder(PollyIRBuilder &Builder, LoopAnnotator &Annotator, Pass *P)
Tobias Grosser34c87872014-04-22 16:39:41 +000062 : Builder(Builder), Annotator(Annotator), ExprBuilder(Builder, IDToValue),
63 P(P) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000064
Johannes Doerferta63b2572014-08-03 01:51:59 +000065 /// @brief Add the mappings from array id's to array llvm::Value's.
66 void addMemoryAccesses(Scop &S);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000067 void addParameters(__isl_take isl_set *Context);
68 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000069 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000070
71private:
Tobias Grosser5103ba72014-03-04 14:58:49 +000072 PollyIRBuilder &Builder;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +000073 LoopAnnotator &Annotator;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000074 IslExprBuilder ExprBuilder;
75 Pass *P;
76
77 // This maps an isl_id* to the Value* it has in the generated program. For now
78 // on, the only isl_ids that are stored here are the newly calculated loop
79 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +000080 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000081
82 // Extract the upper bound of this loop
83 //
84 // The isl code generation can generate arbitrary expressions to check if the
85 // upper bound of a loop is reached, but it provides an option to enforce
86 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
87 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
88 //
89 // This function extracts 'atomic' upper bounds. Polly, in general, requires
90 // atomic upper bounds for the following reasons:
91 //
92 // 1. An atomic upper bound is loop invariant
93 //
94 // It must not be calculated at each loop iteration and can often even be
95 // hoisted out further by the loop invariant code motion.
96 //
97 // 2. OpenMP needs a loop invarient upper bound to calculate the number
98 // of loop iterations.
99 //
100 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000101 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
102 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000103
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000104 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
105
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000106 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000107 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
108 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000109
110 /// Generate LLVM-IR that computes the values of the original induction
111 /// variables in function of the newly generated loop induction variables.
112 ///
113 /// Example:
114 ///
115 /// // Original
116 /// for i
117 /// for j
118 /// S(i)
119 ///
120 /// Schedule: [i,j] -> [i+j, j]
121 ///
122 /// // New
123 /// for c0
124 /// for c1
125 /// S(c0 - c1, c1)
126 ///
127 /// Assuming the original code consists of two loops which are
128 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
129 /// ast models the original statement as a call expression where each argument
130 /// is an expression that computes the old induction variables from the new
131 /// ones, ordered such that the first argument computes the value of induction
132 /// variable that was outermost in the original code.
133 ///
134 /// @param Expr The call expression that represents the statement.
135 /// @param Stmt The statement that is called.
136 /// @param VMap The value map into which the mapping from the old induction
137 /// variable to the new one is inserted. This mapping is used
138 /// for the classical code generation (not scev-based) and
139 /// gives an explicit mapping from an original, materialized
140 /// induction variable. It consequently can only be expressed
141 /// if there was an explicit induction variable.
142 /// @param LTS The loop to SCEV map in which the mapping from the original
143 /// loop to a SCEV representing the new loop iv is added. This
144 /// mapping does not require an explicit induction variable.
145 /// Instead, we think in terms of an implicit induction variable
146 /// that counts the number of times a loop is executed. For each
147 /// original loop this count, expressed in function of the new
148 /// induction variables, is added to the LTS map.
149 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000150 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000151 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
152 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000153 std::vector<LoopToScevMapT> &VLTS,
154 std::vector<Value *> &IVS,
155 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000156 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000157 void createUserVector(__isl_take isl_ast_node *User,
158 std::vector<Value *> &IVS,
159 __isl_take isl_id *IteratorID,
160 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000161 void createUser(__isl_take isl_ast_node *User);
162 void createBlock(__isl_take isl_ast_node *Block);
163};
164
Tobias Grossere602a072013-05-07 07:30:56 +0000165__isl_give isl_ast_expr *
166IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
167 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000168 isl_id *UBID, *IteratorID;
169 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000170 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000171
172 Cond = isl_ast_node_for_get_cond(For);
173 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000174 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000175
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000176 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
177 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000178
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000179 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000180 case isl_ast_op_le:
181 Predicate = ICmpInst::ICMP_SLE;
182 break;
183 case isl_ast_op_lt:
184 Predicate = ICmpInst::ICMP_SLT;
185 break;
186 default:
187 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000188 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000189
190 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
191
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000192 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
193 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000194
195 UBID = isl_ast_expr_get_id(Arg0);
196
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000197 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
198 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000199
200 IteratorID = isl_ast_expr_get_id(Iterator);
201
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000202 assert(UBID == IteratorID &&
203 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000204
205 UB = isl_ast_expr_get_op_arg(Cond, 1);
206
207 isl_ast_expr_free(Cond);
208 isl_ast_expr_free(Iterator);
209 isl_ast_expr_free(Arg0);
210 isl_id_free(IteratorID);
211 isl_id_free(UBID);
212
213 return UB;
214}
215
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000216unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000217 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000218 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000219 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
220 if (NumberOfIterations == -1)
221 return -1;
222 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000223}
224
Tobias Grossere602a072013-05-07 07:30:56 +0000225void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
226 std::vector<Value *> &IVS,
227 __isl_take isl_id *IteratorID,
228 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000229 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
230 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
231 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
232 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000233 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000234 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000235 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000236
237 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
238 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
239 isl_map *S = isl_map_from_union_map(Schedule);
240
Tobias Grosserce67a042014-07-02 16:26:47 +0000241 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000242 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000243
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000244 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000245 isl_id_free(Id);
246 isl_ast_node_free(User);
247}
248
Tobias Grossere602a072013-05-07 07:30:56 +0000249void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
250 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000251 isl_ast_node *Body = isl_ast_node_for_get_body(For);
252 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
253 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
254 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
255 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000256
257 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000258 Value *ValueInc = ExprBuilder.create(Inc);
259
260 Type *MaxType = ExprBuilder.getType(Iterator);
261 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000262 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
263
264 if (MaxType != ValueLB->getType())
265 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000266 if (MaxType != ValueInc->getType())
267 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
268
Tobias Grosserc14582f2013-02-05 18:01:29 +0000269 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000270 IVS[0] = ValueLB;
271
272 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000273 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000274
Johannes Doerfert94d90822014-07-23 20:26:25 +0000275 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000276 assert(Schedule && "For statement annotation does not contain its schedule");
277
278 IDToValue[IteratorID] = ValueLB;
279
280 switch (isl_ast_node_get_type(Body)) {
281 case isl_ast_node_user:
282 createUserVector(Body, IVS, isl_id_copy(IteratorID),
283 isl_union_map_copy(Schedule));
284 break;
285 case isl_ast_node_block: {
286 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
287
288 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
289 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000290 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000291
292 isl_ast_node_free(Body);
293 isl_ast_node_list_free(List);
294 break;
295 }
296 default:
297 isl_ast_node_dump(Body);
298 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
299 }
300
301 IDToValue.erase(IteratorID);
302 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000303 isl_union_map_free(Schedule);
304
305 isl_ast_node_free(For);
306 isl_ast_expr_free(Iterator);
307}
308
309void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000310 isl_ast_node *Body;
311 isl_ast_expr *Init, *Inc, *Iterator, *UB;
312 isl_id *IteratorID;
313 Value *ValueLB, *ValueUB, *ValueInc;
314 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000315 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000316 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000317 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000318 bool Parallel;
319
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000320 Parallel = IslAstInfo::isInnermostParallel(For) &&
321 !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000322
323 Body = isl_ast_node_for_get_body(For);
324
325 // isl_ast_node_for_is_degenerate(For)
326 //
327 // TODO: For degenerated loops we could generate a plain assignment.
328 // However, for now we just reuse the logic for normal loops, which will
329 // create a loop with a single iteration.
330
331 Init = isl_ast_node_for_get_init(For);
332 Inc = isl_ast_node_for_get_inc(For);
333 Iterator = isl_ast_node_for_get_iterator(For);
334 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000335 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000336
337 ValueLB = ExprBuilder.create(Init);
338 ValueUB = ExprBuilder.create(UB);
339 ValueInc = ExprBuilder.create(Inc);
340
341 MaxType = ExprBuilder.getType(Iterator);
342 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
343 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
344 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
345
346 if (MaxType != ValueLB->getType())
347 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
348 if (MaxType != ValueUB->getType())
349 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
350 if (MaxType != ValueInc->getType())
351 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
352
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000353 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, ExitBlock, Predicate,
354 &Annotator, Parallel);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000355 IDToValue[IteratorID] = IV;
356
357 create(Body);
358
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000359 Annotator.End();
360
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000361 IDToValue.erase(IteratorID);
362
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000363 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000364
365 isl_ast_node_free(For);
366 isl_ast_expr_free(Iterator);
367 isl_id_free(IteratorID);
368}
369
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000370void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
371 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
372
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000373 if (Vector && IslAstInfo::isInnermostParallel(For) &&
374 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000375 int VectorWidth = getNumberOfIterations(For);
376 if (1 < VectorWidth && VectorWidth <= 16) {
377 createForVector(For, VectorWidth);
378 return;
379 }
380 }
381 createForSequential(For);
382}
383
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000384void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
385 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
386
387 Function *F = Builder.GetInsertBlock()->getParent();
388 LLVMContext &Context = F->getContext();
389
Tobias Grosserc14582f2013-02-05 18:01:29 +0000390 BasicBlock *CondBB =
391 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000392 CondBB->setName("polly.cond");
393 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
394 MergeBB->setName("polly.merge");
395 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
396 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
397
Tobias Grosser42aff302014-01-13 22:29:56 +0000398 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000399 DT.addNewBlock(ThenBB, CondBB);
400 DT.addNewBlock(ElseBB, CondBB);
401 DT.changeImmediateDominator(MergeBB, CondBB);
402
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000403 LoopInfo &LI = P->getAnalysis<LoopInfo>();
404 Loop *L = LI.getLoopFor(CondBB);
405 if (L) {
406 L->addBasicBlockToLoop(ThenBB, LI.getBase());
407 L->addBasicBlockToLoop(ElseBB, LI.getBase());
408 }
409
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000410 CondBB->getTerminator()->eraseFromParent();
411
412 Builder.SetInsertPoint(CondBB);
413 Value *Predicate = ExprBuilder.create(Cond);
414 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
415 Builder.SetInsertPoint(ThenBB);
416 Builder.CreateBr(MergeBB);
417 Builder.SetInsertPoint(ElseBB);
418 Builder.CreateBr(MergeBB);
419 Builder.SetInsertPoint(ThenBB->begin());
420
421 create(isl_ast_node_if_get_then(If));
422
423 Builder.SetInsertPoint(ElseBB->begin());
424
425 if (isl_ast_node_if_has_else(If))
426 create(isl_ast_node_if_get_else(If));
427
428 Builder.SetInsertPoint(MergeBB->begin());
429
430 isl_ast_node_free(If);
431}
432
Tobias Grosserce67a042014-07-02 16:26:47 +0000433void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
434 ValueMapT &VMap, LoopToScevMapT &LTS) {
435 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
436 "Expression of type 'op' expected");
437 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
438 "Opertation of type 'call' expected");
439 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
440 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000441 Value *V;
442
Tobias Grosserce67a042014-07-02 16:26:47 +0000443 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
444 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000445 ScalarEvolution *SE = Stmt->getParent()->getSE();
446 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
447
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000448 // CreateIntCast can introduce trunc expressions. This is correct, as the
449 // result will always fit into the type of the original induction variable
450 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000451 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
452 if (OldIV) {
453 V = Builder.CreateIntCast(V, OldIV->getType(), true);
454 VMap[OldIV] = V;
455 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000456 }
457
Tobias Grosserce67a042014-07-02 16:26:47 +0000458 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000459}
460
Tobias Grosserc14582f2013-02-05 18:01:29 +0000461void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000462 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
463 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
464 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000465 int i = 0;
466
467 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000468 for (Value *IV : IVS) {
469 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000470 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000471 i++;
472 }
473
474 IDToValue[IteratorID] = OldValue;
475 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000476 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000477}
478
479void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
480 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000481 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000482 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000483 ScopStmt *Stmt;
484
Tobias Grosserce67a042014-07-02 16:26:47 +0000485 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
486 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
487 Id = isl_ast_expr_get_id(StmtExpr);
488 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000489
Tobias Grosserc14582f2013-02-05 18:01:29 +0000490 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000491
Tobias Grosserce67a042014-07-02 16:26:47 +0000492 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000493 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P,
494 IslAstInfo::getBuild(User), &ExprBuilder);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000495
496 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000497 isl_id_free(Id);
498}
499
500void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
501 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
502
503 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
504 create(isl_ast_node_list_get_ast_node(List, i));
505
506 isl_ast_node_free(Block);
507 isl_ast_node_list_free(List);
508}
509
510void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
511 switch (isl_ast_node_get_type(Node)) {
512 case isl_ast_node_error:
513 llvm_unreachable("code generation error");
514 case isl_ast_node_for:
515 createFor(Node);
516 return;
517 case isl_ast_node_if:
518 createIf(Node);
519 return;
520 case isl_ast_node_user:
521 createUser(Node);
522 return;
523 case isl_ast_node_block:
524 createBlock(Node);
525 return;
526 }
527
528 llvm_unreachable("Unknown isl_ast_node type");
529}
530
531void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
532 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
533
534 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
535 isl_id *Id;
536 const SCEV *Scev;
537 IntegerType *T;
538 Instruction *InsertLocation;
539
540 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000541 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000542 T = dyn_cast<IntegerType>(Scev->getType());
543 InsertLocation = --(Builder.GetInsertBlock()->end());
544 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
545 IDToValue[Id] = V;
546
547 isl_id_free(Id);
548 }
549
550 isl_set_free(Context);
551}
552
Johannes Doerferta63b2572014-08-03 01:51:59 +0000553void IslNodeBuilder::addMemoryAccesses(Scop &S) {
554 for (ScopStmt *Stmt : S)
555 for (MemoryAccess *MA : *Stmt) {
556 isl_id *Id = MA->getArrayId();
557 IDToValue[Id] = MA->getBaseAddr();
558 isl_id_free(Id);
559 }
560}
561
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000562namespace {
563class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000564public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000565 static char ID;
566
567 IslCodeGeneration() : ScopPass(ID) {}
568
569 bool runOnScop(Scop &S) {
570 IslAstInfo &AstInfo = getAnalysis<IslAstInfo>();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000571
Tobias Grossere602a072013-05-07 07:30:56 +0000572 assert(!S.getRegion().isTopLevelRegion() &&
573 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000574
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000575 simplifyRegion(&S, this);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000576
577 BasicBlock *StartBlock = executeScopConditionally(S, this);
578 isl_ast_node *Ast = AstInfo.getAst();
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000579 LoopAnnotator Annotator;
580 PollyIRBuilder Builder(StartBlock->getContext(), llvm::ConstantFolder(),
581 polly::IRInserter(Annotator));
582 Builder.SetInsertPoint(StartBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000583
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000584 IslNodeBuilder NodeBuilder(Builder, Annotator, this);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000585
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000586 Builder.SetInsertPoint(StartBlock->getSinglePredecessor()->begin());
Johannes Doerferta63b2572014-08-03 01:51:59 +0000587 NodeBuilder.addMemoryAccesses(S);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000588 NodeBuilder.addParameters(S.getContext());
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000589 // Build condition that evaluates at run-time if all assumptions taken
590 // for the scop hold. If we detect some assumptions do not hold, the
591 // original code is executed.
592 Value *V = NodeBuilder.getExprBuilder().create(AstInfo.getRunCondition());
593 Value *Zero = ConstantInt::get(V->getType(), 0);
594 V = Builder.CreateICmp(CmpInst::ICMP_NE, Zero, V);
595 BasicBlock *PrevBB = StartBlock->getUniquePredecessor();
596 BranchInst *Branch = dyn_cast<BranchInst>(PrevBB->getTerminator());
597 Branch->setCondition(V);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598 Builder.SetInsertPoint(StartBlock->begin());
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000599
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000600 NodeBuilder.create(Ast);
601 return true;
602 }
603
Tobias Grosserc14582f2013-02-05 18:01:29 +0000604 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000605
606 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000607 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000608 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000609 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000610 AU.addRequired<ScalarEvolution>();
611 AU.addRequired<ScopDetection>();
612 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000613 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000614
615 AU.addPreserved<Dependences>();
616
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000617 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000618 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000619 AU.addPreserved<IslAstInfo>();
620 AU.addPreserved<ScopDetection>();
621 AU.addPreserved<ScalarEvolution>();
622
623 // FIXME: We do not yet add regions for the newly generated code to the
624 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +0000625 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000626 AU.addPreserved<TempScopInfo>();
627 AU.addPreserved<ScopInfo>();
628 AU.addPreservedID(IndependentBlocksID);
629 }
630};
631}
632
633char IslCodeGeneration::ID = 1;
634
Tobias Grosser7242ad92013-02-22 08:07:06 +0000635Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000636
Tobias Grosser7242ad92013-02-22 08:07:06 +0000637INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
638 "Polly - Create LLVM-IR from SCoPs", false, false);
639INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +0000640INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000641INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000642INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000643INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
644INITIALIZE_PASS_DEPENDENCY(ScopDetection);
645INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
646 "Polly - Create LLVM-IR from SCoPs", false, false)