blob: a3876f195098037401ee82c2b8f335a8689bf370 [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"
26#include "polly/CodeGen/LoopGenerators.h"
27#include "polly/CodeGen/Utils.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000028#include "polly/Dependences.h"
29#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"
Chandler Carruth535d52c2013-01-02 11:47:44 +000044#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46
47#include "isl/union_map.h"
48#include "isl/list.h"
49#include "isl/ast.h"
50#include "isl/ast_build.h"
51#include "isl/set.h"
52#include "isl/map.h"
53#include "isl/aff.h"
54
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000055using namespace polly;
56using namespace llvm;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-codegen-isl"
59
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000060class IslNodeBuilder {
61public:
Johannes Doerfert51d1c742014-10-02 15:32:17 +000062 IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
Tobias Grossere3c05582014-11-15 21:32:53 +000063 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
64 DominatorTree &DT, Scop &S)
65 : S(S), Builder(Builder), Annotator(Annotator),
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000066 Rewriter(new SCEVExpander(SE, "polly")),
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000067 ExprBuilder(Builder, IDToValue, *Rewriter),
Johannes Doerfert275a1752015-02-24 16:16:32 +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
71 ~IslNodeBuilder() { delete Rewriter; }
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.
83 SCEVExpander *Rewriter;
84
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
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000091 Pass *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));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000300 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
301 if (NumberOfIterations == -1)
302 return -1;
303 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000304}
305
Tobias Grossere3c05582014-11-15 21:32:53 +0000306struct FindValuesUser {
307 LoopInfo &LI;
308 ScalarEvolution &SE;
309 Region &R;
310 SetVector<Value *> &Values;
311 SetVector<const SCEV *> &SCEVs;
312};
313
314/// Extract the values and SCEVs needed to generate code for a ScopStmt.
315///
316/// This function extracts a ScopStmt from a given isl_set and computes the
317/// Values this statement depends on as well as a set of SCEV expressions that
318/// need to be synthesized when generating code for this statment.
319static int findValuesInStmt(isl_set *Set, void *UserPtr) {
320 isl_id *Id = isl_set_get_tuple_id(Set);
321 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr);
322 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
323 const BasicBlock *BB = Stmt->getBasicBlock();
324
325 // Check all the operands of instructions in the basic block.
326 for (const Instruction &Inst : *BB) {
327 for (Value *SrcVal : Inst.operands()) {
328 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
329 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) {
330 User.SCEVs.insert(
331 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB)));
332 continue;
333 }
334 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
335 if (Stmt->getParent()->getRegion().contains(OpInst))
336 continue;
337
338 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
339 User.Values.insert(SrcVal);
340 }
341 }
342 isl_id_free(Id);
343 isl_set_free(Set);
344 return 0;
345}
346
347void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
348 SetVector<Value *> &Values,
349 SetVector<const Loop *> &Loops) {
350
351 SetVector<const SCEV *> SCEVs;
352 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs};
353
354 for (const auto &I : IDToValue)
355 Values.insert(I.second);
356
357 for (const auto &I : OutsideLoopIterations)
358 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
359
360 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For));
361
362 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues);
363 isl_union_set_free(Schedule);
364
365 for (const SCEV *Expr : SCEVs) {
366 findValues(Expr, Values);
367 findLoops(Expr, Loops);
368 }
369
370 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
371
372 /// Remove loops that contain the scop or that are part of the scop, as they
373 /// are considered local. This leaves only loops that are before the scop, but
374 /// do not contain the scop itself.
375 Loops.remove_if([this](const Loop *L) {
376 return this->S.getRegion().contains(L) ||
377 L->contains(S.getRegion().getEntry());
378 });
379}
380
381void IslNodeBuilder::updateValues(
382 ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
383 SmallPtrSet<Value *, 5> Inserted;
384
385 for (const auto &I : IDToValue) {
386 IDToValue[I.first] = NewValues[I.second];
387 Inserted.insert(I.second);
388 }
389
390 for (const auto &I : NewValues) {
391 if (Inserted.count(I.first))
392 continue;
393
394 ValueMap[I.first] = I.second;
395 }
396}
397
Tobias Grossere602a072013-05-07 07:30:56 +0000398void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
399 std::vector<Value *> &IVS,
400 __isl_take isl_id *IteratorID,
401 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000402 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
403 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
404 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
405 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000406 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000407 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000408 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000409 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000410
411 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
412 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
413 isl_map *S = isl_map_from_union_map(Schedule);
414
Tobias Grosserce67a042014-07-02 16:26:47 +0000415 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000416 VectorBlockGenerator::generate(BlockGen, *Stmt, VectorMap, VLTS, S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000417
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000418 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000419 isl_id_free(Id);
420 isl_ast_node_free(User);
421}
422
Tobias Grossere602a072013-05-07 07:30:56 +0000423void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
424 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000425 isl_ast_node *Body = isl_ast_node_for_get_body(For);
426 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
427 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
428 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
429 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000430
431 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000432 Value *ValueInc = ExprBuilder.create(Inc);
433
434 Type *MaxType = ExprBuilder.getType(Iterator);
435 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000436 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
437
438 if (MaxType != ValueLB->getType())
439 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000440 if (MaxType != ValueInc->getType())
441 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
442
Tobias Grosserc14582f2013-02-05 18:01:29 +0000443 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000444 IVS[0] = ValueLB;
445
446 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000447 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000448
Johannes Doerfert94d90822014-07-23 20:26:25 +0000449 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000450 assert(Schedule && "For statement annotation does not contain its schedule");
451
452 IDToValue[IteratorID] = ValueLB;
453
454 switch (isl_ast_node_get_type(Body)) {
455 case isl_ast_node_user:
456 createUserVector(Body, IVS, isl_id_copy(IteratorID),
457 isl_union_map_copy(Schedule));
458 break;
459 case isl_ast_node_block: {
460 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
461
462 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
463 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000464 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000465
466 isl_ast_node_free(Body);
467 isl_ast_node_list_free(List);
468 break;
469 }
470 default:
471 isl_ast_node_dump(Body);
472 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
473 }
474
Tobias Grossere3c05582014-11-15 21:32:53 +0000475 IDToValue.erase(IDToValue.find(IteratorID));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000476 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000477 isl_union_map_free(Schedule);
478
479 isl_ast_node_free(For);
480 isl_ast_expr_free(Iterator);
481}
482
483void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000484 isl_ast_node *Body;
485 isl_ast_expr *Init, *Inc, *Iterator, *UB;
486 isl_id *IteratorID;
487 Value *ValueLB, *ValueUB, *ValueInc;
488 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000489 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000490 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000491 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000492 bool Parallel;
493
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000494 Parallel =
495 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000496
497 Body = isl_ast_node_for_get_body(For);
498
499 // isl_ast_node_for_is_degenerate(For)
500 //
501 // TODO: For degenerated loops we could generate a plain assignment.
502 // However, for now we just reuse the logic for normal loops, which will
503 // create a loop with a single iteration.
504
505 Init = isl_ast_node_for_get_init(For);
506 Inc = isl_ast_node_for_get_inc(For);
507 Iterator = isl_ast_node_for_get_iterator(For);
508 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000509 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000510
511 ValueLB = ExprBuilder.create(Init);
512 ValueUB = ExprBuilder.create(UB);
513 ValueInc = ExprBuilder.create(Inc);
514
515 MaxType = ExprBuilder.getType(Iterator);
516 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
517 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
518 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
519
520 if (MaxType != ValueLB->getType())
521 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
522 if (MaxType != ValueUB->getType())
523 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
524 if (MaxType != ValueInc->getType())
525 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
526
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000527 // If we can show that LB <Predicate> UB holds at least once, we can
528 // omit the GuardBB in front of the loop.
529 bool UseGuardBB =
530 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000531 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000532 Predicate, &Annotator, Parallel, UseGuardBB);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000533 IDToValue[IteratorID] = IV;
534
535 create(Body);
536
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000537 Annotator.popLoop(Parallel);
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000538
Tobias Grossere3c05582014-11-15 21:32:53 +0000539 IDToValue.erase(IDToValue.find(IteratorID));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000540
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000541 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000542
543 isl_ast_node_free(For);
544 isl_ast_expr_free(Iterator);
545 isl_id_free(IteratorID);
546}
547
Tobias Grossere3c05582014-11-15 21:32:53 +0000548/// @brief Remove the BBs contained in a (sub)function from the dominator tree.
549///
550/// This function removes the basic blocks that are part of a subfunction from
551/// the dominator tree. Specifically, when generating code it may happen that at
552/// some point the code generation continues in a new sub-function (e.g., when
553/// generating OpenMP code). The basic blocks that are created in this
554/// sub-function are then still part of the dominator tree of the original
555/// function, such that the dominator tree reaches over function boundaries.
556/// This is not only incorrect, but also causes crashes. This function now
557/// removes from the dominator tree all basic blocks that are dominated (and
558/// consequently reachable) from the entry block of this (sub)function.
559///
560/// FIXME: A LLVM (function or region) pass should not touch anything outside of
561/// the function/region it runs on. Hence, the pure need for this function shows
562/// that we do not comply to this rule. At the moment, this does not cause any
563/// issues, but we should be aware that such issues may appear. Unfortunately
564/// the current LLVM pass infrastructure does not allow to make Polly a module
565/// or call-graph pass to solve this issue, as such a pass would not have access
566/// to the per-function analyses passes needed by Polly. A future pass manager
567/// infrastructure is supposed to enable such kind of access possibly allowing
568/// us to create a cleaner solution here.
569///
570/// FIXME: Instead of adding the dominance information and then dropping it
571/// later on, we should try to just not add it in the first place. This requires
572/// some careful testing to make sure this does not break in interaction with
573/// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
574/// which may try to update it.
575///
576/// @param F The function which contains the BBs to removed.
577/// @param DT The dominator tree from which to remove the BBs.
578static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
579 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
580 std::vector<BasicBlock *> Nodes;
581
582 // We can only remove an element from the dominator tree, if all its children
583 // have been removed. To ensure this we obtain the list of nodes to remove
584 // using a post-order tree traversal.
585 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
586 Nodes.push_back(I->getBlock());
587
588 for (BasicBlock *BB : Nodes)
589 DT.eraseNode(BB);
590}
591
592void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
593 isl_ast_node *Body;
594 isl_ast_expr *Init, *Inc, *Iterator, *UB;
595 isl_id *IteratorID;
596 Value *ValueLB, *ValueUB, *ValueInc;
597 Type *MaxType;
598 Value *IV;
599 CmpInst::Predicate Predicate;
600
601 Body = isl_ast_node_for_get_body(For);
602 Init = isl_ast_node_for_get_init(For);
603 Inc = isl_ast_node_for_get_inc(For);
604 Iterator = isl_ast_node_for_get_iterator(For);
605 IteratorID = isl_ast_expr_get_id(Iterator);
606 UB = getUpperBound(For, Predicate);
607
608 ValueLB = ExprBuilder.create(Init);
609 ValueUB = ExprBuilder.create(UB);
610 ValueInc = ExprBuilder.create(Inc);
611
612 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
613 // expression, we need to adjust the loop blound by one.
614 if (Predicate == CmpInst::ICMP_SLT)
615 ValueUB = Builder.CreateAdd(
616 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
617
618 MaxType = ExprBuilder.getType(Iterator);
619 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
620 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
621 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
622
623 if (MaxType != ValueLB->getType())
624 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
625 if (MaxType != ValueUB->getType())
626 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
627 if (MaxType != ValueInc->getType())
628 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
629
630 BasicBlock::iterator LoopBody;
631
632 SetVector<Value *> SubtreeValues;
633 SetVector<const Loop *> Loops;
634
635 getReferencesInSubtree(For, SubtreeValues, Loops);
636
637 // Create for all loops we depend on values that contain the current loop
638 // iteration. These values are necessary to generate code for SCEVs that
639 // depend on such loops. As a result we need to pass them to the subfunction.
640 for (const Loop *L : Loops) {
641 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
642 SE.getUnknown(Builder.getInt64(1)),
643 L, SCEV::FlagAnyWrap);
644 Value *V = generateSCEV(OuterLIV);
645 OutsideLoopIterations[L] = SE.getUnknown(V);
646 SubtreeValues.insert(V);
647 }
648
649 ParallelLoopGenerator::ValueToValueMapTy NewValues;
650 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
651
652 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
653 SubtreeValues, NewValues, &LoopBody);
654 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
655 Builder.SetInsertPoint(LoopBody);
656
657 // Save the current values.
658 ValueMapT ValueMapCopy = ValueMap;
659 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
660
661 updateValues(NewValues);
662 IDToValue[IteratorID] = IV;
663
664 create(Body);
665
666 // Restore the original values.
667 ValueMap = ValueMapCopy;
668 IDToValue = IDToValueCopy;
669
670 Builder.SetInsertPoint(AfterLoop);
671 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
672
673 for (const Loop *L : Loops)
674 OutsideLoopIterations.erase(L);
675
676 isl_ast_node_free(For);
677 isl_ast_expr_free(Iterator);
678 isl_id_free(IteratorID);
679}
680
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000681void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
682 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
683
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000684 if (Vector && IslAstInfo::isInnermostParallel(For) &&
685 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000686 int VectorWidth = getNumberOfIterations(For);
687 if (1 < VectorWidth && VectorWidth <= 16) {
688 createForVector(For, VectorWidth);
689 return;
690 }
691 }
Tobias Grossere3c05582014-11-15 21:32:53 +0000692
693 if (IslAstInfo::isExecutedInParallel(For)) {
694 createForParallel(For);
695 return;
696 }
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000697 createForSequential(For);
698}
699
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000700void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
701 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
702
703 Function *F = Builder.GetInsertBlock()->getParent();
704 LLVMContext &Context = F->getContext();
705
Tobias Grosserc14582f2013-02-05 18:01:29 +0000706 BasicBlock *CondBB =
Chandler Carruth5ec33332015-01-18 10:52:23 +0000707 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000708 CondBB->setName("polly.cond");
Chandler Carruth5ec33332015-01-18 10:52:23 +0000709 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000710 MergeBB->setName("polly.merge");
711 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
712 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
713
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000714 DT.addNewBlock(ThenBB, CondBB);
715 DT.addNewBlock(ElseBB, CondBB);
716 DT.changeImmediateDominator(MergeBB, CondBB);
717
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000718 Loop *L = LI.getLoopFor(CondBB);
719 if (L) {
Chandler Carruth6adcf562015-01-18 01:47:30 +0000720 L->addBasicBlockToLoop(ThenBB, LI);
721 L->addBasicBlockToLoop(ElseBB, LI);
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000722 }
723
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000724 CondBB->getTerminator()->eraseFromParent();
725
726 Builder.SetInsertPoint(CondBB);
727 Value *Predicate = ExprBuilder.create(Cond);
728 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
729 Builder.SetInsertPoint(ThenBB);
730 Builder.CreateBr(MergeBB);
731 Builder.SetInsertPoint(ElseBB);
732 Builder.CreateBr(MergeBB);
733 Builder.SetInsertPoint(ThenBB->begin());
734
735 create(isl_ast_node_if_get_then(If));
736
737 Builder.SetInsertPoint(ElseBB->begin());
738
739 if (isl_ast_node_if_has_else(If))
740 create(isl_ast_node_if_get_else(If));
741
742 Builder.SetInsertPoint(MergeBB->begin());
743
744 isl_ast_node_free(If);
745}
746
Tobias Grosserce67a042014-07-02 16:26:47 +0000747void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
748 ValueMapT &VMap, LoopToScevMapT &LTS) {
749 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
750 "Expression of type 'op' expected");
751 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
752 "Opertation of type 'call' expected");
753 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
754 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000755 Value *V;
756
Tobias Grosserce67a042014-07-02 16:26:47 +0000757 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
758 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000759 ScalarEvolution *SE = Stmt->getParent()->getSE();
760 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000761 }
762
Tobias Grossere3c05582014-11-15 21:32:53 +0000763 // Add the current ValueMap to our per-statement value map.
764 //
765 // This is needed e.g. to rewrite array base addresses when moving code
766 // into a parallely executed subfunction.
767 VMap.insert(ValueMap.begin(), ValueMap.end());
768
Tobias Grosserce67a042014-07-02 16:26:47 +0000769 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000770}
771
Tobias Grosserc14582f2013-02-05 18:01:29 +0000772void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000773 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
774 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
775 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000776 int i = 0;
777
778 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000779 for (Value *IV : IVS) {
780 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000781 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000782 i++;
783 }
784
785 IDToValue[IteratorID] = OldValue;
786 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000787 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000788}
789
790void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
791 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000792 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000793 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000794 ScopStmt *Stmt;
795
Tobias Grosserce67a042014-07-02 16:26:47 +0000796 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
797 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
798 Id = isl_ast_expr_get_id(StmtExpr);
799 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000800
Tobias Grossere3c05582014-11-15 21:32:53 +0000801 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
802
Tobias Grosserc14582f2013-02-05 18:01:29 +0000803 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000804 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Johannes Doerferta63b2572014-08-03 01:51:59 +0000805
Tobias Grosserce67a042014-07-02 16:26:47 +0000806 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000807 if (Stmt->isBlockStmt())
808 BlockGen.copyStmt(*Stmt, VMap, LTS);
809 else
810 RegionGen.copyStmt(*Stmt, VMap, LTS);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000811
812 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000813 isl_id_free(Id);
814}
815
816void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
817 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
818
819 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
820 create(isl_ast_node_list_get_ast_node(List, i));
821
822 isl_ast_node_free(Block);
823 isl_ast_node_list_free(List);
824}
825
826void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
827 switch (isl_ast_node_get_type(Node)) {
828 case isl_ast_node_error:
829 llvm_unreachable("code generation error");
830 case isl_ast_node_for:
831 createFor(Node);
832 return;
833 case isl_ast_node_if:
834 createIf(Node);
835 return;
836 case isl_ast_node_user:
837 createUser(Node);
838 return;
839 case isl_ast_node_block:
840 createBlock(Node);
841 return;
842 }
843
844 llvm_unreachable("Unknown isl_ast_node type");
845}
846
847void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000848
849 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
850 isl_id *Id;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000851
852 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000853 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000854
855 isl_id_free(Id);
856 }
857
Tobias Grossere3c05582014-11-15 21:32:53 +0000858 // Generate values for the current loop iteration for all surrounding loops.
859 //
860 // We may also reference loops outside of the scop which do not contain the
861 // scop itself, but as the number of such scops may be arbitrarily large we do
862 // not generate code for them here, but only at the point of code generation
863 // where these values are needed.
864 Region &R = S.getRegion();
865 Loop *L = LI.getLoopFor(R.getEntry());
866
867 while (L != nullptr && R.contains(L))
868 L = L->getParentLoop();
869
870 while (L != nullptr) {
871 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
872 SE.getUnknown(Builder.getInt64(1)),
873 L, SCEV::FlagAnyWrap);
874 Value *V = generateSCEV(OuterLIV);
875 OutsideLoopIterations[L] = SE.getUnknown(V);
876 L = L->getParentLoop();
877 }
878
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000879 isl_set_free(Context);
880}
881
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000882Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
883 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
Tobias Grosser55bc4c02015-01-08 19:26:53 +0000884 return Rewriter->expandCodeFor(Expr, Expr->getType(), InsertLocation);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000885}
886
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000887namespace {
888class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000889public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000890 static char ID;
891
892 IslCodeGeneration() : ScopPass(ID) {}
893
Tobias Grossere3c05582014-11-15 21:32:53 +0000894 /// @brief The datalayout used
895 const DataLayout *DL;
896
Johannes Doerfert38262242014-09-10 14:50:23 +0000897 /// @name The analysis passes we need to generate code.
898 ///
899 ///{
900 LoopInfo *LI;
901 IslAstInfo *AI;
902 DominatorTree *DT;
903 ScalarEvolution *SE;
904 ///}
905
906 /// @brief The loop annotator to generate llvm.loop metadata.
Johannes Doerfert51d1c742014-10-02 15:32:17 +0000907 ScopAnnotator Annotator;
Johannes Doerfert38262242014-09-10 14:50:23 +0000908
909 /// @brief Build the runtime condition.
910 ///
911 /// Build the condition that evaluates at run-time to true iff all
912 /// assumptions taken for the SCoP hold, and to false otherwise.
913 ///
914 /// @return A value evaluating to true/false if execution is save/unsafe.
915 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
916 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
917 Value *RTC = ExprBuilder.create(AI->getRunCondition());
Johannes Doerfertb164c792014-09-18 11:17:17 +0000918 if (!RTC->getType()->isIntegerTy(1))
919 RTC = Builder.CreateIsNotNull(RTC);
920 return RTC;
Johannes Doerfert38262242014-09-10 14:50:23 +0000921 }
922
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000923 bool runOnScop(Scop &S) {
Johannes Doerfert38262242014-09-10 14:50:23 +0000924 AI = &getAnalysis<IslAstInfo>();
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000925
926 // Check if we created an isl_ast root node, otherwise exit.
927 isl_ast_node *AstRoot = AI->getAst();
928 if (!AstRoot)
929 return false;
930
931 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +0000932 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
933 SE = &getAnalysis<ScalarEvolution>();
Tobias Grossere3c05582014-11-15 21:32:53 +0000934 DL = &getAnalysis<DataLayoutPass>().getDataLayout();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000935
Tobias Grossere602a072013-05-07 07:30:56 +0000936 assert(!S.getRegion().isTopLevelRegion() &&
937 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000938
Johannes Doerfertecdf2632014-10-02 15:31:24 +0000939 // Build the alias scopes for annotations first.
940 if (PollyAnnotateAliasScopes)
941 Annotator.buildAliasScopes(S);
942
Johannes Doerfert38262242014-09-10 14:50:23 +0000943 BasicBlock *EnteringBB = simplifyRegion(&S, this);
944 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000945
Tobias Grossere3c05582014-11-15 21:32:53 +0000946 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
Tobias Grosser28735942014-08-16 09:09:15 +0000947 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert38262242014-09-10 14:50:23 +0000948
949 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
950 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser28735942014-08-16 09:09:15 +0000951 Builder.SetInsertPoint(StartBlock->begin());
952
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000953 NodeBuilder.create(AstRoot);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000954 return true;
955 }
956
Tobias Grosserc14582f2013-02-05 18:01:29 +0000957 virtual void printScop(raw_ostream &OS) const {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000958
959 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grossere3c05582014-11-15 21:32:53 +0000960 AU.addRequired<DataLayoutPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000961 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000962 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000963 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000964 AU.addRequired<ScalarEvolution>();
965 AU.addRequired<ScopDetection>();
966 AU.addRequired<ScopInfo>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000967 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000968
969 AU.addPreserved<Dependences>();
970
Chandler Carruthf5579872015-01-17 14:16:56 +0000971 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000972 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000973 AU.addPreserved<IslAstInfo>();
974 AU.addPreserved<ScopDetection>();
975 AU.addPreserved<ScalarEvolution>();
976
977 // FIXME: We do not yet add regions for the newly generated code to the
978 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +0000979 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000980 AU.addPreserved<TempScopInfo>();
981 AU.addPreserved<ScopInfo>();
982 AU.addPreservedID(IndependentBlocksID);
983 }
984};
985}
986
987char IslCodeGeneration::ID = 1;
988
Tobias Grosser7242ad92013-02-22 08:07:06 +0000989Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000990
Tobias Grosser7242ad92013-02-22 08:07:06 +0000991INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
992 "Polly - Create LLVM-IR from SCoPs", false, false);
993INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +0000994INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +0000995INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +0000996INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000997INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
998INITIALIZE_PASS_DEPENDENCY(ScopDetection);
999INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1000 "Polly - Create LLVM-IR from SCoPs", false, false)