blob: b316b61d414223e717acc0ed5507290dda9f1e21 [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"
Tobias Grosser67707b72011-10-23 20:59:40 +000029#include "polly/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/Dependences.h"
31#include "polly/ScopInfo.h"
32#include "polly/TempScopInfo.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/IRBuilder.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser8c4cfc322011-05-14 19:01:49 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Module.h"
41#include "llvm/ADT/SetVector.h"
42
43#define CLOOG_INT_GMP 1
44#include "cloog/cloog.h"
45#include "cloog/isl/cloog.h"
46
Raghesh Aloora71989c2011-12-28 02:48:26 +000047#include "isl/aff.h"
48
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <vector>
50#include <utility>
51
52using namespace polly;
53using namespace llvm;
54
55struct isl_set;
56
57namespace polly {
58
Tobias Grosser67707b72011-10-23 20:59:40 +000059bool EnablePollyVector;
60
61static cl::opt<bool, true>
Tobias Grosser75805372011-04-29 06:27:02 +000062Vector("enable-polly-vector",
63 cl::desc("Enable polly vector code generation"), cl::Hidden,
Tobias Grosser67707b72011-10-23 20:59:40 +000064 cl::location(EnablePollyVector), cl::init(false));
Tobias Grosser75805372011-04-29 06:27:02 +000065
66static cl::opt<bool>
67OpenMP("enable-polly-openmp",
68 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
69 cl::value_desc("OpenMP code generation enabled if true"),
70 cl::init(false));
71
72static cl::opt<bool>
73AtLeastOnce("enable-polly-atLeastOnce",
74 cl::desc("Give polly the hint, that every loop is executed at least"
75 "once"), cl::Hidden,
76 cl::value_desc("OpenMP code generation enabled if true"),
77 cl::init(false));
78
79static cl::opt<bool>
80Aligned("enable-polly-aligned",
81 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
82 cl::value_desc("OpenMP code generation enabled if true"),
83 cl::init(false));
84
Tobias Grosser75805372011-04-29 06:27:02 +000085typedef DenseMap<const Value*, Value*> ValueMapT;
86typedef DenseMap<const char*, Value*> CharMapT;
87typedef std::vector<ValueMapT> VectorValueMapT;
Raghesh Aloora71989c2011-12-28 02:48:26 +000088typedef struct {
89 Value *BaseAddress;
90 Value *Result;
91 IRBuilder<> *Builder;
92}IslPwAffUserInfo;
Tobias Grosser75805372011-04-29 06:27:02 +000093
94// Create a new loop.
95//
96// @param Builder The builder used to create the loop. It also defines the
97// place where to create the loop.
98// @param UB The upper bound of the loop iv.
99// @param Stride The number by which the loop iv is incremented after every
100// iteration.
101static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
102 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
103 DominatorTree *DT) {
104 Function *F = Builder->GetInsertBlock()->getParent();
105 LLVMContext &Context = F->getContext();
106
107 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
108 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
109 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
110 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
111
112 Builder->CreateBr(HeaderBB);
113 DT->addNewBlock(HeaderBB, PreheaderBB);
114
115 Builder->SetInsertPoint(BodyBB);
116
117 Builder->SetInsertPoint(HeaderBB);
118
119 // Use the type of upper and lower bound.
120 assert(LB->getType() == UB->getType()
121 && "Different types for upper and lower bound.");
122
Tobias Grosser55927aa2011-07-18 09:53:32 +0000123 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000124 assert(LoopIVType && "UB is not integer?");
125
126 // IV
127 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
128 IV->addIncoming(LB, PreheaderBB);
129
130 // IV increment.
131 Value *StrideValue = ConstantInt::get(LoopIVType,
132 Stride.zext(LoopIVType->getBitWidth()));
133 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
134
135 // Exit condition.
136 if (AtLeastOnce) { // At least on iteration.
137 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
138 Value *CMP = Builder->CreateICmpEQ(IV, UB);
139 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
140 } else { // Maybe not executed at all.
141 Value *CMP = Builder->CreateICmpSLE(IV, UB);
142 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
143 }
144 DT->addNewBlock(BodyBB, HeaderBB);
145 DT->addNewBlock(AfterBB, HeaderBB);
146
147 Builder->SetInsertPoint(BodyBB);
148}
149
150class BlockGenerator {
151 IRBuilder<> &Builder;
152 ValueMapT &VMap;
153 VectorValueMapT &ValueMaps;
154 Scop &S;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000155 ScopStmt &Statement;
156 isl_set *ScatteringDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000157
158public:
159 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000160 ScopStmt &Stmt, __isl_keep isl_set *domain);
Tobias Grosser75805372011-04-29 06:27:02 +0000161
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000162 const Region &getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000163
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000164 Value *makeVectorOperand(Value *operand, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000165
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000166 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000167 ValueMapT *VectorMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000168
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000169 Type *getVectorPtrTy(const Value *V, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000170
171 /// @brief Load a vector from a set of adjacent scalars
172 ///
173 /// In case a set of scalars is known to be next to each other in memory,
174 /// create a vector load that loads those scalars
175 ///
176 /// %vector_ptr= bitcast double* %p to <4 x double>*
177 /// %vec_full = load <4 x double>* %vector_ptr
178 ///
179 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000180 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000181
182 /// @brief Load a vector initialized from a single scalar in memory
183 ///
184 /// In case all elements of a vector are initialized to the same
185 /// scalar value, this value is loaded and shuffeled into all elements
186 /// of the vector.
187 ///
188 /// %splat_one = load <1 x double>* %p
189 /// %splat = shufflevector <1 x double> %splat_one, <1 x
190 /// double> %splat_one, <4 x i32> zeroinitializer
191 ///
192 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000193 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000194
195 /// @Load a vector from scalars distributed in memory
196 ///
197 /// In case some scalars a distributed randomly in memory. Create a vector
198 /// by loading each scalar and by inserting one after the other into the
199 /// vector.
200 ///
201 /// %scalar_1= load double* %p_1
202 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
203 /// %scalar 2 = load double* %p_2
204 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
205 ///
206 Value *generateUnknownStrideLoad(const LoadInst *load,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000207 VectorValueMapT &scalarMaps, int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000208
Raghesh Aloora71989c2011-12-28 02:48:26 +0000209 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000210 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000211
212 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000213 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000214
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000215 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff, Value *BaseAddress);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000216
Raghesh Aloor129e8672011-08-15 02:33:39 +0000217 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000218 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000219 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000220
Raghesh Aloor62b13122011-08-03 17:02:50 +0000221 /// @brief Get the new operand address according to the changed access in
222 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000223 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
224 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000225 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000226
227 /// @brief Generate the operand address
228 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000229 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000230
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000231 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000232
233 /// @brief Load a value (or several values as a vector) from memory.
234 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000235 VectorValueMapT &scalarMaps, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000236
Tobias Grosserc9215152011-09-04 11:45:52 +0000237 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
238 ValueMapT &VectorMap, int VectorDimension,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000239 int VectorWidth);
Tobias Grosserc9215152011-09-04 11:45:52 +0000240
Tobias Grosser09c57102011-09-04 11:45:29 +0000241 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000242 ValueMapT &vectorMap, int vectorDimension, int vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000243
244 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000245 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000246 int vectorDimension, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000247
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000248 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000249
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000250 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000251
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000252 int getVectorSize();
Tobias Grosser75805372011-04-29 06:27:02 +0000253
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000254 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000255
Tobias Grosser7551c302011-09-04 11:45:41 +0000256 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
257 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000258 int vectorDimension, int vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000259
Tobias Grosser75805372011-04-29 06:27:02 +0000260 // Insert a copy of a basic block in the newly generated code.
261 //
262 // @param Builder The builder used to insert the code. It also specifies
263 // where to insert the code.
264 // @param BB The basic block to copy
265 // @param VMap A map returning for any old value its new equivalent. This
266 // is used to update the operands of the statements.
267 // For new statements a relation old->new is inserted in this
268 // map.
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000269 void copyBB(BasicBlock *BB, DominatorTree *DT);
Tobias Grosser75805372011-04-29 06:27:02 +0000270};
271
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000272BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
273 VectorValueMapT &vmaps, ScopStmt &Stmt,
274 __isl_keep isl_set *domain)
275 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
276 Statement(Stmt), ScatteringDomain(domain) {}
277
278const Region &BlockGenerator::getRegion() {
279 return S.getRegion();
280}
281
282Value *BlockGenerator::makeVectorOperand(Value *Operand, int VectorWidth) {
283 if (Operand->getType()->isVectorTy())
284 return Operand;
285
286 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
287 Value *Vector = UndefValue::get(VectorType);
288 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
289
290 std::vector<Constant*> Splat;
291
292 for (int i = 0; i < VectorWidth; i++)
293 Splat.push_back (Builder.getInt32(0));
294
295 Constant *SplatVector = ConstantVector::get(Splat);
296
297 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
298}
299
300Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
301 ValueMapT *VectorMap) {
302 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
303
304 if (!OpInst)
305 return const_cast<Value*>(OldOperand);
306
307 if (VectorMap && VectorMap->count(OldOperand))
308 return (*VectorMap)[OldOperand];
309
310 // IVS and Parameters.
311 if (VMap.count(OldOperand)) {
312 Value *NewOperand = VMap[OldOperand];
313
314 // Insert a cast if types are different
315 if (OldOperand->getType()->getScalarSizeInBits()
316 < NewOperand->getType()->getScalarSizeInBits())
317 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
318 OldOperand->getType());
319
320 return NewOperand;
321 }
322
323 // Instructions calculated in the current BB.
324 if (BBMap.count(OldOperand)) {
325 return BBMap[OldOperand];
326 }
327
328 // Ignore instructions that are referencing ops in the old BB. These
329 // instructions are unused. They where replace by new ones during
330 // createIndependentBlocks().
331 if (getRegion().contains(OpInst->getParent()))
332 return NULL;
333
334 return const_cast<Value*>(OldOperand);
335}
336
337Type *BlockGenerator::getVectorPtrTy(const Value *Val, int VectorWidth) {
338 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
339 assert(PointerTy && "PointerType expected");
340
341 Type *ScalarType = PointerTy->getElementType();
342 VectorType *VectorType = VectorType::get(ScalarType, VectorWidth);
343
344 return PointerType::getUnqual(VectorType);
345}
346
347Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
348 ValueMapT &BBMap, int Size) {
349 const Value *Pointer = Load->getPointerOperand();
350 Type *VectorPtrType = getVectorPtrTy(Pointer, Size);
351 Value *NewPointer = getOperand(Pointer, BBMap);
352 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
353 "vector_ptr");
354 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
355 Load->getName() + "_p_vec_full");
356 if (!Aligned)
357 VecLoad->setAlignment(8);
358
359 return VecLoad;
360}
361
362Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
363 ValueMapT &BBMap, int Size) {
364 const Value *Pointer = Load->getPointerOperand();
365 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
366 Value *NewPointer = getOperand(Pointer, BBMap);
367 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
368 Load->getName() + "_p_vec_p");
369 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
370 Load->getName() + "_p_splat_one");
371
372 if (!Aligned)
373 ScalarLoad->setAlignment(8);
374
375 std::vector<Constant*> Splat;
376
377 for (int i = 0; i < Size; i++)
378 Splat.push_back (Builder.getInt32(0));
379
380 Constant *SplatVector = ConstantVector::get(Splat);
381
382 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
383 SplatVector,
384 Load->getName()
385 + "_p_splat");
386 return VectorLoad;
387}
388
389Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
390 VectorValueMapT &ScalarMaps,
391 int Size) {
392 const Value *Pointer = Load->getPointerOperand();
393 VectorType *VectorType = VectorType::get(
394 dyn_cast<PointerType>(Pointer->getType())->getElementType(), Size);
395
396 Value *Vector = UndefValue::get(VectorType);
397
398 for (int i = 0; i < Size; i++) {
399 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
400 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
401 Load->getName() + "_p_scalar_");
402 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
403 Builder.getInt32(i),
404 Load->getName() + "_p_vec_");
405 }
406
407 return Vector;
408}
409
410Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
411 IslPwAffUserInfo *UserInfo) {
412 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
413
414 IRBuilder<> *Builder = UserInfo->Builder;
415
416 isl_int OffsetIsl;
417 mpz_t OffsetMPZ;
418
419 isl_int_init(OffsetIsl);
420 mpz_init(OffsetMPZ);
421 isl_aff_get_constant(Aff, &OffsetIsl);
422 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
423
424 Value *OffsetValue = NULL;
425 APInt Offset = APInt_from_MPZ(OffsetMPZ);
426 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
427
428 mpz_clear(OffsetMPZ);
429 isl_int_clear(OffsetIsl);
430 isl_aff_free(Aff);
431
432 return OffsetValue;
433}
434
435int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
436 __isl_take isl_aff *Aff, void *User) {
437 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
438
439 assert((UserInfo->Result == NULL) && "Result is already set."
440 "Currently only single isl_aff is supported");
441 assert(isl_set_plain_is_universe(Set)
442 && "Code generation failed because the set is not universe");
443
444 UserInfo->Result = islAffToValue(Aff, UserInfo);
445
446 isl_set_free(Set);
447 return 0;
448}
449
450Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff,
451 Value *BaseAddress) {
452 IslPwAffUserInfo UserInfo;
453 UserInfo.BaseAddress = BaseAddress;
454 UserInfo.Result = NULL;
455 UserInfo.Builder = &Builder;
456 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
457 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
458
459 isl_pw_aff_free(PwAff);
460 return UserInfo.Result;
461}
462
463std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
464 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
465 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
466 && "Only single dimensional access functions supported");
467
468 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
469 Value *OffsetValue = islPwAffToValue(PwAff, BaseAddress);
470
471 PointerType *BaseAddressType = dyn_cast<PointerType>(
472 BaseAddress->getType());
473 Type *ArrayTy = BaseAddressType->getElementType();
474 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
475 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
476
477 std::vector<Value*> IndexArray;
478 Value *NullValue = Constant::getNullValue(ArrayElementType);
479 IndexArray.push_back(NullValue);
480 IndexArray.push_back(OffsetValue);
481 return IndexArray;
482}
483
484Value *BlockGenerator::getNewAccessOperand(
485 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
486 *OldOperand, ValueMapT &BBMap) {
487 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
488 BaseAddress);
489 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
490 "p_newarrayidx_");
491 return NewOperand;
492}
493
494Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
495 const Value *Pointer,
496 ValueMapT &BBMap ) {
497 MemoryAccess &Access = Statement.getAccessFor(Inst);
498 isl_map *CurrentAccessRelation = Access.getAccessRelation();
499 isl_map *NewAccessRelation = Access.getNewAccessRelation();
500
501 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
502 && "Current and new access function use different spaces");
503
504 Value *NewPointer;
505
506 if (!NewAccessRelation) {
507 NewPointer = getOperand(Pointer, BBMap);
508 } else {
509 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
510 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
511 BBMap);
512 }
513
514 isl_map_free(CurrentAccessRelation);
515 isl_map_free(NewAccessRelation);
516 return NewPointer;
517}
518
519Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
520 ValueMapT &BBMap) {
521 const Value *Pointer = Load->getPointerOperand();
522 const Instruction *Inst = dyn_cast<Instruction>(Load);
523 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
524 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
525 Load->getName() + "_p_scalar_");
526 return ScalarLoad;
527}
528
529void BlockGenerator::generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
530 VectorValueMapT &ScalarMaps,
531 int VectorWidth) {
532 if (ScalarMaps.size() == 1) {
533 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
534 return;
535 }
536
537 Value *NewLoad;
538
539 MemoryAccess &Access = Statement.getAccessFor(Load);
540
541 assert(ScatteringDomain && "No scattering domain available");
542
543 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
544 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0], VectorWidth);
545 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
546 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0], VectorWidth);
547 else
548 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps, VectorWidth);
549
550 VectorMap[Load] = NewLoad;
551}
552
553void BlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
554 ValueMapT &BBMap, ValueMapT &VectorMap,
555 int VectorDimension, int VectorWidth) {
556 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
557 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
558
559 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
560
561 const CastInst *Cast = dyn_cast<CastInst>(Inst);
562 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
563 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
564}
565
566void BlockGenerator::copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
567 ValueMapT &VectorMap, int VectorDimension,
568 int VectorWidth) {
569 Value *OpZero = Inst->getOperand(0);
570 Value *OpOne = Inst->getOperand(1);
571
572 Value *NewOpZero, *NewOpOne;
573 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
574 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
575
576 NewOpZero = makeVectorOperand(NewOpZero, VectorWidth);
577 NewOpOne = makeVectorOperand(NewOpOne, VectorWidth);
578
579 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
580 NewOpOne,
581 Inst->getName() + "p_vec");
582 VectorMap[Inst] = NewInst;
583}
584
585void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
586 ValueMapT &VectorMap,
587 VectorValueMapT &ScalarMaps,
588 int VectorDimension, int VectorWidth) {
589 // In vector mode we only generate a store for the first dimension.
590 if (VectorDimension > 0)
591 return;
592
593 MemoryAccess &Access = Statement.getAccessFor(Store);
594
595 assert(ScatteringDomain && "No scattering domain available");
596
597 const Value *Pointer = Store->getPointerOperand();
598 Value *Vector = getOperand(Store->getValueOperand(), BBMap, &VectorMap);
599
600 if (Access.isStrideOne(isl_set_copy(ScatteringDomain))) {
601 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
602 Value *NewPointer = getOperand(Pointer, BBMap, &VectorMap);
603
604 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
605 "vector_ptr");
606 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
607
608 if (!Aligned)
609 Store->setAlignment(8);
610 } else {
611 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
612 Value *Scalar = Builder.CreateExtractElement(Vector,
613 Builder.getInt32(i));
614 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
615 Builder.CreateStore(Scalar, NewPointer);
616 }
617 }
618}
619
620void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
621 Instruction *NewInst = Inst->clone();
622
623 // Replace old operands with the new ones.
624 for (Instruction::const_op_iterator OI = Inst->op_begin(),
625 OE = Inst->op_end(); OI != OE; ++OI) {
626 Value *OldOperand = *OI;
627 Value *NewOperand = getOperand(OldOperand, BBMap);
628
629 if (!NewOperand) {
630 assert(!isa<StoreInst>(NewInst)
631 && "Store instructions are always needed!");
632 delete NewInst;
633 return;
634 }
635
636 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
637 }
638
639 Builder.Insert(NewInst);
640 BBMap[Inst] = NewInst;
641
642 if (!NewInst->getType()->isVoidTy())
643 NewInst->setName("p_" + Inst->getName());
644}
645
646bool BlockGenerator::hasVectorOperands(const Instruction *Inst,
647 ValueMapT &VectorMap) {
648 for (Instruction::const_op_iterator OI = Inst->op_begin(),
649 OE = Inst->op_end(); OI != OE; ++OI)
650 if (VectorMap.count(*OI))
651 return true;
652 return false;
653}
654
655int BlockGenerator::getVectorSize() {
656 return ValueMaps.size();
657}
658
659bool BlockGenerator::isVectorBlock() {
660 return getVectorSize() > 1;
661}
662
663void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
664 ValueMapT &VectorMap,
665 VectorValueMapT &ScalarMaps,
666 int VectorDimension, int VectorWidth) {
667 // Terminator instructions control the control flow. They are explicitally
668 // expressed in the clast and do not need to be copied.
669 if (Inst->isTerminator())
670 return;
671
672 if (isVectorBlock()) {
673 // If this instruction is already in the vectorMap, a vector instruction
674 // was already issued, that calculates the values of all dimensions. No
675 // need to create any more instructions.
676 if (VectorMap.count(Inst))
677 return;
678 }
679
680 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
681 generateLoad(Load, VectorMap, ScalarMaps, VectorWidth);
682 return;
683 }
684
685 if (isVectorBlock() && hasVectorOperands(Inst, VectorMap)) {
686 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
687 copyUnaryInst(UnaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
688 else if
689 (const BinaryOperator *BinaryInst = dyn_cast<BinaryOperator>(Inst))
690 copyBinInst(BinaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
691 else if (const StoreInst *Store = dyn_cast<StoreInst>(Inst))
692 copyVectorStore(Store, BBMap, VectorMap, ScalarMaps, VectorDimension,
693 VectorWidth);
694 else
695 llvm_unreachable("Cannot issue vector code for this instruction");
696
697 return;
698 }
699
700 copyInstScalar(Inst, BBMap);
701}
702
703void BlockGenerator::copyBB(BasicBlock *BB, DominatorTree *DT) {
704 Function *F = Builder.GetInsertBlock()->getParent();
705 LLVMContext &Context = F->getContext();
706 BasicBlock *CopyBB = BasicBlock::Create(Context,
707 "polly." + BB->getName() + ".stmt",
708 F);
709 Builder.CreateBr(CopyBB);
710 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
711 Builder.SetInsertPoint(CopyBB);
712
713 // Create two maps that store the mapping from the original instructions of
714 // the old basic block to their copies in the new basic block. Those maps
715 // are basic block local.
716 //
717 // As vector code generation is supported there is one map for scalar values
718 // and one for vector values.
719 //
720 // In case we just do scalar code generation, the vectorMap is not used and
721 // the scalarMap has just one dimension, which contains the mapping.
722 //
723 // In case vector code generation is done, an instruction may either appear
724 // in the vector map once (as it is calculating >vectorwidth< values at a
725 // time. Or (if the values are calculated using scalar operations), it
726 // appears once in every dimension of the scalarMap.
727 VectorValueMapT ScalarBlockMap(getVectorSize());
728 ValueMapT VectorBlockMap;
729
730 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
731 II != IE; ++II)
732 for (int i = 0; i < getVectorSize(); i++) {
733 if (isVectorBlock())
734 VMap = ValueMaps[i];
735
736 copyInstruction(II, ScalarBlockMap[i], VectorBlockMap,
737 ScalarBlockMap, i, getVectorSize());
738 }
739}
740
Tobias Grosser75805372011-04-29 06:27:02 +0000741/// Class to generate LLVM-IR that calculates the value of a clast_expr.
742class ClastExpCodeGen {
743 IRBuilder<> &Builder;
744 const CharMapT *IVS;
745
Tobias Grosser55927aa2011-07-18 09:53:32 +0000746 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000747 CharMapT::const_iterator I = IVS->find(e->name);
748
749 if (I != IVS->end())
750 return Builder.CreateSExtOrBitCast(I->second, Ty);
751 else
752 llvm_unreachable("Clast name not found");
753 }
754
Tobias Grosser55927aa2011-07-18 09:53:32 +0000755 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000756 APInt a = APInt_from_MPZ(e->val);
757
758 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
759 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
760
761 if (e->var) {
762 Value *var = codegen(e->var, Ty);
763 return Builder.CreateMul(ConstOne, var);
764 }
765
766 return ConstOne;
767 }
768
Tobias Grosser55927aa2011-07-18 09:53:32 +0000769 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000770 Value *LHS = codegen(e->LHS, Ty);
771
772 APInt RHS_AP = APInt_from_MPZ(e->RHS);
773
774 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
775 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
776
777 switch (e->type) {
778 case clast_bin_mod:
779 return Builder.CreateSRem(LHS, RHS);
780 case clast_bin_fdiv:
781 {
782 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
783 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
784 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
785 One = Builder.CreateZExtOrBitCast(One, Ty);
786 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
787 Value *Sum1 = Builder.CreateSub(LHS, RHS);
788 Value *Sum2 = Builder.CreateAdd(Sum1, One);
789 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
790 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
791 return Builder.CreateSDiv(Dividend, RHS);
792 }
793 case clast_bin_cdiv:
794 {
795 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
796 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
797 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
798 One = Builder.CreateZExtOrBitCast(One, Ty);
799 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
800 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
801 Value *Sum2 = Builder.CreateSub(Sum1, One);
802 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
803 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
804 return Builder.CreateSDiv(Dividend, RHS);
805 }
806 case clast_bin_div:
807 return Builder.CreateSDiv(LHS, RHS);
808 default:
809 llvm_unreachable("Unknown clast binary expression type");
810 };
811 }
812
Tobias Grosser55927aa2011-07-18 09:53:32 +0000813 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000814 assert(( r->type == clast_red_min
815 || r->type == clast_red_max
816 || r->type == clast_red_sum)
817 && "Clast reduction type not supported");
818 Value *old = codegen(r->elts[0], Ty);
819
820 for (int i=1; i < r->n; ++i) {
821 Value *exprValue = codegen(r->elts[i], Ty);
822
823 switch (r->type) {
824 case clast_red_min:
825 {
826 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
827 old = Builder.CreateSelect(cmp, old, exprValue);
828 break;
829 }
830 case clast_red_max:
831 {
832 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
833 old = Builder.CreateSelect(cmp, old, exprValue);
834 break;
835 }
836 case clast_red_sum:
837 old = Builder.CreateAdd(old, exprValue);
838 break;
839 default:
840 llvm_unreachable("Clast unknown reduction type");
841 }
842 }
843
844 return old;
845 }
846
847public:
848
849 // A generator for clast expressions.
850 //
851 // @param B The IRBuilder that defines where the code to calculate the
852 // clast expressions should be inserted.
853 // @param IVMAP A Map that translates strings describing the induction
854 // variables to the Values* that represent these variables
855 // on the LLVM side.
856 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
857
858 // Generates code to calculate a given clast expression.
859 //
860 // @param e The expression to calculate.
861 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000862 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000863 switch(e->type) {
864 case clast_expr_name:
865 return codegen((const clast_name *)e, Ty);
866 case clast_expr_term:
867 return codegen((const clast_term *)e, Ty);
868 case clast_expr_bin:
869 return codegen((const clast_binary *)e, Ty);
870 case clast_expr_red:
871 return codegen((const clast_reduction *)e, Ty);
872 default:
873 llvm_unreachable("Unknown clast expression!");
874 }
875 }
876
877 // @brief Reset the CharMap.
878 //
879 // This function is called to reset the CharMap to new one, while generating
880 // OpenMP code.
881 void setIVS(CharMapT *IVSNew) {
882 IVS = IVSNew;
883 }
884
885};
886
887class ClastStmtCodeGen {
888 // The Scop we code generate.
889 Scop *S;
890 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000891 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000892 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000893 Dependences *DP;
894 TargetData *TD;
895
896 // The Builder specifies the current location to code generate at.
897 IRBuilder<> &Builder;
898
899 // Map the Values from the old code to their counterparts in the new code.
900 ValueMapT ValueMap;
901
902 // clastVars maps from the textual representation of a clast variable to its
903 // current *Value. clast variables are scheduling variables, original
904 // induction variables or parameters. They are used either in loop bounds or
905 // to define the statement instance that is executed.
906 //
907 // for (s = 0; s < n + 3; ++i)
908 // for (t = s; t < m; ++j)
909 // Stmt(i = s + 3 * m, j = t);
910 //
911 // {s,t,i,j,n,m} is the set of clast variables in this clast.
912 CharMapT *clastVars;
913
914 // Codegenerator for clast expressions.
915 ClastExpCodeGen ExpGen;
916
917 // Do we currently generate parallel code?
918 bool parallelCodeGeneration;
919
920 std::vector<std::string> parallelLoops;
921
922public:
923
924 const std::vector<std::string> &getParallelLoops() {
925 return parallelLoops;
926 }
927
928 protected:
929 void codegen(const clast_assignment *a) {
930 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
931 TD->getIntPtrType(Builder.getContext()));
932 }
933
934 void codegen(const clast_assignment *a, ScopStmt *Statement,
935 unsigned Dimension, int vectorDim,
936 std::vector<ValueMapT> *VectorVMap = 0) {
937 Value *RHS = ExpGen.codegen(a->RHS,
938 TD->getIntPtrType(Builder.getContext()));
939
940 assert(!a->LHS && "Statement assignments do not have left hand side");
941 const PHINode *PN;
942 PN = Statement->getInductionVariableForDimension(Dimension);
943 const Value *V = PN;
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945 if (VectorVMap)
946 (*VectorVMap)[vectorDim][V] = RHS;
947
948 ValueMap[V] = RHS;
949 }
950
951 void codegenSubstitutions(const clast_stmt *Assignment,
952 ScopStmt *Statement, int vectorDim = 0,
953 std::vector<ValueMapT> *VectorVMap = 0) {
954 int Dimension = 0;
955
956 while (Assignment) {
957 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
958 && "Substitions are expected to be assignments");
959 codegen((const clast_assignment *)Assignment, Statement, Dimension,
960 vectorDim, VectorVMap);
961 Assignment = Assignment->next;
962 Dimension++;
963 }
964 }
965
966 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
967 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
968 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
969 BasicBlock *BB = Statement->getBasicBlock();
970
971 if (u->substitutions)
972 codegenSubstitutions(u->substitutions, Statement);
973
974 int vectorDimensions = IVS ? IVS->size() : 1;
975
976 VectorValueMapT VectorValueMap(vectorDimensions);
977
978 if (IVS) {
979 assert (u->substitutions && "Substitutions expected!");
980 int i = 0;
981 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
982 II != IE; ++II) {
983 (*clastVars)[iterator] = *II;
984 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
985 i++;
986 }
987 }
988
989 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
990 scatteringDomain);
991 Generator.copyBB(BB, DT);
992 }
993
994 void codegen(const clast_block *b) {
995 if (b->body)
996 codegen(b->body);
997 }
998
999 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +00001000 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
1001 Value *UpperBound = 0) {
1002 APInt Stride;
Tobias Grosser75805372011-04-29 06:27:02 +00001003 PHINode *IV;
1004 Value *IncrementedIV;
Tobias Grosser545bc312011-12-06 10:48:27 +00001005 BasicBlock *AfterBB, *HeaderBB, *LastBodyBB;
1006 Type *IntPtrTy;
1007
1008 Stride = APInt_from_MPZ(f->stride);
1009 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1010
Tobias Grosser75805372011-04-29 06:27:02 +00001011 // The value of lowerbound and upperbound will be supplied, if this
1012 // function is called while generating OpenMP code. Otherwise get
1013 // the values.
Tobias Grosser545bc312011-12-06 10:48:27 +00001014 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1015
1016 if (LowerBound == 0) {
1017 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1018 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
Tobias Grosser75805372011-04-29 06:27:02 +00001019 }
Tobias Grosser545bc312011-12-06 10:48:27 +00001020
1021 createLoop(&Builder, LowerBound, UpperBound, Stride, IV, AfterBB,
Tobias Grosser75805372011-04-29 06:27:02 +00001022 IncrementedIV, DT);
1023
1024 // Add loop iv to symbols.
1025 (*clastVars)[f->iterator] = IV;
1026
1027 if (f->body)
1028 codegen(f->body);
1029
1030 // Loop is finished, so remove its iv from the live symbols.
1031 clastVars->erase(f->iterator);
1032
Tobias Grosser545bc312011-12-06 10:48:27 +00001033 HeaderBB = *pred_begin(AfterBB);
1034 LastBodyBB = Builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001035 Builder.CreateBr(HeaderBB);
1036 IV->addIncoming(IncrementedIV, LastBodyBB);
1037 Builder.SetInsertPoint(AfterBB);
1038 }
1039
Tobias Grosser75805372011-04-29 06:27:02 +00001040 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001041 Function *addOpenMPSubfunction(Module *M) {
Tobias Grosser75805372011-04-29 06:27:02 +00001042 Function *F = Builder.GetInsertBlock()->getParent();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001043 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001044 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001045 Function *FN = Function::Create(FT, Function::InternalLinkage,
1046 F->getName() + ".omp_subfn", M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001047 // Do not run any polly pass on the new function.
1048 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +00001049
1050 Function::arg_iterator AI = FN->arg_begin();
1051 AI->setName("omp.userContext");
1052
1053 return FN;
1054 }
1055
1056 /// @brief Add values to the OpenMP structure.
1057 ///
1058 /// Create the subfunction structure and add the values from the list.
1059 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1060 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +00001061 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +00001062
1063 // Create the structure.
1064 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1065 structMembers.push_back(OMPDataVals[i]->getType());
1066
Tobias Grosser75805372011-04-29 06:27:02 +00001067 StructType *structTy = StructType::get(Builder.getContext(),
1068 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +00001069 // Store the values into the structure.
1070 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1071 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1072 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1073 Builder.CreateStore(OMPDataVals[i], storeAddr);
1074 }
1075
1076 return structData;
1077 }
1078
1079 /// @brief Create OpenMP structure values.
1080 ///
1081 /// Create a list of values that has to be stored into the subfuncition
1082 /// structure.
1083 SetVector<Value*> createOpenMPStructValues() {
1084 SetVector<Value*> OMPDataVals;
1085
1086 // Push the clast variables available in the clastVars.
1087 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1088 I != E; I++)
1089 OMPDataVals.insert(I->second);
1090
1091 // Push the base addresses of memory references.
1092 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1093 ScopStmt *Stmt = *SI;
1094 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1095 E = Stmt->memacc_end(); I != E; ++I) {
1096 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1097 OMPDataVals.insert((BaseAddr));
1098 }
1099 }
1100
1101 return OMPDataVals;
1102 }
1103
1104 /// @brief Extract the values from the subfunction parameter.
1105 ///
1106 /// Extract the values from the subfunction parameter and update the clast
1107 /// variables to point to the new values.
1108 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1109 SetVector<Value*> OMPDataVals,
1110 Value *userContext) {
1111 // Extract the clast variables.
1112 unsigned i = 0;
1113 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1114 I != E; I++) {
1115 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1116 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1117 i++;
1118 }
1119
1120 // Extract the base addresses of memory references.
1121 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1122 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1123 Value *baseAddr = OMPDataVals[j];
1124 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1125 }
1126
1127 }
1128
1129 /// @brief Add body to the subfunction.
1130 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1131 Value *structData,
1132 SetVector<Value*> OMPDataVals) {
1133 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1134 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001135 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
1137 // Store the previous basic block.
1138 BasicBlock *PrevBB = Builder.GetInsertBlock();
1139
1140 // Create basic blocks.
1141 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1142 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1143 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1144 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1145 FN);
1146
1147 DT->addNewBlock(HeaderBB, PrevBB);
1148 DT->addNewBlock(ExitBB, HeaderBB);
1149 DT->addNewBlock(checkNextBB, HeaderBB);
1150 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1151
1152 // Fill up basic block HeaderBB.
1153 Builder.SetInsertPoint(HeaderBB);
1154 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1155 "omp.lowerBoundPtr");
1156 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1157 "omp.upperBoundPtr");
1158 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1159 structData->getType(),
1160 "omp.userContext");
1161
1162 CharMapT clastVarsOMP;
1163 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1164
1165 Builder.CreateBr(checkNextBB);
1166
1167 // Add code to check if another set of iterations will be executed.
1168 Builder.SetInsertPoint(checkNextBB);
1169 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1170 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1171 lowerBoundPtr, upperBoundPtr);
1172 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1173 "omp.hasNextScheduleBlock");
1174 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1175
1176 // Add code to to load the iv bounds for this set of iterations.
1177 Builder.SetInsertPoint(loadIVBoundsBB);
1178 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1179 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1180
1181 // Subtract one as the upper bound provided by openmp is a < comparison
1182 // whereas the codegenForSequential function creates a <= comparison.
1183 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1184 "omp.upperBoundAdjusted");
1185
1186 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1187 CharMapT *oldClastVars = clastVars;
1188 clastVars = &clastVarsOMP;
1189 ExpGen.setIVS(&clastVarsOMP);
1190
1191 codegenForSequential(f, lowerBound, upperBound);
1192
1193 // Restore the old clastVars.
1194 clastVars = oldClastVars;
1195 ExpGen.setIVS(oldClastVars);
1196
1197 Builder.CreateBr(checkNextBB);
1198
1199 // Add code to terminate this openmp subfunction.
1200 Builder.SetInsertPoint(ExitBB);
1201 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1202 Builder.CreateCall(endnowaitFunction);
1203 Builder.CreateRetVoid();
1204
1205 // Restore the builder back to previous basic block.
1206 Builder.SetInsertPoint(PrevBB);
1207 }
1208
1209 /// @brief Create an OpenMP parallel for loop.
1210 ///
1211 /// This loop reflects a loop as if it would have been created by an OpenMP
1212 /// statement.
1213 void codegenForOpenMP(const clast_for *f) {
1214 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001215 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001216
1217 Function *SubFunction = addOpenMPSubfunction(M);
1218 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1219 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1220
1221 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1222
1223 // Create call for GOMP_parallel_loop_runtime_start.
1224 Value *subfunctionParam = Builder.CreateBitCast(structData,
1225 Builder.getInt8PtrTy(),
1226 "omp_data");
1227
1228 Value *numberOfThreads = Builder.getInt32(0);
1229 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1230 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1231
1232 // Add one as the upper bound provided by openmp is a < comparison
1233 // whereas the codegenForSequential function creates a <= comparison.
1234 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1235 APInt APStride = APInt_from_MPZ(f->stride);
1236 Value *stride = ConstantInt::get(intPtrTy,
1237 APStride.zext(intPtrTy->getBitWidth()));
1238
1239 SmallVector<Value *, 6> Arguments;
1240 Arguments.push_back(SubFunction);
1241 Arguments.push_back(subfunctionParam);
1242 Arguments.push_back(numberOfThreads);
1243 Arguments.push_back(lowerBound);
1244 Arguments.push_back(upperBound);
1245 Arguments.push_back(stride);
1246
1247 Function *parallelStartFunction =
1248 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001249 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001250
1251 // Create call to the subfunction.
1252 Builder.CreateCall(SubFunction, subfunctionParam);
1253
1254 // Create call for GOMP_parallel_end.
1255 Function *FN = M->getFunction("GOMP_parallel_end");
1256 Builder.CreateCall(FN);
1257 }
1258
1259 bool isInnermostLoop(const clast_for *f) {
1260 const clast_stmt *stmt = f->body;
1261
1262 while (stmt) {
1263 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1264 return false;
1265
1266 stmt = stmt->next;
1267 }
1268
1269 return true;
1270 }
1271
1272 /// @brief Get the number of loop iterations for this loop.
1273 /// @param f The clast for loop to check.
1274 int getNumberOfIterations(const clast_for *f) {
1275 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1276 isl_set *tmp = isl_set_copy(loopDomain);
1277
1278 // Calculate a map similar to the identity map, but with the last input
1279 // and output dimension not related.
1280 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001281 isl_space *Space = isl_set_get_space(loopDomain);
1282 Space = isl_space_drop_outputs(Space,
1283 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1284 Space = isl_space_map_from_set(Space);
1285 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001286 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1287 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1288
1289 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1290 map = isl_map_intersect(map, identity);
1291
1292 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001293 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001294 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1295
1296 isl_set *elements = isl_map_range(sub);
1297
Tobias Grosserc532f122011-08-25 08:40:59 +00001298 if (!isl_set_is_singleton(elements)) {
1299 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001300 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001301 }
Tobias Grosser75805372011-04-29 06:27:02 +00001302
1303 isl_point *p = isl_set_sample_point(elements);
1304
1305 isl_int v;
1306 isl_int_init(v);
1307 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1308 int numberIterations = isl_int_get_si(v);
1309 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001310 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001311
1312 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1313 }
1314
1315 /// @brief Create vector instructions for this loop.
1316 void codegenForVector(const clast_for *f) {
1317 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1318 int vectorWidth = getNumberOfIterations(f);
1319
1320 Value *LB = ExpGen.codegen(f->LB,
1321 TD->getIntPtrType(Builder.getContext()));
1322
1323 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001324 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001325 Stride = Stride.zext(LoopIVType->getBitWidth());
1326 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1327
1328 std::vector<Value*> IVS(vectorWidth);
1329 IVS[0] = LB;
1330
1331 for (int i = 1; i < vectorWidth; i++)
1332 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1333
Tobias Grosser28dd4862012-01-24 16:42:16 +00001334 isl_set *scatteringDomain =
1335 isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grosser75805372011-04-29 06:27:02 +00001336
1337 // Add loop iv to symbols.
1338 (*clastVars)[f->iterator] = LB;
1339
1340 const clast_stmt *stmt = f->body;
1341
1342 while (stmt) {
1343 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1344 scatteringDomain);
1345 stmt = stmt->next;
1346 }
1347
1348 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser28dd4862012-01-24 16:42:16 +00001349 isl_set_free(scatteringDomain);
Tobias Grosser75805372011-04-29 06:27:02 +00001350 clastVars->erase(f->iterator);
1351 }
1352
1353 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001354 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001355 && (-1 != getNumberOfIterations(f))
1356 && (getNumberOfIterations(f) <= 16)) {
1357 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001358 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001359 parallelCodeGeneration = true;
1360 parallelLoops.push_back(f->iterator);
1361 codegenForOpenMP(f);
1362 parallelCodeGeneration = false;
1363 } else
1364 codegenForSequential(f);
1365 }
1366
1367 Value *codegen(const clast_equation *eq) {
1368 Value *LHS = ExpGen.codegen(eq->LHS,
1369 TD->getIntPtrType(Builder.getContext()));
1370 Value *RHS = ExpGen.codegen(eq->RHS,
1371 TD->getIntPtrType(Builder.getContext()));
1372 CmpInst::Predicate P;
1373
1374 if (eq->sign == 0)
1375 P = ICmpInst::ICMP_EQ;
1376 else if (eq->sign > 0)
1377 P = ICmpInst::ICMP_SGE;
1378 else
1379 P = ICmpInst::ICMP_SLE;
1380
1381 return Builder.CreateICmp(P, LHS, RHS);
1382 }
1383
1384 void codegen(const clast_guard *g) {
1385 Function *F = Builder.GetInsertBlock()->getParent();
1386 LLVMContext &Context = F->getContext();
1387 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1388 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1389 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1390 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1391
1392 Value *Predicate = codegen(&(g->eq[0]));
1393
1394 for (int i = 1; i < g->n; ++i) {
1395 Value *TmpPredicate = codegen(&(g->eq[i]));
1396 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1397 }
1398
1399 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1400 Builder.SetInsertPoint(ThenBB);
1401
1402 codegen(g->then);
1403
1404 Builder.CreateBr(MergeBB);
1405 Builder.SetInsertPoint(MergeBB);
1406 }
1407
1408 void codegen(const clast_stmt *stmt) {
1409 if (CLAST_STMT_IS_A(stmt, stmt_root))
1410 assert(false && "No second root statement expected");
1411 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1412 codegen((const clast_assignment *)stmt);
1413 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1414 codegen((const clast_user_stmt *)stmt);
1415 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1416 codegen((const clast_block *)stmt);
1417 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1418 codegen((const clast_for *)stmt);
1419 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1420 codegen((const clast_guard *)stmt);
1421
1422 if (stmt->next)
1423 codegen(stmt->next);
1424 }
1425
1426 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001427 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001428
1429 // Create an instruction that specifies the location where the parameters
1430 // are expanded.
1431 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1432 Builder.getInt16Ty(), false, "insertInst",
1433 Builder.GetInsertBlock());
1434
1435 int i = 0;
1436 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1437 PI != PE; ++PI) {
1438 assert(i < names->nb_parameters && "Not enough parameter names");
1439
1440 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001441 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001442
1443 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1444 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1445 (*clastVars)[names->parameters[i]] = V;
1446
1447 ++i;
1448 }
1449 }
1450
1451 public:
1452 void codegen(const clast_root *r) {
1453 clastVars = new CharMapT();
1454 addParameters(r->names);
1455 ExpGen.setIVS(clastVars);
1456
1457 parallelCodeGeneration = false;
1458
1459 const clast_stmt *stmt = (const clast_stmt*) r;
1460 if (stmt->next)
1461 codegen(stmt->next);
1462
1463 delete clastVars;
1464 }
1465
1466 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001467 ScopDetection *sd, Dependences *dp, TargetData *td,
1468 IRBuilder<> &B) :
1469 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1470 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001471
1472};
1473}
1474
1475namespace {
1476class CodeGeneration : public ScopPass {
1477 Region *region;
1478 Scop *S;
1479 DominatorTree *DT;
1480 ScalarEvolution *SE;
1481 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001482 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001483 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001484
1485 std::vector<std::string> parallelLoops;
1486
1487 public:
1488 static char ID;
1489
1490 CodeGeneration() : ScopPass(ID) {}
1491
Tobias Grosser75805372011-04-29 06:27:02 +00001492 // Adding prototypes required if OpenMP is enabled.
1493 void addOpenMPDefinitions(IRBuilder<> &Builder)
1494 {
1495 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1496 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001497 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001498
1499 if (!M->getFunction("GOMP_parallel_end")) {
1500 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1501 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1502 }
1503
1504 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1505 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001506 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001507 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1508 false);
1509 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1510
Tobias Grosser851b96e2011-07-12 12:42:54 +00001511 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001512 args.push_back(FnPtrTy);
1513 args.push_back(Builder.getInt8PtrTy());
1514 args.push_back(Builder.getInt32Ty());
1515 args.push_back(intPtrTy);
1516 args.push_back(intPtrTy);
1517 args.push_back(intPtrTy);
1518
1519 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1520 Function::Create(type, Function::ExternalLinkage,
1521 "GOMP_parallel_loop_runtime_start", M);
1522 }
1523
1524 if (!M->getFunction("GOMP_loop_runtime_next")) {
1525 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1526
Tobias Grosser851b96e2011-07-12 12:42:54 +00001527 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001528 args.push_back(intLongPtrTy);
1529 args.push_back(intLongPtrTy);
1530
1531 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1532 Function::Create(type, Function::ExternalLinkage,
1533 "GOMP_loop_runtime_next", M);
1534 }
1535
1536 if (!M->getFunction("GOMP_loop_end_nowait")) {
1537 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001538 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001539 Function::Create(FT, Function::ExternalLinkage,
1540 "GOMP_loop_end_nowait", M);
1541 }
1542 }
1543
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001544 // Split the entry edge of the region and generate a new basic block on this
1545 // edge. This function also updates ScopInfo and RegionInfo.
1546 //
1547 // @param region The region where the entry edge will be splitted.
1548 BasicBlock *splitEdgeAdvanced(Region *region) {
1549 BasicBlock *newBlock;
1550 BasicBlock *splitBlock;
1551
1552 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1553
1554 if (DT->dominates(region->getEntry(), newBlock)) {
1555 // Update ScopInfo.
1556 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1557 if ((*SI)->getBasicBlock() == newBlock) {
1558 (*SI)->setBasicBlock(newBlock);
1559 break;
1560 }
1561
1562 // Update RegionInfo.
1563 splitBlock = region->getEntry();
1564 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001565 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001566 } else {
1567 RI->setRegionFor(newBlock, region->getParent());
1568 splitBlock = newBlock;
1569 }
1570
1571 return splitBlock;
1572 }
1573
1574 // Create a split block that branches either to the old code or to a new basic
1575 // block where the new code can be inserted.
1576 //
1577 // @param builder A builder that will be set to point to a basic block, where
1578 // the new code can be generated.
1579 // @return The split basic block.
1580 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1581 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1582
1583 splitBlock->setName("polly.enterScop");
1584
1585 Function *function = splitBlock->getParent();
1586 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1587 "polly.start", function);
1588 splitBlock->getTerminator()->eraseFromParent();
1589 builder->SetInsertPoint(splitBlock);
1590 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1591 DT->addNewBlock(startBlock, splitBlock);
1592
1593 // Start code generation here.
1594 builder->SetInsertPoint(startBlock);
1595 return splitBlock;
1596 }
1597
1598 // Merge the control flow of the newly generated code with the existing code.
1599 //
1600 // @param splitBlock The basic block where the control flow was split between
1601 // old and new version of the Scop.
1602 // @param builder An IRBuilder that points to the last instruction of the
1603 // newly generated code.
1604 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1605 BasicBlock *mergeBlock;
1606 Region *R = region;
1607
1608 if (R->getExit()->getSinglePredecessor())
1609 // No splitEdge required. A block with a single predecessor cannot have
1610 // PHI nodes that would complicate life.
1611 mergeBlock = R->getExit();
1612 else {
1613 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1614 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1615 // one predecessor. Hence, mergeBlock is always a newly generated block.
1616 mergeBlock->setName("polly.finalMerge");
1617 R->replaceExit(mergeBlock);
1618 }
1619
1620 builder->CreateBr(mergeBlock);
1621
1622 if (DT->dominates(splitBlock, mergeBlock))
1623 DT->changeImmediateDominator(mergeBlock, splitBlock);
1624 }
1625
Tobias Grosser75805372011-04-29 06:27:02 +00001626 bool runOnScop(Scop &scop) {
1627 S = &scop;
1628 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001629 DT = &getAnalysis<DominatorTree>();
1630 Dependences *DP = &getAnalysis<Dependences>();
1631 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001632 SD = &getAnalysis<ScopDetection>();
1633 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001634 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001635
1636 parallelLoops.clear();
1637
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001638 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001639
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001640 // In the CFG and we generate next to original code of the Scop the
1641 // optimized version. Both the new and the original version of the code
1642 // remain in the CFG. A branch statement decides which version is executed.
1643 // At the moment, we always execute the newly generated version (the old one
1644 // is dead code eliminated by the cleanup passes). Later we may decide to
1645 // execute the new version only under certain conditions. This will be the
1646 // case if we support constructs for which we cannot prove all assumptions
1647 // at compile time.
1648 //
1649 // Before transformation:
1650 //
1651 // bb0
1652 // |
1653 // orig_scop
1654 // |
1655 // bb1
1656 //
1657 // After transformation:
1658 // bb0
1659 // |
1660 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001661 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001662 // | startBlock
1663 // | |
1664 // orig_scop new_scop
1665 // \ /
1666 // \ /
1667 // bb1 (joinBlock)
1668 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001669
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 // The builder will be set to startBlock.
1671 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001672
1673 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001674 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001675
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001676 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001677 CloogInfo &C = getAnalysis<CloogInfo>();
1678 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001679
Tobias Grosser75805372011-04-29 06:27:02 +00001680 parallelLoops.insert(parallelLoops.begin(),
1681 CodeGen.getParallelLoops().begin(),
1682 CodeGen.getParallelLoops().end());
1683
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001684 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001685
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001686 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001687 }
1688
1689 virtual void printScop(raw_ostream &OS) const {
1690 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1691 PE = parallelLoops.end(); PI != PE; ++PI)
1692 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1693 }
1694
1695 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1696 AU.addRequired<CloogInfo>();
1697 AU.addRequired<Dependences>();
1698 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001699 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001700 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001701 AU.addRequired<ScopDetection>();
1702 AU.addRequired<ScopInfo>();
1703 AU.addRequired<TargetData>();
1704
1705 AU.addPreserved<CloogInfo>();
1706 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001707
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001708 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001709 AU.addPreserved<LoopInfo>();
1710 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001711 AU.addPreserved<ScopDetection>();
1712 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001713
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001714 // FIXME: We do not yet add regions for the newly generated code to the
1715 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001716 AU.addPreserved<RegionInfo>();
1717 AU.addPreserved<TempScopInfo>();
1718 AU.addPreserved<ScopInfo>();
1719 AU.addPreservedID(IndependentBlocksID);
1720 }
1721};
1722}
1723
1724char CodeGeneration::ID = 1;
1725
Tobias Grosser73600b82011-10-08 00:30:40 +00001726INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1727 "Polly - Create LLVM-IR form SCoPs", false, false)
1728INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1729INITIALIZE_PASS_DEPENDENCY(Dependences)
1730INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1731INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1732INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1733INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1734INITIALIZE_PASS_DEPENDENCY(TargetData)
1735INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1736 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001737
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001738Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001739 return new CodeGeneration();
1740}