blob: c18905ffbf43fa5fdd7be1e32246a05c91bb747a [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 Grosser75805372011-04-29 06:27:02 +000029#include "polly/ScopInfo.h"
30#include "polly/TempScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000031#include "polly/CodeGen/CodeGeneration.h"
32#include "polly/CodeGen/BlockGenerators.h"
33#include "polly/CodeGen/LoopGenerators.h"
Tobias Grosser6217e182012-08-03 12:50:07 +000034#include "polly/CodeGen/PTXGenerator.h"
Tobias Grosser3a275d22012-05-29 09:11:54 +000035#include "polly/CodeGen/Utils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000036#include "polly/Support/GICHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000037
38#include "llvm/Module.h"
39#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000040#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Micah Villmow7a3d8202012-10-08 17:26:19 +000045#include "llvm/DataLayout.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000047
48#define CLOOG_INT_GMP 1
49#include "cloog/cloog.h"
50#include "cloog/isl/cloog.h"
51
Raghesh Aloora71989c2011-12-28 02:48:26 +000052#include "isl/aff.h"
53
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <vector>
55#include <utility>
56
57using namespace polly;
58using namespace llvm;
59
60struct isl_set;
61
62namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000063static cl::opt<bool>
64OpenMP("enable-polly-openmp",
65 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
66 cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000067 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000068
Tobias Grosser6217e182012-08-03 12:50:07 +000069#ifdef GPU_CODEGEN
70static cl::opt<bool>
71GPGPU("enable-polly-gpgpu",
72 cl::desc("Generate GPU parallel code"), cl::Hidden,
73 cl::value_desc("GPGPU code generation enabled if true"),
74 cl::init(false), cl::ZeroOrMore);
75
76static cl::opt<std::string>
77GPUTriple("polly-gpgpu-triple",
78 cl::desc("Target triple for GPU code generation"),
79 cl::Hidden, cl::init(""));
80#endif /* GPU_CODEGEN */
81
Tobias Grosser75805372011-04-29 06:27:02 +000082static cl::opt<bool>
83AtLeastOnce("enable-polly-atLeastOnce",
84 cl::desc("Give polly the hint, that every loop is executed at least"
85 "once"), cl::Hidden,
86 cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000087 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000088
Tobias Grosser75805372011-04-29 06:27:02 +000089typedef DenseMap<const char*, Value*> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000090
Tobias Grosser75805372011-04-29 06:27:02 +000091/// Class to generate LLVM-IR that calculates the value of a clast_expr.
92class ClastExpCodeGen {
93 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000094 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000095
Tobias Grosserbb137e32012-01-24 16:42:28 +000096 Value *codegen(const clast_name *e, Type *Ty);
97 Value *codegen(const clast_term *e, Type *Ty);
98 Value *codegen(const clast_binary *e, Type *Ty);
99 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000100public:
101
102 // A generator for clast expressions.
103 //
104 // @param B The IRBuilder that defines where the code to calculate the
105 // clast expressions should be inserted.
106 // @param IVMAP A Map that translates strings describing the induction
107 // variables to the Values* that represent these variables
108 // on the LLVM side.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000109 ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000110
111 // Generates code to calculate a given clast expression.
112 //
113 // @param e The expression to calculate.
114 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000115 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000116};
117
118Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000119 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000120
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000121 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000122
123 return Builder.CreateSExtOrBitCast(I->second, Ty);
124}
125
126Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
127 APInt a = APInt_from_MPZ(e->val);
128
129 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
130 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
131
132 if (!e->var)
133 return ConstOne;
134
135 Value *var = codegen(e->var, Ty);
136 return Builder.CreateMul(ConstOne, var);
137}
138
139Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
140 Value *LHS = codegen(e->LHS, Ty);
141
142 APInt RHS_AP = APInt_from_MPZ(e->RHS);
143
144 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
145 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
146
147 switch (e->type) {
148 case clast_bin_mod:
149 return Builder.CreateSRem(LHS, RHS);
150 case clast_bin_fdiv:
151 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000152 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000153 Value *One = ConstantInt::get(Ty, 1);
154 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000155 Value *Sum1 = Builder.CreateSub(LHS, RHS);
156 Value *Sum2 = Builder.CreateAdd(Sum1, One);
157 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
158 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
159 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000160 }
161 case clast_bin_cdiv:
162 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000163 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
164 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000165 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000166 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
167 Value *Sum2 = Builder.CreateSub(Sum1, One);
168 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
169 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
170 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000171 }
172 case clast_bin_div:
173 return Builder.CreateSDiv(LHS, RHS);
174 };
175
176 llvm_unreachable("Unknown clast binary expression type");
177}
178
179Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
180 assert(( r->type == clast_red_min
181 || r->type == clast_red_max
182 || r->type == clast_red_sum)
183 && "Clast reduction type not supported");
184 Value *old = codegen(r->elts[0], Ty);
185
186 for (int i=1; i < r->n; ++i) {
187 Value *exprValue = codegen(r->elts[i], Ty);
188
189 switch (r->type) {
190 case clast_red_min:
191 {
192 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
193 old = Builder.CreateSelect(cmp, old, exprValue);
194 break;
195 }
196 case clast_red_max:
197 {
198 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
199 old = Builder.CreateSelect(cmp, old, exprValue);
200 break;
201 }
202 case clast_red_sum:
203 old = Builder.CreateAdd(old, exprValue);
204 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000205 }
Tobias Grosser75805372011-04-29 06:27:02 +0000206 }
207
Tobias Grosserbb137e32012-01-24 16:42:28 +0000208 return old;
209}
210
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000211ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosserbb137e32012-01-24 16:42:28 +0000212 : Builder(B), IVS(IVMap) {}
213
214Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
215 switch(e->type) {
216 case clast_expr_name:
217 return codegen((const clast_name *)e, Ty);
218 case clast_expr_term:
219 return codegen((const clast_term *)e, Ty);
220 case clast_expr_bin:
221 return codegen((const clast_binary *)e, Ty);
222 case clast_expr_red:
223 return codegen((const clast_reduction *)e, Ty);
224 }
225
226 llvm_unreachable("Unknown clast expression!");
227}
228
Tobias Grosser75805372011-04-29 06:27:02 +0000229class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000230public:
231 const std::vector<std::string> &getParallelLoops();
232
233private:
Tobias Grosser75805372011-04-29 06:27:02 +0000234 // The Scop we code generate.
235 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000236 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000237
238 // The Builder specifies the current location to code generate at.
239 IRBuilder<> &Builder;
240
241 // Map the Values from the old code to their counterparts in the new code.
242 ValueMapT ValueMap;
243
244 // clastVars maps from the textual representation of a clast variable to its
245 // current *Value. clast variables are scheduling variables, original
246 // induction variables or parameters. They are used either in loop bounds or
247 // to define the statement instance that is executed.
248 //
249 // for (s = 0; s < n + 3; ++i)
250 // for (t = s; t < m; ++j)
251 // Stmt(i = s + 3 * m, j = t);
252 //
253 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000254 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000255
256 // Codegenerator for clast expressions.
257 ClastExpCodeGen ExpGen;
258
259 // Do we currently generate parallel code?
260 bool parallelCodeGeneration;
261
262 std::vector<std::string> parallelLoops;
263
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000264 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000265
266 void codegen(const clast_assignment *a, ScopStmt *Statement,
267 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000268 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
270 void codegenSubstitutions(const clast_stmt *Assignment,
271 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000272 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000273
274 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000275 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000276
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000277 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000278
279 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000280 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000281
282 /// @brief Create OpenMP structure values.
283 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000284 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000285 /// structure.
Tobias Grosser177982c2012-11-01 05:34:48 +0000286 SetVector<Value*> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000287
Tobias Grossera17f6662012-11-01 05:34:35 +0000288 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000289 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000290 /// @param VMap A map from old to new values.
291 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000292
293 /// @brief Create an OpenMP parallel for loop.
294 ///
295 /// This loop reflects a loop as if it would have been created by an OpenMP
296 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000297 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000298
Tobias Grosser6217e182012-08-03 12:50:07 +0000299#ifdef GPU_CODEGEN
300 /// @brief Create GPGPU device memory access values.
301 ///
302 /// Create a list of values that will be set to be parameters of the GPGPU
303 /// subfunction. These parameters represent device memory base addresses
304 /// and the size in bytes.
305 SetVector<Value*> getGPUValues(unsigned &OutputBytes);
306
307 /// @brief Create a GPU parallel for loop.
308 ///
309 /// This loop reflects a loop as if it would have been created by a GPU
310 /// statement.
311 void codegenForGPGPU(const clast_for *F);
312
313 /// @brief Get innermost for loop.
314 const clast_stmt *getScheduleInfo(const clast_for *F,
315 std::vector<int> &NumIters,
316 unsigned &LoopDepth,
317 unsigned &NonPLoopDepth);
318#endif /* GPU_CODEGEN */
319
Tobias Grossere192b232012-05-22 08:46:07 +0000320 /// @brief Check if a loop is parallel
321 ///
322 /// Detect if a clast_for loop can be executed in parallel.
323 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000324 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000325 ///
326 /// @return bool Returns true if the incoming clast_for statement can
327 /// execute in parallel.
328 bool isParallelFor(const clast_for *For);
329
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000330 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000331
332 /// @brief Get the number of loop iterations for this loop.
333 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000334 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000335
336 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000337 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000338
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000339 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000340
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000341 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000342
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000343 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000344
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000345 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000347 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Tobias Grossere9ffea22012-03-15 09:34:48 +0000349 IntegerType *getIntPtrTy();
350
Tobias Grosser75805372011-04-29 06:27:02 +0000351 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000352 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000353
Tobias Grosserd596b372012-03-15 09:34:52 +0000354 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000355};
356}
357
Tobias Grossere9ffea22012-03-15 09:34:48 +0000358IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Tobias Grosser5d01691d2012-11-01 16:45:18 +0000359 return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000360}
361
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000362const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
363 return parallelLoops;
364}
365
366void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000367 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000368 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000369}
370
Tobias Grosserf00bd962012-04-02 12:26:13 +0000371void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
372 unsigned Dim, int VectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000373 std::vector<ValueMapT> *VectorVMap) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000374 const PHINode *PN;
Tobias Grosserf00bd962012-04-02 12:26:13 +0000375 Value *RHS;
376
377 assert(!A->LHS && "Statement assignments do not have left hand side");
378
Tobias Grosserf00bd962012-04-02 12:26:13 +0000379 PN = Stmt->getInductionVariableForDimension(Dim);
Tobias Grosser0905a232012-04-03 12:24:32 +0000380 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
381 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000382
383 if (VectorVMap)
Tobias Grosserf00bd962012-04-02 12:26:13 +0000384 (*VectorVMap)[VectorDim][PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000385
Tobias Grosserf00bd962012-04-02 12:26:13 +0000386 ValueMap[PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000387}
388
389void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
390 ScopStmt *Statement, int vectorDim,
391 std::vector<ValueMapT> *VectorVMap) {
392 int Dimension = 0;
393
394 while (Assignment) {
395 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
396 && "Substitions are expected to be assignments");
397 codegen((const clast_assignment *)Assignment, Statement, Dimension,
398 vectorDim, VectorVMap);
399 Assignment = Assignment->next;
400 Dimension++;
401 }
402}
403
404void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
405 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000406 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000407 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000408
409 if (u->substitutions)
410 codegenSubstitutions(u->substitutions, Statement);
411
Tobias Grosser80998e72012-03-02 11:27:28 +0000412 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000413
Tobias Grosser80998e72012-03-02 11:27:28 +0000414 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000415 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000416 return;
417 }
418
419 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000420
421 if (IVS) {
422 assert (u->substitutions && "Substitutions expected!");
423 int i = 0;
424 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
425 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000426 ClastVars[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000427 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000428 i++;
429 }
430 }
431
Tobias Grosser55d52082012-03-02 15:20:39 +0000432 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000433}
434
435void ClastStmtCodeGen::codegen(const clast_block *b) {
436 if (b->body)
437 codegen(b->body);
438}
439
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000440void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
441 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000442 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000443 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000444
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000445 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
446 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
447 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000448
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000449 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
450 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000451
452 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000453 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000454
455 if (f->body)
456 codegen(f->body);
457
458 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000459 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000460 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000461}
462
Tobias Grosser177982c2012-11-01 05:34:48 +0000463// Helper class to determine all scalar parameters used in the basic blocks of a
464// clast. Scalar parameters are scalar variables defined outside of the SCoP.
465class ParameterVisitor : public ClastVisitor {
466 std::set<Value *> Values;
467public:
468 ParameterVisitor() : ClastVisitor(), Values() { }
469
470 void visitUser(const clast_user_stmt *Stmt) {
471 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
472 const BasicBlock *BB = S->getBasicBlock();
473
474 // Check all the operands of instructions in the basic block.
475 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
476 ++BI) {
477 const Instruction &Inst = *BI;
478 for (Instruction::const_op_iterator II = Inst.op_begin(),
479 IE = Inst.op_end(); II != IE; ++II) {
480 Value *SrcVal = *II;
481
482 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
483 if (S->getParent()->getRegion().contains(OpInst))
484 continue;
485
486 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
487 Values.insert(SrcVal);
488 }
489 }
490 }
491
492 // Iterator to iterate over the values found.
493 typedef std::set<Value *>::const_iterator const_iterator;
494 inline const_iterator begin() const { return Values.begin(); }
495 inline const_iterator end() const { return Values.end(); }
496};
497
498SetVector<Value*> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000499 SetVector<Value*> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000500
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000501 // The clast variables
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000502 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000503 I != E; I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000504 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000505
Tobias Grosser177982c2012-11-01 05:34:48 +0000506 // Find the temporaries that are referenced in the clast statements'
507 // basic blocks but are not defined by these blocks (e.g., references
508 // to function arguments or temporaries defined before the start of
509 // the SCoP).
510 ParameterVisitor Params;
511 Params.visit(Body);
512
513 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
514 PI != PE; ++PI) {
515 Value *V = *PI;
516 Values.insert(V);
517 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
518 }
519
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000520 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000521}
522
Tobias Grossera17f6662012-11-01 05:34:35 +0000523void ClastStmtCodeGen::updateWithValueMap(
524 OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000525 std::set<Value*> Inserted;
526
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000527 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000528 I != E; I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000529 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000530 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000531 }
532
Tobias Grossera17f6662012-11-01 05:34:35 +0000533 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
534 E = VMap.end(); I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000535 if (Inserted.count(I->first))
536 continue;
537
538 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000539 }
540}
541
Tobias Grosser900893d2012-03-29 13:10:26 +0000542static void clearDomtree(Function *F, DominatorTree &DT) {
543 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
544 std::vector<BasicBlock*> Nodes;
545 for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
546 Nodes.push_back(I->getBlock());
547
548 for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
549 I != E; ++I)
550 DT.eraseNode(*I);
551}
552
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000553void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000554 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000555 BasicBlock::iterator LoopBody;
556 IntegerType *IntPtrTy = getIntPtrTy();
557 SetVector<Value*> Values;
558 OMPGenerator::ValueToValueMapTy VMap;
559 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000560
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000561 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
562 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000563 LB = ExpGen.codegen(For->LB, IntPtrTy);
564 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000565
Tobias Grosser177982c2012-11-01 05:34:48 +0000566 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000567
Tobias Grosserebf30082012-03-23 12:20:32 +0000568 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000569 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
570 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000571
Tobias Grossera17f6662012-11-01 05:34:35 +0000572 // Save the current values.
573 const ValueMapT ValueMapCopy = ValueMap;
574 const CharMapT ClastVarsCopy = ClastVars;
575
576 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000577 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000578
579 if (For->body)
580 codegen(For->body);
581
Tobias Grossera17f6662012-11-01 05:34:35 +0000582 // Restore the original values.
583 ValueMap = ValueMapCopy;
584 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000585
Tobias Grosser900893d2012-03-29 13:10:26 +0000586 clearDomtree((*LoopBody).getParent()->getParent(),
587 P->getAnalysis<DominatorTree>());
588
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000589 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000590}
591
Tobias Grosser6217e182012-08-03 12:50:07 +0000592#ifdef GPU_CODEGEN
593static unsigned getArraySizeInBytes(const ArrayType *AT) {
594 unsigned Bytes = AT->getNumElements();
595 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
596 Bytes *= getArraySizeInBytes(T);
597 else
598 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
599
600 return Bytes;
601}
602
603SetVector<Value*> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
604 SetVector<Value*> Values;
605 OutputBytes = 0;
606
607 // Record the memory reference base addresses.
608 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
609 ScopStmt *Stmt = *SI;
610 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
611 E = Stmt->memacc_end(); I != E; ++I) {
612 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
613 Values.insert((BaseAddr));
614
615 // FIXME: we assume that there is one and only one array to be written
616 // in a SCoP.
617 int NumWrites = 0;
618 if ((*I)->isWrite()) {
619 ++NumWrites;
620 assert(NumWrites <= 1 &&
621 "We support at most one array to be written in a SCoP.");
622 if (const PointerType * PT =
623 dyn_cast<PointerType>(BaseAddr->getType())) {
624 Type *T = PT->getArrayElementType();
625 const ArrayType *ATy = dyn_cast<ArrayType>(T);
626 OutputBytes = getArraySizeInBytes(ATy);
627 }
628 }
629 }
630 }
631
632 return Values;
633}
634
635const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
636 std::vector<int> &NumIters,
637 unsigned &LoopDepth,
638 unsigned &NonPLoopDepth) {
639 clast_stmt *Stmt = (clast_stmt *)F;
640 const clast_for *Result;
641 bool NonParaFlag = false;
642 LoopDepth = 0;
643 NonPLoopDepth = 0;
644
645 while (Stmt) {
646 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
647 const clast_for *T = (clast_for *) Stmt;
648 if (isParallelFor(T)) {
649 if (!NonParaFlag) {
650 NumIters.push_back(getNumberOfIterations(T));
651 Result = T;
652 }
653 } else
654 NonParaFlag = true;
655
656 Stmt = T->body;
657 LoopDepth++;
658 continue;
659 }
660 Stmt = Stmt->next;
661 }
662
663 assert(NumIters.size() == 4 &&
664 "The loops should be tiled into 4-depth parallel loops and an "
665 "innermost non-parallel one (if exist).");
666 NonPLoopDepth = LoopDepth - NumIters.size();
667 assert(NonPLoopDepth <= 1
668 && "We support only one innermost non-parallel loop currently.");
669 return (const clast_stmt *)Result->body;
670}
671
672void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
673 BasicBlock::iterator LoopBody;
674 SetVector<Value *> Values;
675 SetVector<Value *> IVS;
676 std::vector<int> NumIterations;
677 PTXGenerator::ValueToValueMapTy VMap;
678
679 assert(!GPUTriple.empty()
680 && "Target triple should be set properly for GPGPU code generation.");
681 PTXGenerator PTXGen(Builder, P, GPUTriple);
682
683 // Get original IVS and ScopStmt
684 unsigned TiledLoopDepth, NonPLoopDepth;
685 const clast_stmt *InnerStmt = getScheduleInfo(F, NumIterations,
686 TiledLoopDepth, NonPLoopDepth);
687 const clast_stmt *TmpStmt;
688 const clast_user_stmt *U;
689 const clast_for *InnerFor;
690 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
691 InnerFor = (const clast_for *)InnerStmt;
692 TmpStmt = InnerFor->body;
693 } else
694 TmpStmt = InnerStmt;
695 U = (const clast_user_stmt *) TmpStmt;
696 ScopStmt *Statement = (ScopStmt *) U->statement->usr;
697 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
698 const Value* IV = Statement->getInductionVariableForDimension(i);
699 IVS.insert(const_cast<Value *>(IV));
700 }
701
702 unsigned OutBytes;
703 Values = getGPUValues(OutBytes);
704 PTXGen.setOutputBytes(OutBytes);
705 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
706
707 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
708 Builder.SetInsertPoint(LoopBody);
709
710 BasicBlock *AfterBB = 0;
711 if (NonPLoopDepth) {
712 Value *LowerBound, *UpperBound, *IV, *Stride;
713 Type *IntPtrTy = getIntPtrTy();
714 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
715 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
716 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
717 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB);
718 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
719 Value *OldIV = const_cast<Value *>(OldIV_);
720 VMap.insert(std::make_pair<Value*, Value*>(OldIV, IV));
721 }
722
Tobias Grossera17f6662012-11-01 05:34:35 +0000723 // Preserve the current values.
724 const ValueMapT ValueMapCopy = ValueMap;
725 const CharMapT ClastVarsCopy = ClastVars;
726 updateWithVMap(VMap);
727
Tobias Grosser6217e182012-08-03 12:50:07 +0000728 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000729
730 // Restore the original values.
731 ValueMap = ValueMapCopy;
732 ClastVars = ClastVarsCopy;
Tobias Grosser6217e182012-08-03 12:50:07 +0000733
734 if (AfterBB)
735 Builder.SetInsertPoint(AfterBB->begin());
736
737 // FIXME: The replacement of the host base address with the parameter of ptx
738 // subfunction should have been done by updateWithValueMap. We use the
739 // following codes to avoid affecting other parts of Polly. This should be
740 // fixed later.
741 Function *FN = Builder.GetInsertBlock()->getParent();
742 for (unsigned j = 0; j < Values.size(); j++) {
743 Value *baseAddr = Values[j];
744 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
745 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
746 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
747 }
748 }
749 Builder.SetInsertPoint(AfterLoop);
750 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
751 NumIterations[2], NumIterations[3]);
752 PTXGen.finishGeneration(FN);
753}
754#endif
755
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000756bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
757 const clast_stmt *stmt = f->body;
758
759 while (stmt) {
760 if (!CLAST_STMT_IS_A(stmt, stmt_user))
761 return false;
762
763 stmt = stmt->next;
764 }
765
766 return true;
767}
768
769int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
770 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
771 isl_set *tmp = isl_set_copy(loopDomain);
772
773 // Calculate a map similar to the identity map, but with the last input
774 // and output dimension not related.
775 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
776 isl_space *Space = isl_set_get_space(loopDomain);
777 Space = isl_space_drop_outputs(Space,
778 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
779 Space = isl_space_map_from_set(Space);
780 isl_map *identity = isl_map_identity(Space);
781 identity = isl_map_add_dims(identity, isl_dim_in, 1);
782 identity = isl_map_add_dims(identity, isl_dim_out, 1);
783
784 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
785 map = isl_map_intersect(map, identity);
786
787 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
788 isl_map *lexmin = isl_map_lexmin(map);
789 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
790
791 isl_set *elements = isl_map_range(sub);
792
793 if (!isl_set_is_singleton(elements)) {
794 isl_set_free(elements);
795 return -1;
796 }
797
798 isl_point *p = isl_set_sample_point(elements);
799
800 isl_int v;
801 isl_int_init(v);
802 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
803 int numberIterations = isl_int_get_si(v);
804 isl_int_clear(v);
805 isl_point_free(p);
806
807 return (numberIterations) / isl_int_get_si(f->stride) + 1;
808}
809
Tobias Grosser2da263e2012-03-15 09:34:55 +0000810void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
811 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
812 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000813
Tobias Grosser2da263e2012-03-15 09:34:55 +0000814 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000815
Tobias Grosser2da263e2012-03-15 09:34:55 +0000816 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000817 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
818 Stride = Stride.zext(LoopIVType->getBitWidth());
819 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
820
Tobias Grosser2da263e2012-03-15 09:34:55 +0000821 std::vector<Value*> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000822 IVS[0] = LB;
823
Tobias Grosser2da263e2012-03-15 09:34:55 +0000824 for (int i = 1; i < VectorWidth; i++)
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000825 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
826
Tobias Grosser00d898d2012-03-15 09:34:58 +0000827 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000828
829 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000830 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000831
Tobias Grosser2da263e2012-03-15 09:34:55 +0000832 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000833
Tobias Grosser2da263e2012-03-15 09:34:55 +0000834 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000835 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
836 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000837 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000838 }
839
840 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000841 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000842 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000843}
844
Tobias Grossere192b232012-05-22 08:46:07 +0000845
846bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
847 isl_set *Domain = isl_set_from_cloog_domain(f->domain);
848 assert(Domain && "Cannot access domain of loop");
849
850 Dependences &D = P->getAnalysis<Dependences>();
851
852 return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
853}
854
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000855void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000856 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000857 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000858 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
859 && (getNumberOfIterations(f) <= 16)) {
860 codegenForVector(f);
861 return;
862 }
863
864 if (OpenMP && !parallelCodeGeneration) {
865 parallelCodeGeneration = true;
866 parallelLoops.push_back(f->iterator);
867 codegenForOpenMP(f);
868 parallelCodeGeneration = false;
869 return;
870 }
871 }
872
Tobias Grosser6217e182012-08-03 12:50:07 +0000873#ifdef GPU_CODEGEN
874 if (GPGPU && isParallelFor(f)) {
875 if (!parallelCodeGeneration) {
876 parallelCodeGeneration = true;
877 parallelLoops.push_back(f->iterator);
878 codegenForGPGPU(f);
879 parallelCodeGeneration = false;
880 return;
881 }
882 }
883#endif
884
Tobias Grosserce3f5372012-03-02 11:26:42 +0000885 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000886}
887
888Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000889 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
890 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000891 CmpInst::Predicate P;
892
893 if (eq->sign == 0)
894 P = ICmpInst::ICMP_EQ;
895 else if (eq->sign > 0)
896 P = ICmpInst::ICMP_SGE;
897 else
898 P = ICmpInst::ICMP_SLE;
899
900 return Builder.CreateICmp(P, LHS, RHS);
901}
902
903void ClastStmtCodeGen::codegen(const clast_guard *g) {
904 Function *F = Builder.GetInsertBlock()->getParent();
905 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000906
907 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
908 Builder.GetInsertPoint(), P);
909 CondBB->setName("polly.cond");
910 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
911 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000912 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000913
Tobias Grosserd596b372012-03-15 09:34:52 +0000914 DominatorTree &DT = P->getAnalysis<DominatorTree>();
915 DT.addNewBlock(ThenBB, CondBB);
916 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000917
918 CondBB->getTerminator()->eraseFromParent();
919
920 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000921
922 Value *Predicate = codegen(&(g->eq[0]));
923
924 for (int i = 1; i < g->n; ++i) {
925 Value *TmpPredicate = codegen(&(g->eq[i]));
926 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
927 }
928
929 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
930 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000931 Builder.CreateBr(MergeBB);
932 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000933
934 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000935
936 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000937}
938
939void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
940 if (CLAST_STMT_IS_A(stmt, stmt_root))
941 assert(false && "No second root statement expected");
942 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
943 codegen((const clast_assignment *)stmt);
944 else if (CLAST_STMT_IS_A(stmt, stmt_user))
945 codegen((const clast_user_stmt *)stmt);
946 else if (CLAST_STMT_IS_A(stmt, stmt_block))
947 codegen((const clast_block *)stmt);
948 else if (CLAST_STMT_IS_A(stmt, stmt_for))
949 codegen((const clast_for *)stmt);
950 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
951 codegen((const clast_guard *)stmt);
952
953 if (stmt->next)
954 codegen(stmt->next);
955}
956
957void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000958 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000959
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000960 int i = 0;
961 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
962 PI != PE; ++PI) {
963 assert(i < names->nb_parameters && "Not enough parameter names");
964
965 const SCEV *Param = *PI;
966 Type *Ty = Param->getType();
967
968 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
969 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000970 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000971
972 ++i;
973 }
974}
975
976void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000977 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000978
979 parallelCodeGeneration = false;
980
981 const clast_stmt *stmt = (const clast_stmt*) r;
982 if (stmt->next)
983 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984}
985
Tobias Grosserd596b372012-03-15 09:34:52 +0000986ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000987 S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000988
Tobias Grosser75805372011-04-29 06:27:02 +0000989namespace {
990class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000991 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000992
993 public:
994 static char ID;
995
996 CodeGeneration() : ScopPass(ID) {}
997
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000998
Tobias Grosser3a275d22012-05-29 09:11:54 +0000999 bool runOnScop(Scop &S) {
1000 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001001
Tobias Grosser3a275d22012-05-29 09:11:54 +00001002 assert(S.getRegion().isSimple() && "Only simple regions are supported");
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001003
Tobias Grosser3a275d22012-05-29 09:11:54 +00001004 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001005
Tobias Grosser3a275d22012-05-29 09:11:54 +00001006 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001007
Tobias Grosser3a275d22012-05-29 09:11:54 +00001008 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001009 CloogInfo &C = getAnalysis<CloogInfo>();
1010 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001011
Tobias Grosser3a275d22012-05-29 09:11:54 +00001012 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001013 CodeGen.getParallelLoops().begin(),
1014 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001015 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001016 }
1017
1018 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001019 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
1020 PE = ParallelLoops.end(); PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001021 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1022 }
1023
1024 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1025 AU.addRequired<CloogInfo>();
1026 AU.addRequired<Dependences>();
1027 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001028 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001029 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001030 AU.addRequired<ScopDetection>();
1031 AU.addRequired<ScopInfo>();
Micah Villmow7a3d8202012-10-08 17:26:19 +00001032 AU.addRequired<DataLayout>();
Tobias Grosser75805372011-04-29 06:27:02 +00001033
1034 AU.addPreserved<CloogInfo>();
1035 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001036
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001037 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001038 AU.addPreserved<LoopInfo>();
1039 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001040 AU.addPreserved<ScopDetection>();
1041 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001042
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001043 // FIXME: We do not yet add regions for the newly generated code to the
1044 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001045 AU.addPreserved<RegionInfo>();
1046 AU.addPreserved<TempScopInfo>();
1047 AU.addPreserved<ScopInfo>();
1048 AU.addPreservedID(IndependentBlocksID);
1049 }
1050};
1051}
1052
1053char CodeGeneration::ID = 1;
1054
Tobias Grosser73600b82011-10-08 00:30:40 +00001055INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001056 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +00001057INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1058INITIALIZE_PASS_DEPENDENCY(Dependences)
1059INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1060INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1061INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1062INITIALIZE_PASS_DEPENDENCY(ScopDetection)
Tobias Grosser660b58d2012-10-08 08:56:52 +00001063INITIALIZE_PASS_DEPENDENCY(DataLayout)
Tobias Grosser73600b82011-10-08 00:30:40 +00001064INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001065 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001066
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001067Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001068 return new CodeGeneration();
1069}
Sebastian Pope1f65542012-05-07 16:35:11 +00001070
1071#endif // CLOOG_FOUND