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