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