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 #define DEBUG_TYPE "polly-codegen"
24 
25 #include "polly/Cloog.h"
26 #include "polly/Dependences.h"
27 #include "polly/LinkAllPasses.h"
28 #include "polly/ScopInfo.h"
29 #include "polly/TempScopInfo.h"
30 #include "polly/CodeGen/CodeGeneration.h"
31 #include "polly/CodeGen/BlockGenerators.h"
32 #include "polly/CodeGen/LoopGenerators.h"
33 #include "polly/Support/GICHelper.h"
34 
35 #include "llvm/Module.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/PostOrderIterator.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/ScalarEvolutionExpander.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 
45 #define CLOOG_INT_GMP 1
46 #include "cloog/cloog.h"
47 #include "cloog/isl/cloog.h"
48 
49 #include "isl/aff.h"
50 
51 #include <vector>
52 #include <utility>
53 
54 using namespace polly;
55 using namespace llvm;
56 
57 struct isl_set;
58 
59 namespace polly {
60 static cl::opt<bool>
61 OpenMP("enable-polly-openmp",
62        cl::desc("Generate OpenMP parallel code"), cl::Hidden,
63        cl::value_desc("OpenMP code generation enabled if true"),
64        cl::init(false), cl::ZeroOrMore);
65 
66 static cl::opt<bool>
67 AtLeastOnce("enable-polly-atLeastOnce",
68        cl::desc("Give polly the hint, that every loop is executed at least"
69                 "once"), cl::Hidden,
70        cl::value_desc("OpenMP code generation enabled if true"),
71        cl::init(false), cl::ZeroOrMore);
72 
73 typedef DenseMap<const char*, Value*> CharMapT;
74 
75 /// Class to generate LLVM-IR that calculates the value of a clast_expr.
76 class ClastExpCodeGen {
77   IRBuilder<> &Builder;
78   const CharMapT &IVS;
79 
80   Value *codegen(const clast_name *e, Type *Ty);
81   Value *codegen(const clast_term *e, Type *Ty);
82   Value *codegen(const clast_binary *e, Type *Ty);
83   Value *codegen(const clast_reduction *r, Type *Ty);
84 public:
85 
86   // A generator for clast expressions.
87   //
88   // @param B The IRBuilder that defines where the code to calculate the
89   //          clast expressions should be inserted.
90   // @param IVMAP A Map that translates strings describing the induction
91   //              variables to the Values* that represent these variables
92   //              on the LLVM side.
93   ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
94 
95   // Generates code to calculate a given clast expression.
96   //
97   // @param e The expression to calculate.
98   // @return The Value that holds the result.
99   Value *codegen(const clast_expr *e, Type *Ty);
100 };
101 
102 Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
103   CharMapT::const_iterator I = IVS.find(e->name);
104 
105   assert(I != IVS.end() && "Clast name not found");
106 
107   return Builder.CreateSExtOrBitCast(I->second, Ty);
108 }
109 
110 Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
111   APInt a = APInt_from_MPZ(e->val);
112 
113   Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
114   ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
115 
116   if (!e->var)
117     return ConstOne;
118 
119   Value *var = codegen(e->var, Ty);
120   return Builder.CreateMul(ConstOne, var);
121 }
122 
123 Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
124   Value *LHS = codegen(e->LHS, Ty);
125 
126   APInt RHS_AP = APInt_from_MPZ(e->RHS);
127 
128   Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
129   RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
130 
131   switch (e->type) {
132   case clast_bin_mod:
133     return Builder.CreateSRem(LHS, RHS);
134   case clast_bin_fdiv:
135     {
136       // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
137       Value *One = ConstantInt::get(Ty, 1);
138       Value *Zero = ConstantInt::get(Ty, 0);
139       Value *Sum1 = Builder.CreateSub(LHS, RHS);
140       Value *Sum2 = Builder.CreateAdd(Sum1, One);
141       Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
142       Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
143       return Builder.CreateSDiv(Dividend, RHS);
144     }
145   case clast_bin_cdiv:
146     {
147       // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
148       Value *One = ConstantInt::get(Ty, 1);
149       Value *Zero = ConstantInt::get(Ty, 0);
150       Value *Sum1 = Builder.CreateAdd(LHS, RHS);
151       Value *Sum2 = Builder.CreateSub(Sum1, One);
152       Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
153       Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
154       return Builder.CreateSDiv(Dividend, RHS);
155     }
156   case clast_bin_div:
157     return Builder.CreateSDiv(LHS, RHS);
158   };
159 
160   llvm_unreachable("Unknown clast binary expression type");
161 }
162 
163 Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
164   assert((   r->type == clast_red_min
165              || r->type == clast_red_max
166              || r->type == clast_red_sum)
167          && "Clast reduction type not supported");
168   Value *old = codegen(r->elts[0], Ty);
169 
170   for (int i=1; i < r->n; ++i) {
171     Value *exprValue = codegen(r->elts[i], Ty);
172 
173     switch (r->type) {
174     case clast_red_min:
175       {
176         Value *cmp = Builder.CreateICmpSLT(old, exprValue);
177         old = Builder.CreateSelect(cmp, old, exprValue);
178         break;
179       }
180     case clast_red_max:
181       {
182         Value *cmp = Builder.CreateICmpSGT(old, exprValue);
183         old = Builder.CreateSelect(cmp, old, exprValue);
184         break;
185       }
186     case clast_red_sum:
187       old = Builder.CreateAdd(old, exprValue);
188       break;
189     }
190   }
191 
192   return old;
193 }
194 
195 ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
196   : Builder(B), IVS(IVMap) {}
197 
198 Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
199   switch(e->type) {
200   case clast_expr_name:
201     return codegen((const clast_name *)e, Ty);
202   case clast_expr_term:
203     return codegen((const clast_term *)e, Ty);
204   case clast_expr_bin:
205     return codegen((const clast_binary *)e, Ty);
206   case clast_expr_red:
207     return codegen((const clast_reduction *)e, Ty);
208   }
209 
210   llvm_unreachable("Unknown clast expression!");
211 }
212 
213 class ClastStmtCodeGen {
214 public:
215   const std::vector<std::string> &getParallelLoops();
216 
217 private:
218   // The Scop we code generate.
219   Scop *S;
220   Pass *P;
221 
222   // The Builder specifies the current location to code generate at.
223   IRBuilder<> &Builder;
224 
225   // Map the Values from the old code to their counterparts in the new code.
226   ValueMapT ValueMap;
227 
228   // clastVars maps from the textual representation of a clast variable to its
229   // current *Value. clast variables are scheduling variables, original
230   // induction variables or parameters. They are used either in loop bounds or
231   // to define the statement instance that is executed.
232   //
233   //   for (s = 0; s < n + 3; ++i)
234   //     for (t = s; t < m; ++j)
235   //       Stmt(i = s + 3 * m, j = t);
236   //
237   // {s,t,i,j,n,m} is the set of clast variables in this clast.
238   CharMapT ClastVars;
239 
240   // Codegenerator for clast expressions.
241   ClastExpCodeGen ExpGen;
242 
243   // Do we currently generate parallel code?
244   bool parallelCodeGeneration;
245 
246   std::vector<std::string> parallelLoops;
247 
248   void codegen(const clast_assignment *a);
249 
250   void codegen(const clast_assignment *a, ScopStmt *Statement,
251                unsigned Dimension, int vectorDim,
252                std::vector<ValueMapT> *VectorVMap = 0);
253 
254   void codegenSubstitutions(const clast_stmt *Assignment,
255                             ScopStmt *Statement, int vectorDim = 0,
256                             std::vector<ValueMapT> *VectorVMap = 0);
257 
258   void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
259                const char *iterator = NULL, isl_set *scatteringDomain = 0);
260 
261   void codegen(const clast_block *b);
262 
263   /// @brief Create a classical sequential loop.
264   void codegenForSequential(const clast_for *f);
265 
266   /// @brief Create OpenMP structure values.
267   ///
268   /// Create a list of values that has to be stored into the OpenMP subfuncition
269   /// structure.
270   SetVector<Value*> getOMPValues();
271 
272   /// @brief Update the internal structures according to a Value Map.
273   ///
274   /// @param VMap     A map from old to new values.
275   /// @param Reverse  If true, we assume the update should be reversed.
276   void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
277                           bool Reverse);
278 
279   /// @brief Create an OpenMP parallel for loop.
280   ///
281   /// This loop reflects a loop as if it would have been created by an OpenMP
282   /// statement.
283   void codegenForOpenMP(const clast_for *f);
284 
285   bool isInnermostLoop(const clast_for *f);
286 
287   /// @brief Get the number of loop iterations for this loop.
288   /// @param f The clast for loop to check.
289   int getNumberOfIterations(const clast_for *f);
290 
291   /// @brief Create vector instructions for this loop.
292   void codegenForVector(const clast_for *f);
293 
294   void codegen(const clast_for *f);
295 
296   Value *codegen(const clast_equation *eq);
297 
298   void codegen(const clast_guard *g);
299 
300   void codegen(const clast_stmt *stmt);
301 
302   void addParameters(const CloogNames *names);
303 
304   IntegerType *getIntPtrTy();
305 
306   public:
307   void codegen(const clast_root *r);
308 
309   ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
310 };
311 }
312 
313 IntegerType *ClastStmtCodeGen::getIntPtrTy() {
314   return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
315 }
316 
317 const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
318   return parallelLoops;
319 }
320 
321 void ClastStmtCodeGen::codegen(const clast_assignment *a) {
322   Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
323   ClastVars[a->LHS] = V;
324 }
325 
326 void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
327                                unsigned Dim, int VectorDim,
328                                std::vector<ValueMapT> *VectorVMap) {
329   const PHINode *PN;
330   Value *RHS;
331 
332   assert(!A->LHS && "Statement assignments do not have left hand side");
333 
334   PN = Stmt->getInductionVariableForDimension(Dim);
335   RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
336   RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
337 
338   if (VectorVMap)
339     (*VectorVMap)[VectorDim][PN] = RHS;
340 
341   ValueMap[PN] = RHS;
342 }
343 
344 void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
345                                              ScopStmt *Statement, int vectorDim,
346   std::vector<ValueMapT> *VectorVMap) {
347   int Dimension = 0;
348 
349   while (Assignment) {
350     assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
351            && "Substitions are expected to be assignments");
352     codegen((const clast_assignment *)Assignment, Statement, Dimension,
353             vectorDim, VectorVMap);
354     Assignment = Assignment->next;
355     Dimension++;
356   }
357 }
358 
359 void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
360                                std::vector<Value*> *IVS , const char *iterator,
361                                isl_set *Domain) {
362   ScopStmt *Statement = (ScopStmt *)u->statement->usr;
363 
364   if (u->substitutions)
365     codegenSubstitutions(u->substitutions, Statement);
366 
367   int VectorDimensions = IVS ? IVS->size() : 1;
368 
369   if (VectorDimensions == 1) {
370     BlockGenerator::generate(Builder, *Statement, ValueMap, P);
371     return;
372   }
373 
374   VectorValueMapT VectorMap(VectorDimensions);
375 
376   if (IVS) {
377     assert (u->substitutions && "Substitutions expected!");
378     int i = 0;
379     for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
380          II != IE; ++II) {
381       ClastVars[iterator] = *II;
382       codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
383       i++;
384     }
385   }
386 
387   VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
388 }
389 
390 void ClastStmtCodeGen::codegen(const clast_block *b) {
391   if (b->body)
392     codegen(b->body);
393 }
394 
395 void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
396   Value *LowerBound, *UpperBound, *IV, *Stride;
397   BasicBlock *AfterBB;
398   Type *IntPtrTy = getIntPtrTy();
399 
400   LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
401   UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
402   Stride = Builder.getInt(APInt_from_MPZ(f->stride));
403 
404   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB);
405 
406   // Add loop iv to symbols.
407   ClastVars[f->iterator] = IV;
408 
409   if (f->body)
410     codegen(f->body);
411 
412   // Loop is finished, so remove its iv from the live symbols.
413   ClastVars.erase(f->iterator);
414   Builder.SetInsertPoint(AfterBB->begin());
415 }
416 
417 SetVector<Value*> ClastStmtCodeGen::getOMPValues() {
418   SetVector<Value*> Values;
419 
420   // The clast variables
421   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
422        I != E; I++)
423     Values.insert(I->second);
424 
425   // The memory reference base addresses
426   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
427     ScopStmt *Stmt = *SI;
428     for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
429          E = Stmt->memacc_end(); I != E; ++I) {
430       Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
431       Values.insert((BaseAddr));
432     }
433   }
434 
435   return Values;
436 }
437 
438 void ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
439                                           bool Reverse) {
440   std::set<Value*> Inserted;
441 
442   if (Reverse) {
443     OMPGenerator::ValueToValueMapTy ReverseMap;
444 
445     for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
446          I != E; ++I)
447        ReverseMap.insert(std::make_pair(I->second, I->first));
448 
449     for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
450          I != E; I++) {
451       ClastVars[I->first] = ReverseMap[I->second];
452       Inserted.insert(I->second);
453     }
454 
455     /// FIXME: At the moment we do not reverse the update of the ValueMap.
456     ///        This is incomplet, but the failure should be obvious, such that
457     ///        we can fix this later.
458     return;
459   }
460 
461   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
462        I != E; I++) {
463     ClastVars[I->first] = VMap[I->second];
464     Inserted.insert(I->second);
465   }
466 
467   for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
468        I != E; ++I) {
469     if (Inserted.count(I->first))
470       continue;
471 
472     ValueMap[I->first] = I->second;
473   }
474 }
475 
476 static void clearDomtree(Function *F, DominatorTree &DT) {
477   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
478   std::vector<BasicBlock*> Nodes;
479   for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
480     Nodes.push_back(I->getBlock());
481 
482   for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
483        I != E; ++I)
484     DT.eraseNode(*I);
485 }
486 
487 void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
488   Value *Stride, *LB, *UB, *IV;
489   BasicBlock::iterator LoopBody;
490   IntegerType *IntPtrTy = getIntPtrTy();
491   SetVector<Value*> Values;
492   OMPGenerator::ValueToValueMapTy VMap;
493   OMPGenerator OMPGen(Builder, P);
494 
495   Stride = Builder.getInt(APInt_from_MPZ(For->stride));
496   Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
497   LB = ExpGen.codegen(For->LB, IntPtrTy);
498   UB = ExpGen.codegen(For->UB, IntPtrTy);
499 
500   Values = getOMPValues();
501 
502   IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
503   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
504   Builder.SetInsertPoint(LoopBody);
505 
506   updateWithValueMap(VMap, /* reverse */ false);
507   ClastVars[For->iterator] = IV;
508 
509   if (For->body)
510     codegen(For->body);
511 
512   ClastVars.erase(For->iterator);
513   updateWithValueMap(VMap, /* reverse */ true);
514 
515   clearDomtree((*LoopBody).getParent()->getParent(),
516                P->getAnalysis<DominatorTree>());
517 
518   Builder.SetInsertPoint(AfterLoop);
519 }
520 
521 bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
522   const clast_stmt *stmt = f->body;
523 
524   while (stmt) {
525     if (!CLAST_STMT_IS_A(stmt, stmt_user))
526       return false;
527 
528     stmt = stmt->next;
529   }
530 
531   return true;
532 }
533 
534 int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
535   isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
536   isl_set *tmp = isl_set_copy(loopDomain);
537 
538   // Calculate a map similar to the identity map, but with the last input
539   // and output dimension not related.
540   //  [i0, i1, i2, i3] -> [i0, i1, i2, o0]
541   isl_space *Space = isl_set_get_space(loopDomain);
542   Space = isl_space_drop_outputs(Space,
543                                  isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
544   Space = isl_space_map_from_set(Space);
545   isl_map *identity = isl_map_identity(Space);
546   identity = isl_map_add_dims(identity, isl_dim_in, 1);
547   identity = isl_map_add_dims(identity, isl_dim_out, 1);
548 
549   isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
550   map = isl_map_intersect(map, identity);
551 
552   isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
553   isl_map *lexmin = isl_map_lexmin(map);
554   isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
555 
556   isl_set *elements = isl_map_range(sub);
557 
558   if (!isl_set_is_singleton(elements)) {
559     isl_set_free(elements);
560     return -1;
561   }
562 
563   isl_point *p = isl_set_sample_point(elements);
564 
565   isl_int v;
566   isl_int_init(v);
567   isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
568   int numberIterations = isl_int_get_si(v);
569   isl_int_clear(v);
570   isl_point_free(p);
571 
572   return (numberIterations) / isl_int_get_si(f->stride) + 1;
573 }
574 
575 void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
576   DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
577   int VectorWidth = getNumberOfIterations(F);
578 
579   Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
580 
581   APInt Stride = APInt_from_MPZ(F->stride);
582   IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
583   Stride =  Stride.zext(LoopIVType->getBitWidth());
584   Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
585 
586   std::vector<Value*> IVS(VectorWidth);
587   IVS[0] = LB;
588 
589   for (int i = 1; i < VectorWidth; i++)
590     IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
591 
592   isl_set *Domain = isl_set_from_cloog_domain(F->domain);
593 
594   // Add loop iv to symbols.
595   ClastVars[F->iterator] = LB;
596 
597   const clast_stmt *Stmt = F->body;
598 
599   while (Stmt) {
600     codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
601             isl_set_copy(Domain));
602     Stmt = Stmt->next;
603   }
604 
605   // Loop is finished, so remove its iv from the live symbols.
606   isl_set_free(Domain);
607   ClastVars.erase(F->iterator);
608 }
609 
610 void ClastStmtCodeGen::codegen(const clast_for *f) {
611   bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
612   if ((Vector || OpenMP) && P->getAnalysis<Dependences>().isParallelFor(f)) {
613     if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
614         && (getNumberOfIterations(f) <= 16)) {
615       codegenForVector(f);
616       return;
617     }
618 
619     if (OpenMP && !parallelCodeGeneration) {
620       parallelCodeGeneration = true;
621       parallelLoops.push_back(f->iterator);
622       codegenForOpenMP(f);
623       parallelCodeGeneration = false;
624       return;
625     }
626   }
627 
628   codegenForSequential(f);
629 }
630 
631 Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
632   Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
633   Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
634   CmpInst::Predicate P;
635 
636   if (eq->sign == 0)
637     P = ICmpInst::ICMP_EQ;
638   else if (eq->sign > 0)
639     P = ICmpInst::ICMP_SGE;
640   else
641     P = ICmpInst::ICMP_SLE;
642 
643   return Builder.CreateICmp(P, LHS, RHS);
644 }
645 
646 void ClastStmtCodeGen::codegen(const clast_guard *g) {
647   Function *F = Builder.GetInsertBlock()->getParent();
648   LLVMContext &Context = F->getContext();
649 
650   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
651                                       Builder.GetInsertPoint(), P);
652   CondBB->setName("polly.cond");
653   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
654   MergeBB->setName("polly.merge");
655   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
656 
657   DominatorTree &DT = P->getAnalysis<DominatorTree>();
658   DT.addNewBlock(ThenBB, CondBB);
659   DT.changeImmediateDominator(MergeBB, CondBB);
660 
661   CondBB->getTerminator()->eraseFromParent();
662 
663   Builder.SetInsertPoint(CondBB);
664 
665   Value *Predicate = codegen(&(g->eq[0]));
666 
667   for (int i = 1; i < g->n; ++i) {
668     Value *TmpPredicate = codegen(&(g->eq[i]));
669     Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
670   }
671 
672   Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
673   Builder.SetInsertPoint(ThenBB);
674   Builder.CreateBr(MergeBB);
675   Builder.SetInsertPoint(ThenBB->begin());
676 
677   codegen(g->then);
678 
679   Builder.SetInsertPoint(MergeBB->begin());
680 }
681 
682 void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
683   if	    (CLAST_STMT_IS_A(stmt, stmt_root))
684     assert(false && "No second root statement expected");
685   else if (CLAST_STMT_IS_A(stmt, stmt_ass))
686     codegen((const clast_assignment *)stmt);
687   else if (CLAST_STMT_IS_A(stmt, stmt_user))
688     codegen((const clast_user_stmt *)stmt);
689   else if (CLAST_STMT_IS_A(stmt, stmt_block))
690     codegen((const clast_block *)stmt);
691   else if (CLAST_STMT_IS_A(stmt, stmt_for))
692     codegen((const clast_for *)stmt);
693   else if (CLAST_STMT_IS_A(stmt, stmt_guard))
694     codegen((const clast_guard *)stmt);
695 
696   if (stmt->next)
697     codegen(stmt->next);
698 }
699 
700 void ClastStmtCodeGen::addParameters(const CloogNames *names) {
701   SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
702 
703   int i = 0;
704   for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
705        PI != PE; ++PI) {
706     assert(i < names->nb_parameters && "Not enough parameter names");
707 
708     const SCEV *Param = *PI;
709     Type *Ty = Param->getType();
710 
711     Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
712     Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
713     ClastVars[names->parameters[i]] = V;
714 
715     ++i;
716   }
717 }
718 
719 void ClastStmtCodeGen::codegen(const clast_root *r) {
720   addParameters(r->names);
721 
722   parallelCodeGeneration = false;
723 
724   const clast_stmt *stmt = (const clast_stmt*) r;
725   if (stmt->next)
726     codegen(stmt->next);
727 }
728 
729 ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
730     S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
731 
732 namespace {
733 class CodeGeneration : public ScopPass {
734   Region *region;
735   Scop *S;
736   DominatorTree *DT;
737   RegionInfo *RI;
738 
739   std::vector<std::string> parallelLoops;
740 
741   public:
742   static char ID;
743 
744   CodeGeneration() : ScopPass(ID) {}
745 
746   // Split the entry edge of the region and generate a new basic block on this
747   // edge. This function also updates ScopInfo and RegionInfo.
748   //
749   // @param region The region where the entry edge will be splitted.
750   BasicBlock *splitEdgeAdvanced(Region *region) {
751     BasicBlock *newBlock;
752     BasicBlock *splitBlock;
753 
754     newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
755 
756     if (DT->dominates(region->getEntry(), newBlock)) {
757       BasicBlock *OldBlock = region->getEntry();
758       std::string OldName = OldBlock->getName();
759 
760       // Update ScopInfo.
761       for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
762         if ((*SI)->getBasicBlock() == OldBlock) {
763           (*SI)->setBasicBlock(newBlock);
764           break;
765         }
766 
767       // Update RegionInfo.
768       splitBlock = OldBlock;
769       OldBlock->setName("polly.split");
770       newBlock->setName(OldName);
771       region->replaceEntry(newBlock);
772       RI->setRegionFor(newBlock, region);
773     } else {
774       RI->setRegionFor(newBlock, region->getParent());
775       splitBlock = newBlock;
776     }
777 
778     return splitBlock;
779   }
780 
781   // Create a split block that branches either to the old code or to a new basic
782   // block where the new code can be inserted.
783   //
784   // @param Builder A builder that will be set to point to a basic block, where
785   //                the new code can be generated.
786   // @return The split basic block.
787   BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
788     BasicBlock *StartBlock, *SplitBlock;
789 
790     SplitBlock = splitEdgeAdvanced(region);
791     SplitBlock->setName("polly.split_new_and_old");
792     Function *F = SplitBlock->getParent();
793     StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
794     SplitBlock->getTerminator()->eraseFromParent();
795     Builder->SetInsertPoint(SplitBlock);
796     Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
797     DT->addNewBlock(StartBlock, SplitBlock);
798     Builder->SetInsertPoint(StartBlock);
799     return SplitBlock;
800   }
801 
802   // Merge the control flow of the newly generated code with the existing code.
803   //
804   // @param SplitBlock The basic block where the control flow was split between
805   //                   old and new version of the Scop.
806   // @param Builder    An IRBuilder that points to the last instruction of the
807   //                   newly generated code.
808   void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
809     BasicBlock *MergeBlock;
810     Region *R = region;
811 
812     if (R->getExit()->getSinglePredecessor())
813       // No splitEdge required.  A block with a single predecessor cannot have
814       // PHI nodes that would complicate life.
815       MergeBlock = R->getExit();
816     else {
817       MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
818       // SplitEdge will never split R->getExit(), as R->getExit() has more than
819       // one predecessor. Hence, mergeBlock is always a newly generated block.
820       R->replaceExit(MergeBlock);
821     }
822 
823     Builder->CreateBr(MergeBlock);
824     MergeBlock->setName("polly.merge_new_and_old");
825 
826     if (DT->dominates(SplitBlock, MergeBlock))
827       DT->changeImmediateDominator(MergeBlock, SplitBlock);
828   }
829 
830   bool runOnScop(Scop &scop) {
831     S = &scop;
832     region = &S->getRegion();
833     DT = &getAnalysis<DominatorTree>();
834     RI = &getAnalysis<RegionInfo>();
835 
836     parallelLoops.clear();
837 
838     assert(region->isSimple() && "Only simple regions are supported");
839 
840     // In the CFG the optimized code of the SCoP is generated next to the
841     // original code. Both the new and the original version of the code remain
842     // in the CFG. A branch statement decides which version is executed.
843     // For now, we always execute the new version (the old one is dead code
844     // eliminated by the cleanup passes). In the future we may decide to execute
845     // the new version only if certain run time checks succeed. This will be
846     // useful to support constructs for which we cannot prove all assumptions at
847     // compile time.
848     //
849     // Before transformation:
850     //
851     //                        bb0
852     //                         |
853     //                     orig_scop
854     //                         |
855     //                        bb1
856     //
857     // After transformation:
858     //                        bb0
859     //                         |
860     //                  polly.splitBlock
861     //                     /       \.
862     //                     |     startBlock
863     //                     |        |
864     //               orig_scop   new_scop
865     //                     \      /
866     //                      \    /
867     //                        bb1 (joinBlock)
868     IRBuilder<> builder(region->getEntry());
869 
870     // The builder will be set to startBlock.
871     BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
872     BasicBlock *StartBlock = builder.GetInsertBlock();
873 
874     mergeControlFlow(splitBlock, &builder);
875     builder.SetInsertPoint(StartBlock->begin());
876 
877     ClastStmtCodeGen CodeGen(S, builder, this);
878     CloogInfo &C = getAnalysis<CloogInfo>();
879     CodeGen.codegen(C.getClast());
880 
881     parallelLoops.insert(parallelLoops.begin(),
882                          CodeGen.getParallelLoops().begin(),
883                          CodeGen.getParallelLoops().end());
884 
885     return true;
886   }
887 
888   virtual void printScop(raw_ostream &OS) const {
889     for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
890          PE = parallelLoops.end(); PI != PE; ++PI)
891       OS << "Parallel loop with iterator '" << *PI << "' generated\n";
892   }
893 
894   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
895     AU.addRequired<CloogInfo>();
896     AU.addRequired<Dependences>();
897     AU.addRequired<DominatorTree>();
898     AU.addRequired<RegionInfo>();
899     AU.addRequired<ScalarEvolution>();
900     AU.addRequired<ScopDetection>();
901     AU.addRequired<ScopInfo>();
902     AU.addRequired<TargetData>();
903 
904     AU.addPreserved<CloogInfo>();
905     AU.addPreserved<Dependences>();
906 
907     // FIXME: We do not create LoopInfo for the newly generated loops.
908     AU.addPreserved<LoopInfo>();
909     AU.addPreserved<DominatorTree>();
910     AU.addPreserved<ScopDetection>();
911     AU.addPreserved<ScalarEvolution>();
912 
913     // FIXME: We do not yet add regions for the newly generated code to the
914     //        region tree.
915     AU.addPreserved<RegionInfo>();
916     AU.addPreserved<TempScopInfo>();
917     AU.addPreserved<ScopInfo>();
918     AU.addPreservedID(IndependentBlocksID);
919   }
920 };
921 }
922 
923 char CodeGeneration::ID = 1;
924 
925 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
926                       "Polly - Create LLVM-IR from SCoPs", false, false)
927 INITIALIZE_PASS_DEPENDENCY(CloogInfo)
928 INITIALIZE_PASS_DEPENDENCY(Dependences)
929 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
930 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
931 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
932 INITIALIZE_PASS_DEPENDENCY(ScopDetection)
933 INITIALIZE_PASS_DEPENDENCY(TargetData)
934 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
935                       "Polly - Create LLVM-IR from SCoPs", false, false)
936 
937 Pass *polly::createCodeGenerationPass() {
938   return new CodeGeneration();
939 }
940