blob: 77c50a4b59878abc5cae8f86975ee75c1e09a947 [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 {
85 IRBuilder<> &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:
94
95 // 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 Grosser5e8ffa82012-03-23 12:20:36 +0000102 ClastExpCodeGen(IRBuilder<> &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
119Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
120 APInt a = APInt_from_MPZ(e->val);
121
122 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
123 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
124
125 if (!e->var)
126 return ConstOne;
127
128 Value *var = codegen(e->var, Ty);
129 return Builder.CreateMul(ConstOne, var);
130}
131
132Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
133 Value *LHS = codegen(e->LHS, Ty);
134
135 APInt RHS_AP = APInt_from_MPZ(e->RHS);
136
137 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
138 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
139
140 switch (e->type) {
141 case clast_bin_mod:
142 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000143 case clast_bin_fdiv: {
144 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
145 Value *One = ConstantInt::get(Ty, 1);
146 Value *Zero = ConstantInt::get(Ty, 0);
147 Value *Sum1 = Builder.CreateSub(LHS, RHS);
148 Value *Sum2 = Builder.CreateAdd(Sum1, One);
149 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
150 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
151 return Builder.CreateSDiv(Dividend, RHS);
152 }
153 case clast_bin_cdiv: {
154 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
155 Value *One = ConstantInt::get(Ty, 1);
156 Value *Zero = ConstantInt::get(Ty, 0);
157 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
158 Value *Sum2 = Builder.CreateSub(Sum1, One);
159 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
160 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
161 return Builder.CreateSDiv(Dividend, RHS);
162 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000163 case clast_bin_div:
164 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000165 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000166
167 llvm_unreachable("Unknown clast binary expression type");
168}
169
170Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000171 assert((r->type == clast_red_min || r->type == clast_red_max ||
Tobias Grosser58032cb2013-06-23 01:29:29 +0000172 r->type == clast_red_sum) &&
173 "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000174 Value *old = codegen(r->elts[0], Ty);
175
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000176 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000177 Value *exprValue = codegen(r->elts[i], Ty);
178
179 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000180 case clast_red_min: {
181 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
182 old = Builder.CreateSelect(cmp, old, exprValue);
183 break;
184 }
185 case clast_red_max: {
186 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
187 old = Builder.CreateSelect(cmp, old, exprValue);
188 break;
189 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000190 case clast_red_sum:
191 old = Builder.CreateAdd(old, exprValue);
192 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000193 }
Tobias Grosser75805372011-04-29 06:27:02 +0000194 }
195
Tobias Grosserbb137e32012-01-24 16:42:28 +0000196 return old;
197}
198
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000199ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000200 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000201
202Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000203 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000204 case clast_expr_name:
205 return codegen((const clast_name *)e, Ty);
206 case clast_expr_term:
207 return codegen((const clast_term *)e, Ty);
208 case clast_expr_bin:
209 return codegen((const clast_binary *)e, Ty);
210 case clast_expr_red:
211 return codegen((const clast_reduction *)e, Ty);
212 }
213
214 llvm_unreachable("Unknown clast expression!");
215}
216
Tobias Grosser75805372011-04-29 06:27:02 +0000217class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000218public:
219 const std::vector<std::string> &getParallelLoops();
220
221private:
Tobias Grosser75805372011-04-29 06:27:02 +0000222 // The Scop we code generate.
223 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000224 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000225
226 // The Builder specifies the current location to code generate at.
227 IRBuilder<> &Builder;
228
229 // Map the Values from the old code to their counterparts in the new code.
230 ValueMapT ValueMap;
231
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000232 // Map the loops from the old code to expressions function of the induction
233 // variables in the new code. For example, when the code generator produces
234 // this AST:
235 //
236 // for (int c1 = 0; c1 <= 1023; c1 += 1)
237 // for (int c2 = 0; c2 <= 1023; c2 += 1)
238 // Stmt(c2 + 3, c1);
239 //
240 // LoopToScev is a map associating:
241 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
242 // "inner loop in the old loop nest" -> SCEV("c1").
243 LoopToScevMapT LoopToScev;
244
Tobias Grosser75805372011-04-29 06:27:02 +0000245 // clastVars maps from the textual representation of a clast variable to its
246 // current *Value. clast variables are scheduling variables, original
247 // induction variables or parameters. They are used either in loop bounds or
248 // to define the statement instance that is executed.
249 //
250 // for (s = 0; s < n + 3; ++i)
251 // for (t = s; t < m; ++j)
252 // Stmt(i = s + 3 * m, j = t);
253 //
254 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000255 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000256
257 // Codegenerator for clast expressions.
258 ClastExpCodeGen ExpGen;
259
260 // Do we currently generate parallel code?
261 bool parallelCodeGeneration;
262
263 std::vector<std::string> parallelLoops;
264
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000265 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
Tobias Grossere602a072013-05-07 07:30:56 +0000267 void codegen(const clast_assignment *a, ScopStmt *Statement,
268 unsigned Dimension, int vectorDim,
269 std::vector<ValueMapT> *VectorVMap = 0,
270 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000271
Tobias Grosserc14582f2013-02-05 18:01:29 +0000272 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
273 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000274 std::vector<ValueMapT> *VectorVMap = 0,
275 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000276
Tobias Grosserc14582f2013-02-05 18:01:29 +0000277 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = NULL,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000278 const char *iterator = NULL,
279 __isl_take isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000280
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000281 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000282
283 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000284 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000285
286 /// @brief Create OpenMP structure values.
287 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000288 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000289 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000290 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000291
Tobias Grossera17f6662012-11-01 05:34:35 +0000292 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000293 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000294 /// @param VMap A map from old to new values.
295 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000296
297 /// @brief Create an OpenMP parallel for loop.
298 ///
299 /// This loop reflects a loop as if it would have been created by an OpenMP
300 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000301 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000302
Tobias Grosser6217e182012-08-03 12:50:07 +0000303#ifdef GPU_CODEGEN
304 /// @brief Create GPGPU device memory access values.
305 ///
306 /// Create a list of values that will be set to be parameters of the GPGPU
307 /// subfunction. These parameters represent device memory base addresses
308 /// and the size in bytes.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000309 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000310
311 /// @brief Create a GPU parallel for loop.
312 ///
313 /// This loop reflects a loop as if it would have been created by a GPU
314 /// statement.
315 void codegenForGPGPU(const clast_for *F);
316
317 /// @brief Get innermost for loop.
Tobias Grossere602a072013-05-07 07:30:56 +0000318 const clast_stmt *getScheduleInfo(const clast_for *F,
319 std::vector<int> &NumIters,
320 unsigned &LoopDepth,
321 unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000322#endif /* GPU_CODEGEN */
323
Tobias Grossere192b232012-05-22 08:46:07 +0000324 /// @brief Check if a loop is parallel
325 ///
326 /// Detect if a clast_for loop can be executed in parallel.
327 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000328 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000329 ///
330 /// @return bool Returns true if the incoming clast_for statement can
331 /// execute in parallel.
332 bool isParallelFor(const clast_for *For);
333
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000334 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000335
336 /// @brief Get the number of loop iterations for this loop.
337 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000338 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000339
340 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000341 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000342
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000343 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000344
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000345 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000347 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000349 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000350
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000351 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000352
Tobias Grossere9ffea22012-03-15 09:34:48 +0000353 IntegerType *getIntPtrTy();
354
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000355public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000356 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000357
Tobias Grosserd596b372012-03-15 09:34:52 +0000358 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000359};
360}
361
Tobias Grossere9ffea22012-03-15 09:34:48 +0000362IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Tobias Grosser5d01691d2012-11-01 16:45:18 +0000363 return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000364}
365
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000366const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
367 return parallelLoops;
368}
369
370void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000371 Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000372 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000373}
374
Tobias Grossere602a072013-05-07 07:30:56 +0000375void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
376 unsigned Dim, int VectorDim,
377 std::vector<ValueMapT> *VectorVMap,
378 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosserf00bd962012-04-02 12:26:13 +0000379 Value *RHS;
380
381 assert(!A->LHS && "Statement assignments do not have left hand side");
382
Tobias Grosser0905a232012-04-03 12:24:32 +0000383 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000384
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000385 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
386 if (VLTS)
387 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000388 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000389
390 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
391 if (PN) {
392 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
393
394 if (VectorVMap)
395 (*VectorVMap)[VectorDim][PN] = RHS;
396
397 ValueMap[PN] = RHS;
398 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000399}
400
Tobias Grossere602a072013-05-07 07:30:56 +0000401void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
402 ScopStmt *Statement, int vectorDim,
403 std::vector<ValueMapT> *VectorVMap,
404 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000405 int Dimension = 0;
406
407 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000408 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
409 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000410 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000411 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000412 Assignment = Assignment->next;
413 Dimension++;
414 }
415}
416
Sebastian Popa00a0292012-12-18 07:46:06 +0000417// Takes the cloog specific domain and translates it into a map Statement ->
418// PartialSchedule, where the PartialSchedule contains all the dimensions that
419// have been code generated up to this point.
Tobias Grossere602a072013-05-07 07:30:56 +0000420static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000421 __isl_take isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000422 isl_map *Schedule = Statement->getScattering();
423 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000424 int UnscheduledDimensions =
425 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000426
Tobias Grosser880c52f2013-07-29 01:58:07 +0000427 isl_set_free(Domain);
428
Sebastian Popa00a0292012-12-18 07:46:06 +0000429 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
430 UnscheduledDimensions);
431}
432
Tobias Grossere602a072013-05-07 07:30:56 +0000433void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
434 std::vector<Value *> *IVS, const char *iterator,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000435 __isl_take isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000436 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000437
438 if (u->substitutions)
439 codegenSubstitutions(u->substitutions, Statement);
440
Tobias Grosser80998e72012-03-02 11:27:28 +0000441 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000442
Tobias Grosser80998e72012-03-02 11:27:28 +0000443 if (VectorDimensions == 1) {
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000444 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000445 return;
446 }
447
448 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000449 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000450
451 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000452 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000453 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000454 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000455 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000456 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000457 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000458 i++;
459 }
460 }
461
Sebastian Popa00a0292012-12-18 07:46:06 +0000462 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000463 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
464 P);
Sebastian Popa00a0292012-12-18 07:46:06 +0000465 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000466}
467
468void ClastStmtCodeGen::codegen(const clast_block *b) {
469 if (b->body)
470 codegen(b->body);
471}
472
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000473void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
474 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000475 BasicBlock *ExitBlock;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000476 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000477
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000478 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
479 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
480 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000481
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000482 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, ExitBlock,
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000483 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000484
485 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000486 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000487
488 if (f->body)
489 codegen(f->body);
490
491 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000492 ClastVars.erase(f->iterator);
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000493 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000494}
495
Tobias Grosser177982c2012-11-01 05:34:48 +0000496// Helper class to determine all scalar parameters used in the basic blocks of a
497// clast. Scalar parameters are scalar variables defined outside of the SCoP.
498class ParameterVisitor : public ClastVisitor {
499 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000500
Tobias Grosser177982c2012-11-01 05:34:48 +0000501public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000502 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000503
504 void visitUser(const clast_user_stmt *Stmt) {
505 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
506 const BasicBlock *BB = S->getBasicBlock();
507
508 // Check all the operands of instructions in the basic block.
509 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
510 ++BI) {
511 const Instruction &Inst = *BI;
512 for (Instruction::const_op_iterator II = Inst.op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000513 IE = Inst.op_end();
514 II != IE; ++II) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000515 Value *SrcVal = *II;
516
517 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
518 if (S->getParent()->getRegion().contains(OpInst))
519 continue;
520
521 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
522 Values.insert(SrcVal);
523 }
524 }
525 }
526
527 // Iterator to iterate over the values found.
528 typedef std::set<Value *>::const_iterator const_iterator;
529 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000530 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000531};
532
Tobias Grosserc14582f2013-02-05 18:01:29 +0000533SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
534 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000535
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000536 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000537 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
538 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000539 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000540
Tobias Grosser177982c2012-11-01 05:34:48 +0000541 // Find the temporaries that are referenced in the clast statements'
542 // basic blocks but are not defined by these blocks (e.g., references
543 // to function arguments or temporaries defined before the start of
544 // the SCoP).
545 ParameterVisitor Params;
546 Params.visit(Body);
547
548 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
549 PI != PE; ++PI) {
550 Value *V = *PI;
551 Values.insert(V);
552 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
553 }
554
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000555 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000556}
557
Tobias Grosserd7e58642013-04-10 06:55:45 +0000558void
559ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000560 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000561
Tobias Grosserc14582f2013-02-05 18:01:29 +0000562 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
563 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000564 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000565 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000566 }
567
Tobias Grossera17f6662012-11-01 05:34:35 +0000568 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000569 E = VMap.end();
570 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000571 if (Inserted.count(I->first))
572 continue;
573
574 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000575 }
576}
577
Tobias Grosser900893d2012-03-29 13:10:26 +0000578static void clearDomtree(Function *F, DominatorTree &DT) {
579 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000580 std::vector<BasicBlock *> Nodes;
581 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000582 Nodes.push_back(I->getBlock());
583
Tobias Grosserc14582f2013-02-05 18:01:29 +0000584 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000585 I != E; ++I)
586 DT.eraseNode(*I);
587}
588
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000589void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000590 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000591 BasicBlock::iterator LoopBody;
592 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000593 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000594 OMPGenerator::ValueToValueMapTy VMap;
595 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000596
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000597 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
598 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000599 LB = ExpGen.codegen(For->LB, IntPtrTy);
600 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000601
Tobias Grosser177982c2012-11-01 05:34:48 +0000602 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000603
Tobias Grosserebf30082012-03-23 12:20:32 +0000604 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000605 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
606 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000607
Tobias Grossera17f6662012-11-01 05:34:35 +0000608 // Save the current values.
609 const ValueMapT ValueMapCopy = ValueMap;
610 const CharMapT ClastVarsCopy = ClastVars;
611
612 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000613 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000614
615 if (For->body)
616 codegen(For->body);
617
Tobias Grossera17f6662012-11-01 05:34:35 +0000618 // Restore the original values.
619 ValueMap = ValueMapCopy;
620 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000621
Tobias Grosser900893d2012-03-29 13:10:26 +0000622 clearDomtree((*LoopBody).getParent()->getParent(),
623 P->getAnalysis<DominatorTree>());
624
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000625 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000626}
627
Tobias Grosser6217e182012-08-03 12:50:07 +0000628#ifdef GPU_CODEGEN
629static unsigned getArraySizeInBytes(const ArrayType *AT) {
630 unsigned Bytes = AT->getNumElements();
631 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
632 Bytes *= getArraySizeInBytes(T);
633 else
634 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
635
636 return Bytes;
637}
638
Tobias Grosserc14582f2013-02-05 18:01:29 +0000639SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
640 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000641 OutputBytes = 0;
642
643 // Record the memory reference base addresses.
644 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
645 ScopStmt *Stmt = *SI;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000646 for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
647 E = Stmt->memacc_end();
648 I != E; ++I) {
649 Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
Tobias Grosser6217e182012-08-03 12:50:07 +0000650 Values.insert((BaseAddr));
651
652 // FIXME: we assume that there is one and only one array to be written
653 // in a SCoP.
654 int NumWrites = 0;
655 if ((*I)->isWrite()) {
656 ++NumWrites;
657 assert(NumWrites <= 1 &&
658 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000659 if (const PointerType *PT =
660 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000661 Type *T = PT->getArrayElementType();
662 const ArrayType *ATy = dyn_cast<ArrayType>(T);
663 OutputBytes = getArraySizeInBytes(ATy);
664 }
665 }
666 }
667 }
668
669 return Values;
670}
671
Tobias Grossere602a072013-05-07 07:30:56 +0000672const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
673 std::vector<int> &NumIters,
674 unsigned &LoopDepth,
675 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000676 clast_stmt *Stmt = (clast_stmt *)F;
677 const clast_for *Result;
678 bool NonParaFlag = false;
679 LoopDepth = 0;
680 NonPLoopDepth = 0;
681
682 while (Stmt) {
683 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000684 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000685 if (isParallelFor(T)) {
686 if (!NonParaFlag) {
687 NumIters.push_back(getNumberOfIterations(T));
688 Result = T;
689 }
690 } else
691 NonParaFlag = true;
692
693 Stmt = T->body;
694 LoopDepth++;
695 continue;
696 }
697 Stmt = Stmt->next;
698 }
699
700 assert(NumIters.size() == 4 &&
701 "The loops should be tiled into 4-depth parallel loops and an "
702 "innermost non-parallel one (if exist).");
703 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000704 assert(NonPLoopDepth <= 1 &&
705 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000706 return (const clast_stmt *)Result->body;
707}
708
709void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
710 BasicBlock::iterator LoopBody;
711 SetVector<Value *> Values;
712 SetVector<Value *> IVS;
713 std::vector<int> NumIterations;
714 PTXGenerator::ValueToValueMapTy VMap;
715
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000716 assert(!GPUTriple.empty() &&
717 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000718 PTXGenerator PTXGen(Builder, P, GPUTriple);
719
720 // Get original IVS and ScopStmt
721 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000722 const clast_stmt *InnerStmt =
723 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000724 const clast_stmt *TmpStmt;
725 const clast_user_stmt *U;
726 const clast_for *InnerFor;
727 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
728 InnerFor = (const clast_for *)InnerStmt;
729 TmpStmt = InnerFor->body;
730 } else
731 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000732 U = (const clast_user_stmt *)TmpStmt;
733 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000734 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000735 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000736 IVS.insert(const_cast<Value *>(IV));
737 }
738
739 unsigned OutBytes;
740 Values = getGPUValues(OutBytes);
741 PTXGen.setOutputBytes(OutBytes);
742 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
743
744 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
745 Builder.SetInsertPoint(LoopBody);
746
747 BasicBlock *AfterBB = 0;
748 if (NonPLoopDepth) {
749 Value *LowerBound, *UpperBound, *IV, *Stride;
750 Type *IntPtrTy = getIntPtrTy();
751 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
752 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
753 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000754 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
755 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000756 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
757 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000758 VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000759 }
760
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000761 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000762
Tobias Grosser6217e182012-08-03 12:50:07 +0000763 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000764
Tobias Grosser6217e182012-08-03 12:50:07 +0000765 if (AfterBB)
766 Builder.SetInsertPoint(AfterBB->begin());
767
768 // FIXME: The replacement of the host base address with the parameter of ptx
769 // subfunction should have been done by updateWithValueMap. We use the
770 // following codes to avoid affecting other parts of Polly. This should be
771 // fixed later.
772 Function *FN = Builder.GetInsertBlock()->getParent();
773 for (unsigned j = 0; j < Values.size(); j++) {
774 Value *baseAddr = Values[j];
775 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
776 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
777 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
778 }
779 }
780 Builder.SetInsertPoint(AfterLoop);
781 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
782 NumIterations[2], NumIterations[3]);
783 PTXGen.finishGeneration(FN);
784}
785#endif
786
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000787bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
788 const clast_stmt *stmt = f->body;
789
790 while (stmt) {
791 if (!CLAST_STMT_IS_A(stmt, stmt_user))
792 return false;
793
794 stmt = stmt->next;
795 }
796
797 return true;
798}
799
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000800int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
801 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000802 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
803 if (NumberOfIterations == -1)
804 return -1;
805 return NumberOfIterations / isl_int_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000806}
807
Tobias Grosser2da263e2012-03-15 09:34:55 +0000808void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
809 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
810 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000811
Tobias Grosser2da263e2012-03-15 09:34:55 +0000812 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000813
Tobias Grosser2da263e2012-03-15 09:34:55 +0000814 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000815 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000816 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000817 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
818
Tobias Grosserc14582f2013-02-05 18:01:29 +0000819 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000820 IVS[0] = LB;
821
Tobias Grosser2da263e2012-03-15 09:34:55 +0000822 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000823 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000824
Tobias Grosser880c52f2013-07-29 01:58:07 +0000825 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(F->domain));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000826
827 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000828 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000829
Tobias Grosser2da263e2012-03-15 09:34:55 +0000830 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000831
Tobias Grosser2da263e2012-03-15 09:34:55 +0000832 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000833 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
834 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000835 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000836 }
837
838 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000839 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000840 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000841}
842
Tobias Grossere192b232012-05-22 08:46:07 +0000843bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
Tobias Grosser880c52f2013-07-29 01:58:07 +0000844 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000845 assert(Domain && "Cannot access domain of loop");
846
847 Dependences &D = P->getAnalysis<Dependences>();
848
Tobias Grosser880c52f2013-07-29 01:58:07 +0000849 return D.isParallelDimension(Domain, isl_set_n_dim(Domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000850}
851
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000852void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000853 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000854 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000855 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
856 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000857 codegenForVector(f);
858 return;
859 }
860
861 if (OpenMP && !parallelCodeGeneration) {
862 parallelCodeGeneration = true;
863 parallelLoops.push_back(f->iterator);
864 codegenForOpenMP(f);
865 parallelCodeGeneration = false;
866 return;
867 }
868 }
869
Tobias Grosser6217e182012-08-03 12:50:07 +0000870#ifdef GPU_CODEGEN
871 if (GPGPU && isParallelFor(f)) {
872 if (!parallelCodeGeneration) {
873 parallelCodeGeneration = true;
874 parallelLoops.push_back(f->iterator);
875 codegenForGPGPU(f);
876 parallelCodeGeneration = false;
877 return;
878 }
879 }
880#endif
881
Tobias Grosserce3f5372012-03-02 11:26:42 +0000882 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000883}
884
885Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000886 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
887 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000888 CmpInst::Predicate P;
889
890 if (eq->sign == 0)
891 P = ICmpInst::ICMP_EQ;
892 else if (eq->sign > 0)
893 P = ICmpInst::ICMP_SGE;
894 else
895 P = ICmpInst::ICMP_SLE;
896
897 return Builder.CreateICmp(P, LHS, RHS);
898}
899
900void ClastStmtCodeGen::codegen(const clast_guard *g) {
901 Function *F = Builder.GetInsertBlock()->getParent();
902 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000903
Tobias Grosserc14582f2013-02-05 18:01:29 +0000904 BasicBlock *CondBB =
905 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000906 CondBB->setName("polly.cond");
907 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
908 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000909 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000910
Tobias Grosserd596b372012-03-15 09:34:52 +0000911 DominatorTree &DT = P->getAnalysis<DominatorTree>();
912 DT.addNewBlock(ThenBB, CondBB);
913 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000914
915 CondBB->getTerminator()->eraseFromParent();
916
917 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000918
919 Value *Predicate = codegen(&(g->eq[0]));
920
921 for (int i = 1; i < g->n; ++i) {
922 Value *TmpPredicate = codegen(&(g->eq[i]));
923 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
924 }
925
926 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
927 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000928 Builder.CreateBr(MergeBB);
929 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000930
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000931 LoopInfo &LI = P->getAnalysis<LoopInfo>();
932 Loop *L = LI.getLoopFor(CondBB);
Tobias Grosser815c6352013-09-02 16:13:00 +0000933 if (L)
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000934 L->addBasicBlockToLoop(ThenBB, LI.getBase());
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000935
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000936 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000937
938 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000939}
940
941void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000942 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000943 assert(false && "No second root statement expected");
944 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
945 codegen((const clast_assignment *)stmt);
946 else if (CLAST_STMT_IS_A(stmt, stmt_user))
947 codegen((const clast_user_stmt *)stmt);
948 else if (CLAST_STMT_IS_A(stmt, stmt_block))
949 codegen((const clast_block *)stmt);
950 else if (CLAST_STMT_IS_A(stmt, stmt_for))
951 codegen((const clast_for *)stmt);
952 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
953 codegen((const clast_guard *)stmt);
954
955 if (stmt->next)
956 codegen(stmt->next);
957}
958
959void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000960 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000961
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000962 int i = 0;
963 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
964 PI != PE; ++PI) {
965 assert(i < names->nb_parameters && "Not enough parameter names");
966
967 const SCEV *Param = *PI;
968 Type *Ty = Param->getType();
969
970 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
971 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000972 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000973
974 ++i;
975 }
976}
977
978void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000979 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000980
981 parallelCodeGeneration = false;
982
Tobias Grosserc14582f2013-02-05 18:01:29 +0000983 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984 if (stmt->next)
985 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000986}
987
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000988ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000989 : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000990
Tobias Grosser75805372011-04-29 06:27:02 +0000991namespace {
992class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000993 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000995public:
Tobias Grosser75805372011-04-29 06:27:02 +0000996 static char ID;
997
998 CodeGeneration() : ScopPass(ID) {}
999
Tobias Grosser3a275d22012-05-29 09:11:54 +00001000 bool runOnScop(Scop &S) {
1001 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001002
Tobias Grossere602a072013-05-07 07:30:56 +00001003 assert(!S.getRegion().isTopLevelRegion() &&
1004 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001005
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001006 simplifyRegion(&S, this);
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001007
Tobias Grosser3a275d22012-05-29 09:11:54 +00001008 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001009
Tobias Grosser3a275d22012-05-29 09:11:54 +00001010 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001011
Tobias Grosser3a275d22012-05-29 09:11:54 +00001012 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001013 CloogInfo &C = getAnalysis<CloogInfo>();
1014 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001015
Tobias Grosser3a275d22012-05-29 09:11:54 +00001016 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001017 CodeGen.getParallelLoops().begin(),
1018 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001019 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001020 }
1021
1022 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001023 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001024 PE = ParallelLoops.end();
1025 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001026 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1027 }
1028
1029 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1030 AU.addRequired<CloogInfo>();
1031 AU.addRequired<Dependences>();
1032 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001033 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001034 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001035 AU.addRequired<ScopDetection>();
1036 AU.addRequired<ScopInfo>();
Micah Villmow7a3d8202012-10-08 17:26:19 +00001037 AU.addRequired<DataLayout>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001038 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001039
1040 AU.addPreserved<CloogInfo>();
1041 AU.addPreserved<Dependences>();
1042 AU.addPreserved<LoopInfo>();
1043 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001044 AU.addPreserved<ScopDetection>();
1045 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001046
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001047 // FIXME: We do not yet add regions for the newly generated code to the
1048 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001049 AU.addPreserved<RegionInfo>();
1050 AU.addPreserved<TempScopInfo>();
1051 AU.addPreserved<ScopInfo>();
1052 AU.addPreservedID(IndependentBlocksID);
1053 }
1054};
1055}
1056
1057char CodeGeneration::ID = 1;
1058
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001059Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001060
Tobias Grosser7242ad92013-02-22 08:07:06 +00001061INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1062 "Polly - Create LLVM-IR from SCoPs", false, false);
1063INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1064INITIALIZE_PASS_DEPENDENCY(Dependences);
1065INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1066INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1067INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1068INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1069INITIALIZE_PASS_DEPENDENCY(DataLayout);
1070INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001071 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001072
Sebastian Pope1f65542012-05-07 16:35:11 +00001073#endif // CLOOG_FOUND