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