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