blob: 01bbaae665c811e8f0fdd3278cca6406da7ec827 [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
Tobias Grosser75805372011-04-29 06:27:02 +000081typedef DenseMap<const Value*, Value*> ValueMapT;
82typedef DenseMap<const char*, Value*> CharMapT;
83typedef std::vector<ValueMapT> VectorValueMapT;
84
85// Create a new loop.
86//
87// @param Builder The builder used to create the loop. It also defines the
88// place where to create the loop.
89// @param UB The upper bound of the loop iv.
90// @param Stride The number by which the loop iv is incremented after every
91// iteration.
92static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
93 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
94 DominatorTree *DT) {
95 Function *F = Builder->GetInsertBlock()->getParent();
96 LLVMContext &Context = F->getContext();
97
98 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
99 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
100 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
101 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
102
103 Builder->CreateBr(HeaderBB);
104 DT->addNewBlock(HeaderBB, PreheaderBB);
105
106 Builder->SetInsertPoint(BodyBB);
107
108 Builder->SetInsertPoint(HeaderBB);
109
110 // Use the type of upper and lower bound.
111 assert(LB->getType() == UB->getType()
112 && "Different types for upper and lower bound.");
113
Tobias Grosser55927aa2011-07-18 09:53:32 +0000114 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000115 assert(LoopIVType && "UB is not integer?");
116
117 // IV
118 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
119 IV->addIncoming(LB, PreheaderBB);
120
121 // IV increment.
122 Value *StrideValue = ConstantInt::get(LoopIVType,
123 Stride.zext(LoopIVType->getBitWidth()));
124 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
125
126 // Exit condition.
127 if (AtLeastOnce) { // At least on iteration.
128 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
129 Value *CMP = Builder->CreateICmpEQ(IV, UB);
130 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
131 } else { // Maybe not executed at all.
132 Value *CMP = Builder->CreateICmpSLE(IV, UB);
133 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
134 }
135 DT->addNewBlock(BodyBB, HeaderBB);
136 DT->addNewBlock(AfterBB, HeaderBB);
137
138 Builder->SetInsertPoint(BodyBB);
139}
140
141class BlockGenerator {
142 IRBuilder<> &Builder;
143 ValueMapT &VMap;
144 VectorValueMapT &ValueMaps;
145 Scop &S;
146 ScopStmt &statement;
147 isl_set *scatteringDomain;
148
149public:
150 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
151 ScopStmt &Stmt, isl_set *domain)
152 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
153 statement(Stmt), scatteringDomain(domain) {}
154
155 const Region &getRegion() {
156 return S.getRegion();
157 }
158
159 Value* makeVectorOperand(Value *operand, int vectorWidth) {
160 if (operand->getType()->isVectorTy())
161 return operand;
162
163 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
164 Value *vector = UndefValue::get(vectorType);
165 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
166
167 std::vector<Constant*> splat;
168
169 for (int i = 0; i < vectorWidth; i++)
170 splat.push_back (Builder.getInt32(0));
171
172 Constant *splatVector = ConstantVector::get(splat);
173
174 return Builder.CreateShuffleVector(vector, vector, splatVector);
175 }
176
Raghesh Aloor490c5982011-08-08 08:34:16 +0000177 Value* getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000178 ValueMapT *VectorMap = 0) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000179 const Instruction *OpInst = dyn_cast<Instruction>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000180
181 if (!OpInst)
Raghesh Aloor490c5982011-08-08 08:34:16 +0000182 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000183
Raghesh Aloor490c5982011-08-08 08:34:16 +0000184 if (VectorMap && VectorMap->count(oldOperand))
185 return (*VectorMap)[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000186
187 // IVS and Parameters.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000188 if (VMap.count(oldOperand)) {
189 Value *NewOperand = VMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000190
191 // Insert a cast if types are different
Raghesh Aloor490c5982011-08-08 08:34:16 +0000192 if (oldOperand->getType()->getScalarSizeInBits()
Tobias Grosser75805372011-04-29 06:27:02 +0000193 < NewOperand->getType()->getScalarSizeInBits())
194 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000195 oldOperand->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000196
197 return NewOperand;
198 }
199
200 // Instructions calculated in the current BB.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000201 if (BBMap.count(oldOperand)) {
202 return BBMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000203 }
204
205 // Ignore instructions that are referencing ops in the old BB. These
206 // instructions are unused. They where replace by new ones during
207 // createIndependentBlocks().
208 if (getRegion().contains(OpInst->getParent()))
209 return NULL;
210
Raghesh Aloor490c5982011-08-08 08:34:16 +0000211 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000212 }
213
Tobias Grosser55927aa2011-07-18 09:53:32 +0000214 Type *getVectorPtrTy(const Value *V, int vectorWidth) {
215 PointerType *pointerType = dyn_cast<PointerType>(V->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000216 assert(pointerType && "PointerType expected");
217
Tobias Grosser55927aa2011-07-18 09:53:32 +0000218 Type *scalarType = pointerType->getElementType();
Tobias Grosser75805372011-04-29 06:27:02 +0000219 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
220
221 return PointerType::getUnqual(vectorType);
222 }
223
224 /// @brief Load a vector from a set of adjacent scalars
225 ///
226 /// In case a set of scalars is known to be next to each other in memory,
227 /// create a vector load that loads those scalars
228 ///
229 /// %vector_ptr= bitcast double* %p to <4 x double>*
230 /// %vec_full = load <4 x double>* %vector_ptr
231 ///
232 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
233 int size) {
234 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000235 Type *vectorPtrType = getVectorPtrTy(pointer, size);
Tobias Grosser75805372011-04-29 06:27:02 +0000236 Value *newPointer = getOperand(pointer, BBMap);
237 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
238 "vector_ptr");
239 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
240 load->getNameStr()
241 + "_p_vec_full");
242 if (!Aligned)
243 VecLoad->setAlignment(8);
244
245 return VecLoad;
246 }
247
248 /// @brief Load a vector initialized from a single scalar in memory
249 ///
250 /// In case all elements of a vector are initialized to the same
251 /// scalar value, this value is loaded and shuffeled into all elements
252 /// of the vector.
253 ///
254 /// %splat_one = load <1 x double>* %p
255 /// %splat = shufflevector <1 x double> %splat_one, <1 x
256 /// double> %splat_one, <4 x i32> zeroinitializer
257 ///
258 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
259 int size) {
260 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000261 Type *vectorPtrType = getVectorPtrTy(pointer, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000262 Value *newPointer = getOperand(pointer, BBMap);
263 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
264 load->getNameStr() + "_p_vec_p");
265 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
266 load->getNameStr() + "_p_splat_one");
267
268 if (!Aligned)
269 scalarLoad->setAlignment(8);
270
271 std::vector<Constant*> splat;
272
273 for (int i = 0; i < size; i++)
274 splat.push_back (Builder.getInt32(0));
275
276 Constant *splatVector = ConstantVector::get(splat);
277
278 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
279 splatVector,
280 load->getNameStr()
281 + "_p_splat");
282 return vectorLoad;
283 }
284
285 /// @Load a vector from scalars distributed in memory
286 ///
287 /// In case some scalars a distributed randomly in memory. Create a vector
288 /// by loading each scalar and by inserting one after the other into the
289 /// vector.
290 ///
291 /// %scalar_1= load double* %p_1
292 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
293 /// %scalar 2 = load double* %p_2
294 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
295 ///
296 Value *generateUnknownStrideLoad(const LoadInst *load,
297 VectorValueMapT &scalarMaps,
298 int size) {
299 const Value *pointer = load->getPointerOperand();
300 VectorType *vectorType = VectorType::get(
301 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
302
303 Value *vector = UndefValue::get(vectorType);
304
305 for (int i = 0; i < size; i++) {
306 Value *newPointer = getOperand(pointer, scalarMaps[i]);
307 Value *scalarLoad = Builder.CreateLoad(newPointer,
308 load->getNameStr() + "_p_scalar_");
309 vector = Builder.CreateInsertElement(vector, scalarLoad,
310 Builder.getInt32(i),
311 load->getNameStr() + "_p_vec_");
312 }
313
314 return vector;
315 }
316
Raghesh Aloor129e8672011-08-15 02:33:39 +0000317 /// @brief Get the memory access offset to be added to the base address
318 std::vector <Value*> getMemoryAccessIndex(isl_map *accessRelation,
319 Value *baseAddr) {
320 isl_int offsetMPZ;
321 isl_int_init(offsetMPZ);
322
323 assert((isl_map_dim(accessRelation, isl_dim_out) == 1)
324 && "Only single dimensional access functions supported");
325
326 if (isl_map_plain_is_fixed(accessRelation, isl_dim_out,
327 0, &offsetMPZ) == -1)
328 errs() << "Only fixed value access functions supported\n";
329
330 // Convert the offset from MPZ to Value*.
331 APInt offset = APInt_from_MPZ(offsetMPZ);
332 Value *offsetValue = ConstantInt::get(Builder.getContext(), offset);
333 PointerType *baseAddrType = dyn_cast<PointerType>(baseAddr->getType());
334 Type *arrayType = baseAddrType->getElementType();
335 Type *arrayElementType = dyn_cast<ArrayType>(arrayType)->getElementType();
336 offsetValue = Builder.CreateSExtOrBitCast(offsetValue, arrayElementType);
337
338 std::vector<Value*> indexArray;
339 Value *nullValue = Constant::getNullValue(arrayElementType);
340 indexArray.push_back(nullValue);
341 indexArray.push_back(offsetValue);
342
343 isl_int_clear(offsetMPZ);
344 return indexArray;
345 }
346
Raghesh Aloor62b13122011-08-03 17:02:50 +0000347 /// @brief Get the new operand address according to the changed access in
348 /// JSCOP file.
349 Value *getNewAccessOperand(isl_map *newAccessRelation, Value *baseAddr,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000350 const Value *oldOperand, ValueMapT &BBMap) {
Raghesh Aloor129e8672011-08-15 02:33:39 +0000351 std::vector<Value*> indexArray = getMemoryAccessIndex(newAccessRelation,
352 baseAddr);
353 Value *newOperand = Builder.CreateGEP(baseAddr, indexArray,
354 "p_newarrayidx_");
Raghesh Aloor62b13122011-08-03 17:02:50 +0000355 return newOperand;
356 }
357
358 /// @brief Generate the operand address
359 Value *generateLocationAccessed(const Instruction *Inst,
360 const Value *pointer, ValueMapT &BBMap ) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000361 MemoryAccess &access = statement.getAccessFor(Inst);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000362 isl_map *currentAccessRelation = access.getAccessFunction();
Raghesh Aloor490c5982011-08-08 08:34:16 +0000363 isl_map *newAccessRelation = access.getNewAccessFunction();
Raghesh Aloor129e8672011-08-15 02:33:39 +0000364
365 assert(isl_map_has_equal_dim(currentAccessRelation, newAccessRelation)
366 && "Current and new access function dimensions differ");
367
Raghesh Aloor62b13122011-08-03 17:02:50 +0000368 if (!newAccessRelation) {
369 Value *newPointer = getOperand(pointer, BBMap);
370 return newPointer;
371 }
Raghesh Aloore75e9862011-08-11 08:44:56 +0000372
Raghesh Aloor490c5982011-08-08 08:34:16 +0000373 Value *baseAddr = const_cast<Value*>(access.getBaseAddr());
Raghesh Aloor62b13122011-08-03 17:02:50 +0000374 Value *newPointer = getNewAccessOperand(newAccessRelation, baseAddr,
375 pointer, BBMap);
376 return newPointer;
377 }
378
Tobias Grosser75805372011-04-29 06:27:02 +0000379 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
380 const Value *pointer = load->getPointerOperand();
Raghesh Aloor62b13122011-08-03 17:02:50 +0000381 const Instruction *Inst = dyn_cast<Instruction>(load);
382 Value *newPointer = generateLocationAccessed(Inst, pointer, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000383 Value *scalarLoad = Builder.CreateLoad(newPointer,
384 load->getNameStr() + "_p_scalar_");
385 return scalarLoad;
386 }
387
388 /// @brief Load a value (or several values as a vector) from memory.
389 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
390 VectorValueMapT &scalarMaps, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000391 if (scalarMaps.size() == 1) {
392 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
393 return;
394 }
395
396 Value *newLoad;
397
398 MemoryAccess &Access = statement.getAccessFor(load);
399
400 assert(scatteringDomain && "No scattering domain available");
401
402 if (Access.isStrideZero(scatteringDomain))
403 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
404 else if (Access.isStrideOne(scatteringDomain))
405 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
406 else
407 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
408
409 vectorMap[load] = newLoad;
410 }
411
Tobias Grosser09c57102011-09-04 11:45:29 +0000412 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
413 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
414 int vectorDimension, int vectorWidth) {
415 Value *opZero = Inst->getOperand(0);
416 Value *opOne = Inst->getOperand(1);
417
418 // This is an old instruction that can be ignored.
419 if (!opZero && !opOne)
420 return;
421
422 bool isVectorOp = vectorMap.count(opZero) || vectorMap.count(opOne);
423
424 if (isVectorOp && vectorDimension > 0)
425 return;
426
427 Value *newOpZero, *newOpOne;
428 newOpZero = getOperand(opZero, BBMap, &vectorMap);
429 newOpOne = getOperand(opOne, BBMap, &vectorMap);
430
431 std::string name;
432 if (isVectorOp) {
433 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
434 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
435 name = Inst->getNameStr() + "p_vec";
436 } else
437 name = Inst->getNameStr() + "p_sca";
438
439 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
440 newOpOne, name);
441 if (isVectorOp)
442 vectorMap[Inst] = newInst;
443 else
444 BBMap[Inst] = newInst;
445
446 return;
447 }
448
449 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000450 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
451 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000452 // In vector mode we only generate a store for the first dimension.
453 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000454 return;
455
Tobias Grosser09c57102011-09-04 11:45:29 +0000456 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000457
Tobias Grosser09c57102011-09-04 11:45:29 +0000458 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000459
Tobias Grosser09c57102011-09-04 11:45:29 +0000460 const Value *pointer = store->getPointerOperand();
461 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Tobias Grosser09c57102011-09-04 11:45:29 +0000463 if (Access.isStrideOne(scatteringDomain)) {
464 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
465 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000466
Tobias Grosser09c57102011-09-04 11:45:29 +0000467 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
468 "vector_ptr");
469 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000470
Tobias Grosser09c57102011-09-04 11:45:29 +0000471 if (!Aligned)
472 Store->setAlignment(8);
473 } else {
474 for (unsigned i = 0; i < scalarMaps.size(); i++) {
475 Value *scalar = Builder.CreateExtractElement(vector,
476 Builder.getInt32(i));
477 Value *newPointer = getOperand(pointer, scalarMaps[i]);
478 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000479 }
480 }
481
Tobias Grosser09c57102011-09-04 11:45:29 +0000482 return;
483 }
484
485 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000486 ValueMapT &VectorMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000487 Instruction *NewInst = Inst->clone();
488
Tobias Grosser75805372011-04-29 06:27:02 +0000489 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000490 for (Instruction::const_op_iterator OI = Inst->op_begin(),
491 OE = Inst->op_end(); OI != OE; ++OI) {
492 Value *OldOperand = *OI;
493 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000494
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000495 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000496 assert(!isa<StoreInst>(NewInst)
497 && "Store instructions are always needed!");
498 delete NewInst;
499 return;
500 }
501
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000502 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000503 }
504
505 Builder.Insert(NewInst);
506 BBMap[Inst] = NewInst;
507
508 if (!NewInst->getType()->isVoidTy())
509 NewInst->setName("p_" + Inst->getName());
510 }
511
Tobias Grosser09c57102011-09-04 11:45:29 +0000512 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
513 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
514 int vectorDimension, int vectorWidth) {
515 // If this instruction is already in the vectorMap, a vector instruction
516 // was already issued, that calculates the values of all dimensions. No
517 // need to create any more instructions.
518 if (vectorMap.count(Inst))
519 return;
520
521 // Terminator instructions control the control flow. They are explicitally
522 // expressed in the clast and do not need to be copied.
523 if (Inst->isTerminator())
524 return;
525
526 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
527 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
528 return;
529 }
530
531 if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst)) {
532 copyBinInst(binaryInst, BBMap, vectorMap, scalarMaps, vectorDimension,
533 vectorWidth);
534 return;
535 }
536
537 if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
538 if (vectorMap.count(store->getValueOperand()) > 0) {
539 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
540 vectorWidth);
541 return;
542 }
543
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000544 copyInstScalar(Inst, BBMap, vectorMap);
Tobias Grosser09c57102011-09-04 11:45:29 +0000545 }
546
Tobias Grosser75805372011-04-29 06:27:02 +0000547 int getVectorSize() {
548 return ValueMaps.size();
549 }
550
551 bool isVectorBlock() {
552 return getVectorSize() > 1;
553 }
554
555 // Insert a copy of a basic block in the newly generated code.
556 //
557 // @param Builder The builder used to insert the code. It also specifies
558 // where to insert the code.
559 // @param BB The basic block to copy
560 // @param VMap A map returning for any old value its new equivalent. This
561 // is used to update the operands of the statements.
562 // For new statements a relation old->new is inserted in this
563 // map.
564 void copyBB(BasicBlock *BB, DominatorTree *DT) {
565 Function *F = Builder.GetInsertBlock()->getParent();
566 LLVMContext &Context = F->getContext();
567 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser8ae9aca2011-09-04 11:45:22 +0000568 "polly." + BB->getNameStr()
569 + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000570 F);
571 Builder.CreateBr(CopyBB);
572 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
573 Builder.SetInsertPoint(CopyBB);
574
575 // Create two maps that store the mapping from the original instructions of
576 // the old basic block to their copies in the new basic block. Those maps
577 // are basic block local.
578 //
579 // As vector code generation is supported there is one map for scalar values
580 // and one for vector values.
581 //
582 // In case we just do scalar code generation, the vectorMap is not used and
583 // the scalarMap has just one dimension, which contains the mapping.
584 //
585 // In case vector code generation is done, an instruction may either appear
586 // in the vector map once (as it is calculating >vectorwidth< values at a
587 // time. Or (if the values are calculated using scalar operations), it
588 // appears once in every dimension of the scalarMap.
589 VectorValueMapT scalarBlockMap(getVectorSize());
590 ValueMapT vectorBlockMap;
591
592 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
593 II != IE; ++II)
594 for (int i = 0; i < getVectorSize(); i++) {
595 if (isVectorBlock())
596 VMap = ValueMaps[i];
597
598 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
599 scalarBlockMap, i, getVectorSize());
600 }
601 }
602};
603
604/// Class to generate LLVM-IR that calculates the value of a clast_expr.
605class ClastExpCodeGen {
606 IRBuilder<> &Builder;
607 const CharMapT *IVS;
608
Tobias Grosser55927aa2011-07-18 09:53:32 +0000609 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000610 CharMapT::const_iterator I = IVS->find(e->name);
611
612 if (I != IVS->end())
613 return Builder.CreateSExtOrBitCast(I->second, Ty);
614 else
615 llvm_unreachable("Clast name not found");
616 }
617
Tobias Grosser55927aa2011-07-18 09:53:32 +0000618 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000619 APInt a = APInt_from_MPZ(e->val);
620
621 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
622 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
623
624 if (e->var) {
625 Value *var = codegen(e->var, Ty);
626 return Builder.CreateMul(ConstOne, var);
627 }
628
629 return ConstOne;
630 }
631
Tobias Grosser55927aa2011-07-18 09:53:32 +0000632 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000633 Value *LHS = codegen(e->LHS, Ty);
634
635 APInt RHS_AP = APInt_from_MPZ(e->RHS);
636
637 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
638 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
639
640 switch (e->type) {
641 case clast_bin_mod:
642 return Builder.CreateSRem(LHS, RHS);
643 case clast_bin_fdiv:
644 {
645 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
646 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
647 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
648 One = Builder.CreateZExtOrBitCast(One, Ty);
649 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
650 Value *Sum1 = Builder.CreateSub(LHS, RHS);
651 Value *Sum2 = Builder.CreateAdd(Sum1, One);
652 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
653 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
654 return Builder.CreateSDiv(Dividend, RHS);
655 }
656 case clast_bin_cdiv:
657 {
658 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
659 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
660 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
661 One = Builder.CreateZExtOrBitCast(One, Ty);
662 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
663 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
664 Value *Sum2 = Builder.CreateSub(Sum1, One);
665 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
666 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
667 return Builder.CreateSDiv(Dividend, RHS);
668 }
669 case clast_bin_div:
670 return Builder.CreateSDiv(LHS, RHS);
671 default:
672 llvm_unreachable("Unknown clast binary expression type");
673 };
674 }
675
Tobias Grosser55927aa2011-07-18 09:53:32 +0000676 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000677 assert(( r->type == clast_red_min
678 || r->type == clast_red_max
679 || r->type == clast_red_sum)
680 && "Clast reduction type not supported");
681 Value *old = codegen(r->elts[0], Ty);
682
683 for (int i=1; i < r->n; ++i) {
684 Value *exprValue = codegen(r->elts[i], Ty);
685
686 switch (r->type) {
687 case clast_red_min:
688 {
689 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
690 old = Builder.CreateSelect(cmp, old, exprValue);
691 break;
692 }
693 case clast_red_max:
694 {
695 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
696 old = Builder.CreateSelect(cmp, old, exprValue);
697 break;
698 }
699 case clast_red_sum:
700 old = Builder.CreateAdd(old, exprValue);
701 break;
702 default:
703 llvm_unreachable("Clast unknown reduction type");
704 }
705 }
706
707 return old;
708 }
709
710public:
711
712 // A generator for clast expressions.
713 //
714 // @param B The IRBuilder that defines where the code to calculate the
715 // clast expressions should be inserted.
716 // @param IVMAP A Map that translates strings describing the induction
717 // variables to the Values* that represent these variables
718 // on the LLVM side.
719 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
720
721 // Generates code to calculate a given clast expression.
722 //
723 // @param e The expression to calculate.
724 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000725 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000726 switch(e->type) {
727 case clast_expr_name:
728 return codegen((const clast_name *)e, Ty);
729 case clast_expr_term:
730 return codegen((const clast_term *)e, Ty);
731 case clast_expr_bin:
732 return codegen((const clast_binary *)e, Ty);
733 case clast_expr_red:
734 return codegen((const clast_reduction *)e, Ty);
735 default:
736 llvm_unreachable("Unknown clast expression!");
737 }
738 }
739
740 // @brief Reset the CharMap.
741 //
742 // This function is called to reset the CharMap to new one, while generating
743 // OpenMP code.
744 void setIVS(CharMapT *IVSNew) {
745 IVS = IVSNew;
746 }
747
748};
749
750class ClastStmtCodeGen {
751 // The Scop we code generate.
752 Scop *S;
753 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000754 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000755 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000756 Dependences *DP;
757 TargetData *TD;
758
759 // The Builder specifies the current location to code generate at.
760 IRBuilder<> &Builder;
761
762 // Map the Values from the old code to their counterparts in the new code.
763 ValueMapT ValueMap;
764
765 // clastVars maps from the textual representation of a clast variable to its
766 // current *Value. clast variables are scheduling variables, original
767 // induction variables or parameters. They are used either in loop bounds or
768 // to define the statement instance that is executed.
769 //
770 // for (s = 0; s < n + 3; ++i)
771 // for (t = s; t < m; ++j)
772 // Stmt(i = s + 3 * m, j = t);
773 //
774 // {s,t,i,j,n,m} is the set of clast variables in this clast.
775 CharMapT *clastVars;
776
777 // Codegenerator for clast expressions.
778 ClastExpCodeGen ExpGen;
779
780 // Do we currently generate parallel code?
781 bool parallelCodeGeneration;
782
783 std::vector<std::string> parallelLoops;
784
785public:
786
787 const std::vector<std::string> &getParallelLoops() {
788 return parallelLoops;
789 }
790
791 protected:
792 void codegen(const clast_assignment *a) {
793 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
794 TD->getIntPtrType(Builder.getContext()));
795 }
796
797 void codegen(const clast_assignment *a, ScopStmt *Statement,
798 unsigned Dimension, int vectorDim,
799 std::vector<ValueMapT> *VectorVMap = 0) {
800 Value *RHS = ExpGen.codegen(a->RHS,
801 TD->getIntPtrType(Builder.getContext()));
802
803 assert(!a->LHS && "Statement assignments do not have left hand side");
804 const PHINode *PN;
805 PN = Statement->getInductionVariableForDimension(Dimension);
806 const Value *V = PN;
807
Tobias Grosser75805372011-04-29 06:27:02 +0000808 if (VectorVMap)
809 (*VectorVMap)[vectorDim][V] = RHS;
810
811 ValueMap[V] = RHS;
812 }
813
814 void codegenSubstitutions(const clast_stmt *Assignment,
815 ScopStmt *Statement, int vectorDim = 0,
816 std::vector<ValueMapT> *VectorVMap = 0) {
817 int Dimension = 0;
818
819 while (Assignment) {
820 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
821 && "Substitions are expected to be assignments");
822 codegen((const clast_assignment *)Assignment, Statement, Dimension,
823 vectorDim, VectorVMap);
824 Assignment = Assignment->next;
825 Dimension++;
826 }
827 }
828
829 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
830 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
831 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
832 BasicBlock *BB = Statement->getBasicBlock();
833
834 if (u->substitutions)
835 codegenSubstitutions(u->substitutions, Statement);
836
837 int vectorDimensions = IVS ? IVS->size() : 1;
838
839 VectorValueMapT VectorValueMap(vectorDimensions);
840
841 if (IVS) {
842 assert (u->substitutions && "Substitutions expected!");
843 int i = 0;
844 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
845 II != IE; ++II) {
846 (*clastVars)[iterator] = *II;
847 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
848 i++;
849 }
850 }
851
852 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
853 scatteringDomain);
854 Generator.copyBB(BB, DT);
855 }
856
857 void codegen(const clast_block *b) {
858 if (b->body)
859 codegen(b->body);
860 }
861
862 /// @brief Create a classical sequential loop.
863 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
864 Value *upperBound = 0) {
865 APInt Stride = APInt_from_MPZ(f->stride);
866 PHINode *IV;
867 Value *IncrementedIV;
868 BasicBlock *AfterBB;
869 // The value of lowerbound and upperbound will be supplied, if this
870 // function is called while generating OpenMP code. Otherwise get
871 // the values.
872 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
873 && "Either give both bounds or none");
874 if (lowerBound == 0 || upperBound == 0) {
875 lowerBound = ExpGen.codegen(f->LB,
876 TD->getIntPtrType(Builder.getContext()));
877 upperBound = ExpGen.codegen(f->UB,
878 TD->getIntPtrType(Builder.getContext()));
879 }
880 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
881 IncrementedIV, DT);
882
883 // Add loop iv to symbols.
884 (*clastVars)[f->iterator] = IV;
885
886 if (f->body)
887 codegen(f->body);
888
889 // Loop is finished, so remove its iv from the live symbols.
890 clastVars->erase(f->iterator);
891
892 BasicBlock *HeaderBB = *pred_begin(AfterBB);
893 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
894 Builder.CreateBr(HeaderBB);
895 IV->addIncoming(IncrementedIV, LastBodyBB);
896 Builder.SetInsertPoint(AfterBB);
897 }
898
Tobias Grosser75805372011-04-29 06:27:02 +0000899 /// @brief Add a new definition of an openmp subfunction.
900 Function* addOpenMPSubfunction(Module *M) {
901 Function *F = Builder.GetInsertBlock()->getParent();
902 const std::string &Name = F->getNameStr() + ".omp_subfn";
903
Tobias Grosser851b96e2011-07-12 12:42:54 +0000904 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000905 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
906 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000907 // Do not run any polly pass on the new function.
908 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000909
910 Function::arg_iterator AI = FN->arg_begin();
911 AI->setName("omp.userContext");
912
913 return FN;
914 }
915
916 /// @brief Add values to the OpenMP structure.
917 ///
918 /// Create the subfunction structure and add the values from the list.
919 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
920 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000921 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000922
923 // Create the structure.
924 for (unsigned i = 0; i < OMPDataVals.size(); i++)
925 structMembers.push_back(OMPDataVals[i]->getType());
926
Tobias Grosser75805372011-04-29 06:27:02 +0000927 StructType *structTy = StructType::get(Builder.getContext(),
928 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000929 // Store the values into the structure.
930 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
931 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
932 Value *storeAddr = Builder.CreateStructGEP(structData, i);
933 Builder.CreateStore(OMPDataVals[i], storeAddr);
934 }
935
936 return structData;
937 }
938
939 /// @brief Create OpenMP structure values.
940 ///
941 /// Create a list of values that has to be stored into the subfuncition
942 /// structure.
943 SetVector<Value*> createOpenMPStructValues() {
944 SetVector<Value*> OMPDataVals;
945
946 // Push the clast variables available in the clastVars.
947 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
948 I != E; I++)
949 OMPDataVals.insert(I->second);
950
951 // Push the base addresses of memory references.
952 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
953 ScopStmt *Stmt = *SI;
954 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
955 E = Stmt->memacc_end(); I != E; ++I) {
956 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
957 OMPDataVals.insert((BaseAddr));
958 }
959 }
960
961 return OMPDataVals;
962 }
963
964 /// @brief Extract the values from the subfunction parameter.
965 ///
966 /// Extract the values from the subfunction parameter and update the clast
967 /// variables to point to the new values.
968 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
969 SetVector<Value*> OMPDataVals,
970 Value *userContext) {
971 // Extract the clast variables.
972 unsigned i = 0;
973 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
974 I != E; I++) {
975 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
976 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
977 i++;
978 }
979
980 // Extract the base addresses of memory references.
981 for (unsigned j = i; j < OMPDataVals.size(); j++) {
982 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
983 Value *baseAddr = OMPDataVals[j];
984 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
985 }
986
987 }
988
989 /// @brief Add body to the subfunction.
990 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
991 Value *structData,
992 SetVector<Value*> OMPDataVals) {
993 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
994 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000995 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
997 // Store the previous basic block.
998 BasicBlock *PrevBB = Builder.GetInsertBlock();
999
1000 // Create basic blocks.
1001 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1002 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1003 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1004 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1005 FN);
1006
1007 DT->addNewBlock(HeaderBB, PrevBB);
1008 DT->addNewBlock(ExitBB, HeaderBB);
1009 DT->addNewBlock(checkNextBB, HeaderBB);
1010 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1011
1012 // Fill up basic block HeaderBB.
1013 Builder.SetInsertPoint(HeaderBB);
1014 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1015 "omp.lowerBoundPtr");
1016 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1017 "omp.upperBoundPtr");
1018 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1019 structData->getType(),
1020 "omp.userContext");
1021
1022 CharMapT clastVarsOMP;
1023 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1024
1025 Builder.CreateBr(checkNextBB);
1026
1027 // Add code to check if another set of iterations will be executed.
1028 Builder.SetInsertPoint(checkNextBB);
1029 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1030 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1031 lowerBoundPtr, upperBoundPtr);
1032 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1033 "omp.hasNextScheduleBlock");
1034 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1035
1036 // Add code to to load the iv bounds for this set of iterations.
1037 Builder.SetInsertPoint(loadIVBoundsBB);
1038 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1039 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1040
1041 // Subtract one as the upper bound provided by openmp is a < comparison
1042 // whereas the codegenForSequential function creates a <= comparison.
1043 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1044 "omp.upperBoundAdjusted");
1045
1046 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1047 CharMapT *oldClastVars = clastVars;
1048 clastVars = &clastVarsOMP;
1049 ExpGen.setIVS(&clastVarsOMP);
1050
1051 codegenForSequential(f, lowerBound, upperBound);
1052
1053 // Restore the old clastVars.
1054 clastVars = oldClastVars;
1055 ExpGen.setIVS(oldClastVars);
1056
1057 Builder.CreateBr(checkNextBB);
1058
1059 // Add code to terminate this openmp subfunction.
1060 Builder.SetInsertPoint(ExitBB);
1061 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1062 Builder.CreateCall(endnowaitFunction);
1063 Builder.CreateRetVoid();
1064
1065 // Restore the builder back to previous basic block.
1066 Builder.SetInsertPoint(PrevBB);
1067 }
1068
1069 /// @brief Create an OpenMP parallel for loop.
1070 ///
1071 /// This loop reflects a loop as if it would have been created by an OpenMP
1072 /// statement.
1073 void codegenForOpenMP(const clast_for *f) {
1074 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001075 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001076
1077 Function *SubFunction = addOpenMPSubfunction(M);
1078 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1079 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1080
1081 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1082
1083 // Create call for GOMP_parallel_loop_runtime_start.
1084 Value *subfunctionParam = Builder.CreateBitCast(structData,
1085 Builder.getInt8PtrTy(),
1086 "omp_data");
1087
1088 Value *numberOfThreads = Builder.getInt32(0);
1089 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1090 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1091
1092 // Add one as the upper bound provided by openmp is a < comparison
1093 // whereas the codegenForSequential function creates a <= comparison.
1094 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1095 APInt APStride = APInt_from_MPZ(f->stride);
1096 Value *stride = ConstantInt::get(intPtrTy,
1097 APStride.zext(intPtrTy->getBitWidth()));
1098
1099 SmallVector<Value *, 6> Arguments;
1100 Arguments.push_back(SubFunction);
1101 Arguments.push_back(subfunctionParam);
1102 Arguments.push_back(numberOfThreads);
1103 Arguments.push_back(lowerBound);
1104 Arguments.push_back(upperBound);
1105 Arguments.push_back(stride);
1106
1107 Function *parallelStartFunction =
1108 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001109 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001110
1111 // Create call to the subfunction.
1112 Builder.CreateCall(SubFunction, subfunctionParam);
1113
1114 // Create call for GOMP_parallel_end.
1115 Function *FN = M->getFunction("GOMP_parallel_end");
1116 Builder.CreateCall(FN);
1117 }
1118
1119 bool isInnermostLoop(const clast_for *f) {
1120 const clast_stmt *stmt = f->body;
1121
1122 while (stmt) {
1123 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1124 return false;
1125
1126 stmt = stmt->next;
1127 }
1128
1129 return true;
1130 }
1131
1132 /// @brief Get the number of loop iterations for this loop.
1133 /// @param f The clast for loop to check.
1134 int getNumberOfIterations(const clast_for *f) {
1135 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1136 isl_set *tmp = isl_set_copy(loopDomain);
1137
1138 // Calculate a map similar to the identity map, but with the last input
1139 // and output dimension not related.
1140 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1141 isl_dim *dim = isl_set_get_dim(loopDomain);
1142 dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1);
1143 dim = isl_dim_map_from_set(dim);
1144 isl_map *identity = isl_map_identity(dim);
1145 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1146 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1147
1148 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1149 map = isl_map_intersect(map, identity);
1150
1151 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001152 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001153 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1154
1155 isl_set *elements = isl_map_range(sub);
1156
Tobias Grosserc532f122011-08-25 08:40:59 +00001157 if (!isl_set_is_singleton(elements)) {
1158 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001159 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001160 }
Tobias Grosser75805372011-04-29 06:27:02 +00001161
1162 isl_point *p = isl_set_sample_point(elements);
1163
1164 isl_int v;
1165 isl_int_init(v);
1166 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1167 int numberIterations = isl_int_get_si(v);
1168 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001169 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001170
1171 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1172 }
1173
1174 /// @brief Create vector instructions for this loop.
1175 void codegenForVector(const clast_for *f) {
1176 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1177 int vectorWidth = getNumberOfIterations(f);
1178
1179 Value *LB = ExpGen.codegen(f->LB,
1180 TD->getIntPtrType(Builder.getContext()));
1181
1182 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001183 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001184 Stride = Stride.zext(LoopIVType->getBitWidth());
1185 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1186
1187 std::vector<Value*> IVS(vectorWidth);
1188 IVS[0] = LB;
1189
1190 for (int i = 1; i < vectorWidth; i++)
1191 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1192
1193 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1194
1195 // Add loop iv to symbols.
1196 (*clastVars)[f->iterator] = LB;
1197
1198 const clast_stmt *stmt = f->body;
1199
1200 while (stmt) {
1201 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1202 scatteringDomain);
1203 stmt = stmt->next;
1204 }
1205
1206 // Loop is finished, so remove its iv from the live symbols.
1207 clastVars->erase(f->iterator);
1208 }
1209
1210 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001211 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001212 && (-1 != getNumberOfIterations(f))
1213 && (getNumberOfIterations(f) <= 16)) {
1214 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001215 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001216 parallelCodeGeneration = true;
1217 parallelLoops.push_back(f->iterator);
1218 codegenForOpenMP(f);
1219 parallelCodeGeneration = false;
1220 } else
1221 codegenForSequential(f);
1222 }
1223
1224 Value *codegen(const clast_equation *eq) {
1225 Value *LHS = ExpGen.codegen(eq->LHS,
1226 TD->getIntPtrType(Builder.getContext()));
1227 Value *RHS = ExpGen.codegen(eq->RHS,
1228 TD->getIntPtrType(Builder.getContext()));
1229 CmpInst::Predicate P;
1230
1231 if (eq->sign == 0)
1232 P = ICmpInst::ICMP_EQ;
1233 else if (eq->sign > 0)
1234 P = ICmpInst::ICMP_SGE;
1235 else
1236 P = ICmpInst::ICMP_SLE;
1237
1238 return Builder.CreateICmp(P, LHS, RHS);
1239 }
1240
1241 void codegen(const clast_guard *g) {
1242 Function *F = Builder.GetInsertBlock()->getParent();
1243 LLVMContext &Context = F->getContext();
1244 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1245 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1246 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1247 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1248
1249 Value *Predicate = codegen(&(g->eq[0]));
1250
1251 for (int i = 1; i < g->n; ++i) {
1252 Value *TmpPredicate = codegen(&(g->eq[i]));
1253 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1254 }
1255
1256 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1257 Builder.SetInsertPoint(ThenBB);
1258
1259 codegen(g->then);
1260
1261 Builder.CreateBr(MergeBB);
1262 Builder.SetInsertPoint(MergeBB);
1263 }
1264
1265 void codegen(const clast_stmt *stmt) {
1266 if (CLAST_STMT_IS_A(stmt, stmt_root))
1267 assert(false && "No second root statement expected");
1268 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1269 codegen((const clast_assignment *)stmt);
1270 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1271 codegen((const clast_user_stmt *)stmt);
1272 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1273 codegen((const clast_block *)stmt);
1274 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1275 codegen((const clast_for *)stmt);
1276 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1277 codegen((const clast_guard *)stmt);
1278
1279 if (stmt->next)
1280 codegen(stmt->next);
1281 }
1282
1283 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001284 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001285
1286 // Create an instruction that specifies the location where the parameters
1287 // are expanded.
1288 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1289 Builder.getInt16Ty(), false, "insertInst",
1290 Builder.GetInsertBlock());
1291
1292 int i = 0;
1293 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1294 PI != PE; ++PI) {
1295 assert(i < names->nb_parameters && "Not enough parameter names");
1296
1297 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001298 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001299
1300 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1301 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1302 (*clastVars)[names->parameters[i]] = V;
1303
1304 ++i;
1305 }
1306 }
1307
1308 public:
1309 void codegen(const clast_root *r) {
1310 clastVars = new CharMapT();
1311 addParameters(r->names);
1312 ExpGen.setIVS(clastVars);
1313
1314 parallelCodeGeneration = false;
1315
1316 const clast_stmt *stmt = (const clast_stmt*) r;
1317 if (stmt->next)
1318 codegen(stmt->next);
1319
1320 delete clastVars;
1321 }
1322
1323 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001324 ScopDetection *sd, Dependences *dp, TargetData *td,
1325 IRBuilder<> &B) :
1326 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1327 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001328
1329};
1330}
1331
1332namespace {
1333class CodeGeneration : public ScopPass {
1334 Region *region;
1335 Scop *S;
1336 DominatorTree *DT;
1337 ScalarEvolution *SE;
1338 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001339 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001340 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001341
1342 std::vector<std::string> parallelLoops;
1343
1344 public:
1345 static char ID;
1346
1347 CodeGeneration() : ScopPass(ID) {}
1348
Tobias Grosser75805372011-04-29 06:27:02 +00001349 // Adding prototypes required if OpenMP is enabled.
1350 void addOpenMPDefinitions(IRBuilder<> &Builder)
1351 {
1352 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1353 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001354 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001355
1356 if (!M->getFunction("GOMP_parallel_end")) {
1357 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1358 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1359 }
1360
1361 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1362 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001363 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001364 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1365 false);
1366 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1367
Tobias Grosser851b96e2011-07-12 12:42:54 +00001368 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001369 args.push_back(FnPtrTy);
1370 args.push_back(Builder.getInt8PtrTy());
1371 args.push_back(Builder.getInt32Ty());
1372 args.push_back(intPtrTy);
1373 args.push_back(intPtrTy);
1374 args.push_back(intPtrTy);
1375
1376 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1377 Function::Create(type, Function::ExternalLinkage,
1378 "GOMP_parallel_loop_runtime_start", M);
1379 }
1380
1381 if (!M->getFunction("GOMP_loop_runtime_next")) {
1382 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1383
Tobias Grosser851b96e2011-07-12 12:42:54 +00001384 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001385 args.push_back(intLongPtrTy);
1386 args.push_back(intLongPtrTy);
1387
1388 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1389 Function::Create(type, Function::ExternalLinkage,
1390 "GOMP_loop_runtime_next", M);
1391 }
1392
1393 if (!M->getFunction("GOMP_loop_end_nowait")) {
1394 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001395 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001396 Function::Create(FT, Function::ExternalLinkage,
1397 "GOMP_loop_end_nowait", M);
1398 }
1399 }
1400
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001401 // Split the entry edge of the region and generate a new basic block on this
1402 // edge. This function also updates ScopInfo and RegionInfo.
1403 //
1404 // @param region The region where the entry edge will be splitted.
1405 BasicBlock *splitEdgeAdvanced(Region *region) {
1406 BasicBlock *newBlock;
1407 BasicBlock *splitBlock;
1408
1409 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1410
1411 if (DT->dominates(region->getEntry(), newBlock)) {
1412 // Update ScopInfo.
1413 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1414 if ((*SI)->getBasicBlock() == newBlock) {
1415 (*SI)->setBasicBlock(newBlock);
1416 break;
1417 }
1418
1419 // Update RegionInfo.
1420 splitBlock = region->getEntry();
1421 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001422 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001423 } else {
1424 RI->setRegionFor(newBlock, region->getParent());
1425 splitBlock = newBlock;
1426 }
1427
1428 return splitBlock;
1429 }
1430
1431 // Create a split block that branches either to the old code or to a new basic
1432 // block where the new code can be inserted.
1433 //
1434 // @param builder A builder that will be set to point to a basic block, where
1435 // the new code can be generated.
1436 // @return The split basic block.
1437 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1438 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1439
1440 splitBlock->setName("polly.enterScop");
1441
1442 Function *function = splitBlock->getParent();
1443 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1444 "polly.start", function);
1445 splitBlock->getTerminator()->eraseFromParent();
1446 builder->SetInsertPoint(splitBlock);
1447 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1448 DT->addNewBlock(startBlock, splitBlock);
1449
1450 // Start code generation here.
1451 builder->SetInsertPoint(startBlock);
1452 return splitBlock;
1453 }
1454
1455 // Merge the control flow of the newly generated code with the existing code.
1456 //
1457 // @param splitBlock The basic block where the control flow was split between
1458 // old and new version of the Scop.
1459 // @param builder An IRBuilder that points to the last instruction of the
1460 // newly generated code.
1461 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1462 BasicBlock *mergeBlock;
1463 Region *R = region;
1464
1465 if (R->getExit()->getSinglePredecessor())
1466 // No splitEdge required. A block with a single predecessor cannot have
1467 // PHI nodes that would complicate life.
1468 mergeBlock = R->getExit();
1469 else {
1470 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1471 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1472 // one predecessor. Hence, mergeBlock is always a newly generated block.
1473 mergeBlock->setName("polly.finalMerge");
1474 R->replaceExit(mergeBlock);
1475 }
1476
1477 builder->CreateBr(mergeBlock);
1478
1479 if (DT->dominates(splitBlock, mergeBlock))
1480 DT->changeImmediateDominator(mergeBlock, splitBlock);
1481 }
1482
Tobias Grosser75805372011-04-29 06:27:02 +00001483 bool runOnScop(Scop &scop) {
1484 S = &scop;
1485 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001486 DT = &getAnalysis<DominatorTree>();
1487 Dependences *DP = &getAnalysis<Dependences>();
1488 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001489 SD = &getAnalysis<ScopDetection>();
1490 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001491 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001492
1493 parallelLoops.clear();
1494
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001495 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001496
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001497 // In the CFG and we generate next to original code of the Scop the
1498 // optimized version. Both the new and the original version of the code
1499 // remain in the CFG. A branch statement decides which version is executed.
1500 // At the moment, we always execute the newly generated version (the old one
1501 // is dead code eliminated by the cleanup passes). Later we may decide to
1502 // execute the new version only under certain conditions. This will be the
1503 // case if we support constructs for which we cannot prove all assumptions
1504 // at compile time.
1505 //
1506 // Before transformation:
1507 //
1508 // bb0
1509 // |
1510 // orig_scop
1511 // |
1512 // bb1
1513 //
1514 // After transformation:
1515 // bb0
1516 // |
1517 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001518 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001519 // | startBlock
1520 // | |
1521 // orig_scop new_scop
1522 // \ /
1523 // \ /
1524 // bb1 (joinBlock)
1525 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001526
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001527 // The builder will be set to startBlock.
1528 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001529
1530 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001531 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001532
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001533 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001534 CloogInfo &C = getAnalysis<CloogInfo>();
1535 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001536
Tobias Grosser75805372011-04-29 06:27:02 +00001537 parallelLoops.insert(parallelLoops.begin(),
1538 CodeGen.getParallelLoops().begin(),
1539 CodeGen.getParallelLoops().end());
1540
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001541 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001542
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001543 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001544 }
1545
1546 virtual void printScop(raw_ostream &OS) const {
1547 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1548 PE = parallelLoops.end(); PI != PE; ++PI)
1549 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1550 }
1551
1552 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1553 AU.addRequired<CloogInfo>();
1554 AU.addRequired<Dependences>();
1555 AU.addRequired<DominatorTree>();
1556 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001557 AU.addRequired<RegionInfo>();
1558 AU.addRequired<ScopDetection>();
1559 AU.addRequired<ScopInfo>();
1560 AU.addRequired<TargetData>();
1561
1562 AU.addPreserved<CloogInfo>();
1563 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001564
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001565 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001566 AU.addPreserved<LoopInfo>();
1567 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001568 AU.addPreserved<ScopDetection>();
1569 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001570
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001571 // FIXME: We do not yet add regions for the newly generated code to the
1572 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001573 AU.addPreserved<RegionInfo>();
1574 AU.addPreserved<TempScopInfo>();
1575 AU.addPreserved<ScopInfo>();
1576 AU.addPreservedID(IndependentBlocksID);
1577 }
1578};
1579}
1580
1581char CodeGeneration::ID = 1;
1582
1583static RegisterPass<CodeGeneration>
1584Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1585
1586Pass* polly::createCodeGenerationPass() {
1587 return new CodeGeneration();
1588}