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