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