blob: 4a1f2ea1ff551f20ab16a3c952ef3501210ad192 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ CodeGeneration.cpp - Code generate the Scops. -----------------===//
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 CodeGeneration pass takes a Scop created by ScopInfo and translates it
11// back to LLVM-IR using Cloog.
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. Cloog is used to generate an abstract syntax tree (clast) that
16// reflects the updated execution order. This clast is used to create new
17// LLVM-IR that is computational equivalent to the original control flow region,
18// but executes its code in the new execution order defined by the changed
19// scattering.
20//
21//===----------------------------------------------------------------------===//
22
Tobias Grosser0a91f322012-05-29 09:11:46 +000023#include "polly/CodeGen/Cloog.h"
Sebastian Pope1f65542012-05-07 16:35:11 +000024#ifdef CLOOG_FOUND
25
Tobias Grosser75805372011-04-29 06:27:02 +000026#include "polly/Dependences.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000027#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000028#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000029#include "polly/ScopInfo.h"
30#include "polly/TempScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000031#include "polly/CodeGen/CodeGeneration.h"
32#include "polly/CodeGen/BlockGenerators.h"
33#include "polly/CodeGen/LoopGenerators.h"
Tobias Grosser6217e182012-08-03 12:50:07 +000034#include "polly/CodeGen/PTXGenerator.h"
Tobias Grosser3a275d22012-05-29 09:11:54 +000035#include "polly/CodeGen/Utils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000036#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000037#include "polly/Support/ScopHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000038
Chandler Carruth535d52c2013-01-02 11:47:44 +000039#include "llvm/IR/Module.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000040#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000041#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000042#include "llvm/Analysis/LoopInfo.h"
43#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000044#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000045#include "llvm/IR/DataLayout.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000047
48#define CLOOG_INT_GMP 1
49#include "cloog/cloog.h"
50#include "cloog/isl/cloog.h"
51
Raghesh Aloora71989c2011-12-28 02:48:26 +000052#include "isl/aff.h"
53
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <vector>
55#include <utility>
56
57using namespace polly;
58using namespace llvm;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-codegen"
61
Tobias Grosser75805372011-04-29 06:27:02 +000062struct isl_set;
63
64namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000065static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000066 OpenMP("enable-polly-openmp", cl::desc("Generate OpenMP parallel code"),
67 cl::value_desc("OpenMP code generation enabled if true"),
68 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser75805372011-04-29 06:27:02 +000069
Tobias Grosser6217e182012-08-03 12:50:07 +000070#ifdef GPU_CODEGEN
71static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000072 GPGPU("enable-polly-gpgpu", cl::desc("Generate GPU parallel code"),
73 cl::Hidden, cl::value_desc("GPGPU code generation enabled if true"),
74 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000075
Tobias Grossere602a072013-05-07 07:30:56 +000076static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000077 GPUTriple("polly-gpgpu-triple",
78 cl::desc("Target triple for GPU code generation"), cl::Hidden,
79 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000080#endif /* GPU_CODEGEN */
81
Tobias Grosserc14582f2013-02-05 18:01:29 +000082typedef DenseMap<const char *, Value *> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000083
Tobias Grosser75805372011-04-29 06:27:02 +000084/// Class to generate LLVM-IR that calculates the value of a clast_expr.
85class ClastExpCodeGen {
Tobias Grosser5103ba72014-03-04 14:58:49 +000086 PollyIRBuilder &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000087 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000088
Tobias Grosserbb137e32012-01-24 16:42:28 +000089 Value *codegen(const clast_name *e, Type *Ty);
90 Value *codegen(const clast_term *e, Type *Ty);
91 Value *codegen(const clast_binary *e, Type *Ty);
92 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosserd7e58642013-04-10 06:55:45 +000093
Tobias Grosser75805372011-04-29 06:27:02 +000094public:
Tobias Grosser75805372011-04-29 06:27:02 +000095 // A generator for clast expressions.
96 //
97 // @param B The IRBuilder that defines where the code to calculate the
98 // clast expressions should be inserted.
99 // @param IVMAP A Map that translates strings describing the induction
100 // variables to the Values* that represent these variables
101 // on the LLVM side.
Tobias Grosser5103ba72014-03-04 14:58:49 +0000102 ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000103
104 // Generates code to calculate a given clast expression.
105 //
106 // @param e The expression to calculate.
107 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000108 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000109};
110
111Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000112 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000113
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000114 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000115
116 return Builder.CreateSExtOrBitCast(I->second, Ty);
117}
118
Sebastian Popbfec3612014-02-22 02:15:39 +0000119static APInt APInt_from_MPZ(const mpz_t mpz) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000120 uint64_t *p = nullptr;
Sebastian Popbfec3612014-02-22 02:15:39 +0000121 size_t sz;
122
123 p = (uint64_t *)mpz_export(p, &sz, -1, sizeof(uint64_t), 0, 0, mpz);
124
125 if (p) {
126 APInt A((unsigned)mpz_sizeinbase(mpz, 2), (unsigned)sz, p);
127 A = A.zext(A.getBitWidth() + 1);
128 free(p);
129
130 if (mpz_sgn(mpz) == -1)
131 return -A;
132 else
133 return A;
134 } else {
135 uint64_t val = 0;
136 return APInt(1, 1, &val);
137 }
138}
139
Tobias Grosserbb137e32012-01-24 16:42:28 +0000140Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
141 APInt a = APInt_from_MPZ(e->val);
142
143 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
144 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
145
146 if (!e->var)
147 return ConstOne;
148
149 Value *var = codegen(e->var, Ty);
150 return Builder.CreateMul(ConstOne, var);
151}
152
153Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
154 Value *LHS = codegen(e->LHS, Ty);
155
156 APInt RHS_AP = APInt_from_MPZ(e->RHS);
157
158 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
159 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
160
161 switch (e->type) {
162 case clast_bin_mod:
163 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000164 case clast_bin_fdiv: {
165 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
166 Value *One = ConstantInt::get(Ty, 1);
167 Value *Zero = ConstantInt::get(Ty, 0);
168 Value *Sum1 = Builder.CreateSub(LHS, RHS);
169 Value *Sum2 = Builder.CreateAdd(Sum1, One);
170 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
171 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
172 return Builder.CreateSDiv(Dividend, RHS);
173 }
174 case clast_bin_cdiv: {
175 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
176 Value *One = ConstantInt::get(Ty, 1);
177 Value *Zero = ConstantInt::get(Ty, 0);
178 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
179 Value *Sum2 = Builder.CreateSub(Sum1, One);
180 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
181 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
182 return Builder.CreateSDiv(Dividend, RHS);
183 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000184 case clast_bin_div:
185 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000186 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000187
188 llvm_unreachable("Unknown clast binary expression type");
189}
190
191Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000192 assert((r->type == clast_red_min || r->type == clast_red_max ||
Tobias Grosser58032cb2013-06-23 01:29:29 +0000193 r->type == clast_red_sum) &&
194 "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000195 Value *old = codegen(r->elts[0], Ty);
196
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000197 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000198 Value *exprValue = codegen(r->elts[i], Ty);
199
200 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000201 case clast_red_min: {
202 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
203 old = Builder.CreateSelect(cmp, old, exprValue);
204 break;
205 }
206 case clast_red_max: {
207 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
208 old = Builder.CreateSelect(cmp, old, exprValue);
209 break;
210 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000211 case clast_red_sum:
212 old = Builder.CreateAdd(old, exprValue);
213 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000214 }
Tobias Grosser75805372011-04-29 06:27:02 +0000215 }
216
Tobias Grosserbb137e32012-01-24 16:42:28 +0000217 return old;
218}
219
Tobias Grosser5103ba72014-03-04 14:58:49 +0000220ClastExpCodeGen::ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000221 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000222
223Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000224 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000225 case clast_expr_name:
226 return codegen((const clast_name *)e, Ty);
227 case clast_expr_term:
228 return codegen((const clast_term *)e, Ty);
229 case clast_expr_bin:
230 return codegen((const clast_binary *)e, Ty);
231 case clast_expr_red:
232 return codegen((const clast_reduction *)e, Ty);
233 }
234
235 llvm_unreachable("Unknown clast expression!");
236}
237
Tobias Grosser75805372011-04-29 06:27:02 +0000238class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000239public:
240 const std::vector<std::string> &getParallelLoops();
241
242private:
Tobias Grosser75805372011-04-29 06:27:02 +0000243 // The Scop we code generate.
244 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000245 Pass *P;
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000246 LoopInfo &LI;
247 ScalarEvolution &SE;
248 DominatorTree &DT;
Tobias Grosser75805372011-04-29 06:27:02 +0000249
250 // The Builder specifies the current location to code generate at.
Tobias Grosser5103ba72014-03-04 14:58:49 +0000251 PollyIRBuilder &Builder;
Tobias Grosser75805372011-04-29 06:27:02 +0000252
253 // Map the Values from the old code to their counterparts in the new code.
254 ValueMapT ValueMap;
255
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000256 // Map the loops from the old code to expressions function of the induction
257 // variables in the new code. For example, when the code generator produces
258 // this AST:
259 //
260 // for (int c1 = 0; c1 <= 1023; c1 += 1)
261 // for (int c2 = 0; c2 <= 1023; c2 += 1)
262 // Stmt(c2 + 3, c1);
263 //
264 // LoopToScev is a map associating:
265 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
266 // "inner loop in the old loop nest" -> SCEV("c1").
267 LoopToScevMapT LoopToScev;
268
Tobias Grosser75805372011-04-29 06:27:02 +0000269 // clastVars maps from the textual representation of a clast variable to its
270 // current *Value. clast variables are scheduling variables, original
271 // induction variables or parameters. They are used either in loop bounds or
272 // to define the statement instance that is executed.
273 //
274 // for (s = 0; s < n + 3; ++i)
275 // for (t = s; t < m; ++j)
276 // Stmt(i = s + 3 * m, j = t);
277 //
278 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000279 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000280
281 // Codegenerator for clast expressions.
282 ClastExpCodeGen ExpGen;
283
284 // Do we currently generate parallel code?
285 bool parallelCodeGeneration;
286
287 std::vector<std::string> parallelLoops;
288
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000289 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000290
Tobias Grossere602a072013-05-07 07:30:56 +0000291 void codegen(const clast_assignment *a, ScopStmt *Statement,
292 unsigned Dimension, int vectorDim,
293 std::vector<ValueMapT> *VectorVMap = 0,
294 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000295
Tobias Grosserc14582f2013-02-05 18:01:29 +0000296 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
297 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000298 std::vector<ValueMapT> *VectorVMap = 0,
299 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000300
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000301 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = nullptr,
302 const char *iterator = nullptr,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000303 __isl_take isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000304
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000305 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000306
307 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000308 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000309
310 /// @brief Create OpenMP structure values.
311 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000312 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000313 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000314 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000315
Tobias Grossera17f6662012-11-01 05:34:35 +0000316 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000317 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000318 /// @param VMap A map from old to new values.
319 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000320
321 /// @brief Create an OpenMP parallel for loop.
322 ///
323 /// This loop reflects a loop as if it would have been created by an OpenMP
324 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000325 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000326
Tobias Grosser6217e182012-08-03 12:50:07 +0000327#ifdef GPU_CODEGEN
328 /// @brief Create GPGPU device memory access values.
329 ///
330 /// Create a list of values that will be set to be parameters of the GPGPU
331 /// subfunction. These parameters represent device memory base addresses
332 /// and the size in bytes.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000333 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000334
335 /// @brief Create a GPU parallel for loop.
336 ///
337 /// This loop reflects a loop as if it would have been created by a GPU
338 /// statement.
339 void codegenForGPGPU(const clast_for *F);
340
341 /// @brief Get innermost for loop.
Tobias Grossere602a072013-05-07 07:30:56 +0000342 const clast_stmt *getScheduleInfo(const clast_for *F,
343 std::vector<int> &NumIters,
344 unsigned &LoopDepth,
345 unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000346#endif /* GPU_CODEGEN */
347
Tobias Grossere192b232012-05-22 08:46:07 +0000348 /// @brief Check if a loop is parallel
349 ///
350 /// Detect if a clast_for loop can be executed in parallel.
351 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000352 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000353 ///
354 /// @return bool Returns true if the incoming clast_for statement can
355 /// execute in parallel.
356 bool isParallelFor(const clast_for *For);
357
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000358 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000359
360 /// @brief Get the number of loop iterations for this loop.
361 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000362 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000363
364 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000365 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000367 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000368
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000369 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000371 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000372
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000373 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000374
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000375 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000376
Tobias Grossere9ffea22012-03-15 09:34:48 +0000377 IntegerType *getIntPtrTy();
378
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000379public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000380 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000381
Tobias Grosser5103ba72014-03-04 14:58:49 +0000382 ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000383};
384}
385
Tobias Grossere9ffea22012-03-15 09:34:48 +0000386IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Rafael Espindolac5d16892014-02-25 19:17:57 +0000387 return P->getAnalysis<DataLayoutPass>().getDataLayout().getIntPtrType(
388 Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000389}
390
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000391const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
392 return parallelLoops;
393}
394
395void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000396 Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000397 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000398}
399
Tobias Grossere602a072013-05-07 07:30:56 +0000400void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
401 unsigned Dim, int VectorDim,
402 std::vector<ValueMapT> *VectorVMap,
403 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosserf00bd962012-04-02 12:26:13 +0000404 Value *RHS;
405
406 assert(!A->LHS && "Statement assignments do not have left hand side");
407
Tobias Grosser0905a232012-04-03 12:24:32 +0000408 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000409
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000410 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
411 if (VLTS)
412 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000413 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000414
415 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
416 if (PN) {
417 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
418
419 if (VectorVMap)
420 (*VectorVMap)[VectorDim][PN] = RHS;
421
422 ValueMap[PN] = RHS;
423 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000424}
425
Tobias Grossere602a072013-05-07 07:30:56 +0000426void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
427 ScopStmt *Statement, int vectorDim,
428 std::vector<ValueMapT> *VectorVMap,
429 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000430 int Dimension = 0;
431
432 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000433 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
434 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000435 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000436 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000437 Assignment = Assignment->next;
438 Dimension++;
439 }
440}
441
Sebastian Popa00a0292012-12-18 07:46:06 +0000442// Takes the cloog specific domain and translates it into a map Statement ->
443// PartialSchedule, where the PartialSchedule contains all the dimensions that
444// have been code generated up to this point.
Tobias Grossere602a072013-05-07 07:30:56 +0000445static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000446 __isl_take isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000447 isl_map *Schedule = Statement->getScattering();
448 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000449 int UnscheduledDimensions =
450 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000451
Tobias Grosser880c52f2013-07-29 01:58:07 +0000452 isl_set_free(Domain);
453
Sebastian Popa00a0292012-12-18 07:46:06 +0000454 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
455 UnscheduledDimensions);
456}
457
Tobias Grossere602a072013-05-07 07:30:56 +0000458void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
459 std::vector<Value *> *IVS, const char *iterator,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000460 __isl_take isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000461 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000462
463 if (u->substitutions)
464 codegenSubstitutions(u->substitutions, Statement);
465
Tobias Grosser80998e72012-03-02 11:27:28 +0000466 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000467
Tobias Grosser80998e72012-03-02 11:27:28 +0000468 if (VectorDimensions == 1) {
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000469 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P, LI,
470 SE);
Tobias Grosserefc30132014-04-14 08:33:24 +0000471 isl_set_free(Domain);
Tobias Grosser80998e72012-03-02 11:27:28 +0000472 return;
473 }
474
475 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000476 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000477
478 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000479 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000480 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000481 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000482 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000483 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000484 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000485 i++;
486 }
487 }
488
Tobias Grosser75b76722014-04-15 22:30:06 +0000489 // Copy the current value map into all vector maps if the key wasn't
490 // available yet. This is needed in case vector codegen is performed in
491 // OpenMP subfunctions.
492 for (auto KV : ValueMap)
493 for (int i = 0; i < VectorDimensions; ++i)
494 VectorMap[i].insert(KV);
495
Sebastian Popa00a0292012-12-18 07:46:06 +0000496 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000497 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000498 P, LI, SE);
Sebastian Popa00a0292012-12-18 07:46:06 +0000499 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000500}
501
502void ClastStmtCodeGen::codegen(const clast_block *b) {
503 if (b->body)
504 codegen(b->body);
505}
506
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000507void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
508 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000509 BasicBlock *ExitBlock;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000510 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000511
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000512 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
513 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
514 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000515
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000516 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, LI, DT, ExitBlock,
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000517 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000518
519 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000520 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000521
522 if (f->body)
523 codegen(f->body);
524
525 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000526 ClastVars.erase(f->iterator);
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000527 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000528}
529
Tobias Grosser177982c2012-11-01 05:34:48 +0000530// Helper class to determine all scalar parameters used in the basic blocks of a
531// clast. Scalar parameters are scalar variables defined outside of the SCoP.
532class ParameterVisitor : public ClastVisitor {
533 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000534
Tobias Grosser177982c2012-11-01 05:34:48 +0000535public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000536 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000537
538 void visitUser(const clast_user_stmt *Stmt) {
539 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
540 const BasicBlock *BB = S->getBasicBlock();
541
542 // Check all the operands of instructions in the basic block.
Tobias Grosser083d3d32014-06-28 08:59:45 +0000543 for (const Instruction &Inst : *BB) {
544 for (Value *SrcVal : Inst.operands()) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000545 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
546 if (S->getParent()->getRegion().contains(OpInst))
547 continue;
548
549 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
550 Values.insert(SrcVal);
551 }
552 }
553 }
554
555 // Iterator to iterate over the values found.
556 typedef std::set<Value *>::const_iterator const_iterator;
557 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000558 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000559};
560
Tobias Grosserc14582f2013-02-05 18:01:29 +0000561SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
562 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000563
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000564 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000565 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
566 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000567 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000568
Tobias Grosser177982c2012-11-01 05:34:48 +0000569 // Find the temporaries that are referenced in the clast statements'
570 // basic blocks but are not defined by these blocks (e.g., references
571 // to function arguments or temporaries defined before the start of
572 // the SCoP).
573 ParameterVisitor Params;
574 Params.visit(Body);
575
576 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
577 PI != PE; ++PI) {
578 Value *V = *PI;
579 Values.insert(V);
580 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
581 }
582
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000583 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000584}
585
Tobias Grosserd7e58642013-04-10 06:55:45 +0000586void
587ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000588 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000589
Tobias Grosserc14582f2013-02-05 18:01:29 +0000590 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
591 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000592 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000593 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000594 }
595
Tobias Grossera17f6662012-11-01 05:34:35 +0000596 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000597 E = VMap.end();
598 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000599 if (Inserted.count(I->first))
600 continue;
601
602 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000603 }
604}
605
Tobias Grosser900893d2012-03-29 13:10:26 +0000606static void clearDomtree(Function *F, DominatorTree &DT) {
607 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000608 std::vector<BasicBlock *> Nodes;
609 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000610 Nodes.push_back(I->getBlock());
611
Tobias Grosserc14582f2013-02-05 18:01:29 +0000612 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000613 I != E; ++I)
614 DT.eraseNode(*I);
615}
616
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000617void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000618 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000619 BasicBlock::iterator LoopBody;
620 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000621 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000622 OMPGenerator::ValueToValueMapTy VMap;
623 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000624
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000625 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
626 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000627 LB = ExpGen.codegen(For->LB, IntPtrTy);
628 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000629
Tobias Grosser177982c2012-11-01 05:34:48 +0000630 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000631
Tobias Grosserebf30082012-03-23 12:20:32 +0000632 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000633 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
634 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000635
Tobias Grossera17f6662012-11-01 05:34:35 +0000636 // Save the current values.
637 const ValueMapT ValueMapCopy = ValueMap;
638 const CharMapT ClastVarsCopy = ClastVars;
639
640 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000641 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000642
643 if (For->body)
644 codegen(For->body);
645
Tobias Grossera17f6662012-11-01 05:34:35 +0000646 // Restore the original values.
647 ValueMap = ValueMapCopy;
648 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000649
Tobias Grosser900893d2012-03-29 13:10:26 +0000650 clearDomtree((*LoopBody).getParent()->getParent(),
Tobias Grosser42aff302014-01-13 22:29:56 +0000651 P->getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Tobias Grosser900893d2012-03-29 13:10:26 +0000652
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000653 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000654}
655
Tobias Grosser6217e182012-08-03 12:50:07 +0000656#ifdef GPU_CODEGEN
657static unsigned getArraySizeInBytes(const ArrayType *AT) {
658 unsigned Bytes = AT->getNumElements();
659 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
660 Bytes *= getArraySizeInBytes(T);
661 else
662 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
663
664 return Bytes;
665}
666
Tobias Grosserc14582f2013-02-05 18:01:29 +0000667SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
668 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000669 OutputBytes = 0;
670
671 // Record the memory reference base addresses.
Tobias Grosser868832b2014-06-19 16:45:04 +0000672 for (ScopStmt *Stmt : *S) {
673 for (MemoryAccess *MA : *Stmt) {
Johannes Doerfertd9e1dbd32014-07-29 08:36:18 +0000674 Value *BaseAddr = MA->getBaseAddr();
Tobias Grosser6217e182012-08-03 12:50:07 +0000675 Values.insert((BaseAddr));
676
677 // FIXME: we assume that there is one and only one array to be written
678 // in a SCoP.
679 int NumWrites = 0;
Tobias Grosser868832b2014-06-19 16:45:04 +0000680 if (MA->isWrite()) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000681 ++NumWrites;
682 assert(NumWrites <= 1 &&
683 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000684 if (const PointerType *PT =
685 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000686 Type *T = PT->getArrayElementType();
687 const ArrayType *ATy = dyn_cast<ArrayType>(T);
688 OutputBytes = getArraySizeInBytes(ATy);
689 }
690 }
691 }
692 }
693
694 return Values;
695}
696
Tobias Grossere602a072013-05-07 07:30:56 +0000697const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
698 std::vector<int> &NumIters,
699 unsigned &LoopDepth,
700 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000701 clast_stmt *Stmt = (clast_stmt *)F;
702 const clast_for *Result;
703 bool NonParaFlag = false;
704 LoopDepth = 0;
705 NonPLoopDepth = 0;
706
707 while (Stmt) {
708 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000709 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000710 if (isParallelFor(T)) {
711 if (!NonParaFlag) {
712 NumIters.push_back(getNumberOfIterations(T));
713 Result = T;
714 }
715 } else
716 NonParaFlag = true;
717
718 Stmt = T->body;
719 LoopDepth++;
720 continue;
721 }
722 Stmt = Stmt->next;
723 }
724
725 assert(NumIters.size() == 4 &&
726 "The loops should be tiled into 4-depth parallel loops and an "
727 "innermost non-parallel one (if exist).");
728 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000729 assert(NonPLoopDepth <= 1 &&
730 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000731 return (const clast_stmt *)Result->body;
732}
733
734void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
735 BasicBlock::iterator LoopBody;
736 SetVector<Value *> Values;
737 SetVector<Value *> IVS;
738 std::vector<int> NumIterations;
739 PTXGenerator::ValueToValueMapTy VMap;
740
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000741 assert(!GPUTriple.empty() &&
742 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000743 PTXGenerator PTXGen(Builder, P, GPUTriple);
744
745 // Get original IVS and ScopStmt
746 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000747 const clast_stmt *InnerStmt =
748 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000749 const clast_stmt *TmpStmt;
750 const clast_user_stmt *U;
751 const clast_for *InnerFor;
752 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
753 InnerFor = (const clast_for *)InnerStmt;
754 TmpStmt = InnerFor->body;
755 } else
756 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000757 U = (const clast_user_stmt *)TmpStmt;
758 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000759 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000760 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000761 IVS.insert(const_cast<Value *>(IV));
762 }
763
764 unsigned OutBytes;
765 Values = getGPUValues(OutBytes);
766 PTXGen.setOutputBytes(OutBytes);
767 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
768
769 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
770 Builder.SetInsertPoint(LoopBody);
771
772 BasicBlock *AfterBB = 0;
773 if (NonPLoopDepth) {
774 Value *LowerBound, *UpperBound, *IV, *Stride;
775 Type *IntPtrTy = getIntPtrTy();
776 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
777 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
778 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000779 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, LI, DT, AfterBB,
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000780 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000781 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
782 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserba1724d2014-05-07 10:06:33 +0000783 VMap.insert(std::make_pair(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000784 }
785
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000786 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000787
Johannes Doerfertc5129d82014-08-08 04:23:13 +0000788 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P, LI,
789 SE);
Tobias Grossera17f6662012-11-01 05:34:35 +0000790
Tobias Grosser6217e182012-08-03 12:50:07 +0000791 if (AfterBB)
792 Builder.SetInsertPoint(AfterBB->begin());
793
794 // FIXME: The replacement of the host base address with the parameter of ptx
795 // subfunction should have been done by updateWithValueMap. We use the
796 // following codes to avoid affecting other parts of Polly. This should be
797 // fixed later.
798 Function *FN = Builder.GetInsertBlock()->getParent();
799 for (unsigned j = 0; j < Values.size(); j++) {
800 Value *baseAddr = Values[j];
801 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
802 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
803 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
804 }
805 }
806 Builder.SetInsertPoint(AfterLoop);
807 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
808 NumIterations[2], NumIterations[3]);
809 PTXGen.finishGeneration(FN);
810}
811#endif
812
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000813bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
814 const clast_stmt *stmt = f->body;
815
816 while (stmt) {
817 if (!CLAST_STMT_IS_A(stmt, stmt_user))
818 return false;
819
820 stmt = stmt->next;
821 }
822
823 return true;
824}
825
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000826int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
827 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000828 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
829 if (NumberOfIterations == -1)
830 return -1;
Tobias Grosserb8cd4a82014-01-19 11:31:23 +0000831 return NumberOfIterations / mpz_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000832}
833
Tobias Grosser2da263e2012-03-15 09:34:55 +0000834void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
835 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
836 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000837
Tobias Grosser2da263e2012-03-15 09:34:55 +0000838 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000839
Tobias Grosser2da263e2012-03-15 09:34:55 +0000840 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000841 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000842 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000843 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
844
Tobias Grosserc14582f2013-02-05 18:01:29 +0000845 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000846 IVS[0] = LB;
847
Tobias Grosser2da263e2012-03-15 09:34:55 +0000848 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000849 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000850
Tobias Grosser880c52f2013-07-29 01:58:07 +0000851 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(F->domain));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000852
853 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000854 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000855
Tobias Grosser2da263e2012-03-15 09:34:55 +0000856 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000857
Tobias Grosser2da263e2012-03-15 09:34:55 +0000858 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000859 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
860 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000861 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000862 }
863
864 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000865 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000866 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000867}
868
Johannes Doerfert515f8572014-07-28 03:46:28 +0000869static isl_union_map *getCombinedScheduleForSpace(Scop *S, unsigned dimLevel) {
870 isl_space *Space = S->getParamSpace();
871 isl_union_map *schedule = isl_union_map_empty(Space);
872
873 for (ScopStmt *Stmt : *S) {
874 unsigned remainingDimensions = Stmt->getNumScattering() - dimLevel;
875 isl_map *Scattering = isl_map_project_out(
876 Stmt->getScattering(), isl_dim_out, dimLevel, remainingDimensions);
877 schedule = isl_union_map_add_map(schedule, Scattering);
878 }
879
880 return schedule;
881}
882
Tobias Grossere192b232012-05-22 08:46:07 +0000883bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
Tobias Grosser880c52f2013-07-29 01:58:07 +0000884 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000885 assert(Domain && "Cannot access domain of loop");
886
887 Dependences &D = P->getAnalysis<Dependences>();
Johannes Doerfert515f8572014-07-28 03:46:28 +0000888 isl_union_map *Deps =
889 D.getDependences(Dependences::TYPE_RAW | Dependences::TYPE_WAW |
890 Dependences::TYPE_WAR | Dependences::TYPE_RAW);
891 isl_union_map *Schedule =
892 getCombinedScheduleForSpace(S, isl_set_n_dim(Domain));
893 Schedule =
894 isl_union_map_intersect_range(Schedule, isl_union_set_from_set(Domain));
895 bool IsParallel = D.isParallel(Schedule, Deps);
896 isl_union_map_free(Schedule);
897 return IsParallel;
Tobias Grossere192b232012-05-22 08:46:07 +0000898}
899
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000900void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000901 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000902 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000903 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
904 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000905 codegenForVector(f);
906 return;
907 }
908
909 if (OpenMP && !parallelCodeGeneration) {
910 parallelCodeGeneration = true;
911 parallelLoops.push_back(f->iterator);
912 codegenForOpenMP(f);
913 parallelCodeGeneration = false;
914 return;
915 }
916 }
917
Tobias Grosser6217e182012-08-03 12:50:07 +0000918#ifdef GPU_CODEGEN
919 if (GPGPU && isParallelFor(f)) {
920 if (!parallelCodeGeneration) {
921 parallelCodeGeneration = true;
922 parallelLoops.push_back(f->iterator);
923 codegenForGPGPU(f);
924 parallelCodeGeneration = false;
925 return;
926 }
927 }
928#endif
929
Tobias Grosserce3f5372012-03-02 11:26:42 +0000930 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000931}
932
933Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000934 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
935 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000936 CmpInst::Predicate P;
937
938 if (eq->sign == 0)
939 P = ICmpInst::ICMP_EQ;
940 else if (eq->sign > 0)
941 P = ICmpInst::ICMP_SGE;
942 else
943 P = ICmpInst::ICMP_SLE;
944
945 return Builder.CreateICmp(P, LHS, RHS);
946}
947
948void ClastStmtCodeGen::codegen(const clast_guard *g) {
949 Function *F = Builder.GetInsertBlock()->getParent();
950 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000951
Tobias Grosserc14582f2013-02-05 18:01:29 +0000952 BasicBlock *CondBB =
953 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000954 CondBB->setName("polly.cond");
955 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
956 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000957 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000958
Tobias Grosser42aff302014-01-13 22:29:56 +0000959 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosserd596b372012-03-15 09:34:52 +0000960 DT.addNewBlock(ThenBB, CondBB);
961 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000962
963 CondBB->getTerminator()->eraseFromParent();
964
965 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000966
967 Value *Predicate = codegen(&(g->eq[0]));
968
969 for (int i = 1; i < g->n; ++i) {
970 Value *TmpPredicate = codegen(&(g->eq[i]));
971 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
972 }
973
974 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
975 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000976 Builder.CreateBr(MergeBB);
977 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000978
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000979 LoopInfo &LI = P->getAnalysis<LoopInfo>();
980 Loop *L = LI.getLoopFor(CondBB);
Tobias Grosser815c6352013-09-02 16:13:00 +0000981 if (L)
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000982 L->addBasicBlockToLoop(ThenBB, LI.getBase());
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000983
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000985
986 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000987}
988
989void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000990 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 assert(false && "No second root statement expected");
992 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
993 codegen((const clast_assignment *)stmt);
994 else if (CLAST_STMT_IS_A(stmt, stmt_user))
995 codegen((const clast_user_stmt *)stmt);
996 else if (CLAST_STMT_IS_A(stmt, stmt_block))
997 codegen((const clast_block *)stmt);
998 else if (CLAST_STMT_IS_A(stmt, stmt_for))
999 codegen((const clast_for *)stmt);
1000 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1001 codegen((const clast_guard *)stmt);
1002
1003 if (stmt->next)
1004 codegen(stmt->next);
1005}
1006
1007void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +00001008 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001009
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001010 int i = 0;
1011 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1012 PI != PE; ++PI) {
1013 assert(i < names->nb_parameters && "Not enough parameter names");
1014
1015 const SCEV *Param = *PI;
1016 Type *Ty = Param->getType();
1017
1018 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1019 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +00001020 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001021
1022 ++i;
1023 }
1024}
1025
1026void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001027 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001028
1029 parallelCodeGeneration = false;
1030
Tobias Grosserc14582f2013-02-05 18:01:29 +00001031 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001032 if (stmt->next)
1033 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001034}
1035
Tobias Grosser5103ba72014-03-04 14:58:49 +00001036ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P)
Johannes Doerfertc5129d82014-08-08 04:23:13 +00001037 : S(scop), P(P), LI(P->getAnalysis<LoopInfo>()),
1038 SE(P->getAnalysis<ScalarEvolution>()),
1039 DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()), Builder(B),
1040 ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001041
Tobias Grosser75805372011-04-29 06:27:02 +00001042namespace {
1043class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001044 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001045
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001046public:
Tobias Grosser75805372011-04-29 06:27:02 +00001047 static char ID;
1048
1049 CodeGeneration() : ScopPass(ID) {}
1050
Tobias Grosser3a275d22012-05-29 09:11:54 +00001051 bool runOnScop(Scop &S) {
1052 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001053
Tobias Grossere602a072013-05-07 07:30:56 +00001054 assert(!S.getRegion().isTopLevelRegion() &&
1055 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001056
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001057 simplifyRegion(&S, this);
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001058
Johannes Doerfert9744c4a2014-08-12 18:35:54 +00001059 Value *RTC = ConstantInt::getTrue(S.getRegionEntry()->getContext());
1060 BasicBlock *StartBlock = executeScopConditionally(S, this, RTC);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001061
Tobias Grosser5103ba72014-03-04 14:58:49 +00001062 PollyIRBuilder Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001063
Tobias Grosser3a275d22012-05-29 09:11:54 +00001064 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001065 CloogInfo &C = getAnalysis<CloogInfo>();
1066 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001067
Tobias Grosser3a275d22012-05-29 09:11:54 +00001068 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001069 CodeGen.getParallelLoops().begin(),
1070 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001071 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001072 }
1073
1074 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001075 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001076 PE = ParallelLoops.end();
1077 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001078 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1079 }
1080
1081 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1082 AU.addRequired<CloogInfo>();
1083 AU.addRequired<Dependences>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001084 AU.addRequired<DominatorTreeWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001085 AU.addRequired<RegionInfoPass>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001086 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001087 AU.addRequired<ScopDetection>();
1088 AU.addRequired<ScopInfo>();
Rafael Espindolac5d16892014-02-25 19:17:57 +00001089 AU.addRequired<DataLayoutPass>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001090 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001091
1092 AU.addPreserved<CloogInfo>();
1093 AU.addPreserved<Dependences>();
1094 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001095 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001096 AU.addPreserved<ScopDetection>();
1097 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001098
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001099 // FIXME: We do not yet add regions for the newly generated code to the
1100 // region tree.
Matt Arsenault8ca36812014-07-19 18:40:17 +00001101 AU.addPreserved<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001102 AU.addPreserved<TempScopInfo>();
1103 AU.addPreserved<ScopInfo>();
1104 AU.addPreservedID(IndependentBlocksID);
1105 }
1106};
1107}
1108
1109char CodeGeneration::ID = 1;
1110
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001111Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001112
Tobias Grosser7242ad92013-02-22 08:07:06 +00001113INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1114 "Polly - Create LLVM-IR from SCoPs", false, false);
1115INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1116INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001117INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001118INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001119INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1120INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Rafael Espindolac5d16892014-02-25 19:17:57 +00001121INITIALIZE_PASS_DEPENDENCY(DataLayoutPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001122INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001123 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001124
Sebastian Pope1f65542012-05-07 16:35:11 +00001125#endif // CLOOG_FOUND