1 //===------ 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 
23 #include "polly/CodeGen/Cloog.h"
24 #ifdef CLOOG_FOUND
25 
26 #define DEBUG_TYPE "polly-codegen"
27 #include "polly/Dependences.h"
28 #include "polly/LinkAllPasses.h"
29 #include "polly/Options.h"
30 #include "polly/ScopInfo.h"
31 #include "polly/TempScopInfo.h"
32 #include "polly/CodeGen/CodeGeneration.h"
33 #include "polly/CodeGen/BlockGenerators.h"
34 #include "polly/CodeGen/LoopGenerators.h"
35 #include "polly/CodeGen/PTXGenerator.h"
36 #include "polly/CodeGen/Utils.h"
37 #include "polly/Support/GICHelper.h"
38 #include "polly/Support/ScopHelper.h"
39 
40 #include "llvm/IR/Module.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/PostOrderIterator.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/ScalarEvolutionExpander.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 
49 #define CLOOG_INT_GMP 1
50 #include "cloog/cloog.h"
51 #include "cloog/isl/cloog.h"
52 
53 #include "isl/aff.h"
54 
55 #include <vector>
56 #include <utility>
57 
58 using namespace polly;
59 using namespace llvm;
60 
61 struct isl_set;
62 
63 namespace polly {
64 static cl::opt<bool>
65 OpenMP("enable-polly-openmp", cl::desc("Generate OpenMP parallel code"),
66        cl::value_desc("OpenMP code generation enabled if true"),
67        cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
68 
69 #ifdef GPU_CODEGEN
70 static cl::opt<bool>
71 GPGPU("enable-polly-gpgpu", cl::desc("Generate GPU parallel code"), cl::Hidden,
72       cl::value_desc("GPGPU code generation enabled if true"), cl::init(false),
73       cl::ZeroOrMore, cl::cat(PollyCategory));
74 
75 static cl::opt<std::string>
76 GPUTriple("polly-gpgpu-triple",
77           cl::desc("Target triple for GPU code generation"), cl::Hidden,
78           cl::init(""), cl::cat(PollyCategory));
79 #endif /* GPU_CODEGEN */
80 
81 typedef DenseMap<const char *, Value *> CharMapT;
82 
83 /// Class to generate LLVM-IR that calculates the value of a clast_expr.
84 class ClastExpCodeGen {
85   IRBuilder<> &Builder;
86   const CharMapT &IVS;
87 
88   Value *codegen(const clast_name *e, Type *Ty);
89   Value *codegen(const clast_term *e, Type *Ty);
90   Value *codegen(const clast_binary *e, Type *Ty);
91   Value *codegen(const clast_reduction *r, Type *Ty);
92 
93 public:
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.
102   ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
103 
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.
108   Value *codegen(const clast_expr *e, Type *Ty);
109 };
110 
111 Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
112   CharMapT::const_iterator I = IVS.find(e->name);
113 
114   assert(I != IVS.end() && "Clast name not found");
115 
116   return Builder.CreateSExtOrBitCast(I->second, Ty);
117 }
118 
119 Value *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 
132 Value *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     // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
145     Value *One = ConstantInt::get(Ty, 1);
146     Value *Zero = ConstantInt::get(Ty, 0);
147     Value *Sum1 = Builder.CreateSub(LHS, RHS);
148     Value *Sum2 = Builder.CreateAdd(Sum1, One);
149     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
150     Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
151     return Builder.CreateSDiv(Dividend, RHS);
152   }
153   case clast_bin_cdiv: {
154     // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
155     Value *One = ConstantInt::get(Ty, 1);
156     Value *Zero = ConstantInt::get(Ty, 0);
157     Value *Sum1 = Builder.CreateAdd(LHS, RHS);
158     Value *Sum2 = Builder.CreateSub(Sum1, One);
159     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
160     Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
161     return Builder.CreateSDiv(Dividend, RHS);
162   }
163   case clast_bin_div:
164     return Builder.CreateSDiv(LHS, RHS);
165   }
166 
167   llvm_unreachable("Unknown clast binary expression type");
168 }
169 
170 Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
171   assert((r->type == clast_red_min || r->type == clast_red_max ||
172           r->type == clast_red_sum) &&
173          "Clast reduction type not supported");
174   Value *old = codegen(r->elts[0], Ty);
175 
176   for (int i = 1; i < r->n; ++i) {
177     Value *exprValue = codegen(r->elts[i], Ty);
178 
179     switch (r->type) {
180     case clast_red_min: {
181       Value *cmp = Builder.CreateICmpSLT(old, exprValue);
182       old = Builder.CreateSelect(cmp, old, exprValue);
183       break;
184     }
185     case clast_red_max: {
186       Value *cmp = Builder.CreateICmpSGT(old, exprValue);
187       old = Builder.CreateSelect(cmp, old, exprValue);
188       break;
189     }
190     case clast_red_sum:
191       old = Builder.CreateAdd(old, exprValue);
192       break;
193     }
194   }
195 
196   return old;
197 }
198 
199 ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
200     : Builder(B), IVS(IVMap) {}
201 
202 Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
203   switch (e->type) {
204   case clast_expr_name:
205     return codegen((const clast_name *)e, Ty);
206   case clast_expr_term:
207     return codegen((const clast_term *)e, Ty);
208   case clast_expr_bin:
209     return codegen((const clast_binary *)e, Ty);
210   case clast_expr_red:
211     return codegen((const clast_reduction *)e, Ty);
212   }
213 
214   llvm_unreachable("Unknown clast expression!");
215 }
216 
217 class ClastStmtCodeGen {
218 public:
219   const std::vector<std::string> &getParallelLoops();
220 
221 private:
222   // The Scop we code generate.
223   Scop *S;
224   Pass *P;
225 
226   // The Builder specifies the current location to code generate at.
227   IRBuilder<> &Builder;
228 
229   // Map the Values from the old code to their counterparts in the new code.
230   ValueMapT ValueMap;
231 
232   // Map the loops from the old code to expressions function of the induction
233   // variables in the new code.  For example, when the code generator produces
234   // this AST:
235   //
236   //   for (int c1 = 0; c1 <= 1023; c1 += 1)
237   //     for (int c2 = 0; c2 <= 1023; c2 += 1)
238   //       Stmt(c2 + 3, c1);
239   //
240   // LoopToScev is a map associating:
241   //   "outer loop in the old loop nest" -> SCEV("c2 + 3"),
242   //   "inner loop in the old loop nest" -> SCEV("c1").
243   LoopToScevMapT LoopToScev;
244 
245   // clastVars maps from the textual representation of a clast variable to its
246   // current *Value. clast variables are scheduling variables, original
247   // induction variables or parameters. They are used either in loop bounds or
248   // to define the statement instance that is executed.
249   //
250   //   for (s = 0; s < n + 3; ++i)
251   //     for (t = s; t < m; ++j)
252   //       Stmt(i = s + 3 * m, j = t);
253   //
254   // {s,t,i,j,n,m} is the set of clast variables in this clast.
255   CharMapT ClastVars;
256 
257   // Codegenerator for clast expressions.
258   ClastExpCodeGen ExpGen;
259 
260   // Do we currently generate parallel code?
261   bool parallelCodeGeneration;
262 
263   std::vector<std::string> parallelLoops;
264 
265   void codegen(const clast_assignment *a);
266 
267   void codegen(const clast_assignment *a, ScopStmt *Statement,
268                unsigned Dimension, int vectorDim,
269                std::vector<ValueMapT> *VectorVMap = 0,
270                std::vector<LoopToScevMapT> *VLTS = 0);
271 
272   void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
273                             int vectorDim = 0,
274                             std::vector<ValueMapT> *VectorVMap = 0,
275                             std::vector<LoopToScevMapT> *VLTS = 0);
276 
277   void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = NULL,
278                const char *iterator = NULL, isl_set *scatteringDomain = 0);
279 
280   void codegen(const clast_block *b);
281 
282   /// @brief Create a classical sequential loop.
283   void codegenForSequential(const clast_for *f);
284 
285   /// @brief Create OpenMP structure values.
286   ///
287   /// Create a list of values that has to be stored into the OpenMP subfuncition
288   /// structure.
289   SetVector<Value *> getOMPValues(const clast_stmt *Body);
290 
291   /// @brief Update ClastVars and ValueMap according to a value map.
292   ///
293   /// @param VMap A map from old to new values.
294   void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
295 
296   /// @brief Create an OpenMP parallel for loop.
297   ///
298   /// This loop reflects a loop as if it would have been created by an OpenMP
299   /// statement.
300   void codegenForOpenMP(const clast_for *f);
301 
302 #ifdef GPU_CODEGEN
303   /// @brief Create GPGPU device memory access values.
304   ///
305   /// Create a list of values that will be set to be parameters of the GPGPU
306   /// subfunction. These parameters represent device memory base addresses
307   /// and the size in bytes.
308   SetVector<Value *> getGPUValues(unsigned &OutputBytes);
309 
310   /// @brief Create a GPU parallel for loop.
311   ///
312   /// This loop reflects a loop as if it would have been created by a GPU
313   /// statement.
314   void codegenForGPGPU(const clast_for *F);
315 
316   /// @brief Get innermost for loop.
317   const clast_stmt *getScheduleInfo(const clast_for *F,
318                                     std::vector<int> &NumIters,
319                                     unsigned &LoopDepth,
320                                     unsigned &NonPLoopDepth);
321 #endif /* GPU_CODEGEN */
322 
323   /// @brief Check if a loop is parallel
324   ///
325   /// Detect if a clast_for loop can be executed in parallel.
326   ///
327   /// @param For The clast for loop to check.
328   ///
329   /// @return bool Returns true if the incoming clast_for statement can
330   ///              execute in parallel.
331   bool isParallelFor(const clast_for *For);
332 
333   bool isInnermostLoop(const clast_for *f);
334 
335   /// @brief Get the number of loop iterations for this loop.
336   /// @param f The clast for loop to check.
337   int getNumberOfIterations(const clast_for *f);
338 
339   /// @brief Create vector instructions for this loop.
340   void codegenForVector(const clast_for *f);
341 
342   void codegen(const clast_for *f);
343 
344   Value *codegen(const clast_equation *eq);
345 
346   void codegen(const clast_guard *g);
347 
348   void codegen(const clast_stmt *stmt);
349 
350   void addParameters(const CloogNames *names);
351 
352   IntegerType *getIntPtrTy();
353 
354 public:
355   void codegen(const clast_root *r);
356 
357   ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
358 };
359 }
360 
361 IntegerType *ClastStmtCodeGen::getIntPtrTy() {
362   return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
363 }
364 
365 const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
366   return parallelLoops;
367 }
368 
369 void ClastStmtCodeGen::codegen(const clast_assignment *a) {
370   Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
371   ClastVars[a->LHS] = V;
372 }
373 
374 void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
375                                unsigned Dim, int VectorDim,
376                                std::vector<ValueMapT> *VectorVMap,
377                                std::vector<LoopToScevMapT> *VLTS) {
378   Value *RHS;
379 
380   assert(!A->LHS && "Statement assignments do not have left hand side");
381 
382   RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
383 
384   const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
385   if (VLTS)
386     (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
387   LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
388 
389   const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
390   if (PN) {
391     RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
392 
393     if (VectorVMap)
394       (*VectorVMap)[VectorDim][PN] = RHS;
395 
396     ValueMap[PN] = RHS;
397   }
398 }
399 
400 void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
401                                             ScopStmt *Statement, int vectorDim,
402                                             std::vector<ValueMapT> *VectorVMap,
403                                             std::vector<LoopToScevMapT> *VLTS) {
404   int Dimension = 0;
405 
406   while (Assignment) {
407     assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
408            "Substitions are expected to be assignments");
409     codegen((const clast_assignment *)Assignment, Statement, Dimension,
410             vectorDim, VectorVMap, VLTS);
411     Assignment = Assignment->next;
412     Dimension++;
413   }
414 }
415 
416 // Takes the cloog specific domain and translates it into a map Statement ->
417 // PartialSchedule, where the PartialSchedule contains all the dimensions that
418 // have been code generated up to this point.
419 static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
420                                                   isl_set *Domain) {
421   isl_map *Schedule = Statement->getScattering();
422   int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
423   int UnscheduledDimensions =
424       isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
425 
426   return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
427                              UnscheduledDimensions);
428 }
429 
430 void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
431                                std::vector<Value *> *IVS, const char *iterator,
432                                isl_set *Domain) {
433   ScopStmt *Statement = (ScopStmt *)u->statement->usr;
434 
435   if (u->substitutions)
436     codegenSubstitutions(u->substitutions, Statement);
437 
438   int VectorDimensions = IVS ? IVS->size() : 1;
439 
440   if (VectorDimensions == 1) {
441     BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
442     return;
443   }
444 
445   VectorValueMapT VectorMap(VectorDimensions);
446   std::vector<LoopToScevMapT> VLTS(VectorDimensions);
447 
448   if (IVS) {
449     assert(u->substitutions && "Substitutions expected!");
450     int i = 0;
451     for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
452          II != IE; ++II) {
453       ClastVars[iterator] = *II;
454       codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
455       i++;
456     }
457   }
458 
459   isl_map *Schedule = extractPartialSchedule(Statement, Domain);
460   VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
461                                  P);
462   isl_map_free(Schedule);
463 }
464 
465 void ClastStmtCodeGen::codegen(const clast_block *b) {
466   if (b->body)
467     codegen(b->body);
468 }
469 
470 void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
471   Value *LowerBound, *UpperBound, *IV, *Stride;
472   BasicBlock *ExitBlock;
473   Type *IntPtrTy = getIntPtrTy();
474 
475   LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
476   UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
477   Stride = Builder.getInt(APInt_from_MPZ(f->stride));
478 
479   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, ExitBlock,
480                   CmpInst::ICMP_SLE);
481 
482   // Add loop iv to symbols.
483   ClastVars[f->iterator] = IV;
484 
485   if (f->body)
486     codegen(f->body);
487 
488   // Loop is finished, so remove its iv from the live symbols.
489   ClastVars.erase(f->iterator);
490   Builder.SetInsertPoint(ExitBlock->begin());
491 }
492 
493 // Helper class to determine all scalar parameters used in the basic blocks of a
494 // clast. Scalar parameters are scalar variables defined outside of the SCoP.
495 class ParameterVisitor : public ClastVisitor {
496   std::set<Value *> Values;
497 
498 public:
499   ParameterVisitor() : ClastVisitor(), Values() {}
500 
501   void visitUser(const clast_user_stmt *Stmt) {
502     const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
503     const BasicBlock *BB = S->getBasicBlock();
504 
505     // Check all the operands of instructions in the basic block.
506     for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
507          ++BI) {
508       const Instruction &Inst = *BI;
509       for (Instruction::const_op_iterator II = Inst.op_begin(),
510                                           IE = Inst.op_end();
511            II != IE; ++II) {
512         Value *SrcVal = *II;
513 
514         if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
515           if (S->getParent()->getRegion().contains(OpInst))
516             continue;
517 
518         if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
519           Values.insert(SrcVal);
520       }
521     }
522   }
523 
524   // Iterator to iterate over the values found.
525   typedef std::set<Value *>::const_iterator const_iterator;
526   inline const_iterator begin() const { return Values.begin(); }
527   inline const_iterator end() const { return Values.end(); }
528 };
529 
530 SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
531   SetVector<Value *> Values;
532 
533   // The clast variables
534   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
535        I++)
536     Values.insert(I->second);
537 
538   // Find the temporaries that are referenced in the clast statements'
539   // basic blocks but are not defined by these blocks (e.g., references
540   // to function arguments or temporaries defined before the start of
541   // the SCoP).
542   ParameterVisitor Params;
543   Params.visit(Body);
544 
545   for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
546        PI != PE; ++PI) {
547     Value *V = *PI;
548     Values.insert(V);
549     DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
550   }
551 
552   return Values;
553 }
554 
555 void
556 ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
557   std::set<Value *> Inserted;
558 
559   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
560        I++) {
561     ClastVars[I->first] = VMap[I->second];
562     Inserted.insert(I->second);
563   }
564 
565   for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
566                                                  E = VMap.end();
567        I != E; ++I) {
568     if (Inserted.count(I->first))
569       continue;
570 
571     ValueMap[I->first] = I->second;
572   }
573 }
574 
575 static void clearDomtree(Function *F, DominatorTree &DT) {
576   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
577   std::vector<BasicBlock *> Nodes;
578   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
579     Nodes.push_back(I->getBlock());
580 
581   for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
582        I != E; ++I)
583     DT.eraseNode(*I);
584 }
585 
586 void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
587   Value *Stride, *LB, *UB, *IV;
588   BasicBlock::iterator LoopBody;
589   IntegerType *IntPtrTy = getIntPtrTy();
590   SetVector<Value *> Values;
591   OMPGenerator::ValueToValueMapTy VMap;
592   OMPGenerator OMPGen(Builder, P);
593 
594   Stride = Builder.getInt(APInt_from_MPZ(For->stride));
595   Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
596   LB = ExpGen.codegen(For->LB, IntPtrTy);
597   UB = ExpGen.codegen(For->UB, IntPtrTy);
598 
599   Values = getOMPValues(For->body);
600 
601   IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
602   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
603   Builder.SetInsertPoint(LoopBody);
604 
605   // Save the current values.
606   const ValueMapT ValueMapCopy = ValueMap;
607   const CharMapT ClastVarsCopy = ClastVars;
608 
609   updateWithValueMap(VMap);
610   ClastVars[For->iterator] = IV;
611 
612   if (For->body)
613     codegen(For->body);
614 
615   // Restore the original values.
616   ValueMap = ValueMapCopy;
617   ClastVars = ClastVarsCopy;
618 
619   clearDomtree((*LoopBody).getParent()->getParent(),
620                P->getAnalysis<DominatorTree>());
621 
622   Builder.SetInsertPoint(AfterLoop);
623 }
624 
625 #ifdef GPU_CODEGEN
626 static unsigned getArraySizeInBytes(const ArrayType *AT) {
627   unsigned Bytes = AT->getNumElements();
628   if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
629     Bytes *= getArraySizeInBytes(T);
630   else
631     Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
632 
633   return Bytes;
634 }
635 
636 SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
637   SetVector<Value *> Values;
638   OutputBytes = 0;
639 
640   // Record the memory reference base addresses.
641   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
642     ScopStmt *Stmt = *SI;
643     for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
644                                                   E = Stmt->memacc_end();
645          I != E; ++I) {
646       Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
647       Values.insert((BaseAddr));
648 
649       // FIXME: we assume that there is one and only one array to be written
650       // in a SCoP.
651       int NumWrites = 0;
652       if ((*I)->isWrite()) {
653         ++NumWrites;
654         assert(NumWrites <= 1 &&
655                "We support at most one array to be written in a SCoP.");
656         if (const PointerType *PT =
657                 dyn_cast<PointerType>(BaseAddr->getType())) {
658           Type *T = PT->getArrayElementType();
659           const ArrayType *ATy = dyn_cast<ArrayType>(T);
660           OutputBytes = getArraySizeInBytes(ATy);
661         }
662       }
663     }
664   }
665 
666   return Values;
667 }
668 
669 const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
670                                                     std::vector<int> &NumIters,
671                                                     unsigned &LoopDepth,
672                                                     unsigned &NonPLoopDepth) {
673   clast_stmt *Stmt = (clast_stmt *)F;
674   const clast_for *Result;
675   bool NonParaFlag = false;
676   LoopDepth = 0;
677   NonPLoopDepth = 0;
678 
679   while (Stmt) {
680     if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
681       const clast_for *T = (clast_for *)Stmt;
682       if (isParallelFor(T)) {
683         if (!NonParaFlag) {
684           NumIters.push_back(getNumberOfIterations(T));
685           Result = T;
686         }
687       } else
688         NonParaFlag = true;
689 
690       Stmt = T->body;
691       LoopDepth++;
692       continue;
693     }
694     Stmt = Stmt->next;
695   }
696 
697   assert(NumIters.size() == 4 &&
698          "The loops should be tiled into 4-depth parallel loops and an "
699          "innermost non-parallel one (if exist).");
700   NonPLoopDepth = LoopDepth - NumIters.size();
701   assert(NonPLoopDepth <= 1 &&
702          "We support only one innermost non-parallel loop currently.");
703   return (const clast_stmt *)Result->body;
704 }
705 
706 void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
707   BasicBlock::iterator LoopBody;
708   SetVector<Value *> Values;
709   SetVector<Value *> IVS;
710   std::vector<int> NumIterations;
711   PTXGenerator::ValueToValueMapTy VMap;
712 
713   assert(!GPUTriple.empty() &&
714          "Target triple should be set properly for GPGPU code generation.");
715   PTXGenerator PTXGen(Builder, P, GPUTriple);
716 
717   // Get original IVS and ScopStmt
718   unsigned TiledLoopDepth, NonPLoopDepth;
719   const clast_stmt *InnerStmt =
720       getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
721   const clast_stmt *TmpStmt;
722   const clast_user_stmt *U;
723   const clast_for *InnerFor;
724   if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
725     InnerFor = (const clast_for *)InnerStmt;
726     TmpStmt = InnerFor->body;
727   } else
728     TmpStmt = InnerStmt;
729   U = (const clast_user_stmt *)TmpStmt;
730   ScopStmt *Statement = (ScopStmt *)U->statement->usr;
731   for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
732     const Value *IV = Statement->getInductionVariableForDimension(i);
733     IVS.insert(const_cast<Value *>(IV));
734   }
735 
736   unsigned OutBytes;
737   Values = getGPUValues(OutBytes);
738   PTXGen.setOutputBytes(OutBytes);
739   PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
740 
741   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
742   Builder.SetInsertPoint(LoopBody);
743 
744   BasicBlock *AfterBB = 0;
745   if (NonPLoopDepth) {
746     Value *LowerBound, *UpperBound, *IV, *Stride;
747     Type *IntPtrTy = getIntPtrTy();
748     LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
749     UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
750     Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
751     IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
752                     CmpInst::ICMP_SLE);
753     const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
754     Value *OldIV = const_cast<Value *>(OldIV_);
755     VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
756   }
757 
758   updateWithValueMap(VMap);
759 
760   BlockGenerator::generate(Builder, *Statement, ValueMap, P);
761 
762   if (AfterBB)
763     Builder.SetInsertPoint(AfterBB->begin());
764 
765   // FIXME: The replacement of the host base address with the parameter of ptx
766   // subfunction should have been done by updateWithValueMap. We use the
767   // following codes to avoid affecting other parts of Polly. This should be
768   // fixed later.
769   Function *FN = Builder.GetInsertBlock()->getParent();
770   for (unsigned j = 0; j < Values.size(); j++) {
771     Value *baseAddr = Values[j];
772     for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
773       for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
774         I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
775     }
776   }
777   Builder.SetInsertPoint(AfterLoop);
778   PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
779                                 NumIterations[2], NumIterations[3]);
780   PTXGen.finishGeneration(FN);
781 }
782 #endif
783 
784 bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
785   const clast_stmt *stmt = f->body;
786 
787   while (stmt) {
788     if (!CLAST_STMT_IS_A(stmt, stmt_user))
789       return false;
790 
791     stmt = stmt->next;
792   }
793 
794   return true;
795 }
796 
797 int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
798   isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
799   int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
800   if (NumberOfIterations == -1)
801     return -1;
802   return NumberOfIterations / isl_int_get_si(For->stride) + 1;
803 }
804 
805 void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
806   DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
807   int VectorWidth = getNumberOfIterations(F);
808 
809   Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
810 
811   APInt Stride = APInt_from_MPZ(F->stride);
812   IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
813   Stride = Stride.zext(LoopIVType->getBitWidth());
814   Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
815 
816   std::vector<Value *> IVS(VectorWidth);
817   IVS[0] = LB;
818 
819   for (int i = 1; i < VectorWidth; i++)
820     IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
821 
822   isl_set *Domain = isl_set_from_cloog_domain(F->domain);
823 
824   // Add loop iv to symbols.
825   ClastVars[F->iterator] = LB;
826 
827   const clast_stmt *Stmt = F->body;
828 
829   while (Stmt) {
830     codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
831             isl_set_copy(Domain));
832     Stmt = Stmt->next;
833   }
834 
835   // Loop is finished, so remove its iv from the live symbols.
836   isl_set_free(Domain);
837   ClastVars.erase(F->iterator);
838 }
839 
840 bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
841   isl_set *Domain = isl_set_from_cloog_domain(f->domain);
842   assert(Domain && "Cannot access domain of loop");
843 
844   Dependences &D = P->getAnalysis<Dependences>();
845 
846   return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
847 }
848 
849 void ClastStmtCodeGen::codegen(const clast_for *f) {
850   bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
851   if ((Vector || OpenMP) && isParallelFor(f)) {
852     if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
853         (getNumberOfIterations(f) <= 16)) {
854       codegenForVector(f);
855       return;
856     }
857 
858     if (OpenMP && !parallelCodeGeneration) {
859       parallelCodeGeneration = true;
860       parallelLoops.push_back(f->iterator);
861       codegenForOpenMP(f);
862       parallelCodeGeneration = false;
863       return;
864     }
865   }
866 
867 #ifdef GPU_CODEGEN
868   if (GPGPU && isParallelFor(f)) {
869     if (!parallelCodeGeneration) {
870       parallelCodeGeneration = true;
871       parallelLoops.push_back(f->iterator);
872       codegenForGPGPU(f);
873       parallelCodeGeneration = false;
874       return;
875     }
876   }
877 #endif
878 
879   codegenForSequential(f);
880 }
881 
882 Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
883   Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
884   Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
885   CmpInst::Predicate P;
886 
887   if (eq->sign == 0)
888     P = ICmpInst::ICMP_EQ;
889   else if (eq->sign > 0)
890     P = ICmpInst::ICMP_SGE;
891   else
892     P = ICmpInst::ICMP_SLE;
893 
894   return Builder.CreateICmp(P, LHS, RHS);
895 }
896 
897 void ClastStmtCodeGen::codegen(const clast_guard *g) {
898   Function *F = Builder.GetInsertBlock()->getParent();
899   LLVMContext &Context = F->getContext();
900 
901   BasicBlock *CondBB =
902       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
903   CondBB->setName("polly.cond");
904   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
905   MergeBB->setName("polly.merge");
906   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
907 
908   DominatorTree &DT = P->getAnalysis<DominatorTree>();
909   DT.addNewBlock(ThenBB, CondBB);
910   DT.changeImmediateDominator(MergeBB, CondBB);
911 
912   CondBB->getTerminator()->eraseFromParent();
913 
914   Builder.SetInsertPoint(CondBB);
915 
916   Value *Predicate = codegen(&(g->eq[0]));
917 
918   for (int i = 1; i < g->n; ++i) {
919     Value *TmpPredicate = codegen(&(g->eq[i]));
920     Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
921   }
922 
923   Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
924   Builder.SetInsertPoint(ThenBB);
925   Builder.CreateBr(MergeBB);
926   Builder.SetInsertPoint(ThenBB->begin());
927 
928   LoopInfo &LI = P->getAnalysis<LoopInfo>();
929   Loop *L = LI.getLoopFor(CondBB);
930   if (L) {
931     L->addBasicBlockToLoop(ThenBB, LI.getBase());
932     L->addBasicBlockToLoop(MergeBB, LI.getBase());
933   }
934 
935   codegen(g->then);
936 
937   Builder.SetInsertPoint(MergeBB->begin());
938 }
939 
940 void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
941   if (CLAST_STMT_IS_A(stmt, stmt_root))
942     assert(false && "No second root statement expected");
943   else if (CLAST_STMT_IS_A(stmt, stmt_ass))
944     codegen((const clast_assignment *)stmt);
945   else if (CLAST_STMT_IS_A(stmt, stmt_user))
946     codegen((const clast_user_stmt *)stmt);
947   else if (CLAST_STMT_IS_A(stmt, stmt_block))
948     codegen((const clast_block *)stmt);
949   else if (CLAST_STMT_IS_A(stmt, stmt_for))
950     codegen((const clast_for *)stmt);
951   else if (CLAST_STMT_IS_A(stmt, stmt_guard))
952     codegen((const clast_guard *)stmt);
953 
954   if (stmt->next)
955     codegen(stmt->next);
956 }
957 
958 void ClastStmtCodeGen::addParameters(const CloogNames *names) {
959   SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
960 
961   int i = 0;
962   for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
963        PI != PE; ++PI) {
964     assert(i < names->nb_parameters && "Not enough parameter names");
965 
966     const SCEV *Param = *PI;
967     Type *Ty = Param->getType();
968 
969     Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
970     Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
971     ClastVars[names->parameters[i]] = V;
972 
973     ++i;
974   }
975 }
976 
977 void ClastStmtCodeGen::codegen(const clast_root *r) {
978   addParameters(r->names);
979 
980   parallelCodeGeneration = false;
981 
982   const clast_stmt *stmt = (const clast_stmt *)r;
983   if (stmt->next)
984     codegen(stmt->next);
985 }
986 
987 ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P)
988     : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
989 
990 namespace {
991 class CodeGeneration : public ScopPass {
992   std::vector<std::string> ParallelLoops;
993 
994 public:
995   static char ID;
996 
997   CodeGeneration() : ScopPass(ID) {}
998 
999   bool runOnScop(Scop &S) {
1000     ParallelLoops.clear();
1001 
1002     assert(!S.getRegion().isTopLevelRegion() &&
1003            "Top level regions are not supported");
1004 
1005     simplifyRegion(&S, this);
1006 
1007     BasicBlock *StartBlock = executeScopConditionally(S, this);
1008 
1009     IRBuilder<> Builder(StartBlock->begin());
1010 
1011     ClastStmtCodeGen CodeGen(&S, Builder, this);
1012     CloogInfo &C = getAnalysis<CloogInfo>();
1013     CodeGen.codegen(C.getClast());
1014 
1015     ParallelLoops.insert(ParallelLoops.begin(),
1016                          CodeGen.getParallelLoops().begin(),
1017                          CodeGen.getParallelLoops().end());
1018     return true;
1019   }
1020 
1021   virtual void printScop(raw_ostream &OS) const {
1022     for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
1023                                                   PE = ParallelLoops.end();
1024          PI != PE; ++PI)
1025       OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1026   }
1027 
1028   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1029     AU.addRequired<CloogInfo>();
1030     AU.addRequired<Dependences>();
1031     AU.addRequired<DominatorTree>();
1032     AU.addRequired<RegionInfo>();
1033     AU.addRequired<ScalarEvolution>();
1034     AU.addRequired<ScopDetection>();
1035     AU.addRequired<ScopInfo>();
1036     AU.addRequired<DataLayout>();
1037     AU.addRequired<LoopInfo>();
1038 
1039     AU.addPreserved<CloogInfo>();
1040     AU.addPreserved<Dependences>();
1041     AU.addPreserved<LoopInfo>();
1042     AU.addPreserved<DominatorTree>();
1043     AU.addPreserved<ScopDetection>();
1044     AU.addPreserved<ScalarEvolution>();
1045 
1046     // FIXME: We do not yet add regions for the newly generated code to the
1047     //        region tree.
1048     AU.addPreserved<RegionInfo>();
1049     AU.addPreserved<TempScopInfo>();
1050     AU.addPreserved<ScopInfo>();
1051     AU.addPreservedID(IndependentBlocksID);
1052   }
1053 };
1054 }
1055 
1056 char CodeGeneration::ID = 1;
1057 
1058 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
1059 
1060 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1061                       "Polly - Create LLVM-IR from SCoPs", false, false);
1062 INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1063 INITIALIZE_PASS_DEPENDENCY(Dependences);
1064 INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1065 INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1066 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1067 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1068 INITIALIZE_PASS_DEPENDENCY(DataLayout);
1069 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1070                     "Polly - Create LLVM-IR from SCoPs", false, false)
1071 
1072 #endif // CLOOG_FOUND
1073