blob: 24ee350de50f78ee5673b84de829dc6e624c791d [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ 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/LinkAllPasses.h"
26#include "polly/Support/GICHelper.h"
27#include "polly/Support/ScopHelper.h"
28#include "polly/Cloog.h"
29#include "polly/Dependences.h"
30#include "polly/ScopInfo.h"
31#include "polly/TempScopInfo.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/IRBuilder.h"
35#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/ScalarEvolutionExpander.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Module.h"
39#include "llvm/ADT/SetVector.h"
40
41#define CLOOG_INT_GMP 1
42#include "cloog/cloog.h"
43#include "cloog/isl/cloog.h"
44
45#include <vector>
46#include <utility>
47
48using namespace polly;
49using namespace llvm;
50
51struct isl_set;
52
53namespace polly {
54
55static cl::opt<bool>
56Vector("enable-polly-vector",
57 cl::desc("Enable polly vector code generation"), cl::Hidden,
58 cl::value_desc("Vector code generation enabled if true"),
59 cl::init(false));
60
61static cl::opt<bool>
62OpenMP("enable-polly-openmp",
63 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
64 cl::value_desc("OpenMP code generation enabled if true"),
65 cl::init(false));
66
67static cl::opt<bool>
68AtLeastOnce("enable-polly-atLeastOnce",
69 cl::desc("Give polly the hint, that every loop is executed at least"
70 "once"), cl::Hidden,
71 cl::value_desc("OpenMP code generation enabled if true"),
72 cl::init(false));
73
74static cl::opt<bool>
75Aligned("enable-polly-aligned",
76 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
77 cl::value_desc("OpenMP code generation enabled if true"),
78 cl::init(false));
79
80static cl::opt<std::string>
81CodegenOnly("polly-codegen-only",
82 cl::desc("Codegen only this function"), cl::Hidden,
83 cl::value_desc("The function name to codegen"),
84 cl::ValueRequired, cl::init(""));
85
86typedef DenseMap<const Value*, Value*> ValueMapT;
87typedef DenseMap<const char*, Value*> CharMapT;
88typedef std::vector<ValueMapT> VectorValueMapT;
89
90// Create a new loop.
91//
92// @param Builder The builder used to create the loop. It also defines the
93// place where to create the loop.
94// @param UB The upper bound of the loop iv.
95// @param Stride The number by which the loop iv is incremented after every
96// iteration.
97static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
98 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
99 DominatorTree *DT) {
100 Function *F = Builder->GetInsertBlock()->getParent();
101 LLVMContext &Context = F->getContext();
102
103 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
104 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
105 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
106 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
107
108 Builder->CreateBr(HeaderBB);
109 DT->addNewBlock(HeaderBB, PreheaderBB);
110
111 Builder->SetInsertPoint(BodyBB);
112
113 Builder->SetInsertPoint(HeaderBB);
114
115 // Use the type of upper and lower bound.
116 assert(LB->getType() == UB->getType()
117 && "Different types for upper and lower bound.");
118
119 const IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
120 assert(LoopIVType && "UB is not integer?");
121
122 // IV
123 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
124 IV->addIncoming(LB, PreheaderBB);
125
126 // IV increment.
127 Value *StrideValue = ConstantInt::get(LoopIVType,
128 Stride.zext(LoopIVType->getBitWidth()));
129 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
130
131 // Exit condition.
132 if (AtLeastOnce) { // At least on iteration.
133 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
134 Value *CMP = Builder->CreateICmpEQ(IV, UB);
135 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
136 } else { // Maybe not executed at all.
137 Value *CMP = Builder->CreateICmpSLE(IV, UB);
138 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
139 }
140 DT->addNewBlock(BodyBB, HeaderBB);
141 DT->addNewBlock(AfterBB, HeaderBB);
142
143 Builder->SetInsertPoint(BodyBB);
144}
145
146class BlockGenerator {
147 IRBuilder<> &Builder;
148 ValueMapT &VMap;
149 VectorValueMapT &ValueMaps;
150 Scop &S;
151 ScopStmt &statement;
152 isl_set *scatteringDomain;
153
154public:
155 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
156 ScopStmt &Stmt, isl_set *domain)
157 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
158 statement(Stmt), scatteringDomain(domain) {}
159
160 const Region &getRegion() {
161 return S.getRegion();
162 }
163
164 Value* makeVectorOperand(Value *operand, int vectorWidth) {
165 if (operand->getType()->isVectorTy())
166 return operand;
167
168 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
169 Value *vector = UndefValue::get(vectorType);
170 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
171
172 std::vector<Constant*> splat;
173
174 for (int i = 0; i < vectorWidth; i++)
175 splat.push_back (Builder.getInt32(0));
176
177 Constant *splatVector = ConstantVector::get(splat);
178
179 return Builder.CreateShuffleVector(vector, vector, splatVector);
180 }
181
182 Value* getOperand(const Value *OldOperand, ValueMapT &BBMap,
183 ValueMapT *VectorMap = 0) {
184 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
185
186 if (!OpInst)
187 return const_cast<Value*>(OldOperand);
188
189 if (VectorMap && VectorMap->count(OldOperand))
190 return (*VectorMap)[OldOperand];
191
192 // IVS and Parameters.
193 if (VMap.count(OldOperand)) {
194 Value *NewOperand = VMap[OldOperand];
195
196 // Insert a cast if types are different
197 if (OldOperand->getType()->getScalarSizeInBits()
198 < NewOperand->getType()->getScalarSizeInBits())
199 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
200 OldOperand->getType());
201
202 return NewOperand;
203 }
204
205 // Instructions calculated in the current BB.
206 if (BBMap.count(OldOperand)) {
207 return BBMap[OldOperand];
208 }
209
210 // Ignore instructions that are referencing ops in the old BB. These
211 // instructions are unused. They where replace by new ones during
212 // createIndependentBlocks().
213 if (getRegion().contains(OpInst->getParent()))
214 return NULL;
215
216 return const_cast<Value*>(OldOperand);
217 }
218
219 const Type *getVectorPtrTy(const Value *V, int vectorWidth) {
220 const PointerType *pointerType = dyn_cast<PointerType>(V->getType());
221 assert(pointerType && "PointerType expected");
222
223 const Type *scalarType = pointerType->getElementType();
224 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
225
226 return PointerType::getUnqual(vectorType);
227 }
228
229 /// @brief Load a vector from a set of adjacent scalars
230 ///
231 /// In case a set of scalars is known to be next to each other in memory,
232 /// create a vector load that loads those scalars
233 ///
234 /// %vector_ptr= bitcast double* %p to <4 x double>*
235 /// %vec_full = load <4 x double>* %vector_ptr
236 ///
237 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
238 int size) {
239 const Value *pointer = load->getPointerOperand();
240 const Type *vectorPtrType = getVectorPtrTy(pointer, size);
241 Value *newPointer = getOperand(pointer, BBMap);
242 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
243 "vector_ptr");
244 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
245 load->getNameStr()
246 + "_p_vec_full");
247 if (!Aligned)
248 VecLoad->setAlignment(8);
249
250 return VecLoad;
251 }
252
253 /// @brief Load a vector initialized from a single scalar in memory
254 ///
255 /// In case all elements of a vector are initialized to the same
256 /// scalar value, this value is loaded and shuffeled into all elements
257 /// of the vector.
258 ///
259 /// %splat_one = load <1 x double>* %p
260 /// %splat = shufflevector <1 x double> %splat_one, <1 x
261 /// double> %splat_one, <4 x i32> zeroinitializer
262 ///
263 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
264 int size) {
265 const Value *pointer = load->getPointerOperand();
266 const Type *vectorPtrType = getVectorPtrTy(pointer, 1);
267 Value *newPointer = getOperand(pointer, BBMap);
268 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
269 load->getNameStr() + "_p_vec_p");
270 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
271 load->getNameStr() + "_p_splat_one");
272
273 if (!Aligned)
274 scalarLoad->setAlignment(8);
275
276 std::vector<Constant*> splat;
277
278 for (int i = 0; i < size; i++)
279 splat.push_back (Builder.getInt32(0));
280
281 Constant *splatVector = ConstantVector::get(splat);
282
283 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
284 splatVector,
285 load->getNameStr()
286 + "_p_splat");
287 return vectorLoad;
288 }
289
290 /// @Load a vector from scalars distributed in memory
291 ///
292 /// In case some scalars a distributed randomly in memory. Create a vector
293 /// by loading each scalar and by inserting one after the other into the
294 /// vector.
295 ///
296 /// %scalar_1= load double* %p_1
297 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
298 /// %scalar 2 = load double* %p_2
299 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
300 ///
301 Value *generateUnknownStrideLoad(const LoadInst *load,
302 VectorValueMapT &scalarMaps,
303 int size) {
304 const Value *pointer = load->getPointerOperand();
305 VectorType *vectorType = VectorType::get(
306 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
307
308 Value *vector = UndefValue::get(vectorType);
309
310 for (int i = 0; i < size; i++) {
311 Value *newPointer = getOperand(pointer, scalarMaps[i]);
312 Value *scalarLoad = Builder.CreateLoad(newPointer,
313 load->getNameStr() + "_p_scalar_");
314 vector = Builder.CreateInsertElement(vector, scalarLoad,
315 Builder.getInt32(i),
316 load->getNameStr() + "_p_vec_");
317 }
318
319 return vector;
320 }
321
322 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
323 const Value *pointer = load->getPointerOperand();
324 Value *newPointer = getOperand(pointer, BBMap);
325 Value *scalarLoad = Builder.CreateLoad(newPointer,
326 load->getNameStr() + "_p_scalar_");
327 return scalarLoad;
328 }
329
330 /// @brief Load a value (or several values as a vector) from memory.
331 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
332 VectorValueMapT &scalarMaps, int vectorWidth) {
333
334 if (scalarMaps.size() == 1) {
335 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
336 return;
337 }
338
339 Value *newLoad;
340
341 MemoryAccess &Access = statement.getAccessFor(load);
342
343 assert(scatteringDomain && "No scattering domain available");
344
345 if (Access.isStrideZero(scatteringDomain))
346 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
347 else if (Access.isStrideOne(scatteringDomain))
348 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
349 else
350 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
351
352 vectorMap[load] = newLoad;
353 }
354
355 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
356 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
357 int vectorDimension, int vectorWidth) {
358 // If this instruction is already in the vectorMap, a vector instruction
359 // was already issued, that calculates the values of all dimensions. No
360 // need to create any more instructions.
361 if (vectorMap.count(Inst))
362 return;
363
364 // Terminator instructions control the control flow. They are explicitally
365 // expressed in the clast and do not need to be copied.
366 if (Inst->isTerminator())
367 return;
368
369 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
370 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
371 return;
372 }
373
374 if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst)) {
375 Value *opZero = Inst->getOperand(0);
376 Value *opOne = Inst->getOperand(1);
377
378 // This is an old instruction that can be ignored.
379 if (!opZero && !opOne)
380 return;
381
382 bool isVectorOp = vectorMap.count(opZero) || vectorMap.count(opOne);
383
384 if (isVectorOp && vectorDimension > 0)
385 return;
386
387 Value *newOpZero, *newOpOne;
388 newOpZero = getOperand(opZero, BBMap, &vectorMap);
389 newOpOne = getOperand(opOne, BBMap, &vectorMap);
390
391
392 std::string name;
393 if (isVectorOp) {
394 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
395 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
396 name = Inst->getNameStr() + "p_vec";
397 } else
398 name = Inst->getNameStr() + "p_sca";
399
400 Value *newInst = Builder.CreateBinOp(binaryInst->getOpcode(), newOpZero,
401 newOpOne, name);
402 if (isVectorOp)
403 vectorMap[Inst] = newInst;
404 else
405 BBMap[Inst] = newInst;
406
407 return;
408 }
409
410 if (const StoreInst *store = dyn_cast<StoreInst>(Inst)) {
411 if (vectorMap.count(store->getValueOperand()) > 0) {
412
413 // We only need to generate one store if we are in vector mode.
414 if (vectorDimension > 0)
415 return;
416
417 MemoryAccess &Access = statement.getAccessFor(store);
418
419 assert(scatteringDomain && "No scattering domain available");
420
421 const Value *pointer = store->getPointerOperand();
422 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
423
424 if (Access.isStrideOne(scatteringDomain)) {
425 const Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
426 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
427
428 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
429 "vector_ptr");
430 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
431
432 if (!Aligned)
433 Store->setAlignment(8);
434 } else {
435 for (unsigned i = 0; i < scalarMaps.size(); i++) {
436 Value *scalar = Builder.CreateExtractElement(vector,
437 Builder.getInt32(i));
438 Value *newPointer = getOperand(pointer, scalarMaps[i]);
439 Builder.CreateStore(scalar, newPointer);
440 }
441 }
442
443 return;
444 }
445 }
446
447 Instruction *NewInst = Inst->clone();
448
449 // Copy the operands in temporary vector, as an in place update
450 // fails if an instruction is referencing the same operand twice.
451 std::vector<Value*> Operands(NewInst->op_begin(), NewInst->op_end());
452
453 // Replace old operands with the new ones.
454 for (std::vector<Value*>::iterator UI = Operands.begin(),
455 UE = Operands.end(); UI != UE; ++UI) {
456 Value *newOperand = getOperand(*UI, BBMap);
457
458 if (!newOperand) {
459 assert(!isa<StoreInst>(NewInst)
460 && "Store instructions are always needed!");
461 delete NewInst;
462 return;
463 }
464
465 NewInst->replaceUsesOfWith(*UI, newOperand);
466 }
467
468 Builder.Insert(NewInst);
469 BBMap[Inst] = NewInst;
470
471 if (!NewInst->getType()->isVoidTy())
472 NewInst->setName("p_" + Inst->getName());
473 }
474
475 int getVectorSize() {
476 return ValueMaps.size();
477 }
478
479 bool isVectorBlock() {
480 return getVectorSize() > 1;
481 }
482
483 // Insert a copy of a basic block in the newly generated code.
484 //
485 // @param Builder The builder used to insert the code. It also specifies
486 // where to insert the code.
487 // @param BB The basic block to copy
488 // @param VMap A map returning for any old value its new equivalent. This
489 // is used to update the operands of the statements.
490 // For new statements a relation old->new is inserted in this
491 // map.
492 void copyBB(BasicBlock *BB, DominatorTree *DT) {
493 Function *F = Builder.GetInsertBlock()->getParent();
494 LLVMContext &Context = F->getContext();
495 BasicBlock *CopyBB = BasicBlock::Create(Context,
496 "polly.stmt_" + BB->getNameStr(),
497 F);
498 Builder.CreateBr(CopyBB);
499 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
500 Builder.SetInsertPoint(CopyBB);
501
502 // Create two maps that store the mapping from the original instructions of
503 // the old basic block to their copies in the new basic block. Those maps
504 // are basic block local.
505 //
506 // As vector code generation is supported there is one map for scalar values
507 // and one for vector values.
508 //
509 // In case we just do scalar code generation, the vectorMap is not used and
510 // the scalarMap has just one dimension, which contains the mapping.
511 //
512 // In case vector code generation is done, an instruction may either appear
513 // in the vector map once (as it is calculating >vectorwidth< values at a
514 // time. Or (if the values are calculated using scalar operations), it
515 // appears once in every dimension of the scalarMap.
516 VectorValueMapT scalarBlockMap(getVectorSize());
517 ValueMapT vectorBlockMap;
518
519 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
520 II != IE; ++II)
521 for (int i = 0; i < getVectorSize(); i++) {
522 if (isVectorBlock())
523 VMap = ValueMaps[i];
524
525 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
526 scalarBlockMap, i, getVectorSize());
527 }
528 }
529};
530
531/// Class to generate LLVM-IR that calculates the value of a clast_expr.
532class ClastExpCodeGen {
533 IRBuilder<> &Builder;
534 const CharMapT *IVS;
535
536 Value *codegen(const clast_name *e, const Type *Ty) {
537 CharMapT::const_iterator I = IVS->find(e->name);
538
539 if (I != IVS->end())
540 return Builder.CreateSExtOrBitCast(I->second, Ty);
541 else
542 llvm_unreachable("Clast name not found");
543 }
544
545 Value *codegen(const clast_term *e, const Type *Ty) {
546 APInt a = APInt_from_MPZ(e->val);
547
548 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
549 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
550
551 if (e->var) {
552 Value *var = codegen(e->var, Ty);
553 return Builder.CreateMul(ConstOne, var);
554 }
555
556 return ConstOne;
557 }
558
559 Value *codegen(const clast_binary *e, const Type *Ty) {
560 Value *LHS = codegen(e->LHS, Ty);
561
562 APInt RHS_AP = APInt_from_MPZ(e->RHS);
563
564 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
565 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
566
567 switch (e->type) {
568 case clast_bin_mod:
569 return Builder.CreateSRem(LHS, RHS);
570 case clast_bin_fdiv:
571 {
572 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
573 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
574 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
575 One = Builder.CreateZExtOrBitCast(One, Ty);
576 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
577 Value *Sum1 = Builder.CreateSub(LHS, RHS);
578 Value *Sum2 = Builder.CreateAdd(Sum1, One);
579 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
580 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
581 return Builder.CreateSDiv(Dividend, RHS);
582 }
583 case clast_bin_cdiv:
584 {
585 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
586 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
587 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
588 One = Builder.CreateZExtOrBitCast(One, Ty);
589 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
590 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
591 Value *Sum2 = Builder.CreateSub(Sum1, One);
592 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
593 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
594 return Builder.CreateSDiv(Dividend, RHS);
595 }
596 case clast_bin_div:
597 return Builder.CreateSDiv(LHS, RHS);
598 default:
599 llvm_unreachable("Unknown clast binary expression type");
600 };
601 }
602
603 Value *codegen(const clast_reduction *r, const Type *Ty) {
604 assert(( r->type == clast_red_min
605 || r->type == clast_red_max
606 || r->type == clast_red_sum)
607 && "Clast reduction type not supported");
608 Value *old = codegen(r->elts[0], Ty);
609
610 for (int i=1; i < r->n; ++i) {
611 Value *exprValue = codegen(r->elts[i], Ty);
612
613 switch (r->type) {
614 case clast_red_min:
615 {
616 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
617 old = Builder.CreateSelect(cmp, old, exprValue);
618 break;
619 }
620 case clast_red_max:
621 {
622 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
623 old = Builder.CreateSelect(cmp, old, exprValue);
624 break;
625 }
626 case clast_red_sum:
627 old = Builder.CreateAdd(old, exprValue);
628 break;
629 default:
630 llvm_unreachable("Clast unknown reduction type");
631 }
632 }
633
634 return old;
635 }
636
637public:
638
639 // A generator for clast expressions.
640 //
641 // @param B The IRBuilder that defines where the code to calculate the
642 // clast expressions should be inserted.
643 // @param IVMAP A Map that translates strings describing the induction
644 // variables to the Values* that represent these variables
645 // on the LLVM side.
646 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
647
648 // Generates code to calculate a given clast expression.
649 //
650 // @param e The expression to calculate.
651 // @return The Value that holds the result.
652 Value *codegen(const clast_expr *e, const Type *Ty) {
653 switch(e->type) {
654 case clast_expr_name:
655 return codegen((const clast_name *)e, Ty);
656 case clast_expr_term:
657 return codegen((const clast_term *)e, Ty);
658 case clast_expr_bin:
659 return codegen((const clast_binary *)e, Ty);
660 case clast_expr_red:
661 return codegen((const clast_reduction *)e, Ty);
662 default:
663 llvm_unreachable("Unknown clast expression!");
664 }
665 }
666
667 // @brief Reset the CharMap.
668 //
669 // This function is called to reset the CharMap to new one, while generating
670 // OpenMP code.
671 void setIVS(CharMapT *IVSNew) {
672 IVS = IVSNew;
673 }
674
675};
676
677class ClastStmtCodeGen {
678 // The Scop we code generate.
679 Scop *S;
680 ScalarEvolution &SE;
681
682 DominatorTree *DT;
683 Dependences *DP;
684 TargetData *TD;
685
686 // The Builder specifies the current location to code generate at.
687 IRBuilder<> &Builder;
688
689 // Map the Values from the old code to their counterparts in the new code.
690 ValueMapT ValueMap;
691
692 // clastVars maps from the textual representation of a clast variable to its
693 // current *Value. clast variables are scheduling variables, original
694 // induction variables or parameters. They are used either in loop bounds or
695 // to define the statement instance that is executed.
696 //
697 // for (s = 0; s < n + 3; ++i)
698 // for (t = s; t < m; ++j)
699 // Stmt(i = s + 3 * m, j = t);
700 //
701 // {s,t,i,j,n,m} is the set of clast variables in this clast.
702 CharMapT *clastVars;
703
704 // Codegenerator for clast expressions.
705 ClastExpCodeGen ExpGen;
706
707 // Do we currently generate parallel code?
708 bool parallelCodeGeneration;
709
710 std::vector<std::string> parallelLoops;
711
712public:
713
714 const std::vector<std::string> &getParallelLoops() {
715 return parallelLoops;
716 }
717
718 protected:
719 void codegen(const clast_assignment *a) {
720 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
721 TD->getIntPtrType(Builder.getContext()));
722 }
723
724 void codegen(const clast_assignment *a, ScopStmt *Statement,
725 unsigned Dimension, int vectorDim,
726 std::vector<ValueMapT> *VectorVMap = 0) {
727 Value *RHS = ExpGen.codegen(a->RHS,
728 TD->getIntPtrType(Builder.getContext()));
729
730 assert(!a->LHS && "Statement assignments do not have left hand side");
731 const PHINode *PN;
732 PN = Statement->getInductionVariableForDimension(Dimension);
733 const Value *V = PN;
734
735 if (PN->getNumOperands() == 2)
736 V = *(PN->use_begin());
737
738 if (VectorVMap)
739 (*VectorVMap)[vectorDim][V] = RHS;
740
741 ValueMap[V] = RHS;
742 }
743
744 void codegenSubstitutions(const clast_stmt *Assignment,
745 ScopStmt *Statement, int vectorDim = 0,
746 std::vector<ValueMapT> *VectorVMap = 0) {
747 int Dimension = 0;
748
749 while (Assignment) {
750 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
751 && "Substitions are expected to be assignments");
752 codegen((const clast_assignment *)Assignment, Statement, Dimension,
753 vectorDim, VectorVMap);
754 Assignment = Assignment->next;
755 Dimension++;
756 }
757 }
758
759 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
760 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
761 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
762 BasicBlock *BB = Statement->getBasicBlock();
763
764 if (u->substitutions)
765 codegenSubstitutions(u->substitutions, Statement);
766
767 int vectorDimensions = IVS ? IVS->size() : 1;
768
769 VectorValueMapT VectorValueMap(vectorDimensions);
770
771 if (IVS) {
772 assert (u->substitutions && "Substitutions expected!");
773 int i = 0;
774 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
775 II != IE; ++II) {
776 (*clastVars)[iterator] = *II;
777 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
778 i++;
779 }
780 }
781
782 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
783 scatteringDomain);
784 Generator.copyBB(BB, DT);
785 }
786
787 void codegen(const clast_block *b) {
788 if (b->body)
789 codegen(b->body);
790 }
791
792 /// @brief Create a classical sequential loop.
793 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
794 Value *upperBound = 0) {
795 APInt Stride = APInt_from_MPZ(f->stride);
796 PHINode *IV;
797 Value *IncrementedIV;
798 BasicBlock *AfterBB;
799 // The value of lowerbound and upperbound will be supplied, if this
800 // function is called while generating OpenMP code. Otherwise get
801 // the values.
802 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
803 && "Either give both bounds or none");
804 if (lowerBound == 0 || upperBound == 0) {
805 lowerBound = ExpGen.codegen(f->LB,
806 TD->getIntPtrType(Builder.getContext()));
807 upperBound = ExpGen.codegen(f->UB,
808 TD->getIntPtrType(Builder.getContext()));
809 }
810 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
811 IncrementedIV, DT);
812
813 // Add loop iv to symbols.
814 (*clastVars)[f->iterator] = IV;
815
816 if (f->body)
817 codegen(f->body);
818
819 // Loop is finished, so remove its iv from the live symbols.
820 clastVars->erase(f->iterator);
821
822 BasicBlock *HeaderBB = *pred_begin(AfterBB);
823 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
824 Builder.CreateBr(HeaderBB);
825 IV->addIncoming(IncrementedIV, LastBodyBB);
826 Builder.SetInsertPoint(AfterBB);
827 }
828
Tobias Grosser75805372011-04-29 06:27:02 +0000829 /// @brief Add a new definition of an openmp subfunction.
830 Function* addOpenMPSubfunction(Module *M) {
831 Function *F = Builder.GetInsertBlock()->getParent();
832 const std::string &Name = F->getNameStr() + ".omp_subfn";
833
834 std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy());
835 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
836 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
837
838 Function::arg_iterator AI = FN->arg_begin();
839 AI->setName("omp.userContext");
840
841 return FN;
842 }
843
844 /// @brief Add values to the OpenMP structure.
845 ///
846 /// Create the subfunction structure and add the values from the list.
847 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
848 Function *SubFunction) {
849 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
850 std::vector<const Type*> structMembers;
851
852 // Create the structure.
853 for (unsigned i = 0; i < OMPDataVals.size(); i++)
854 structMembers.push_back(OMPDataVals[i]->getType());
855
856 const std::string &Name = SubFunction->getNameStr() + ".omp.userContext";
857 StructType *structTy = StructType::get(Builder.getContext(),
858 structMembers);
859 M->addTypeName(Name, structTy);
860
861 // Store the values into the structure.
862 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
863 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
864 Value *storeAddr = Builder.CreateStructGEP(structData, i);
865 Builder.CreateStore(OMPDataVals[i], storeAddr);
866 }
867
868 return structData;
869 }
870
871 /// @brief Create OpenMP structure values.
872 ///
873 /// Create a list of values that has to be stored into the subfuncition
874 /// structure.
875 SetVector<Value*> createOpenMPStructValues() {
876 SetVector<Value*> OMPDataVals;
877
878 // Push the clast variables available in the clastVars.
879 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
880 I != E; I++)
881 OMPDataVals.insert(I->second);
882
883 // Push the base addresses of memory references.
884 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
885 ScopStmt *Stmt = *SI;
886 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
887 E = Stmt->memacc_end(); I != E; ++I) {
888 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
889 OMPDataVals.insert((BaseAddr));
890 }
891 }
892
893 return OMPDataVals;
894 }
895
896 /// @brief Extract the values from the subfunction parameter.
897 ///
898 /// Extract the values from the subfunction parameter and update the clast
899 /// variables to point to the new values.
900 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
901 SetVector<Value*> OMPDataVals,
902 Value *userContext) {
903 // Extract the clast variables.
904 unsigned i = 0;
905 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
906 I != E; I++) {
907 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
908 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
909 i++;
910 }
911
912 // Extract the base addresses of memory references.
913 for (unsigned j = i; j < OMPDataVals.size(); j++) {
914 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
915 Value *baseAddr = OMPDataVals[j];
916 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
917 }
918
919 }
920
921 /// @brief Add body to the subfunction.
922 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
923 Value *structData,
924 SetVector<Value*> OMPDataVals) {
925 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
926 LLVMContext &Context = FN->getContext();
927 const IntegerType *intPtrTy = TD->getIntPtrType(Context);
928
929 // Store the previous basic block.
930 BasicBlock *PrevBB = Builder.GetInsertBlock();
931
932 // Create basic blocks.
933 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
934 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
935 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
936 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
937 FN);
938
939 DT->addNewBlock(HeaderBB, PrevBB);
940 DT->addNewBlock(ExitBB, HeaderBB);
941 DT->addNewBlock(checkNextBB, HeaderBB);
942 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
943
944 // Fill up basic block HeaderBB.
945 Builder.SetInsertPoint(HeaderBB);
946 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
947 "omp.lowerBoundPtr");
948 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
949 "omp.upperBoundPtr");
950 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
951 structData->getType(),
952 "omp.userContext");
953
954 CharMapT clastVarsOMP;
955 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
956
957 Builder.CreateBr(checkNextBB);
958
959 // Add code to check if another set of iterations will be executed.
960 Builder.SetInsertPoint(checkNextBB);
961 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
962 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
963 lowerBoundPtr, upperBoundPtr);
964 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
965 "omp.hasNextScheduleBlock");
966 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
967
968 // Add code to to load the iv bounds for this set of iterations.
969 Builder.SetInsertPoint(loadIVBoundsBB);
970 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
971 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
972
973 // Subtract one as the upper bound provided by openmp is a < comparison
974 // whereas the codegenForSequential function creates a <= comparison.
975 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
976 "omp.upperBoundAdjusted");
977
978 // Use clastVarsOMP during code generation of the OpenMP subfunction.
979 CharMapT *oldClastVars = clastVars;
980 clastVars = &clastVarsOMP;
981 ExpGen.setIVS(&clastVarsOMP);
982
983 codegenForSequential(f, lowerBound, upperBound);
984
985 // Restore the old clastVars.
986 clastVars = oldClastVars;
987 ExpGen.setIVS(oldClastVars);
988
989 Builder.CreateBr(checkNextBB);
990
991 // Add code to terminate this openmp subfunction.
992 Builder.SetInsertPoint(ExitBB);
993 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
994 Builder.CreateCall(endnowaitFunction);
995 Builder.CreateRetVoid();
996
997 // Restore the builder back to previous basic block.
998 Builder.SetInsertPoint(PrevBB);
999 }
1000
1001 /// @brief Create an OpenMP parallel for loop.
1002 ///
1003 /// This loop reflects a loop as if it would have been created by an OpenMP
1004 /// statement.
1005 void codegenForOpenMP(const clast_for *f) {
1006 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1007 const IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1008
1009 Function *SubFunction = addOpenMPSubfunction(M);
1010 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1011 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1012
1013 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1014
1015 // Create call for GOMP_parallel_loop_runtime_start.
1016 Value *subfunctionParam = Builder.CreateBitCast(structData,
1017 Builder.getInt8PtrTy(),
1018 "omp_data");
1019
1020 Value *numberOfThreads = Builder.getInt32(0);
1021 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1022 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1023
1024 // Add one as the upper bound provided by openmp is a < comparison
1025 // whereas the codegenForSequential function creates a <= comparison.
1026 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1027 APInt APStride = APInt_from_MPZ(f->stride);
1028 Value *stride = ConstantInt::get(intPtrTy,
1029 APStride.zext(intPtrTy->getBitWidth()));
1030
1031 SmallVector<Value *, 6> Arguments;
1032 Arguments.push_back(SubFunction);
1033 Arguments.push_back(subfunctionParam);
1034 Arguments.push_back(numberOfThreads);
1035 Arguments.push_back(lowerBound);
1036 Arguments.push_back(upperBound);
1037 Arguments.push_back(stride);
1038
1039 Function *parallelStartFunction =
1040 M->getFunction("GOMP_parallel_loop_runtime_start");
1041 Builder.CreateCall(parallelStartFunction, Arguments.begin(),
1042 Arguments.end());
1043
1044 // Create call to the subfunction.
1045 Builder.CreateCall(SubFunction, subfunctionParam);
1046
1047 // Create call for GOMP_parallel_end.
1048 Function *FN = M->getFunction("GOMP_parallel_end");
1049 Builder.CreateCall(FN);
1050 }
1051
1052 bool isInnermostLoop(const clast_for *f) {
1053 const clast_stmt *stmt = f->body;
1054
1055 while (stmt) {
1056 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1057 return false;
1058
1059 stmt = stmt->next;
1060 }
1061
1062 return true;
1063 }
1064
1065 /// @brief Get the number of loop iterations for this loop.
1066 /// @param f The clast for loop to check.
1067 int getNumberOfIterations(const clast_for *f) {
1068 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1069 isl_set *tmp = isl_set_copy(loopDomain);
1070
1071 // Calculate a map similar to the identity map, but with the last input
1072 // and output dimension not related.
1073 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1074 isl_dim *dim = isl_set_get_dim(loopDomain);
1075 dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1);
1076 dim = isl_dim_map_from_set(dim);
1077 isl_map *identity = isl_map_identity(dim);
1078 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1079 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1080
1081 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1082 map = isl_map_intersect(map, identity);
1083
1084 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1085 isl_map *lexmin = isl_map_lexmin(isl_map_copy(map));
1086 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1087
1088 isl_set *elements = isl_map_range(sub);
1089
1090 if (!isl_set_is_singleton(elements))
1091 return -1;
1092
1093 isl_point *p = isl_set_sample_point(elements);
1094
1095 isl_int v;
1096 isl_int_init(v);
1097 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1098 int numberIterations = isl_int_get_si(v);
1099 isl_int_clear(v);
1100
1101 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1102 }
1103
1104 /// @brief Create vector instructions for this loop.
1105 void codegenForVector(const clast_for *f) {
1106 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1107 int vectorWidth = getNumberOfIterations(f);
1108
1109 Value *LB = ExpGen.codegen(f->LB,
1110 TD->getIntPtrType(Builder.getContext()));
1111
1112 APInt Stride = APInt_from_MPZ(f->stride);
1113 const IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1114 Stride = Stride.zext(LoopIVType->getBitWidth());
1115 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1116
1117 std::vector<Value*> IVS(vectorWidth);
1118 IVS[0] = LB;
1119
1120 for (int i = 1; i < vectorWidth; i++)
1121 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1122
1123 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1124
1125 // Add loop iv to symbols.
1126 (*clastVars)[f->iterator] = LB;
1127
1128 const clast_stmt *stmt = f->body;
1129
1130 while (stmt) {
1131 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1132 scatteringDomain);
1133 stmt = stmt->next;
1134 }
1135
1136 // Loop is finished, so remove its iv from the live symbols.
1137 clastVars->erase(f->iterator);
1138 }
1139
1140 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001141 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001142 && (-1 != getNumberOfIterations(f))
1143 && (getNumberOfIterations(f) <= 16)) {
1144 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001145 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001146 parallelCodeGeneration = true;
1147 parallelLoops.push_back(f->iterator);
1148 codegenForOpenMP(f);
1149 parallelCodeGeneration = false;
1150 } else
1151 codegenForSequential(f);
1152 }
1153
1154 Value *codegen(const clast_equation *eq) {
1155 Value *LHS = ExpGen.codegen(eq->LHS,
1156 TD->getIntPtrType(Builder.getContext()));
1157 Value *RHS = ExpGen.codegen(eq->RHS,
1158 TD->getIntPtrType(Builder.getContext()));
1159 CmpInst::Predicate P;
1160
1161 if (eq->sign == 0)
1162 P = ICmpInst::ICMP_EQ;
1163 else if (eq->sign > 0)
1164 P = ICmpInst::ICMP_SGE;
1165 else
1166 P = ICmpInst::ICMP_SLE;
1167
1168 return Builder.CreateICmp(P, LHS, RHS);
1169 }
1170
1171 void codegen(const clast_guard *g) {
1172 Function *F = Builder.GetInsertBlock()->getParent();
1173 LLVMContext &Context = F->getContext();
1174 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1175 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1176 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1177 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1178
1179 Value *Predicate = codegen(&(g->eq[0]));
1180
1181 for (int i = 1; i < g->n; ++i) {
1182 Value *TmpPredicate = codegen(&(g->eq[i]));
1183 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1184 }
1185
1186 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1187 Builder.SetInsertPoint(ThenBB);
1188
1189 codegen(g->then);
1190
1191 Builder.CreateBr(MergeBB);
1192 Builder.SetInsertPoint(MergeBB);
1193 }
1194
1195 void codegen(const clast_stmt *stmt) {
1196 if (CLAST_STMT_IS_A(stmt, stmt_root))
1197 assert(false && "No second root statement expected");
1198 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1199 codegen((const clast_assignment *)stmt);
1200 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1201 codegen((const clast_user_stmt *)stmt);
1202 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1203 codegen((const clast_block *)stmt);
1204 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1205 codegen((const clast_for *)stmt);
1206 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1207 codegen((const clast_guard *)stmt);
1208
1209 if (stmt->next)
1210 codegen(stmt->next);
1211 }
1212
1213 void addParameters(const CloogNames *names) {
1214 SCEVExpander Rewriter(SE);
1215
1216 // Create an instruction that specifies the location where the parameters
1217 // are expanded.
1218 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1219 Builder.getInt16Ty(), false, "insertInst",
1220 Builder.GetInsertBlock());
1221
1222 int i = 0;
1223 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1224 PI != PE; ++PI) {
1225 assert(i < names->nb_parameters && "Not enough parameter names");
1226
1227 const SCEV *Param = *PI;
1228 const Type *Ty = Param->getType();
1229
1230 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1231 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1232 (*clastVars)[names->parameters[i]] = V;
1233
1234 ++i;
1235 }
1236 }
1237
1238 public:
1239 void codegen(const clast_root *r) {
1240 clastVars = new CharMapT();
1241 addParameters(r->names);
1242 ExpGen.setIVS(clastVars);
1243
1244 parallelCodeGeneration = false;
1245
1246 const clast_stmt *stmt = (const clast_stmt*) r;
1247 if (stmt->next)
1248 codegen(stmt->next);
1249
1250 delete clastVars;
1251 }
1252
1253 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
1254 Dependences *dp, TargetData *td, IRBuilder<> &B) :
1255 S(scop), SE(se), DT(dt), DP(dp), TD(td), Builder(B), ExpGen(Builder, NULL) {}
1256
1257};
1258}
1259
1260namespace {
1261class CodeGeneration : public ScopPass {
1262 Region *region;
1263 Scop *S;
1264 DominatorTree *DT;
1265 ScalarEvolution *SE;
1266 ScopDetection *SD;
1267 CloogInfo *C;
1268 LoopInfo *LI;
1269 TargetData *TD;
1270
1271 std::vector<std::string> parallelLoops;
1272
1273 public:
1274 static char ID;
1275
1276 CodeGeneration() : ScopPass(ID) {}
1277
1278 void createSeSeEdges(Region *R) {
1279 BasicBlock *newEntry = createSingleEntryEdge(R, this);
1280
1281 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1282 if ((*SI)->getBasicBlock() == R->getEntry())
1283 (*SI)->setBasicBlock(newEntry);
1284
1285 createSingleExitEdge(R, this);
1286 }
1287
1288
1289 // Adding prototypes required if OpenMP is enabled.
1290 void addOpenMPDefinitions(IRBuilder<> &Builder)
1291 {
1292 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1293 LLVMContext &Context = Builder.getContext();
1294 const IntegerType *intPtrTy = TD->getIntPtrType(Context);
1295
1296 if (!M->getFunction("GOMP_parallel_end")) {
1297 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1298 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1299 }
1300
1301 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1302 // Type of first argument.
1303 std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy());
1304 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1305 false);
1306 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1307
1308 std::vector<const Type*> args;
1309 args.push_back(FnPtrTy);
1310 args.push_back(Builder.getInt8PtrTy());
1311 args.push_back(Builder.getInt32Ty());
1312 args.push_back(intPtrTy);
1313 args.push_back(intPtrTy);
1314 args.push_back(intPtrTy);
1315
1316 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1317 Function::Create(type, Function::ExternalLinkage,
1318 "GOMP_parallel_loop_runtime_start", M);
1319 }
1320
1321 if (!M->getFunction("GOMP_loop_runtime_next")) {
1322 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1323
1324 std::vector<const Type*> args;
1325 args.push_back(intLongPtrTy);
1326 args.push_back(intLongPtrTy);
1327
1328 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1329 Function::Create(type, Function::ExternalLinkage,
1330 "GOMP_loop_runtime_next", M);
1331 }
1332
1333 if (!M->getFunction("GOMP_loop_end_nowait")) {
1334 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
1335 std::vector<const Type*>(), false);
1336 Function::Create(FT, Function::ExternalLinkage,
1337 "GOMP_loop_end_nowait", M);
1338 }
1339 }
1340
1341 bool runOnScop(Scop &scop) {
1342 S = &scop;
1343 region = &S->getRegion();
1344 Region *R = region;
1345 DT = &getAnalysis<DominatorTree>();
1346 Dependences *DP = &getAnalysis<Dependences>();
1347 SE = &getAnalysis<ScalarEvolution>();
1348 LI = &getAnalysis<LoopInfo>();
1349 C = &getAnalysis<CloogInfo>();
1350 SD = &getAnalysis<ScopDetection>();
1351 TD = &getAnalysis<TargetData>();
1352
1353 Function *F = R->getEntry()->getParent();
1354
1355 parallelLoops.clear();
1356
1357 if (CodegenOnly != "" && CodegenOnly != F->getNameStr()) {
1358 errs() << "Codegenerating only function '" << CodegenOnly
1359 << "' skipping '" << F->getNameStr() << "' \n";
1360 return false;
1361 }
1362
1363 createSeSeEdges(R);
1364
1365 // Create a basic block in which to start code generation.
1366 BasicBlock *PollyBB = BasicBlock::Create(F->getContext(), "pollyBB", F);
1367 IRBuilder<> Builder(PollyBB);
1368 DT->addNewBlock(PollyBB, R->getEntry());
1369
1370 const clast_root *clast = (const clast_root *) C->getClast();
1371
1372 ClastStmtCodeGen CodeGen(S, *SE, DT, DP, TD, Builder);
1373
1374 if (OpenMP)
1375 addOpenMPDefinitions(Builder);
1376
1377 CodeGen.codegen(clast);
1378
1379 // Save the parallel loops generated.
1380 parallelLoops.insert(parallelLoops.begin(),
1381 CodeGen.getParallelLoops().begin(),
1382 CodeGen.getParallelLoops().end());
1383
1384 BasicBlock *AfterScop = *pred_begin(R->getExit());
1385 Builder.CreateBr(AfterScop);
1386
1387 BasicBlock *successorBlock = *succ_begin(R->getEntry());
1388
1389 // Update old PHI nodes to pass LLVM verification.
1390 std::vector<PHINode*> PHINodes;
1391 for (BasicBlock::iterator SI = successorBlock->begin(),
1392 SE = successorBlock->getFirstNonPHI(); SI != SE; ++SI) {
1393 PHINode *PN = static_cast<PHINode*>(&*SI);
1394 PHINodes.push_back(PN);
1395 }
1396
1397 for (std::vector<PHINode*>::iterator PI = PHINodes.begin(),
1398 PE = PHINodes.end(); PI != PE; ++PI)
1399 (*PI)->removeIncomingValue(R->getEntry());
1400
1401 DT->changeImmediateDominator(AfterScop, Builder.GetInsertBlock());
1402
1403 BasicBlock *OldRegionEntry = *succ_begin(R->getEntry());
1404
1405 // Enable the new polly code.
1406 R->getEntry()->getTerminator()->setSuccessor(0, PollyBB);
1407
1408 // Remove old Scop nodes from dominator tree.
1409 std::vector<DomTreeNode*> ToVisit;
1410 std::vector<DomTreeNode*> Visited;
1411 ToVisit.push_back(DT->getNode(OldRegionEntry));
1412
1413 while (!ToVisit.empty()) {
1414 DomTreeNode *Node = ToVisit.back();
1415
1416 ToVisit.pop_back();
1417
1418 if (AfterScop == Node->getBlock())
1419 continue;
1420
1421 Visited.push_back(Node);
1422
1423 std::vector<DomTreeNode*> Children = Node->getChildren();
1424 ToVisit.insert(ToVisit.end(), Children.begin(), Children.end());
1425 }
1426
1427 for (std::vector<DomTreeNode*>::reverse_iterator I = Visited.rbegin(),
1428 E = Visited.rend(); I != E; ++I)
1429 DT->eraseNode((*I)->getBlock());
1430
1431 R->getParent()->removeSubRegion(R);
1432
1433 // And forget the Scop if we remove the region.
1434 SD->forgetScop(*R);
1435
1436 return false;
1437 }
1438
1439 virtual void printScop(raw_ostream &OS) const {
1440 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1441 PE = parallelLoops.end(); PI != PE; ++PI)
1442 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1443 }
1444
1445 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1446 AU.addRequired<CloogInfo>();
1447 AU.addRequired<Dependences>();
1448 AU.addRequired<DominatorTree>();
1449 AU.addRequired<ScalarEvolution>();
1450 AU.addRequired<LoopInfo>();
1451 AU.addRequired<RegionInfo>();
1452 AU.addRequired<ScopDetection>();
1453 AU.addRequired<ScopInfo>();
1454 AU.addRequired<TargetData>();
1455
1456 AU.addPreserved<CloogInfo>();
1457 AU.addPreserved<Dependences>();
1458 AU.addPreserved<LoopInfo>();
1459 AU.addPreserved<DominatorTree>();
1460 AU.addPreserved<PostDominatorTree>();
1461 AU.addPreserved<ScopDetection>();
1462 AU.addPreserved<ScalarEvolution>();
1463 AU.addPreserved<RegionInfo>();
1464 AU.addPreserved<TempScopInfo>();
1465 AU.addPreserved<ScopInfo>();
1466 AU.addPreservedID(IndependentBlocksID);
1467 }
1468};
1469}
1470
1471char CodeGeneration::ID = 1;
1472
1473static RegisterPass<CodeGeneration>
1474Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1475
1476Pass* polly::createCodeGenerationPass() {
1477 return new CodeGeneration();
1478}