blob: 9cf8bf89faa3694a83ca361a21592d7ee4034494 [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:
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000061 IslNodeBuilder(PollyIRBuilder &Builder, LoopAnnotator &Annotator, Pass *P,
62 LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT)
Tobias Grosser34c87872014-04-22 16:39:41 +000063 : Builder(Builder), Annotator(Annotator), ExprBuilder(Builder, IDToValue),
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000064 P(P), LI(LI), SE(SE), DT(DT) {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000065
Johannes Doerferta63b2572014-08-03 01:51:59 +000066 /// @brief Add the mappings from array id's to array llvm::Value's.
67 void addMemoryAccesses(Scop &S);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000068 void addParameters(__isl_take isl_set *Context);
69 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000070 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000071
72private:
Tobias Grosser5103ba72014-03-04 14:58:49 +000073 PollyIRBuilder &Builder;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +000074 LoopAnnotator &Annotator;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000075 IslExprBuilder ExprBuilder;
76 Pass *P;
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000077 LoopInfo &LI;
78 ScalarEvolution &SE;
79 DominatorTree &DT;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000080
81 // This maps an isl_id* to the Value* it has in the generated program. For now
82 // on, the only isl_ids that are stored here are the newly calculated loop
83 // ivs.
Tobias Grosserc14582f2013-02-05 18:01:29 +000084 std::map<isl_id *, Value *> IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000085
86 // Extract the upper bound of this loop
87 //
88 // The isl code generation can generate arbitrary expressions to check if the
89 // upper bound of a loop is reached, but it provides an option to enforce
90 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
91 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
92 //
93 // This function extracts 'atomic' upper bounds. Polly, in general, requires
94 // atomic upper bounds for the following reasons:
95 //
96 // 1. An atomic upper bound is loop invariant
97 //
98 // It must not be calculated at each loop iteration and can often even be
99 // hoisted out further by the loop invariant code motion.
100 //
101 // 2. OpenMP needs a loop invarient upper bound to calculate the number
102 // of loop iterations.
103 //
104 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000105 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
106 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000107
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000108 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
109
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000110 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000111 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
112 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000113
114 /// Generate LLVM-IR that computes the values of the original induction
115 /// variables in function of the newly generated loop induction variables.
116 ///
117 /// Example:
118 ///
119 /// // Original
120 /// for i
121 /// for j
122 /// S(i)
123 ///
124 /// Schedule: [i,j] -> [i+j, j]
125 ///
126 /// // New
127 /// for c0
128 /// for c1
129 /// S(c0 - c1, c1)
130 ///
131 /// Assuming the original code consists of two loops which are
132 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
133 /// ast models the original statement as a call expression where each argument
134 /// is an expression that computes the old induction variables from the new
135 /// ones, ordered such that the first argument computes the value of induction
136 /// variable that was outermost in the original code.
137 ///
138 /// @param Expr The call expression that represents the statement.
139 /// @param Stmt The statement that is called.
140 /// @param VMap The value map into which the mapping from the old induction
141 /// variable to the new one is inserted. This mapping is used
142 /// for the classical code generation (not scev-based) and
143 /// gives an explicit mapping from an original, materialized
144 /// induction variable. It consequently can only be expressed
145 /// if there was an explicit induction variable.
146 /// @param LTS The loop to SCEV map in which the mapping from the original
147 /// loop to a SCEV representing the new loop iv is added. This
148 /// mapping does not require an explicit induction variable.
149 /// Instead, we think in terms of an implicit induction variable
150 /// that counts the number of times a loop is executed. For each
151 /// original loop this count, expressed in function of the new
152 /// induction variables, is added to the LTS map.
153 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000154 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000155 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
156 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000157 std::vector<LoopToScevMapT> &VLTS,
158 std::vector<Value *> &IVS,
159 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000160 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000161 void createUserVector(__isl_take isl_ast_node *User,
162 std::vector<Value *> &IVS,
163 __isl_take isl_id *IteratorID,
164 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000165 void createUser(__isl_take isl_ast_node *User);
166 void createBlock(__isl_take isl_ast_node *Block);
167};
168
Tobias Grossere602a072013-05-07 07:30:56 +0000169__isl_give isl_ast_expr *
170IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
171 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000172 isl_id *UBID, *IteratorID;
173 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000174 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000175
176 Cond = isl_ast_node_for_get_cond(For);
177 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000178 Type = isl_ast_expr_get_op_type(Cond);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000179
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000180 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
181 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000182
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000183 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000184 case isl_ast_op_le:
185 Predicate = ICmpInst::ICMP_SLE;
186 break;
187 case isl_ast_op_lt:
188 Predicate = ICmpInst::ICMP_SLT;
189 break;
190 default:
191 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000192 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000193
194 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
195
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000196 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
197 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000198
199 UBID = isl_ast_expr_get_id(Arg0);
200
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000201 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
202 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000203
204 IteratorID = isl_ast_expr_get_id(Iterator);
205
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000206 assert(UBID == IteratorID &&
207 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000208
209 UB = isl_ast_expr_get_op_arg(Cond, 1);
210
211 isl_ast_expr_free(Cond);
212 isl_ast_expr_free(Iterator);
213 isl_ast_expr_free(Arg0);
214 isl_id_free(IteratorID);
215 isl_id_free(UBID);
216
217 return UB;
218}
219
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000220unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000221 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000222 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000223 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
224 if (NumberOfIterations == -1)
225 return -1;
226 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000227}
228
Tobias Grossere602a072013-05-07 07:30:56 +0000229void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
230 std::vector<Value *> &IVS,
231 __isl_take isl_id *IteratorID,
232 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000233 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
234 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
235 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
236 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000237 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000238 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000239 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000240
241 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
242 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
243 isl_map *S = isl_map_from_union_map(Schedule);
244
Tobias Grosserce67a042014-07-02 16:26:47 +0000245 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000246 VectorBlockGenerator::generate(Builder, *Stmt, VectorMap, VLTS, S, P, LI, SE);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000247
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000248 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000249 isl_id_free(Id);
250 isl_ast_node_free(User);
251}
252
Tobias Grossere602a072013-05-07 07:30:56 +0000253void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
254 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000255 isl_ast_node *Body = isl_ast_node_for_get_body(For);
256 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
257 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
258 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
259 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000260
261 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000262 Value *ValueInc = ExprBuilder.create(Inc);
263
264 Type *MaxType = ExprBuilder.getType(Iterator);
265 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000266 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
267
268 if (MaxType != ValueLB->getType())
269 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000270 if (MaxType != ValueInc->getType())
271 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
272
Tobias Grosserc14582f2013-02-05 18:01:29 +0000273 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000274 IVS[0] = ValueLB;
275
276 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000277 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000278
Johannes Doerfert94d90822014-07-23 20:26:25 +0000279 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000280 assert(Schedule && "For statement annotation does not contain its schedule");
281
282 IDToValue[IteratorID] = ValueLB;
283
284 switch (isl_ast_node_get_type(Body)) {
285 case isl_ast_node_user:
286 createUserVector(Body, IVS, isl_id_copy(IteratorID),
287 isl_union_map_copy(Schedule));
288 break;
289 case isl_ast_node_block: {
290 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
291
292 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
293 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000294 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000295
296 isl_ast_node_free(Body);
297 isl_ast_node_list_free(List);
298 break;
299 }
300 default:
301 isl_ast_node_dump(Body);
302 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
303 }
304
305 IDToValue.erase(IteratorID);
306 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000307 isl_union_map_free(Schedule);
308
309 isl_ast_node_free(For);
310 isl_ast_expr_free(Iterator);
311}
312
313void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000314 isl_ast_node *Body;
315 isl_ast_expr *Init, *Inc, *Iterator, *UB;
316 isl_id *IteratorID;
317 Value *ValueLB, *ValueUB, *ValueInc;
318 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000319 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000320 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000321 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000322 bool Parallel;
323
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000324 Parallel = IslAstInfo::isInnermostParallel(For) &&
325 !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000326
327 Body = isl_ast_node_for_get_body(For);
328
329 // isl_ast_node_for_is_degenerate(For)
330 //
331 // TODO: For degenerated loops we could generate a plain assignment.
332 // However, for now we just reuse the logic for normal loops, which will
333 // create a loop with a single iteration.
334
335 Init = isl_ast_node_for_get_init(For);
336 Inc = isl_ast_node_for_get_inc(For);
337 Iterator = isl_ast_node_for_get_iterator(For);
338 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000339 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000340
341 ValueLB = ExprBuilder.create(Init);
342 ValueUB = ExprBuilder.create(UB);
343 ValueInc = ExprBuilder.create(Inc);
344
345 MaxType = ExprBuilder.getType(Iterator);
346 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
347 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
348 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
349
350 if (MaxType != ValueLB->getType())
351 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
352 if (MaxType != ValueUB->getType())
353 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
354 if (MaxType != ValueInc->getType())
355 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
356
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000357 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
358 Predicate, &Annotator, Parallel);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000359 IDToValue[IteratorID] = IV;
360
361 create(Body);
362
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000363 Annotator.End();
364
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000365 IDToValue.erase(IteratorID);
366
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000367 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000368
369 isl_ast_node_free(For);
370 isl_ast_expr_free(Iterator);
371 isl_id_free(IteratorID);
372}
373
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000374void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
375 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
376
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000377 if (Vector && IslAstInfo::isInnermostParallel(For) &&
378 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000379 int VectorWidth = getNumberOfIterations(For);
380 if (1 < VectorWidth && VectorWidth <= 16) {
381 createForVector(For, VectorWidth);
382 return;
383 }
384 }
385 createForSequential(For);
386}
387
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000388void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
389 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
390
391 Function *F = Builder.GetInsertBlock()->getParent();
392 LLVMContext &Context = F->getContext();
393
Tobias Grosserc14582f2013-02-05 18:01:29 +0000394 BasicBlock *CondBB =
395 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000396 CondBB->setName("polly.cond");
397 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
398 MergeBB->setName("polly.merge");
399 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
400 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
401
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000402 DT.addNewBlock(ThenBB, CondBB);
403 DT.addNewBlock(ElseBB, CondBB);
404 DT.changeImmediateDominator(MergeBB, CondBB);
405
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000406 Loop *L = LI.getLoopFor(CondBB);
407 if (L) {
408 L->addBasicBlockToLoop(ThenBB, LI.getBase());
409 L->addBasicBlockToLoop(ElseBB, LI.getBase());
410 }
411
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000412 CondBB->getTerminator()->eraseFromParent();
413
414 Builder.SetInsertPoint(CondBB);
415 Value *Predicate = ExprBuilder.create(Cond);
416 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
417 Builder.SetInsertPoint(ThenBB);
418 Builder.CreateBr(MergeBB);
419 Builder.SetInsertPoint(ElseBB);
420 Builder.CreateBr(MergeBB);
421 Builder.SetInsertPoint(ThenBB->begin());
422
423 create(isl_ast_node_if_get_then(If));
424
425 Builder.SetInsertPoint(ElseBB->begin());
426
427 if (isl_ast_node_if_has_else(If))
428 create(isl_ast_node_if_get_else(If));
429
430 Builder.SetInsertPoint(MergeBB->begin());
431
432 isl_ast_node_free(If);
433}
434
Tobias Grosserce67a042014-07-02 16:26:47 +0000435void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
436 ValueMapT &VMap, LoopToScevMapT &LTS) {
437 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
438 "Expression of type 'op' expected");
439 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
440 "Opertation of type 'call' expected");
441 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
442 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000443 Value *V;
444
Tobias Grosserce67a042014-07-02 16:26:47 +0000445 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
446 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000447 ScalarEvolution *SE = Stmt->getParent()->getSE();
448 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
449
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000450 // CreateIntCast can introduce trunc expressions. This is correct, as the
451 // result will always fit into the type of the original induction variable
452 // (because we calculate a value of the original induction variable).
Sebastian Pope039bb12013-03-18 19:09:49 +0000453 const Value *OldIV = Stmt->getInductionVariableForDimension(i);
454 if (OldIV) {
455 V = Builder.CreateIntCast(V, OldIV->getType(), true);
456 VMap[OldIV] = V;
457 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000458 }
459
Tobias Grosserce67a042014-07-02 16:26:47 +0000460 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000461}
462
Tobias Grosserc14582f2013-02-05 18:01:29 +0000463void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000464 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
465 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
466 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000467 int i = 0;
468
469 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000470 for (Value *IV : IVS) {
471 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000472 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000473 i++;
474 }
475
476 IDToValue[IteratorID] = OldValue;
477 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000478 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000479}
480
481void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
482 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000483 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000484 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000485 ScopStmt *Stmt;
486
Tobias Grosserce67a042014-07-02 16:26:47 +0000487 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
488 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
489 Id = isl_ast_expr_get_id(StmtExpr);
490 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000491
Tobias Grosserc14582f2013-02-05 18:01:29 +0000492 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000493
Tobias Grosserce67a042014-07-02 16:26:47 +0000494 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000495 BlockGenerator::generate(Builder, *Stmt, VMap, LTS, P, LI, SE,
Johannes Doerferta63b2572014-08-03 01:51:59 +0000496 IslAstInfo::getBuild(User), &ExprBuilder);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000497
498 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000499 isl_id_free(Id);
500}
501
502void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
503 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
504
505 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
506 create(isl_ast_node_list_get_ast_node(List, i));
507
508 isl_ast_node_free(Block);
509 isl_ast_node_list_free(List);
510}
511
512void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
513 switch (isl_ast_node_get_type(Node)) {
514 case isl_ast_node_error:
515 llvm_unreachable("code generation error");
516 case isl_ast_node_for:
517 createFor(Node);
518 return;
519 case isl_ast_node_if:
520 createIf(Node);
521 return;
522 case isl_ast_node_user:
523 createUser(Node);
524 return;
525 case isl_ast_node_block:
526 createBlock(Node);
527 return;
528 }
529
530 llvm_unreachable("Unknown isl_ast_node type");
531}
532
533void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000534 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000535
536 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
537 isl_id *Id;
538 const SCEV *Scev;
539 IntegerType *T;
540 Instruction *InsertLocation;
541
542 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000543 Scev = (const SCEV *)isl_id_get_user(Id);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000544 T = dyn_cast<IntegerType>(Scev->getType());
545 InsertLocation = --(Builder.GetInsertBlock()->end());
546 Value *V = Rewriter.expandCodeFor(Scev, T, InsertLocation);
547 IDToValue[Id] = V;
548
549 isl_id_free(Id);
550 }
551
552 isl_set_free(Context);
553}
554
Johannes Doerferta63b2572014-08-03 01:51:59 +0000555void IslNodeBuilder::addMemoryAccesses(Scop &S) {
556 for (ScopStmt *Stmt : S)
557 for (MemoryAccess *MA : *Stmt) {
558 isl_id *Id = MA->getArrayId();
559 IDToValue[Id] = MA->getBaseAddr();
560 isl_id_free(Id);
561 }
562}
563
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000564namespace {
565class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000566public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000567 static char ID;
568
569 IslCodeGeneration() : ScopPass(ID) {}
570
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000571 /// @name The analysis passes we need to generate code.
572 ///
573 ///{
574 LoopInfo *LI;
575 IslAstInfo *AI;
576 DominatorTree *DT;
577 ScalarEvolution *SE;
578 ///}
579
580 /// @brief The loop anotator to generate llvm.loop metadata.
581 LoopAnnotator Annotator;
582
583 /// @brief Build the delinearization runtime condition.
584 ///
585 /// Build the condition that evaluates at run-time to true iff all
586 /// delinearization assumptions taken for the SCoP hold, and to zero
587 /// otherwise.
588 ///
589 /// @return A value evaluating to true/false if delinarization is save/unsave.
590 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
591 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
592 Value *RTC = ExprBuilder.create(AI->getRunCondition());
593 return Builder.CreateIsNotNull(RTC);
594 }
595
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000596 bool runOnScop(Scop &S) {
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000597 LI = &getAnalysis<LoopInfo>();
598 AI = &getAnalysis<IslAstInfo>();
599 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
600 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000601
Tobias Grossere602a072013-05-07 07:30:56 +0000602 assert(!S.getRegion().isTopLevelRegion() &&
603 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000604
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000605 PollyIRBuilder Builder =
606 createPollyIRBuilder(S.getRegionEntry(), Annotator);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000607
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000608 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *LI, *SE, *DT);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000609 NodeBuilder.addMemoryAccesses(S);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000610 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000611
612 simplifyRegion(&S, this);
613 Builder.SetInsertPoint(
614 S.getRegion().getEnteringBlock()->getFirstInsertionPt());
615
616 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
617 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000618 Builder.SetInsertPoint(StartBlock->begin());
Tobias Grosser54ee0ba2013-11-17 03:18:25 +0000619
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000620 NodeBuilder.create(AI->getAst());
621
622 DEBUG(StartBlock->getParent()->dump());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000623 return true;
624 }
625
Tobias Grosserc14582f2013-02-05 18:01:29 +0000626 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000627
628 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000629 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000630 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000631 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000632 AU.addRequired<ScalarEvolution>();
633 AU.addRequired<ScopDetection>();
634 AU.addRequired<ScopInfo>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000635 AU.addRequired<LoopInfo>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000636
637 AU.addPreserved<Dependences>();
638
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000639 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000640 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000641 AU.addPreserved<IslAstInfo>();
642 AU.addPreserved<ScopDetection>();
643 AU.addPreserved<ScalarEvolution>();
644
645 // FIXME: We do not yet add regions for the newly generated code to the
646 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +0000647 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000648 AU.addPreserved<TempScopInfo>();
649 AU.addPreserved<ScopInfo>();
650 AU.addPreservedID(IndependentBlocksID);
651 }
652};
653}
654
655char IslCodeGeneration::ID = 1;
656
Tobias Grosser7242ad92013-02-22 08:07:06 +0000657Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000658
Tobias Grosser7242ad92013-02-22 08:07:06 +0000659INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
660 "Polly - Create LLVM-IR from SCoPs", false, false);
661INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +0000662INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000663INITIALIZE_PASS_DEPENDENCY(LoopInfo);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000664INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000665INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
666INITIALIZE_PASS_DEPENDENCY(ScopDetection);
667INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
668 "Polly - Create LLVM-IR from SCoPs", false, false)