blob: fde674d78b13f55c2b05542c35c93cea48c9a437 [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"
Johannes Doerfert0b169c02015-02-27 17:37:05 +000044#include "llvm/IR/Verifier.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000045#include "llvm/IR/DataLayout.h"
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47
48#include "isl/union_map.h"
49#include "isl/list.h"
50#include "isl/ast.h"
51#include "isl/ast_build.h"
52#include "isl/set.h"
53#include "isl/map.h"
54#include "isl/aff.h"
55
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000056using namespace polly;
57using namespace llvm;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-codegen-isl"
60
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000061class IslNodeBuilder {
62public:
Johannes Doerfert51d1c742014-10-02 15:32:17 +000063 IslNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
Tobias Grossere3c05582014-11-15 21:32:53 +000064 const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
65 DominatorTree &DT, Scop &S)
66 : S(S), Builder(Builder), Annotator(Annotator),
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000067 Rewriter(new SCEVExpander(SE, "polly")),
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000068 ExprBuilder(Builder, IDToValue, *Rewriter),
Johannes Doerfert275a1752015-02-24 16:16:32 +000069 BlockGen(Builder, LI, SE, DT, &ExprBuilder), RegionGen(BlockGen), P(P),
70 DL(DL), LI(LI), SE(SE), DT(DT) {}
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000071
72 ~IslNodeBuilder() { delete Rewriter; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000073
74 void addParameters(__isl_take isl_set *Context);
75 void create(__isl_take isl_ast_node *Node);
Tobias Grosser54ee0ba2013-11-17 03:18:25 +000076 IslExprBuilder &getExprBuilder() { return ExprBuilder; }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000077
78private:
Tobias Grossere3c05582014-11-15 21:32:53 +000079 Scop &S;
Tobias Grosser5103ba72014-03-04 14:58:49 +000080 PollyIRBuilder &Builder;
Johannes Doerfert51d1c742014-10-02 15:32:17 +000081 ScopAnnotator &Annotator;
Johannes Doerfert2ef33e92014-10-05 11:33:59 +000082
83 /// @brief A SCEVExpander to create llvm values from SCEVs.
84 SCEVExpander *Rewriter;
85
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000086 IslExprBuilder ExprBuilder;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000087 BlockGenerator BlockGen;
Johannes Doerfert275a1752015-02-24 16:16:32 +000088
89 /// @brief Generator for region statements.
90 RegionGenerator RegionGen;
91
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000092 Pass *P;
Tobias Grossere3c05582014-11-15 21:32:53 +000093 const DataLayout &DL;
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +000094 LoopInfo &LI;
95 ScalarEvolution &SE;
96 DominatorTree &DT;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +000097
Tobias Grossere3c05582014-11-15 21:32:53 +000098 /// @brief The current iteration of out-of-scop loops
99 ///
100 /// This map provides for a given loop a llvm::Value that contains the current
101 /// loop iteration.
102 LoopToScevMapT OutsideLoopIterations;
103
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000104 // This maps an isl_id* to the Value* it has in the generated program. For now
105 // on, the only isl_ids that are stored here are the newly calculated loop
106 // ivs.
Tobias Grosser566ad582014-08-31 16:21:12 +0000107 IslExprBuilder::IDToValueTy IDToValue;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000108
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000109 /// Generate code for a given SCEV*
110 ///
111 /// This function generates code for a given SCEV expression. It generated
112 /// code is emmitted at the end of the basic block our Builder currently
113 /// points to and the resulting value is returned.
114 ///
115 /// @param Expr The expression to code generate.
116 Value *generateSCEV(const SCEV *Expr);
117
Tobias Grossere3c05582014-11-15 21:32:53 +0000118 /// A set of Value -> Value remappings to apply when generating new code.
119 ///
120 /// When generating new code for a ScopStmt this map is used to map certain
121 /// llvm::Values to new llvm::Values.
122 ValueMapT ValueMap;
123
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000124 // Extract the upper bound of this loop
125 //
126 // The isl code generation can generate arbitrary expressions to check if the
127 // upper bound of a loop is reached, but it provides an option to enforce
128 // 'atomic' upper bounds. An 'atomic upper bound is always of the form
129 // iv <= expr, where expr is an (arbitrary) expression not containing iv.
130 //
131 // This function extracts 'atomic' upper bounds. Polly, in general, requires
132 // atomic upper bounds for the following reasons:
133 //
134 // 1. An atomic upper bound is loop invariant
135 //
136 // It must not be calculated at each loop iteration and can often even be
137 // hoisted out further by the loop invariant code motion.
138 //
139 // 2. OpenMP needs a loop invarient upper bound to calculate the number
140 // of loop iterations.
141 //
142 // 3. With the existing code, upper bounds have been easier to implement.
Tobias Grossere602a072013-05-07 07:30:56 +0000143 __isl_give isl_ast_expr *getUpperBound(__isl_keep isl_ast_node *For,
144 CmpInst::Predicate &Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000145
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000146 unsigned getNumberOfIterations(__isl_keep isl_ast_node *For);
147
Tobias Grossere3c05582014-11-15 21:32:53 +0000148 /// Compute the values and loops referenced in this subtree.
149 ///
150 /// This function looks at all ScopStmts scheduled below the provided For node
151 /// and finds the llvm::Value[s] and llvm::Loops[s] which are referenced but
152 /// not locally defined.
153 ///
154 /// Values that can be synthesized or that are available as globals are
155 /// considered locally defined.
156 ///
157 /// Loops that contain the scop or that are part of the scop are considered
158 /// locally defined. Loops that are before the scop, but do not contain the
159 /// scop itself are considered not locally defined.
160 ///
161 /// @param For The node defining the subtree.
162 /// @param Values A vector that will be filled with the Values referenced in
163 /// this subtree.
164 /// @param Loops A vector that will be filled with the Loops referenced in
165 /// this subtree.
166 void getReferencesInSubtree(__isl_keep isl_ast_node *For,
167 SetVector<Value *> &Values,
168 SetVector<const Loop *> &Loops);
169
170 /// Change the llvm::Value(s) used for code generation.
171 ///
172 /// When generating code certain values (e.g., references to induction
173 /// variables or array base pointers) in the original code may be replaced by
174 /// new values. This function allows to (partially) update the set of values
175 /// used. A typical use case for this function is the case when we continue
176 /// code generation in a subfunction/kernel function and need to explicitly
177 /// pass down certain values.
178 ///
179 /// @param NewValues A map that maps certain llvm::Values to new llvm::Values.
180 void updateValues(ParallelLoopGenerator::ValueToValueMapTy &NewValues);
181
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000182 void createFor(__isl_take isl_ast_node *For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000183 void createForVector(__isl_take isl_ast_node *For, int VectorWidth);
184 void createForSequential(__isl_take isl_ast_node *For);
Tobias Grosserce67a042014-07-02 16:26:47 +0000185
Tobias Grossere3c05582014-11-15 21:32:53 +0000186 /// Create LLVM-IR that executes a for node thread parallel.
187 ///
188 /// @param For The FOR isl_ast_node for which code is generated.
189 void createForParallel(__isl_take isl_ast_node *For);
190
Tobias Grosserce67a042014-07-02 16:26:47 +0000191 /// Generate LLVM-IR that computes the values of the original induction
192 /// variables in function of the newly generated loop induction variables.
193 ///
194 /// Example:
195 ///
196 /// // Original
197 /// for i
198 /// for j
199 /// S(i)
200 ///
201 /// Schedule: [i,j] -> [i+j, j]
202 ///
203 /// // New
204 /// for c0
205 /// for c1
206 /// S(c0 - c1, c1)
207 ///
208 /// Assuming the original code consists of two loops which are
209 /// transformed according to a schedule [i,j] -> [c0=i+j,c1=j]. The resulting
210 /// ast models the original statement as a call expression where each argument
211 /// is an expression that computes the old induction variables from the new
212 /// ones, ordered such that the first argument computes the value of induction
213 /// variable that was outermost in the original code.
214 ///
215 /// @param Expr The call expression that represents the statement.
216 /// @param Stmt The statement that is called.
217 /// @param VMap The value map into which the mapping from the old induction
218 /// variable to the new one is inserted. This mapping is used
219 /// for the classical code generation (not scev-based) and
220 /// gives an explicit mapping from an original, materialized
221 /// induction variable. It consequently can only be expressed
222 /// if there was an explicit induction variable.
223 /// @param LTS The loop to SCEV map in which the mapping from the original
224 /// loop to a SCEV representing the new loop iv is added. This
225 /// mapping does not require an explicit induction variable.
226 /// Instead, we think in terms of an implicit induction variable
227 /// that counts the number of times a loop is executed. For each
228 /// original loop this count, expressed in function of the new
229 /// induction variables, is added to the LTS map.
230 void createSubstitutions(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000231 ValueMapT &VMap, LoopToScevMapT &LTS);
Tobias Grosserce67a042014-07-02 16:26:47 +0000232 void createSubstitutionsVector(__isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
233 VectorValueMapT &VMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000234 std::vector<LoopToScevMapT> &VLTS,
235 std::vector<Value *> &IVS,
236 __isl_take isl_id *IteratorID);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000237 void createIf(__isl_take isl_ast_node *If);
Tobias Grossere602a072013-05-07 07:30:56 +0000238 void createUserVector(__isl_take isl_ast_node *User,
239 std::vector<Value *> &IVS,
240 __isl_take isl_id *IteratorID,
241 __isl_take isl_union_map *Schedule);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000242 void createUser(__isl_take isl_ast_node *User);
243 void createBlock(__isl_take isl_ast_node *Block);
244};
245
Tobias Grossere602a072013-05-07 07:30:56 +0000246__isl_give isl_ast_expr *
247IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
248 ICmpInst::Predicate &Predicate) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000249 isl_id *UBID, *IteratorID;
250 isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000251 isl_ast_op_type Type;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000252
253 Cond = isl_ast_node_for_get_cond(For);
254 Iterator = isl_ast_node_for_get_iterator(For);
Tobias Grosser2784b082015-01-10 07:40:39 +0000255 isl_ast_expr_get_type(Cond);
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000256 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
257 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000258
Tobias Grosser2784b082015-01-10 07:40:39 +0000259 Type = isl_ast_expr_get_op_type(Cond);
260
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000261 switch (Type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000262 case isl_ast_op_le:
263 Predicate = ICmpInst::ICMP_SLE;
264 break;
265 case isl_ast_op_lt:
266 Predicate = ICmpInst::ICMP_SLT;
267 break;
268 default:
269 llvm_unreachable("Unexpected comparision type in loop conditon");
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000270 }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000271
272 Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
273
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000274 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
275 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000276
277 UBID = isl_ast_expr_get_id(Arg0);
278
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000279 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
280 "Could not get the iterator");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000281
282 IteratorID = isl_ast_expr_get_id(Iterator);
283
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000284 assert(UBID == IteratorID &&
285 "conditional expression is not an atomic upper bound");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000286
287 UB = isl_ast_expr_get_op_arg(Cond, 1);
288
289 isl_ast_expr_free(Cond);
290 isl_ast_expr_free(Iterator);
291 isl_ast_expr_free(Arg0);
292 isl_id_free(IteratorID);
293 isl_id_free(UBID);
294
295 return UB;
296}
297
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000298unsigned IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
Johannes Doerfert94d90822014-07-23 20:26:25 +0000299 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000300 isl_set *LoopDomain = isl_set_from_union_set(isl_union_map_range(Schedule));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000301 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
302 if (NumberOfIterations == -1)
303 return -1;
304 return NumberOfIterations + 1;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000305}
306
Tobias Grossere3c05582014-11-15 21:32:53 +0000307struct FindValuesUser {
308 LoopInfo &LI;
309 ScalarEvolution &SE;
310 Region &R;
311 SetVector<Value *> &Values;
312 SetVector<const SCEV *> &SCEVs;
313};
314
315/// Extract the values and SCEVs needed to generate code for a ScopStmt.
316///
317/// This function extracts a ScopStmt from a given isl_set and computes the
318/// Values this statement depends on as well as a set of SCEV expressions that
319/// need to be synthesized when generating code for this statment.
320static int findValuesInStmt(isl_set *Set, void *UserPtr) {
321 isl_id *Id = isl_set_get_tuple_id(Set);
322 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr);
323 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
324 const BasicBlock *BB = Stmt->getBasicBlock();
325
326 // Check all the operands of instructions in the basic block.
327 for (const Instruction &Inst : *BB) {
328 for (Value *SrcVal : Inst.operands()) {
329 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
330 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) {
331 User.SCEVs.insert(
332 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB)));
333 continue;
334 }
335 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
336 if (Stmt->getParent()->getRegion().contains(OpInst))
337 continue;
338
339 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
340 User.Values.insert(SrcVal);
341 }
342 }
343 isl_id_free(Id);
344 isl_set_free(Set);
345 return 0;
346}
347
348void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
349 SetVector<Value *> &Values,
350 SetVector<const Loop *> &Loops) {
351
352 SetVector<const SCEV *> SCEVs;
353 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs};
354
355 for (const auto &I : IDToValue)
356 Values.insert(I.second);
357
358 for (const auto &I : OutsideLoopIterations)
359 Values.insert(cast<SCEVUnknown>(I.second)->getValue());
360
361 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For));
362
363 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues);
364 isl_union_set_free(Schedule);
365
366 for (const SCEV *Expr : SCEVs) {
367 findValues(Expr, Values);
368 findLoops(Expr, Loops);
369 }
370
371 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
372
373 /// Remove loops that contain the scop or that are part of the scop, as they
374 /// are considered local. This leaves only loops that are before the scop, but
375 /// do not contain the scop itself.
376 Loops.remove_if([this](const Loop *L) {
377 return this->S.getRegion().contains(L) ||
378 L->contains(S.getRegion().getEntry());
379 });
380}
381
382void IslNodeBuilder::updateValues(
383 ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
384 SmallPtrSet<Value *, 5> Inserted;
385
386 for (const auto &I : IDToValue) {
387 IDToValue[I.first] = NewValues[I.second];
388 Inserted.insert(I.second);
389 }
390
391 for (const auto &I : NewValues) {
392 if (Inserted.count(I.first))
393 continue;
394
395 ValueMap[I.first] = I.second;
396 }
397}
398
Tobias Grossere602a072013-05-07 07:30:56 +0000399void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
400 std::vector<Value *> &IVS,
401 __isl_take isl_id *IteratorID,
402 __isl_take isl_union_map *Schedule) {
Tobias Grosserce67a042014-07-02 16:26:47 +0000403 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
404 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
405 isl_id *Id = isl_ast_expr_get_id(StmtExpr);
406 isl_ast_expr_free(StmtExpr);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000407 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000408 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000409 VectorValueMapT VectorMap(IVS.size());
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000410 std::vector<LoopToScevMapT> VLTS(IVS.size());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000411
412 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
413 Schedule = isl_union_map_intersect_domain(Schedule, Domain);
414 isl_map *S = isl_map_from_union_map(Schedule);
415
Tobias Grosserce67a042014-07-02 16:26:47 +0000416 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000417 VectorBlockGenerator::generate(BlockGen, *Stmt, VectorMap, VLTS, S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000418
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000419 isl_map_free(S);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000420 isl_id_free(Id);
421 isl_ast_node_free(User);
422}
423
Tobias Grossere602a072013-05-07 07:30:56 +0000424void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
425 int VectorWidth) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000426 isl_ast_node *Body = isl_ast_node_for_get_body(For);
427 isl_ast_expr *Init = isl_ast_node_for_get_init(For);
428 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
429 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
430 isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000431
432 Value *ValueLB = ExprBuilder.create(Init);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000433 Value *ValueInc = ExprBuilder.create(Inc);
434
435 Type *MaxType = ExprBuilder.getType(Iterator);
436 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000437 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
438
439 if (MaxType != ValueLB->getType())
440 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000441 if (MaxType != ValueInc->getType())
442 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
443
Tobias Grosserc14582f2013-02-05 18:01:29 +0000444 std::vector<Value *> IVS(VectorWidth);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000445 IVS[0] = ValueLB;
446
447 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000448 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000449
Johannes Doerfert94d90822014-07-23 20:26:25 +0000450 isl_union_map *Schedule = IslAstInfo::getSchedule(For);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000451 assert(Schedule && "For statement annotation does not contain its schedule");
452
453 IDToValue[IteratorID] = ValueLB;
454
455 switch (isl_ast_node_get_type(Body)) {
456 case isl_ast_node_user:
457 createUserVector(Body, IVS, isl_id_copy(IteratorID),
458 isl_union_map_copy(Schedule));
459 break;
460 case isl_ast_node_block: {
461 isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
462
463 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
464 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000465 isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000466
467 isl_ast_node_free(Body);
468 isl_ast_node_list_free(List);
469 break;
470 }
471 default:
472 isl_ast_node_dump(Body);
473 llvm_unreachable("Unhandled isl_ast_node in vectorizer");
474 }
475
Tobias Grossere3c05582014-11-15 21:32:53 +0000476 IDToValue.erase(IDToValue.find(IteratorID));
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000477 isl_id_free(IteratorID);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000478 isl_union_map_free(Schedule);
479
480 isl_ast_node_free(For);
481 isl_ast_expr_free(Iterator);
482}
483
484void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000485 isl_ast_node *Body;
486 isl_ast_expr *Init, *Inc, *Iterator, *UB;
487 isl_id *IteratorID;
488 Value *ValueLB, *ValueUB, *ValueInc;
489 Type *MaxType;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000490 BasicBlock *ExitBlock;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000491 Value *IV;
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000492 CmpInst::Predicate Predicate;
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000493 bool Parallel;
494
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000495 Parallel =
496 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000497
498 Body = isl_ast_node_for_get_body(For);
499
500 // isl_ast_node_for_is_degenerate(For)
501 //
502 // TODO: For degenerated loops we could generate a plain assignment.
503 // However, for now we just reuse the logic for normal loops, which will
504 // create a loop with a single iteration.
505
506 Init = isl_ast_node_for_get_init(For);
507 Inc = isl_ast_node_for_get_inc(For);
508 Iterator = isl_ast_node_for_get_iterator(For);
509 IteratorID = isl_ast_expr_get_id(Iterator);
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000510 UB = getUpperBound(For, Predicate);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000511
512 ValueLB = ExprBuilder.create(Init);
513 ValueUB = ExprBuilder.create(UB);
514 ValueInc = ExprBuilder.create(Inc);
515
516 MaxType = ExprBuilder.getType(Iterator);
517 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
518 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
519 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
520
521 if (MaxType != ValueLB->getType())
522 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
523 if (MaxType != ValueUB->getType())
524 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
525 if (MaxType != ValueInc->getType())
526 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
527
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000528 // If we can show that LB <Predicate> UB holds at least once, we can
529 // omit the GuardBB in front of the loop.
530 bool UseGuardBB =
531 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000532 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
Johannes Doerfertdd5c1442014-09-10 17:33:32 +0000533 Predicate, &Annotator, Parallel, UseGuardBB);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000534 IDToValue[IteratorID] = IV;
535
536 create(Body);
537
Johannes Doerfertc7b719f2014-10-01 20:10:44 +0000538 Annotator.popLoop(Parallel);
Tobias Grosser37c9b8e2014-03-04 14:59:00 +0000539
Tobias Grossere3c05582014-11-15 21:32:53 +0000540 IDToValue.erase(IDToValue.find(IteratorID));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000541
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000542 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000543
544 isl_ast_node_free(For);
545 isl_ast_expr_free(Iterator);
546 isl_id_free(IteratorID);
547}
548
Tobias Grossere3c05582014-11-15 21:32:53 +0000549/// @brief Remove the BBs contained in a (sub)function from the dominator tree.
550///
551/// This function removes the basic blocks that are part of a subfunction from
552/// the dominator tree. Specifically, when generating code it may happen that at
553/// some point the code generation continues in a new sub-function (e.g., when
554/// generating OpenMP code). The basic blocks that are created in this
555/// sub-function are then still part of the dominator tree of the original
556/// function, such that the dominator tree reaches over function boundaries.
557/// This is not only incorrect, but also causes crashes. This function now
558/// removes from the dominator tree all basic blocks that are dominated (and
559/// consequently reachable) from the entry block of this (sub)function.
560///
561/// FIXME: A LLVM (function or region) pass should not touch anything outside of
562/// the function/region it runs on. Hence, the pure need for this function shows
563/// that we do not comply to this rule. At the moment, this does not cause any
564/// issues, but we should be aware that such issues may appear. Unfortunately
565/// the current LLVM pass infrastructure does not allow to make Polly a module
566/// or call-graph pass to solve this issue, as such a pass would not have access
567/// to the per-function analyses passes needed by Polly. A future pass manager
568/// infrastructure is supposed to enable such kind of access possibly allowing
569/// us to create a cleaner solution here.
570///
571/// FIXME: Instead of adding the dominance information and then dropping it
572/// later on, we should try to just not add it in the first place. This requires
573/// some careful testing to make sure this does not break in interaction with
574/// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
575/// which may try to update it.
576///
577/// @param F The function which contains the BBs to removed.
578/// @param DT The dominator tree from which to remove the BBs.
579static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
580 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
581 std::vector<BasicBlock *> Nodes;
582
583 // We can only remove an element from the dominator tree, if all its children
584 // have been removed. To ensure this we obtain the list of nodes to remove
585 // using a post-order tree traversal.
586 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
587 Nodes.push_back(I->getBlock());
588
589 for (BasicBlock *BB : Nodes)
590 DT.eraseNode(BB);
591}
592
593void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
594 isl_ast_node *Body;
595 isl_ast_expr *Init, *Inc, *Iterator, *UB;
596 isl_id *IteratorID;
597 Value *ValueLB, *ValueUB, *ValueInc;
598 Type *MaxType;
599 Value *IV;
600 CmpInst::Predicate Predicate;
601
602 Body = isl_ast_node_for_get_body(For);
603 Init = isl_ast_node_for_get_init(For);
604 Inc = isl_ast_node_for_get_inc(For);
605 Iterator = isl_ast_node_for_get_iterator(For);
606 IteratorID = isl_ast_expr_get_id(Iterator);
607 UB = getUpperBound(For, Predicate);
608
609 ValueLB = ExprBuilder.create(Init);
610 ValueUB = ExprBuilder.create(UB);
611 ValueInc = ExprBuilder.create(Inc);
612
613 // OpenMP always uses SLE. In case the isl generated AST uses a SLT
614 // expression, we need to adjust the loop blound by one.
615 if (Predicate == CmpInst::ICMP_SLT)
616 ValueUB = Builder.CreateAdd(
617 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
618
619 MaxType = ExprBuilder.getType(Iterator);
620 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
621 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
622 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
623
624 if (MaxType != ValueLB->getType())
625 ValueLB = Builder.CreateSExt(ValueLB, MaxType);
626 if (MaxType != ValueUB->getType())
627 ValueUB = Builder.CreateSExt(ValueUB, MaxType);
628 if (MaxType != ValueInc->getType())
629 ValueInc = Builder.CreateSExt(ValueInc, MaxType);
630
631 BasicBlock::iterator LoopBody;
632
633 SetVector<Value *> SubtreeValues;
634 SetVector<const Loop *> Loops;
635
636 getReferencesInSubtree(For, SubtreeValues, Loops);
637
638 // Create for all loops we depend on values that contain the current loop
639 // iteration. These values are necessary to generate code for SCEVs that
640 // depend on such loops. As a result we need to pass them to the subfunction.
641 for (const Loop *L : Loops) {
642 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
643 SE.getUnknown(Builder.getInt64(1)),
644 L, SCEV::FlagAnyWrap);
645 Value *V = generateSCEV(OuterLIV);
646 OutsideLoopIterations[L] = SE.getUnknown(V);
647 SubtreeValues.insert(V);
648 }
649
650 ParallelLoopGenerator::ValueToValueMapTy NewValues;
651 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
652
653 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
654 SubtreeValues, NewValues, &LoopBody);
655 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
656 Builder.SetInsertPoint(LoopBody);
657
658 // Save the current values.
659 ValueMapT ValueMapCopy = ValueMap;
660 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
661
662 updateValues(NewValues);
663 IDToValue[IteratorID] = IV;
664
665 create(Body);
666
667 // Restore the original values.
668 ValueMap = ValueMapCopy;
669 IDToValue = IDToValueCopy;
670
671 Builder.SetInsertPoint(AfterLoop);
672 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
673
674 for (const Loop *L : Loops)
675 OutsideLoopIterations.erase(L);
676
677 isl_ast_node_free(For);
678 isl_ast_expr_free(Iterator);
679 isl_id_free(IteratorID);
680}
681
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000682void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
683 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
684
Johannes Doerferted67f8b2014-08-01 08:14:28 +0000685 if (Vector && IslAstInfo::isInnermostParallel(For) &&
686 !IslAstInfo::isReductionParallel(For)) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000687 int VectorWidth = getNumberOfIterations(For);
688 if (1 < VectorWidth && VectorWidth <= 16) {
689 createForVector(For, VectorWidth);
690 return;
691 }
692 }
Tobias Grossere3c05582014-11-15 21:32:53 +0000693
694 if (IslAstInfo::isExecutedInParallel(For)) {
695 createForParallel(For);
696 return;
697 }
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000698 createForSequential(For);
699}
700
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000701void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
702 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
703
704 Function *F = Builder.GetInsertBlock()->getParent();
705 LLVMContext &Context = F->getContext();
706
Tobias Grosserc14582f2013-02-05 18:01:29 +0000707 BasicBlock *CondBB =
Chandler Carruth5ec33332015-01-18 10:52:23 +0000708 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000709 CondBB->setName("polly.cond");
Chandler Carruth5ec33332015-01-18 10:52:23 +0000710 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000711 MergeBB->setName("polly.merge");
712 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
713 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
714
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000715 DT.addNewBlock(ThenBB, CondBB);
716 DT.addNewBlock(ElseBB, CondBB);
717 DT.changeImmediateDominator(MergeBB, CondBB);
718
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000719 Loop *L = LI.getLoopFor(CondBB);
720 if (L) {
Chandler Carruth6adcf562015-01-18 01:47:30 +0000721 L->addBasicBlockToLoop(ThenBB, LI);
722 L->addBasicBlockToLoop(ElseBB, LI);
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000723 }
724
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000725 CondBB->getTerminator()->eraseFromParent();
726
727 Builder.SetInsertPoint(CondBB);
728 Value *Predicate = ExprBuilder.create(Cond);
729 Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
730 Builder.SetInsertPoint(ThenBB);
731 Builder.CreateBr(MergeBB);
732 Builder.SetInsertPoint(ElseBB);
733 Builder.CreateBr(MergeBB);
734 Builder.SetInsertPoint(ThenBB->begin());
735
736 create(isl_ast_node_if_get_then(If));
737
738 Builder.SetInsertPoint(ElseBB->begin());
739
740 if (isl_ast_node_if_has_else(If))
741 create(isl_ast_node_if_get_else(If));
742
743 Builder.SetInsertPoint(MergeBB->begin());
744
745 isl_ast_node_free(If);
746}
747
Tobias Grosserce67a042014-07-02 16:26:47 +0000748void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
749 ValueMapT &VMap, LoopToScevMapT &LTS) {
750 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
751 "Expression of type 'op' expected");
752 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
753 "Opertation of type 'call' expected");
754 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
755 isl_ast_expr *SubExpr;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000756 Value *V;
757
Tobias Grosserce67a042014-07-02 16:26:47 +0000758 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
759 V = ExprBuilder.create(SubExpr);
Sebastian Pope039bb12013-03-18 19:09:49 +0000760 ScalarEvolution *SE = Stmt->getParent()->getSE();
761 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000762 }
763
Tobias Grossere3c05582014-11-15 21:32:53 +0000764 // Add the current ValueMap to our per-statement value map.
765 //
766 // This is needed e.g. to rewrite array base addresses when moving code
767 // into a parallely executed subfunction.
768 VMap.insert(ValueMap.begin(), ValueMap.end());
769
Tobias Grosserce67a042014-07-02 16:26:47 +0000770 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000771}
772
Tobias Grosserc14582f2013-02-05 18:01:29 +0000773void IslNodeBuilder::createSubstitutionsVector(
Tobias Grosserce67a042014-07-02 16:26:47 +0000774 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap,
775 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
776 __isl_take isl_id *IteratorID) {
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000777 int i = 0;
778
779 Value *OldValue = IDToValue[IteratorID];
Tobias Grosser91f5b262014-06-04 08:06:40 +0000780 for (Value *IV : IVS) {
781 IDToValue[IteratorID] = IV;
Tobias Grosserce67a042014-07-02 16:26:47 +0000782 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000783 i++;
784 }
785
786 IDToValue[IteratorID] = OldValue;
787 isl_id_free(IteratorID);
Tobias Grosserce67a042014-07-02 16:26:47 +0000788 isl_ast_expr_free(Expr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000789}
790
791void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
792 ValueMapT VMap;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000793 LoopToScevMapT LTS;
Tobias Grosserce67a042014-07-02 16:26:47 +0000794 isl_id *Id;
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000795 ScopStmt *Stmt;
796
Tobias Grosserce67a042014-07-02 16:26:47 +0000797 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
798 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
799 Id = isl_ast_expr_get_id(StmtExpr);
800 isl_ast_expr_free(StmtExpr);
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000801
Tobias Grossere3c05582014-11-15 21:32:53 +0000802 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
803
Tobias Grosserc14582f2013-02-05 18:01:29 +0000804 Stmt = (ScopStmt *)isl_id_get_user(Id);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000805 Stmt->setAstBuild(IslAstInfo::getBuild(User));
Johannes Doerferta63b2572014-08-03 01:51:59 +0000806
Tobias Grosserce67a042014-07-02 16:26:47 +0000807 createSubstitutions(Expr, Stmt, VMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000808 if (Stmt->isBlockStmt())
809 BlockGen.copyStmt(*Stmt, VMap, LTS);
810 else
811 RegionGen.copyStmt(*Stmt, VMap, LTS);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000812
813 isl_ast_node_free(User);
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000814 isl_id_free(Id);
815}
816
817void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
818 isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
819
820 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
821 create(isl_ast_node_list_get_ast_node(List, i));
822
823 isl_ast_node_free(Block);
824 isl_ast_node_list_free(List);
825}
826
827void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
828 switch (isl_ast_node_get_type(Node)) {
829 case isl_ast_node_error:
830 llvm_unreachable("code generation error");
831 case isl_ast_node_for:
832 createFor(Node);
833 return;
834 case isl_ast_node_if:
835 createIf(Node);
836 return;
837 case isl_ast_node_user:
838 createUser(Node);
839 return;
840 case isl_ast_node_block:
841 createBlock(Node);
842 return;
843 }
844
845 llvm_unreachable("Unknown isl_ast_node type");
846}
847
848void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000849
850 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
851 isl_id *Id;
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000852
853 Id = isl_set_get_dim_id(Context, isl_dim_param, i);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000854 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id));
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000855
856 isl_id_free(Id);
857 }
858
Tobias Grossere3c05582014-11-15 21:32:53 +0000859 // Generate values for the current loop iteration for all surrounding loops.
860 //
861 // We may also reference loops outside of the scop which do not contain the
862 // scop itself, but as the number of such scops may be arbitrarily large we do
863 // not generate code for them here, but only at the point of code generation
864 // where these values are needed.
865 Region &R = S.getRegion();
866 Loop *L = LI.getLoopFor(R.getEntry());
867
868 while (L != nullptr && R.contains(L))
869 L = L->getParentLoop();
870
871 while (L != nullptr) {
872 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
873 SE.getUnknown(Builder.getInt64(1)),
874 L, SCEV::FlagAnyWrap);
875 Value *V = generateSCEV(OuterLIV);
876 OutsideLoopIterations[L] = SE.getUnknown(V);
877 L = L->getParentLoop();
878 }
879
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000880 isl_set_free(Context);
881}
882
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000883Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
884 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
Tobias Grosser55bc4c02015-01-08 19:26:53 +0000885 return Rewriter->expandCodeFor(Expr, Expr->getType(), InsertLocation);
Tobias Grosserec7d67e2014-11-06 00:27:01 +0000886}
887
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000888namespace {
889class IslCodeGeneration : public ScopPass {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000890public:
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000891 static char ID;
892
893 IslCodeGeneration() : ScopPass(ID) {}
894
Tobias Grossere3c05582014-11-15 21:32:53 +0000895 /// @brief The datalayout used
896 const DataLayout *DL;
897
Johannes Doerfert38262242014-09-10 14:50:23 +0000898 /// @name The analysis passes we need to generate code.
899 ///
900 ///{
901 LoopInfo *LI;
902 IslAstInfo *AI;
903 DominatorTree *DT;
904 ScalarEvolution *SE;
905 ///}
906
907 /// @brief The loop annotator to generate llvm.loop metadata.
Johannes Doerfert51d1c742014-10-02 15:32:17 +0000908 ScopAnnotator Annotator;
Johannes Doerfert38262242014-09-10 14:50:23 +0000909
910 /// @brief Build the runtime condition.
911 ///
912 /// Build the condition that evaluates at run-time to true iff all
913 /// assumptions taken for the SCoP hold, and to false otherwise.
914 ///
915 /// @return A value evaluating to true/false if execution is save/unsafe.
916 Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
917 Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
918 Value *RTC = ExprBuilder.create(AI->getRunCondition());
Johannes Doerfertb164c792014-09-18 11:17:17 +0000919 if (!RTC->getType()->isIntegerTy(1))
920 RTC = Builder.CreateIsNotNull(RTC);
921 return RTC;
Johannes Doerfert38262242014-09-10 14:50:23 +0000922 }
923
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000924 bool verifyGeneratedFunction(Scop &S, Function &F) {
925 if (!verifyFunction(F))
926 return false;
927
928 DEBUG({
929 errs() << "== ISL Codegen created an invalid function ==\n\n== The "
930 "SCoP ==\n";
931 S.print(errs());
932 errs() << "\n== The isl AST ==\n";
Johannes Doerfert3fe584d2015-03-01 18:40:25 +0000933 AI->printScop(errs(), S);
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000934 errs() << "\n== The invalid function ==\n";
935 F.print(errs());
936 errs() << "\n== The errors ==\n";
937 verifyFunction(F, &errs());
938 });
939
940 return true;
941 }
942
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000943 bool runOnScop(Scop &S) override {
Johannes Doerfert38262242014-09-10 14:50:23 +0000944 AI = &getAnalysis<IslAstInfo>();
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000945
946 // Check if we created an isl_ast root node, otherwise exit.
947 isl_ast_node *AstRoot = AI->getAst();
948 if (!AstRoot)
949 return false;
950
951 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfert38262242014-09-10 14:50:23 +0000952 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
953 SE = &getAnalysis<ScalarEvolution>();
Tobias Grossere3c05582014-11-15 21:32:53 +0000954 DL = &getAnalysis<DataLayoutPass>().getDataLayout();
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000955
Tobias Grossere602a072013-05-07 07:30:56 +0000956 assert(!S.getRegion().isTopLevelRegion() &&
957 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000958
Johannes Doerfertecdf2632014-10-02 15:31:24 +0000959 // Build the alias scopes for annotations first.
960 if (PollyAnnotateAliasScopes)
961 Annotator.buildAliasScopes(S);
962
Johannes Doerfert38262242014-09-10 14:50:23 +0000963 BasicBlock *EnteringBB = simplifyRegion(&S, this);
964 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
Johannes Doerfert9744c4a2014-08-12 18:35:54 +0000965
Tobias Grossere3c05582014-11-15 21:32:53 +0000966 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
Tobias Grosser28735942014-08-16 09:09:15 +0000967 NodeBuilder.addParameters(S.getContext());
Johannes Doerfert38262242014-09-10 14:50:23 +0000968
969 Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
970 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser28735942014-08-16 09:09:15 +0000971 Builder.SetInsertPoint(StartBlock->begin());
972
Johannes Doerfert7ceb0402015-02-11 17:25:09 +0000973 NodeBuilder.create(AstRoot);
Johannes Doerfert0b169c02015-02-27 17:37:05 +0000974
975 assert(!verifyGeneratedFunction(S, *EnteringBB->getParent()) &&
976 "Verification of generated function failed");
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000977 return true;
978 }
979
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000980 void printScop(raw_ostream &, Scop &) const override {}
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000981
Johannes Doerfert909a3bf2015-03-01 18:42:08 +0000982 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tobias Grossere3c05582014-11-15 21:32:53 +0000983 AU.addRequired<DataLayoutPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000984 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000985 AU.addRequired<IslAstInfo>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000986 AU.addRequired<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000987 AU.addRequired<ScalarEvolution>();
988 AU.addRequired<ScopDetection>();
989 AU.addRequired<ScopInfo>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000990 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000991
992 AU.addPreserved<Dependences>();
993
Chandler Carruthf5579872015-01-17 14:16:56 +0000994 AU.addPreserved<LoopInfoWrapperPass>();
Tobias Grosser42aff302014-01-13 22:29:56 +0000995 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +0000996 AU.addPreserved<IslAstInfo>();
997 AU.addPreserved<ScopDetection>();
998 AU.addPreserved<ScalarEvolution>();
999
1000 // FIXME: We do not yet add regions for the newly generated code to the
1001 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +00001002 AU.addPreserved<RegionInfoPass>();
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001003 AU.addPreserved<TempScopInfo>();
1004 AU.addPreserved<ScopInfo>();
1005 AU.addPreservedID(IndependentBlocksID);
1006 }
1007};
1008}
1009
1010char IslCodeGeneration::ID = 1;
1011
Tobias Grosser7242ad92013-02-22 08:07:06 +00001012Pass *polly::createIslCodeGenerationPass() { return new IslCodeGeneration(); }
Tobias Grosser8a5bc6e2012-10-02 19:50:43 +00001013
Tobias Grosser7242ad92013-02-22 08:07:06 +00001014INITIALIZE_PASS_BEGIN(IslCodeGeneration, "polly-codegen-isl",
1015 "Polly - Create LLVM-IR from SCoPs", false, false);
1016INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001017INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001018INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001019INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001020INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1021INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1022INITIALIZE_PASS_END(IslCodeGeneration, "polly-codegen-isl",
1023 "Polly - Create LLVM-IR from SCoPs", false, false)