blob: ad703759e8b1fee52b2813f2ab3ce53d734f6fd7 [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 +000082typedef DenseMap<const char*, Value*> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000083
Tobias Grosser75805372011-04-29 06:27:02 +000084/// Class to generate LLVM-IR that calculates the value of a clast_expr.
85class ClastExpCodeGen {
86 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000087 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000088
Tobias Grosserbb137e32012-01-24 16:42:28 +000089 Value *codegen(const clast_name *e, Type *Ty);
90 Value *codegen(const clast_term *e, Type *Ty);
91 Value *codegen(const clast_binary *e, Type *Ty);
92 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias 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);
143 case clast_bin_fdiv:
144 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000145 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000146 Value *One = ConstantInt::get(Ty, 1);
147 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000148 Value *Sum1 = Builder.CreateSub(LHS, RHS);
149 Value *Sum2 = Builder.CreateAdd(Sum1, One);
150 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
151 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
152 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000153 }
154 case clast_bin_cdiv:
155 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000156 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
157 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000158 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000159 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
160 Value *Sum2 = Builder.CreateSub(Sum1, One);
161 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
162 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
163 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000164 }
165 case clast_bin_div:
166 return Builder.CreateSDiv(LHS, RHS);
167 };
168
169 llvm_unreachable("Unknown clast binary expression type");
170}
171
172Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
173 assert(( r->type == clast_red_min
174 || r->type == clast_red_max
175 || r->type == clast_red_sum)
176 && "Clast reduction type not supported");
177 Value *old = codegen(r->elts[0], Ty);
178
179 for (int i=1; i < r->n; ++i) {
180 Value *exprValue = codegen(r->elts[i], Ty);
181
182 switch (r->type) {
183 case clast_red_min:
184 {
185 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
186 old = Builder.CreateSelect(cmp, old, exprValue);
187 break;
188 }
189 case clast_red_max:
190 {
191 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
192 old = Builder.CreateSelect(cmp, old, exprValue);
193 break;
194 }
195 case clast_red_sum:
196 old = Builder.CreateAdd(old, exprValue);
197 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000198 }
Tobias Grosser75805372011-04-29 06:27:02 +0000199 }
200
Tobias Grosserbb137e32012-01-24 16:42:28 +0000201 return old;
202}
203
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000204ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosserbb137e32012-01-24 16:42:28 +0000205 : Builder(B), IVS(IVMap) {}
206
207Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
208 switch(e->type) {
209 case clast_expr_name:
210 return codegen((const clast_name *)e, Ty);
211 case clast_expr_term:
212 return codegen((const clast_term *)e, Ty);
213 case clast_expr_bin:
214 return codegen((const clast_binary *)e, Ty);
215 case clast_expr_red:
216 return codegen((const clast_reduction *)e, Ty);
217 }
218
219 llvm_unreachable("Unknown clast expression!");
220}
221
Tobias Grosser75805372011-04-29 06:27:02 +0000222class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000223public:
224 const std::vector<std::string> &getParallelLoops();
225
226private:
Tobias Grosser75805372011-04-29 06:27:02 +0000227 // The Scop we code generate.
228 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000229 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000230
231 // The Builder specifies the current location to code generate at.
232 IRBuilder<> &Builder;
233
234 // Map the Values from the old code to their counterparts in the new code.
235 ValueMapT ValueMap;
236
237 // clastVars maps from the textual representation of a clast variable to its
238 // current *Value. clast variables are scheduling variables, original
239 // induction variables or parameters. They are used either in loop bounds or
240 // to define the statement instance that is executed.
241 //
242 // for (s = 0; s < n + 3; ++i)
243 // for (t = s; t < m; ++j)
244 // Stmt(i = s + 3 * m, j = t);
245 //
246 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000247 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000248
249 // Codegenerator for clast expressions.
250 ClastExpCodeGen ExpGen;
251
252 // Do we currently generate parallel code?
253 bool parallelCodeGeneration;
254
255 std::vector<std::string> parallelLoops;
256
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000257 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000258
259 void codegen(const clast_assignment *a, ScopStmt *Statement,
260 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000261 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000262
263 void codegenSubstitutions(const clast_stmt *Assignment,
264 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000265 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
267 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000268 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000270 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000271
272 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000273 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000274
275 /// @brief Create OpenMP structure values.
276 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000277 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000278 /// structure.
Tobias Grosser177982c2012-11-01 05:34:48 +0000279 SetVector<Value*> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000280
Tobias Grossera17f6662012-11-01 05:34:35 +0000281 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000282 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000283 /// @param VMap A map from old to new values.
284 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000285
286 /// @brief Create an OpenMP parallel for loop.
287 ///
288 /// This loop reflects a loop as if it would have been created by an OpenMP
289 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000290 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000291
Tobias Grosser6217e182012-08-03 12:50:07 +0000292#ifdef GPU_CODEGEN
293 /// @brief Create GPGPU device memory access values.
294 ///
295 /// Create a list of values that will be set to be parameters of the GPGPU
296 /// subfunction. These parameters represent device memory base addresses
297 /// and the size in bytes.
298 SetVector<Value*> getGPUValues(unsigned &OutputBytes);
299
300 /// @brief Create a GPU parallel for loop.
301 ///
302 /// This loop reflects a loop as if it would have been created by a GPU
303 /// statement.
304 void codegenForGPGPU(const clast_for *F);
305
306 /// @brief Get innermost for loop.
307 const clast_stmt *getScheduleInfo(const clast_for *F,
308 std::vector<int> &NumIters,
309 unsigned &LoopDepth,
310 unsigned &NonPLoopDepth);
311#endif /* GPU_CODEGEN */
312
Tobias Grossere192b232012-05-22 08:46:07 +0000313 /// @brief Check if a loop is parallel
314 ///
315 /// Detect if a clast_for loop can be executed in parallel.
316 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000317 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000318 ///
319 /// @return bool Returns true if the incoming clast_for statement can
320 /// execute in parallel.
321 bool isParallelFor(const clast_for *For);
322
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000323 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000324
325 /// @brief Get the number of loop iterations for this loop.
326 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000327 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000328
329 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000330 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000331
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000332 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000333
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000334 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000335
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000336 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000337
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000338 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000339
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000340 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000341
Tobias Grossere9ffea22012-03-15 09:34:48 +0000342 IntegerType *getIntPtrTy();
343
Tobias Grosser75805372011-04-29 06:27:02 +0000344 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000345 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Tobias Grosserd596b372012-03-15 09:34:52 +0000347 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000348};
349}
350
Tobias Grossere9ffea22012-03-15 09:34:48 +0000351IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Tobias Grosser5d01691d2012-11-01 16:45:18 +0000352 return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000353}
354
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000355const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
356 return parallelLoops;
357}
358
359void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000360 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000361 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000362}
363
Tobias Grosserf00bd962012-04-02 12:26:13 +0000364void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
365 unsigned Dim, int VectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000366 std::vector<ValueMapT> *VectorVMap) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000367 const PHINode *PN;
Tobias Grosserf00bd962012-04-02 12:26:13 +0000368 Value *RHS;
369
370 assert(!A->LHS && "Statement assignments do not have left hand side");
371
Tobias Grosserf00bd962012-04-02 12:26:13 +0000372 PN = Stmt->getInductionVariableForDimension(Dim);
Tobias Grosser0905a232012-04-03 12:24:32 +0000373 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
374 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000375
376 if (VectorVMap)
Tobias Grosserf00bd962012-04-02 12:26:13 +0000377 (*VectorVMap)[VectorDim][PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000378
Tobias Grosserf00bd962012-04-02 12:26:13 +0000379 ValueMap[PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000380}
381
382void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
383 ScopStmt *Statement, int vectorDim,
384 std::vector<ValueMapT> *VectorVMap) {
385 int Dimension = 0;
386
387 while (Assignment) {
388 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
389 && "Substitions are expected to be assignments");
390 codegen((const clast_assignment *)Assignment, Statement, Dimension,
391 vectorDim, VectorVMap);
392 Assignment = Assignment->next;
393 Dimension++;
394 }
395}
396
Sebastian Popa00a0292012-12-18 07:46:06 +0000397// Takes the cloog specific domain and translates it into a map Statement ->
398// PartialSchedule, where the PartialSchedule contains all the dimensions that
399// have been code generated up to this point.
400static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
401 isl_set *Domain) {
402 isl_map *Schedule = Statement->getScattering();
403 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
404 int UnscheduledDimensions = isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
405
406 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
407 UnscheduledDimensions);
408}
409
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000410void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
411 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000412 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000413 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000414
415 if (u->substitutions)
416 codegenSubstitutions(u->substitutions, Statement);
417
Tobias Grosser80998e72012-03-02 11:27:28 +0000418 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000419
Tobias Grosser80998e72012-03-02 11:27:28 +0000420 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000421 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000422 return;
423 }
424
425 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000426
427 if (IVS) {
428 assert (u->substitutions && "Substitutions expected!");
429 int i = 0;
430 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
431 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000432 ClastVars[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000433 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000434 i++;
435 }
436 }
437
Sebastian Popa00a0292012-12-18 07:46:06 +0000438 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
439 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Schedule, P);
440 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000441}
442
443void ClastStmtCodeGen::codegen(const clast_block *b) {
444 if (b->body)
445 codegen(b->body);
446}
447
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000448void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
449 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000450 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000451 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000452
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000453 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
454 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
455 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000456
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000457 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
458 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000459
460 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000461 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000462
463 if (f->body)
464 codegen(f->body);
465
466 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000467 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000468 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000469}
470
Tobias Grosser177982c2012-11-01 05:34:48 +0000471// Helper class to determine all scalar parameters used in the basic blocks of a
472// clast. Scalar parameters are scalar variables defined outside of the SCoP.
473class ParameterVisitor : public ClastVisitor {
474 std::set<Value *> Values;
475public:
476 ParameterVisitor() : ClastVisitor(), Values() { }
477
478 void visitUser(const clast_user_stmt *Stmt) {
479 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
480 const BasicBlock *BB = S->getBasicBlock();
481
482 // Check all the operands of instructions in the basic block.
483 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
484 ++BI) {
485 const Instruction &Inst = *BI;
486 for (Instruction::const_op_iterator II = Inst.op_begin(),
487 IE = Inst.op_end(); II != IE; ++II) {
488 Value *SrcVal = *II;
489
490 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
491 if (S->getParent()->getRegion().contains(OpInst))
492 continue;
493
494 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
495 Values.insert(SrcVal);
496 }
497 }
498 }
499
500 // Iterator to iterate over the values found.
501 typedef std::set<Value *>::const_iterator const_iterator;
502 inline const_iterator begin() const { return Values.begin(); }
503 inline const_iterator end() const { return Values.end(); }
504};
505
506SetVector<Value*> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000507 SetVector<Value*> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000508
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000509 // The clast variables
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000510 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000511 I != E; I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000512 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000513
Tobias Grosser177982c2012-11-01 05:34:48 +0000514 // Find the temporaries that are referenced in the clast statements'
515 // basic blocks but are not defined by these blocks (e.g., references
516 // to function arguments or temporaries defined before the start of
517 // the SCoP).
518 ParameterVisitor Params;
519 Params.visit(Body);
520
521 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
522 PI != PE; ++PI) {
523 Value *V = *PI;
524 Values.insert(V);
525 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
526 }
527
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000528 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000529}
530
Tobias Grossera17f6662012-11-01 05:34:35 +0000531void ClastStmtCodeGen::updateWithValueMap(
532 OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000533 std::set<Value*> Inserted;
534
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000535 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000536 I != E; I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000537 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000538 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000539 }
540
Tobias Grossera17f6662012-11-01 05:34:35 +0000541 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
542 E = VMap.end(); I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000543 if (Inserted.count(I->first))
544 continue;
545
546 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000547 }
548}
549
Tobias Grosser900893d2012-03-29 13:10:26 +0000550static void clearDomtree(Function *F, DominatorTree &DT) {
551 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
552 std::vector<BasicBlock*> Nodes;
553 for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
554 Nodes.push_back(I->getBlock());
555
556 for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
557 I != E; ++I)
558 DT.eraseNode(*I);
559}
560
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000561void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000562 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000563 BasicBlock::iterator LoopBody;
564 IntegerType *IntPtrTy = getIntPtrTy();
565 SetVector<Value*> Values;
566 OMPGenerator::ValueToValueMapTy VMap;
567 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000568
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000569 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
570 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000571 LB = ExpGen.codegen(For->LB, IntPtrTy);
572 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000573
Tobias Grosser177982c2012-11-01 05:34:48 +0000574 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000575
Tobias Grosserebf30082012-03-23 12:20:32 +0000576 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000577 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
578 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000579
Tobias Grossera17f6662012-11-01 05:34:35 +0000580 // Save the current values.
581 const ValueMapT ValueMapCopy = ValueMap;
582 const CharMapT ClastVarsCopy = ClastVars;
583
584 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000585 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000586
587 if (For->body)
588 codegen(For->body);
589
Tobias Grossera17f6662012-11-01 05:34:35 +0000590 // Restore the original values.
591 ValueMap = ValueMapCopy;
592 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000593
Tobias Grosser900893d2012-03-29 13:10:26 +0000594 clearDomtree((*LoopBody).getParent()->getParent(),
595 P->getAnalysis<DominatorTree>());
596
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000597 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000598}
599
Tobias Grosser6217e182012-08-03 12:50:07 +0000600#ifdef GPU_CODEGEN
601static unsigned getArraySizeInBytes(const ArrayType *AT) {
602 unsigned Bytes = AT->getNumElements();
603 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
604 Bytes *= getArraySizeInBytes(T);
605 else
606 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
607
608 return Bytes;
609}
610
611SetVector<Value*> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
612 SetVector<Value*> Values;
613 OutputBytes = 0;
614
615 // Record the memory reference base addresses.
616 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
617 ScopStmt *Stmt = *SI;
618 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
619 E = Stmt->memacc_end(); I != E; ++I) {
620 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
621 Values.insert((BaseAddr));
622
623 // FIXME: we assume that there is one and only one array to be written
624 // in a SCoP.
625 int NumWrites = 0;
626 if ((*I)->isWrite()) {
627 ++NumWrites;
628 assert(NumWrites <= 1 &&
629 "We support at most one array to be written in a SCoP.");
630 if (const PointerType * PT =
631 dyn_cast<PointerType>(BaseAddr->getType())) {
632 Type *T = PT->getArrayElementType();
633 const ArrayType *ATy = dyn_cast<ArrayType>(T);
634 OutputBytes = getArraySizeInBytes(ATy);
635 }
636 }
637 }
638 }
639
640 return Values;
641}
642
643const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
644 std::vector<int> &NumIters,
645 unsigned &LoopDepth,
646 unsigned &NonPLoopDepth) {
647 clast_stmt *Stmt = (clast_stmt *)F;
648 const clast_for *Result;
649 bool NonParaFlag = false;
650 LoopDepth = 0;
651 NonPLoopDepth = 0;
652
653 while (Stmt) {
654 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
655 const clast_for *T = (clast_for *) Stmt;
656 if (isParallelFor(T)) {
657 if (!NonParaFlag) {
658 NumIters.push_back(getNumberOfIterations(T));
659 Result = T;
660 }
661 } else
662 NonParaFlag = true;
663
664 Stmt = T->body;
665 LoopDepth++;
666 continue;
667 }
668 Stmt = Stmt->next;
669 }
670
671 assert(NumIters.size() == 4 &&
672 "The loops should be tiled into 4-depth parallel loops and an "
673 "innermost non-parallel one (if exist).");
674 NonPLoopDepth = LoopDepth - NumIters.size();
675 assert(NonPLoopDepth <= 1
676 && "We support only one innermost non-parallel loop currently.");
677 return (const clast_stmt *)Result->body;
678}
679
680void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
681 BasicBlock::iterator LoopBody;
682 SetVector<Value *> Values;
683 SetVector<Value *> IVS;
684 std::vector<int> NumIterations;
685 PTXGenerator::ValueToValueMapTy VMap;
686
687 assert(!GPUTriple.empty()
688 && "Target triple should be set properly for GPGPU code generation.");
689 PTXGenerator PTXGen(Builder, P, GPUTriple);
690
691 // Get original IVS and ScopStmt
692 unsigned TiledLoopDepth, NonPLoopDepth;
693 const clast_stmt *InnerStmt = getScheduleInfo(F, NumIterations,
694 TiledLoopDepth, NonPLoopDepth);
695 const clast_stmt *TmpStmt;
696 const clast_user_stmt *U;
697 const clast_for *InnerFor;
698 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
699 InnerFor = (const clast_for *)InnerStmt;
700 TmpStmt = InnerFor->body;
701 } else
702 TmpStmt = InnerStmt;
703 U = (const clast_user_stmt *) TmpStmt;
704 ScopStmt *Statement = (ScopStmt *) U->statement->usr;
705 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
706 const Value* IV = Statement->getInductionVariableForDimension(i);
707 IVS.insert(const_cast<Value *>(IV));
708 }
709
710 unsigned OutBytes;
711 Values = getGPUValues(OutBytes);
712 PTXGen.setOutputBytes(OutBytes);
713 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
714
715 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
716 Builder.SetInsertPoint(LoopBody);
717
718 BasicBlock *AfterBB = 0;
719 if (NonPLoopDepth) {
720 Value *LowerBound, *UpperBound, *IV, *Stride;
721 Type *IntPtrTy = getIntPtrTy();
722 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
723 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
724 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000725 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
726 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000727 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
728 Value *OldIV = const_cast<Value *>(OldIV_);
729 VMap.insert(std::make_pair<Value*, Value*>(OldIV, IV));
730 }
731
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000732 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000733
Tobias Grosser6217e182012-08-03 12:50:07 +0000734 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000735
Tobias Grosser6217e182012-08-03 12:50:07 +0000736 if (AfterBB)
737 Builder.SetInsertPoint(AfterBB->begin());
738
739 // FIXME: The replacement of the host base address with the parameter of ptx
740 // subfunction should have been done by updateWithValueMap. We use the
741 // following codes to avoid affecting other parts of Polly. This should be
742 // fixed later.
743 Function *FN = Builder.GetInsertBlock()->getParent();
744 for (unsigned j = 0; j < Values.size(); j++) {
745 Value *baseAddr = Values[j];
746 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
747 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
748 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
749 }
750 }
751 Builder.SetInsertPoint(AfterLoop);
752 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
753 NumIterations[2], NumIterations[3]);
754 PTXGen.finishGeneration(FN);
755}
756#endif
757
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000758bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
759 const clast_stmt *stmt = f->body;
760
761 while (stmt) {
762 if (!CLAST_STMT_IS_A(stmt, stmt_user))
763 return false;
764
765 stmt = stmt->next;
766 }
767
768 return true;
769}
770
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000771int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
772 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
773 return polly::getNumberOfIterations(LoopDomain) / isl_int_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000774}
775
Tobias Grosser2da263e2012-03-15 09:34:55 +0000776void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
777 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
778 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000779
Tobias Grosser2da263e2012-03-15 09:34:55 +0000780 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000781
Tobias Grosser2da263e2012-03-15 09:34:55 +0000782 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000783 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
784 Stride = Stride.zext(LoopIVType->getBitWidth());
785 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
786
Tobias Grosser2da263e2012-03-15 09:34:55 +0000787 std::vector<Value*> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000788 IVS[0] = LB;
789
Tobias Grosser2da263e2012-03-15 09:34:55 +0000790 for (int i = 1; i < VectorWidth; i++)
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000791 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
792
Tobias Grosser00d898d2012-03-15 09:34:58 +0000793 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000794
795 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000796 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000797
Tobias Grosser2da263e2012-03-15 09:34:55 +0000798 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000799
Tobias Grosser2da263e2012-03-15 09:34:55 +0000800 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000801 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
802 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000803 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000804 }
805
806 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000807 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000808 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000809}
810
Tobias Grossere192b232012-05-22 08:46:07 +0000811
812bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
813 isl_set *Domain = isl_set_from_cloog_domain(f->domain);
814 assert(Domain && "Cannot access domain of loop");
815
816 Dependences &D = P->getAnalysis<Dependences>();
817
818 return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
819}
820
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000821void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000822 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000823 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000824 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
825 && (getNumberOfIterations(f) <= 16)) {
826 codegenForVector(f);
827 return;
828 }
829
830 if (OpenMP && !parallelCodeGeneration) {
831 parallelCodeGeneration = true;
832 parallelLoops.push_back(f->iterator);
833 codegenForOpenMP(f);
834 parallelCodeGeneration = false;
835 return;
836 }
837 }
838
Tobias Grosser6217e182012-08-03 12:50:07 +0000839#ifdef GPU_CODEGEN
840 if (GPGPU && isParallelFor(f)) {
841 if (!parallelCodeGeneration) {
842 parallelCodeGeneration = true;
843 parallelLoops.push_back(f->iterator);
844 codegenForGPGPU(f);
845 parallelCodeGeneration = false;
846 return;
847 }
848 }
849#endif
850
Tobias Grosserce3f5372012-03-02 11:26:42 +0000851 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000852}
853
854Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000855 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
856 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000857 CmpInst::Predicate P;
858
859 if (eq->sign == 0)
860 P = ICmpInst::ICMP_EQ;
861 else if (eq->sign > 0)
862 P = ICmpInst::ICMP_SGE;
863 else
864 P = ICmpInst::ICMP_SLE;
865
866 return Builder.CreateICmp(P, LHS, RHS);
867}
868
869void ClastStmtCodeGen::codegen(const clast_guard *g) {
870 Function *F = Builder.GetInsertBlock()->getParent();
871 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000872
873 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
874 Builder.GetInsertPoint(), P);
875 CondBB->setName("polly.cond");
876 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
877 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000878 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000879
Tobias Grosserd596b372012-03-15 09:34:52 +0000880 DominatorTree &DT = P->getAnalysis<DominatorTree>();
881 DT.addNewBlock(ThenBB, CondBB);
882 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000883
884 CondBB->getTerminator()->eraseFromParent();
885
886 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000887
888 Value *Predicate = codegen(&(g->eq[0]));
889
890 for (int i = 1; i < g->n; ++i) {
891 Value *TmpPredicate = codegen(&(g->eq[i]));
892 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
893 }
894
895 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
896 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000897 Builder.CreateBr(MergeBB);
898 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000899
900 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000901
902 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000903}
904
905void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
906 if (CLAST_STMT_IS_A(stmt, stmt_root))
907 assert(false && "No second root statement expected");
908 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
909 codegen((const clast_assignment *)stmt);
910 else if (CLAST_STMT_IS_A(stmt, stmt_user))
911 codegen((const clast_user_stmt *)stmt);
912 else if (CLAST_STMT_IS_A(stmt, stmt_block))
913 codegen((const clast_block *)stmt);
914 else if (CLAST_STMT_IS_A(stmt, stmt_for))
915 codegen((const clast_for *)stmt);
916 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
917 codegen((const clast_guard *)stmt);
918
919 if (stmt->next)
920 codegen(stmt->next);
921}
922
923void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000924 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000925
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000926 int i = 0;
927 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
928 PI != PE; ++PI) {
929 assert(i < names->nb_parameters && "Not enough parameter names");
930
931 const SCEV *Param = *PI;
932 Type *Ty = Param->getType();
933
934 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
935 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000936 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000937
938 ++i;
939 }
940}
941
942void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000943 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000944
945 parallelCodeGeneration = false;
946
947 const clast_stmt *stmt = (const clast_stmt*) r;
948 if (stmt->next)
949 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000950}
951
Tobias Grosserd596b372012-03-15 09:34:52 +0000952ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000953 S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000954
Tobias Grosser75805372011-04-29 06:27:02 +0000955namespace {
956class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000957 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000958
959 public:
960 static char ID;
961
962 CodeGeneration() : ScopPass(ID) {}
963
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000964
Tobias Grosser3a275d22012-05-29 09:11:54 +0000965 bool runOnScop(Scop &S) {
966 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000967
Tobias Grosser3a275d22012-05-29 09:11:54 +0000968 assert(S.getRegion().isSimple() && "Only simple regions are supported");
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000969
Tobias Grosser3a275d22012-05-29 09:11:54 +0000970 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000971
Tobias Grosser3a275d22012-05-29 09:11:54 +0000972 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000973
Tobias Grosser3a275d22012-05-29 09:11:54 +0000974 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +0000975 CloogInfo &C = getAnalysis<CloogInfo>();
976 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +0000977
Tobias Grosser3a275d22012-05-29 09:11:54 +0000978 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +0000979 CodeGen.getParallelLoops().begin(),
980 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +0000981 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000982 }
983
984 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000985 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
986 PE = ParallelLoops.end(); PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +0000987 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
988 }
989
990 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
991 AU.addRequired<CloogInfo>();
992 AU.addRequired<Dependences>();
993 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +0000994 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +0000995 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000996 AU.addRequired<ScopDetection>();
997 AU.addRequired<ScopInfo>();
Micah Villmow7a3d8202012-10-08 17:26:19 +0000998 AU.addRequired<DataLayout>();
Tobias Grosser75805372011-04-29 06:27:02 +0000999
1000 AU.addPreserved<CloogInfo>();
1001 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001002
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001003 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001004 AU.addPreserved<LoopInfo>();
1005 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001006 AU.addPreserved<ScopDetection>();
1007 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001008
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001009 // FIXME: We do not yet add regions for the newly generated code to the
1010 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001011 AU.addPreserved<RegionInfo>();
1012 AU.addPreserved<TempScopInfo>();
1013 AU.addPreserved<ScopInfo>();
1014 AU.addPreservedID(IndependentBlocksID);
1015 }
1016};
1017}
1018
1019char CodeGeneration::ID = 1;
1020
Tobias Grosser73600b82011-10-08 00:30:40 +00001021INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001022 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +00001023INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1024INITIALIZE_PASS_DEPENDENCY(Dependences)
1025INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1026INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1027INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1028INITIALIZE_PASS_DEPENDENCY(ScopDetection)
Tobias Grosser660b58d2012-10-08 08:56:52 +00001029INITIALIZE_PASS_DEPENDENCY(DataLayout)
Tobias Grosser73600b82011-10-08 00:30:40 +00001030INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001031 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001032
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001033Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001034 return new CodeGeneration();
1035}
Sebastian Pope1f65542012-05-07 16:35:11 +00001036
1037#endif // CLOOG_FOUND