blob: d7270bd48e05f08436842500eb6e5ba29be378cc [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
26#define DEBUG_TYPE "polly-codegen"
Tobias Grosser75805372011-04-29 06:27:02 +000027#include "polly/Dependences.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000028#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000029#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/ScopInfo.h"
31#include "polly/TempScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000032#include "polly/CodeGen/CodeGeneration.h"
33#include "polly/CodeGen/BlockGenerators.h"
34#include "polly/CodeGen/LoopGenerators.h"
Tobias Grosser6217e182012-08-03 12:50:07 +000035#include "polly/CodeGen/PTXGenerator.h"
Tobias Grosser3a275d22012-05-29 09:11:54 +000036#include "polly/CodeGen/Utils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000037#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000038#include "polly/Support/ScopHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000039
Chandler Carruth535d52c2013-01-02 11:47:44 +000040#include "llvm/IR/Module.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000042#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000043#include "llvm/Analysis/LoopInfo.h"
44#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000045#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000046#include "llvm/IR/DataLayout.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048
49#define CLOOG_INT_GMP 1
50#include "cloog/cloog.h"
51#include "cloog/isl/cloog.h"
52
Raghesh Aloora71989c2011-12-28 02:48:26 +000053#include "isl/aff.h"
54
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <vector>
56#include <utility>
57
58using namespace polly;
59using namespace llvm;
60
61struct isl_set;
62
63namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000064static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000065OpenMP("enable-polly-openmp", cl::desc("Generate OpenMP parallel code"),
Tobias Grosser637bd632013-05-07 07:31:10 +000066 cl::value_desc("OpenMP code generation enabled if true"),
67 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser75805372011-04-29 06:27:02 +000068
Tobias Grosser6217e182012-08-03 12:50:07 +000069#ifdef GPU_CODEGEN
70static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000071GPGPU("enable-polly-gpgpu", cl::desc("Generate GPU parallel code"), cl::Hidden,
72 cl::value_desc("GPGPU code generation enabled if true"), cl::init(false),
Tobias Grosser637bd632013-05-07 07:31:10 +000073 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000074
Tobias Grossere602a072013-05-07 07:30:56 +000075static cl::opt<std::string>
76GPUTriple("polly-gpgpu-triple",
77 cl::desc("Target triple for GPU code generation"), cl::Hidden,
Tobias Grosser637bd632013-05-07 07:31:10 +000078 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000079#endif /* GPU_CODEGEN */
80
Tobias Grosserc14582f2013-02-05 18:01:29 +000081typedef DenseMap<const char *, Value *> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000082
Tobias Grosser75805372011-04-29 06:27:02 +000083/// Class to generate LLVM-IR that calculates the value of a clast_expr.
84class ClastExpCodeGen {
Tobias Grosser5103ba72014-03-04 14:58:49 +000085 PollyIRBuilder &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000086 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000087
Tobias Grosserbb137e32012-01-24 16:42:28 +000088 Value *codegen(const clast_name *e, Type *Ty);
89 Value *codegen(const clast_term *e, Type *Ty);
90 Value *codegen(const clast_binary *e, Type *Ty);
91 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosserd7e58642013-04-10 06:55:45 +000092
Tobias Grosser75805372011-04-29 06:27:02 +000093public:
Tobias Grosser75805372011-04-29 06:27:02 +000094 // A generator for clast expressions.
95 //
96 // @param B The IRBuilder that defines where the code to calculate the
97 // clast expressions should be inserted.
98 // @param IVMAP A Map that translates strings describing the induction
99 // variables to the Values* that represent these variables
100 // on the LLVM side.
Tobias Grosser5103ba72014-03-04 14:58:49 +0000101 ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000102
103 // Generates code to calculate a given clast expression.
104 //
105 // @param e The expression to calculate.
106 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000107 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000108};
109
110Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000111 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000112
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000113 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000114
115 return Builder.CreateSExtOrBitCast(I->second, Ty);
116}
117
Sebastian Popbfec3612014-02-22 02:15:39 +0000118static APInt APInt_from_MPZ(const mpz_t mpz) {
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000119 uint64_t *p = nullptr;
Sebastian Popbfec3612014-02-22 02:15:39 +0000120 size_t sz;
121
122 p = (uint64_t *)mpz_export(p, &sz, -1, sizeof(uint64_t), 0, 0, mpz);
123
124 if (p) {
125 APInt A((unsigned)mpz_sizeinbase(mpz, 2), (unsigned)sz, p);
126 A = A.zext(A.getBitWidth() + 1);
127 free(p);
128
129 if (mpz_sgn(mpz) == -1)
130 return -A;
131 else
132 return A;
133 } else {
134 uint64_t val = 0;
135 return APInt(1, 1, &val);
136 }
137}
138
Tobias Grosserbb137e32012-01-24 16:42:28 +0000139Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
140 APInt a = APInt_from_MPZ(e->val);
141
142 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
143 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
144
145 if (!e->var)
146 return ConstOne;
147
148 Value *var = codegen(e->var, Ty);
149 return Builder.CreateMul(ConstOne, var);
150}
151
152Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
153 Value *LHS = codegen(e->LHS, Ty);
154
155 APInt RHS_AP = APInt_from_MPZ(e->RHS);
156
157 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
158 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
159
160 switch (e->type) {
161 case clast_bin_mod:
162 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000163 case clast_bin_fdiv: {
164 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
165 Value *One = ConstantInt::get(Ty, 1);
166 Value *Zero = ConstantInt::get(Ty, 0);
167 Value *Sum1 = Builder.CreateSub(LHS, RHS);
168 Value *Sum2 = Builder.CreateAdd(Sum1, One);
169 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
170 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
171 return Builder.CreateSDiv(Dividend, RHS);
172 }
173 case clast_bin_cdiv: {
174 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
175 Value *One = ConstantInt::get(Ty, 1);
176 Value *Zero = ConstantInt::get(Ty, 0);
177 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
178 Value *Sum2 = Builder.CreateSub(Sum1, One);
179 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
180 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
181 return Builder.CreateSDiv(Dividend, RHS);
182 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000183 case clast_bin_div:
184 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000185 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000186
187 llvm_unreachable("Unknown clast binary expression type");
188}
189
190Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000191 assert((r->type == clast_red_min || r->type == clast_red_max ||
Tobias Grosser58032cb2013-06-23 01:29:29 +0000192 r->type == clast_red_sum) &&
193 "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000194 Value *old = codegen(r->elts[0], Ty);
195
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000196 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000197 Value *exprValue = codegen(r->elts[i], Ty);
198
199 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000200 case clast_red_min: {
201 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
202 old = Builder.CreateSelect(cmp, old, exprValue);
203 break;
204 }
205 case clast_red_max: {
206 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
207 old = Builder.CreateSelect(cmp, old, exprValue);
208 break;
209 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000210 case clast_red_sum:
211 old = Builder.CreateAdd(old, exprValue);
212 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000213 }
Tobias Grosser75805372011-04-29 06:27:02 +0000214 }
215
Tobias Grosserbb137e32012-01-24 16:42:28 +0000216 return old;
217}
218
Tobias Grosser5103ba72014-03-04 14:58:49 +0000219ClastExpCodeGen::ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000220 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000221
222Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000223 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000224 case clast_expr_name:
225 return codegen((const clast_name *)e, Ty);
226 case clast_expr_term:
227 return codegen((const clast_term *)e, Ty);
228 case clast_expr_bin:
229 return codegen((const clast_binary *)e, Ty);
230 case clast_expr_red:
231 return codegen((const clast_reduction *)e, Ty);
232 }
233
234 llvm_unreachable("Unknown clast expression!");
235}
236
Tobias Grosser75805372011-04-29 06:27:02 +0000237class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000238public:
239 const std::vector<std::string> &getParallelLoops();
240
241private:
Tobias Grosser75805372011-04-29 06:27:02 +0000242 // The Scop we code generate.
243 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000244 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000245
246 // The Builder specifies the current location to code generate at.
Tobias Grosser5103ba72014-03-04 14:58:49 +0000247 PollyIRBuilder &Builder;
Tobias Grosser75805372011-04-29 06:27:02 +0000248
249 // Map the Values from the old code to their counterparts in the new code.
250 ValueMapT ValueMap;
251
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000252 // Map the loops from the old code to expressions function of the induction
253 // variables in the new code. For example, when the code generator produces
254 // this AST:
255 //
256 // for (int c1 = 0; c1 <= 1023; c1 += 1)
257 // for (int c2 = 0; c2 <= 1023; c2 += 1)
258 // Stmt(c2 + 3, c1);
259 //
260 // LoopToScev is a map associating:
261 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
262 // "inner loop in the old loop nest" -> SCEV("c1").
263 LoopToScevMapT LoopToScev;
264
Tobias Grosser75805372011-04-29 06:27:02 +0000265 // clastVars maps from the textual representation of a clast variable to its
266 // current *Value. clast variables are scheduling variables, original
267 // induction variables or parameters. They are used either in loop bounds or
268 // to define the statement instance that is executed.
269 //
270 // for (s = 0; s < n + 3; ++i)
271 // for (t = s; t < m; ++j)
272 // Stmt(i = s + 3 * m, j = t);
273 //
274 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000275 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000276
277 // Codegenerator for clast expressions.
278 ClastExpCodeGen ExpGen;
279
280 // Do we currently generate parallel code?
281 bool parallelCodeGeneration;
282
283 std::vector<std::string> parallelLoops;
284
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000285 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000286
Tobias Grossere602a072013-05-07 07:30:56 +0000287 void codegen(const clast_assignment *a, ScopStmt *Statement,
288 unsigned Dimension, int vectorDim,
289 std::vector<ValueMapT> *VectorVMap = 0,
290 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000291
Tobias Grosserc14582f2013-02-05 18:01:29 +0000292 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
293 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000294 std::vector<ValueMapT> *VectorVMap = 0,
295 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000296
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000297 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = nullptr,
298 const char *iterator = nullptr,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000299 __isl_take isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000300
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000301 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000302
303 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000304 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000305
306 /// @brief Create OpenMP structure values.
307 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000308 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000309 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000310 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000311
Tobias Grossera17f6662012-11-01 05:34:35 +0000312 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000313 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000314 /// @param VMap A map from old to new values.
315 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000316
317 /// @brief Create an OpenMP parallel for loop.
318 ///
319 /// This loop reflects a loop as if it would have been created by an OpenMP
320 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000321 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000322
Tobias Grosser6217e182012-08-03 12:50:07 +0000323#ifdef GPU_CODEGEN
324 /// @brief Create GPGPU device memory access values.
325 ///
326 /// Create a list of values that will be set to be parameters of the GPGPU
327 /// subfunction. These parameters represent device memory base addresses
328 /// and the size in bytes.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000329 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000330
331 /// @brief Create a GPU parallel for loop.
332 ///
333 /// This loop reflects a loop as if it would have been created by a GPU
334 /// statement.
335 void codegenForGPGPU(const clast_for *F);
336
337 /// @brief Get innermost for loop.
Tobias Grossere602a072013-05-07 07:30:56 +0000338 const clast_stmt *getScheduleInfo(const clast_for *F,
339 std::vector<int> &NumIters,
340 unsigned &LoopDepth,
341 unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000342#endif /* GPU_CODEGEN */
343
Tobias Grossere192b232012-05-22 08:46:07 +0000344 /// @brief Check if a loop is parallel
345 ///
346 /// Detect if a clast_for loop can be executed in parallel.
347 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000348 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000349 ///
350 /// @return bool Returns true if the incoming clast_for statement can
351 /// execute in parallel.
352 bool isParallelFor(const clast_for *For);
353
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000354 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000355
356 /// @brief Get the number of loop iterations for this loop.
357 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000358 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000359
360 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000361 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000362
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000363 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000364
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000365 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000367 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000368
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000369 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000371 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000372
Tobias Grossere9ffea22012-03-15 09:34:48 +0000373 IntegerType *getIntPtrTy();
374
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000375public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000376 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000377
Tobias Grosser5103ba72014-03-04 14:58:49 +0000378 ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000379};
380}
381
Tobias Grossere9ffea22012-03-15 09:34:48 +0000382IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Rafael Espindolac5d16892014-02-25 19:17:57 +0000383 return P->getAnalysis<DataLayoutPass>().getDataLayout().getIntPtrType(
384 Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000385}
386
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000387const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
388 return parallelLoops;
389}
390
391void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000392 Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000393 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000394}
395
Tobias Grossere602a072013-05-07 07:30:56 +0000396void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
397 unsigned Dim, int VectorDim,
398 std::vector<ValueMapT> *VectorVMap,
399 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosserf00bd962012-04-02 12:26:13 +0000400 Value *RHS;
401
402 assert(!A->LHS && "Statement assignments do not have left hand side");
403
Tobias Grosser0905a232012-04-03 12:24:32 +0000404 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000405
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000406 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
407 if (VLTS)
408 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000409 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000410
411 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
412 if (PN) {
413 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
414
415 if (VectorVMap)
416 (*VectorVMap)[VectorDim][PN] = RHS;
417
418 ValueMap[PN] = RHS;
419 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000420}
421
Tobias Grossere602a072013-05-07 07:30:56 +0000422void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
423 ScopStmt *Statement, int vectorDim,
424 std::vector<ValueMapT> *VectorVMap,
425 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000426 int Dimension = 0;
427
428 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000429 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
430 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000431 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000432 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000433 Assignment = Assignment->next;
434 Dimension++;
435 }
436}
437
Sebastian Popa00a0292012-12-18 07:46:06 +0000438// Takes the cloog specific domain and translates it into a map Statement ->
439// PartialSchedule, where the PartialSchedule contains all the dimensions that
440// have been code generated up to this point.
Tobias Grossere602a072013-05-07 07:30:56 +0000441static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000442 __isl_take isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000443 isl_map *Schedule = Statement->getScattering();
444 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000445 int UnscheduledDimensions =
446 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000447
Tobias Grosser880c52f2013-07-29 01:58:07 +0000448 isl_set_free(Domain);
449
Sebastian Popa00a0292012-12-18 07:46:06 +0000450 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
451 UnscheduledDimensions);
452}
453
Tobias Grossere602a072013-05-07 07:30:56 +0000454void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
455 std::vector<Value *> *IVS, const char *iterator,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000456 __isl_take isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000457 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000458
459 if (u->substitutions)
460 codegenSubstitutions(u->substitutions, Statement);
461
Tobias Grosser80998e72012-03-02 11:27:28 +0000462 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000463
Tobias Grosser80998e72012-03-02 11:27:28 +0000464 if (VectorDimensions == 1) {
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000465 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
Tobias Grosserefc30132014-04-14 08:33:24 +0000466 isl_set_free(Domain);
Tobias Grosser80998e72012-03-02 11:27:28 +0000467 return;
468 }
469
470 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000471 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000472
473 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000474 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000475 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000476 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000477 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000478 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000479 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000480 i++;
481 }
482 }
483
Tobias Grosser75b76722014-04-15 22:30:06 +0000484 // Copy the current value map into all vector maps if the key wasn't
485 // available yet. This is needed in case vector codegen is performed in
486 // OpenMP subfunctions.
487 for (auto KV : ValueMap)
488 for (int i = 0; i < VectorDimensions; ++i)
489 VectorMap[i].insert(KV);
490
Sebastian Popa00a0292012-12-18 07:46:06 +0000491 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000492 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
493 P);
Sebastian Popa00a0292012-12-18 07:46:06 +0000494 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000495}
496
497void ClastStmtCodeGen::codegen(const clast_block *b) {
498 if (b->body)
499 codegen(b->body);
500}
501
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000502void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
503 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000504 BasicBlock *ExitBlock;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000505 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000506
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000507 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
508 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
509 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000510
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000511 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, ExitBlock,
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000512 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000513
514 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000515 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000516
517 if (f->body)
518 codegen(f->body);
519
520 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000521 ClastVars.erase(f->iterator);
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000522 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000523}
524
Tobias Grosser177982c2012-11-01 05:34:48 +0000525// Helper class to determine all scalar parameters used in the basic blocks of a
526// clast. Scalar parameters are scalar variables defined outside of the SCoP.
527class ParameterVisitor : public ClastVisitor {
528 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000529
Tobias Grosser177982c2012-11-01 05:34:48 +0000530public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000531 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000532
533 void visitUser(const clast_user_stmt *Stmt) {
534 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
535 const BasicBlock *BB = S->getBasicBlock();
536
537 // Check all the operands of instructions in the basic block.
538 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
539 ++BI) {
540 const Instruction &Inst = *BI;
541 for (Instruction::const_op_iterator II = Inst.op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000542 IE = Inst.op_end();
543 II != IE; ++II) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000544 Value *SrcVal = *II;
545
546 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
547 if (S->getParent()->getRegion().contains(OpInst))
548 continue;
549
550 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
551 Values.insert(SrcVal);
552 }
553 }
554 }
555
556 // Iterator to iterate over the values found.
557 typedef std::set<Value *>::const_iterator const_iterator;
558 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000559 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000560};
561
Tobias Grosserc14582f2013-02-05 18:01:29 +0000562SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
563 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000564
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000565 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000566 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
567 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000568 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000569
Tobias Grosser177982c2012-11-01 05:34:48 +0000570 // Find the temporaries that are referenced in the clast statements'
571 // basic blocks but are not defined by these blocks (e.g., references
572 // to function arguments or temporaries defined before the start of
573 // the SCoP).
574 ParameterVisitor Params;
575 Params.visit(Body);
576
577 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
578 PI != PE; ++PI) {
579 Value *V = *PI;
580 Values.insert(V);
581 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
582 }
583
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000584 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000585}
586
Tobias Grosserd7e58642013-04-10 06:55:45 +0000587void
588ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000589 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000590
Tobias Grosserc14582f2013-02-05 18:01:29 +0000591 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
592 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000593 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000594 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000595 }
596
Tobias Grossera17f6662012-11-01 05:34:35 +0000597 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000598 E = VMap.end();
599 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000600 if (Inserted.count(I->first))
601 continue;
602
603 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000604 }
605}
606
Tobias Grosser900893d2012-03-29 13:10:26 +0000607static void clearDomtree(Function *F, DominatorTree &DT) {
608 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000609 std::vector<BasicBlock *> Nodes;
610 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000611 Nodes.push_back(I->getBlock());
612
Tobias Grosserc14582f2013-02-05 18:01:29 +0000613 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000614 I != E; ++I)
615 DT.eraseNode(*I);
616}
617
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000618void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000619 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000620 BasicBlock::iterator LoopBody;
621 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000622 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000623 OMPGenerator::ValueToValueMapTy VMap;
624 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000625
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000626 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
627 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000628 LB = ExpGen.codegen(For->LB, IntPtrTy);
629 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000630
Tobias Grosser177982c2012-11-01 05:34:48 +0000631 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000632
Tobias Grosserebf30082012-03-23 12:20:32 +0000633 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000634 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
635 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000636
Tobias Grossera17f6662012-11-01 05:34:35 +0000637 // Save the current values.
638 const ValueMapT ValueMapCopy = ValueMap;
639 const CharMapT ClastVarsCopy = ClastVars;
640
641 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000642 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000643
644 if (For->body)
645 codegen(For->body);
646
Tobias Grossera17f6662012-11-01 05:34:35 +0000647 // Restore the original values.
648 ValueMap = ValueMapCopy;
649 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000650
Tobias Grosser900893d2012-03-29 13:10:26 +0000651 clearDomtree((*LoopBody).getParent()->getParent(),
Tobias Grosser42aff302014-01-13 22:29:56 +0000652 P->getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Tobias Grosser900893d2012-03-29 13:10:26 +0000653
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000654 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000655}
656
Tobias Grosser6217e182012-08-03 12:50:07 +0000657#ifdef GPU_CODEGEN
658static unsigned getArraySizeInBytes(const ArrayType *AT) {
659 unsigned Bytes = AT->getNumElements();
660 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
661 Bytes *= getArraySizeInBytes(T);
662 else
663 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
664
665 return Bytes;
666}
667
Tobias Grosserc14582f2013-02-05 18:01:29 +0000668SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
669 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000670 OutputBytes = 0;
671
672 // Record the memory reference base addresses.
673 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
674 ScopStmt *Stmt = *SI;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000675 for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
676 E = Stmt->memacc_end();
677 I != E; ++I) {
678 Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
Tobias Grosser6217e182012-08-03 12:50:07 +0000679 Values.insert((BaseAddr));
680
681 // FIXME: we assume that there is one and only one array to be written
682 // in a SCoP.
683 int NumWrites = 0;
684 if ((*I)->isWrite()) {
685 ++NumWrites;
686 assert(NumWrites <= 1 &&
687 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000688 if (const PointerType *PT =
689 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000690 Type *T = PT->getArrayElementType();
691 const ArrayType *ATy = dyn_cast<ArrayType>(T);
692 OutputBytes = getArraySizeInBytes(ATy);
693 }
694 }
695 }
696 }
697
698 return Values;
699}
700
Tobias Grossere602a072013-05-07 07:30:56 +0000701const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
702 std::vector<int> &NumIters,
703 unsigned &LoopDepth,
704 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000705 clast_stmt *Stmt = (clast_stmt *)F;
706 const clast_for *Result;
707 bool NonParaFlag = false;
708 LoopDepth = 0;
709 NonPLoopDepth = 0;
710
711 while (Stmt) {
712 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000713 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000714 if (isParallelFor(T)) {
715 if (!NonParaFlag) {
716 NumIters.push_back(getNumberOfIterations(T));
717 Result = T;
718 }
719 } else
720 NonParaFlag = true;
721
722 Stmt = T->body;
723 LoopDepth++;
724 continue;
725 }
726 Stmt = Stmt->next;
727 }
728
729 assert(NumIters.size() == 4 &&
730 "The loops should be tiled into 4-depth parallel loops and an "
731 "innermost non-parallel one (if exist).");
732 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000733 assert(NonPLoopDepth <= 1 &&
734 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000735 return (const clast_stmt *)Result->body;
736}
737
738void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
739 BasicBlock::iterator LoopBody;
740 SetVector<Value *> Values;
741 SetVector<Value *> IVS;
742 std::vector<int> NumIterations;
743 PTXGenerator::ValueToValueMapTy VMap;
744
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000745 assert(!GPUTriple.empty() &&
746 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000747 PTXGenerator PTXGen(Builder, P, GPUTriple);
748
749 // Get original IVS and ScopStmt
750 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000751 const clast_stmt *InnerStmt =
752 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000753 const clast_stmt *TmpStmt;
754 const clast_user_stmt *U;
755 const clast_for *InnerFor;
756 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
757 InnerFor = (const clast_for *)InnerStmt;
758 TmpStmt = InnerFor->body;
759 } else
760 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000761 U = (const clast_user_stmt *)TmpStmt;
762 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000763 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000764 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000765 IVS.insert(const_cast<Value *>(IV));
766 }
767
768 unsigned OutBytes;
769 Values = getGPUValues(OutBytes);
770 PTXGen.setOutputBytes(OutBytes);
771 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
772
773 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
774 Builder.SetInsertPoint(LoopBody);
775
776 BasicBlock *AfterBB = 0;
777 if (NonPLoopDepth) {
778 Value *LowerBound, *UpperBound, *IV, *Stride;
779 Type *IntPtrTy = getIntPtrTy();
780 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
781 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
782 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000783 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
784 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000785 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
786 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000787 VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000788 }
789
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000790 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000791
Tobias Grosser6217e182012-08-03 12:50:07 +0000792 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000793
Tobias Grosser6217e182012-08-03 12:50:07 +0000794 if (AfterBB)
795 Builder.SetInsertPoint(AfterBB->begin());
796
797 // FIXME: The replacement of the host base address with the parameter of ptx
798 // subfunction should have been done by updateWithValueMap. We use the
799 // following codes to avoid affecting other parts of Polly. This should be
800 // fixed later.
801 Function *FN = Builder.GetInsertBlock()->getParent();
802 for (unsigned j = 0; j < Values.size(); j++) {
803 Value *baseAddr = Values[j];
804 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
805 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
806 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
807 }
808 }
809 Builder.SetInsertPoint(AfterLoop);
810 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
811 NumIterations[2], NumIterations[3]);
812 PTXGen.finishGeneration(FN);
813}
814#endif
815
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000816bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
817 const clast_stmt *stmt = f->body;
818
819 while (stmt) {
820 if (!CLAST_STMT_IS_A(stmt, stmt_user))
821 return false;
822
823 stmt = stmt->next;
824 }
825
826 return true;
827}
828
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000829int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
830 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000831 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
832 if (NumberOfIterations == -1)
833 return -1;
Tobias Grosserb8cd4a82014-01-19 11:31:23 +0000834 return NumberOfIterations / mpz_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000835}
836
Tobias Grosser2da263e2012-03-15 09:34:55 +0000837void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
838 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
839 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000840
Tobias Grosser2da263e2012-03-15 09:34:55 +0000841 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000842
Tobias Grosser2da263e2012-03-15 09:34:55 +0000843 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000844 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000845 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000846 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
847
Tobias Grosserc14582f2013-02-05 18:01:29 +0000848 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000849 IVS[0] = LB;
850
Tobias Grosser2da263e2012-03-15 09:34:55 +0000851 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000852 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000853
Tobias Grosser880c52f2013-07-29 01:58:07 +0000854 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(F->domain));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000855
856 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000857 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000858
Tobias Grosser2da263e2012-03-15 09:34:55 +0000859 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000860
Tobias Grosser2da263e2012-03-15 09:34:55 +0000861 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000862 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
863 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000864 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000865 }
866
867 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000868 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000869 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000870}
871
Tobias Grossere192b232012-05-22 08:46:07 +0000872bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
Tobias Grosser880c52f2013-07-29 01:58:07 +0000873 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000874 assert(Domain && "Cannot access domain of loop");
875
876 Dependences &D = P->getAnalysis<Dependences>();
877
Tobias Grosser880c52f2013-07-29 01:58:07 +0000878 return D.isParallelDimension(Domain, isl_set_n_dim(Domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000879}
880
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000881void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000882 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000883 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000884 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
885 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000886 codegenForVector(f);
887 return;
888 }
889
890 if (OpenMP && !parallelCodeGeneration) {
891 parallelCodeGeneration = true;
892 parallelLoops.push_back(f->iterator);
893 codegenForOpenMP(f);
894 parallelCodeGeneration = false;
895 return;
896 }
897 }
898
Tobias Grosser6217e182012-08-03 12:50:07 +0000899#ifdef GPU_CODEGEN
900 if (GPGPU && isParallelFor(f)) {
901 if (!parallelCodeGeneration) {
902 parallelCodeGeneration = true;
903 parallelLoops.push_back(f->iterator);
904 codegenForGPGPU(f);
905 parallelCodeGeneration = false;
906 return;
907 }
908 }
909#endif
910
Tobias Grosserce3f5372012-03-02 11:26:42 +0000911 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000912}
913
914Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000915 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
916 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000917 CmpInst::Predicate P;
918
919 if (eq->sign == 0)
920 P = ICmpInst::ICMP_EQ;
921 else if (eq->sign > 0)
922 P = ICmpInst::ICMP_SGE;
923 else
924 P = ICmpInst::ICMP_SLE;
925
926 return Builder.CreateICmp(P, LHS, RHS);
927}
928
929void ClastStmtCodeGen::codegen(const clast_guard *g) {
930 Function *F = Builder.GetInsertBlock()->getParent();
931 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000932
Tobias Grosserc14582f2013-02-05 18:01:29 +0000933 BasicBlock *CondBB =
934 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000935 CondBB->setName("polly.cond");
936 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
937 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000938 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000939
Tobias Grosser42aff302014-01-13 22:29:56 +0000940 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosserd596b372012-03-15 09:34:52 +0000941 DT.addNewBlock(ThenBB, CondBB);
942 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000943
944 CondBB->getTerminator()->eraseFromParent();
945
946 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000947
948 Value *Predicate = codegen(&(g->eq[0]));
949
950 for (int i = 1; i < g->n; ++i) {
951 Value *TmpPredicate = codegen(&(g->eq[i]));
952 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
953 }
954
955 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
956 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000957 Builder.CreateBr(MergeBB);
958 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000959
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000960 LoopInfo &LI = P->getAnalysis<LoopInfo>();
961 Loop *L = LI.getLoopFor(CondBB);
Tobias Grosser815c6352013-09-02 16:13:00 +0000962 if (L)
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000963 L->addBasicBlockToLoop(ThenBB, LI.getBase());
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000964
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000965 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000966
967 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000968}
969
970void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000971 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000972 assert(false && "No second root statement expected");
973 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
974 codegen((const clast_assignment *)stmt);
975 else if (CLAST_STMT_IS_A(stmt, stmt_user))
976 codegen((const clast_user_stmt *)stmt);
977 else if (CLAST_STMT_IS_A(stmt, stmt_block))
978 codegen((const clast_block *)stmt);
979 else if (CLAST_STMT_IS_A(stmt, stmt_for))
980 codegen((const clast_for *)stmt);
981 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
982 codegen((const clast_guard *)stmt);
983
984 if (stmt->next)
985 codegen(stmt->next);
986}
987
988void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000989 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000990
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 int i = 0;
992 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
993 PI != PE; ++PI) {
994 assert(i < names->nb_parameters && "Not enough parameter names");
995
996 const SCEV *Param = *PI;
997 Type *Ty = Param->getType();
998
999 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1000 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +00001001 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001002
1003 ++i;
1004 }
1005}
1006
1007void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001008 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001009
1010 parallelCodeGeneration = false;
1011
Tobias Grosserc14582f2013-02-05 18:01:29 +00001012 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001013 if (stmt->next)
1014 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001015}
1016
Tobias Grosser5103ba72014-03-04 14:58:49 +00001017ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001018 : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001019
Tobias Grosser75805372011-04-29 06:27:02 +00001020namespace {
1021class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001022 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001024public:
Tobias Grosser75805372011-04-29 06:27:02 +00001025 static char ID;
1026
1027 CodeGeneration() : ScopPass(ID) {}
1028
Tobias Grosser3a275d22012-05-29 09:11:54 +00001029 bool runOnScop(Scop &S) {
1030 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001031
Tobias Grossere602a072013-05-07 07:30:56 +00001032 assert(!S.getRegion().isTopLevelRegion() &&
1033 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001034
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001035 simplifyRegion(&S, this);
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001036
Tobias Grosser3a275d22012-05-29 09:11:54 +00001037 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001038
Tobias Grosser5103ba72014-03-04 14:58:49 +00001039 PollyIRBuilder Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001040
Tobias Grosser3a275d22012-05-29 09:11:54 +00001041 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001042 CloogInfo &C = getAnalysis<CloogInfo>();
1043 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001044
Tobias Grosser3a275d22012-05-29 09:11:54 +00001045 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001046 CodeGen.getParallelLoops().begin(),
1047 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001048 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001049 }
1050
1051 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001052 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001053 PE = ParallelLoops.end();
1054 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001055 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1056 }
1057
1058 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1059 AU.addRequired<CloogInfo>();
1060 AU.addRequired<Dependences>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001061 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001062 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001063 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001064 AU.addRequired<ScopDetection>();
1065 AU.addRequired<ScopInfo>();
Rafael Espindolac5d16892014-02-25 19:17:57 +00001066 AU.addRequired<DataLayoutPass>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001067 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001068
1069 AU.addPreserved<CloogInfo>();
1070 AU.addPreserved<Dependences>();
1071 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001072 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001073 AU.addPreserved<ScopDetection>();
1074 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001075
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001076 // FIXME: We do not yet add regions for the newly generated code to the
1077 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001078 AU.addPreserved<RegionInfo>();
1079 AU.addPreserved<TempScopInfo>();
1080 AU.addPreserved<ScopInfo>();
1081 AU.addPreservedID(IndependentBlocksID);
1082 }
1083};
1084}
1085
1086char CodeGeneration::ID = 1;
1087
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001088Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001089
Tobias Grosser7242ad92013-02-22 08:07:06 +00001090INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1091 "Polly - Create LLVM-IR from SCoPs", false, false);
1092INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1093INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001094INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001095INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1096INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1097INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Rafael Espindolac5d16892014-02-25 19:17:57 +00001098INITIALIZE_PASS_DEPENDENCY(DataLayoutPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001099INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001100 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001101
Sebastian Pope1f65542012-05-07 16:35:11 +00001102#endif // CLOOG_FOUND