blob: cb8a01f4ed4a43c9e46e46a72965c0909535e489 [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,
Tobias Grosser8b00a512011-09-04 11:45:45 +0000413 ValueMapT &vectorMap, int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000414 Value *opZero = Inst->getOperand(0);
415 Value *opOne = Inst->getOperand(1);
416
Tobias Grosser09c57102011-09-04 11:45:29 +0000417 Value *newOpZero, *newOpOne;
418 newOpZero = getOperand(opZero, BBMap, &vectorMap);
419 newOpOne = getOperand(opOne, BBMap, &vectorMap);
420
Tobias Grosser7551c302011-09-04 11:45:41 +0000421 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
422 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000423
424 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
Tobias Grosser7551c302011-09-04 11:45:41 +0000425 newOpOne,
426 Inst->getNameStr() + "p_vec");
427 vectorMap[Inst] = newInst;
Tobias Grosser09c57102011-09-04 11:45:29 +0000428
429 return;
430 }
431
432 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000433 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
434 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000435 // In vector mode we only generate a store for the first dimension.
436 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000437 return;
438
Tobias Grosser09c57102011-09-04 11:45:29 +0000439 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000440
Tobias Grosser09c57102011-09-04 11:45:29 +0000441 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000442
Tobias Grosser09c57102011-09-04 11:45:29 +0000443 const Value *pointer = store->getPointerOperand();
444 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000445
Tobias Grosser09c57102011-09-04 11:45:29 +0000446 if (Access.isStrideOne(scatteringDomain)) {
447 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
448 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000449
Tobias Grosser09c57102011-09-04 11:45:29 +0000450 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
451 "vector_ptr");
452 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Tobias Grosser09c57102011-09-04 11:45:29 +0000454 if (!Aligned)
455 Store->setAlignment(8);
456 } else {
457 for (unsigned i = 0; i < scalarMaps.size(); i++) {
458 Value *scalar = Builder.CreateExtractElement(vector,
459 Builder.getInt32(i));
460 Value *newPointer = getOperand(pointer, scalarMaps[i]);
461 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000462 }
463 }
464
Tobias Grosser09c57102011-09-04 11:45:29 +0000465 return;
466 }
467
Tobias Grosser7551c302011-09-04 11:45:41 +0000468 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000469 Instruction *NewInst = Inst->clone();
470
Tobias Grosser75805372011-04-29 06:27:02 +0000471 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000472 for (Instruction::const_op_iterator OI = Inst->op_begin(),
473 OE = Inst->op_end(); OI != OE; ++OI) {
474 Value *OldOperand = *OI;
475 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000476
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000477 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000478 assert(!isa<StoreInst>(NewInst)
479 && "Store instructions are always needed!");
480 delete NewInst;
481 return;
482 }
483
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000484 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000485 }
486
487 Builder.Insert(NewInst);
488 BBMap[Inst] = NewInst;
489
490 if (!NewInst->getType()->isVoidTy())
491 NewInst->setName("p_" + Inst->getName());
492 }
493
Tobias Grosser7551c302011-09-04 11:45:41 +0000494 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap) {
495 for (Instruction::const_op_iterator OI = Inst->op_begin(),
496 OE = Inst->op_end(); OI != OE; ++OI)
497 if (VectorMap.count(*OI))
498 return true;
499 return false;
Tobias Grosser09c57102011-09-04 11:45:29 +0000500 }
501
Tobias Grosser75805372011-04-29 06:27:02 +0000502 int getVectorSize() {
503 return ValueMaps.size();
504 }
505
506 bool isVectorBlock() {
507 return getVectorSize() > 1;
508 }
509
Tobias Grosser7551c302011-09-04 11:45:41 +0000510 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
511 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
512 int vectorDimension, int vectorWidth) {
513 // Terminator instructions control the control flow. They are explicitally
514 // expressed in the clast and do not need to be copied.
515 if (Inst->isTerminator())
516 return;
517
518 if (isVectorBlock()) {
519 // If this instruction is already in the vectorMap, a vector instruction
520 // was already issued, that calculates the values of all dimensions. No
521 // need to create any more instructions.
522 if (vectorMap.count(Inst))
523 return;
524 }
525
526 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
527 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
528 return;
529 }
530
531 if (isVectorBlock() && hasVectorOperands(Inst, vectorMap)) {
532 if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosser8b00a512011-09-04 11:45:45 +0000533 copyBinInst(binaryInst, BBMap, vectorMap, vectorDimension, vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000534 else if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
535 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
536 vectorWidth);
537 else
538 llvm_unreachable("Cannot issue vector code for this instruction");
539
540 return;
541 }
542
543 copyInstScalar(Inst, BBMap);
544 }
Tobias Grosser75805372011-04-29 06:27:02 +0000545 // Insert a copy of a basic block in the newly generated code.
546 //
547 // @param Builder The builder used to insert the code. It also specifies
548 // where to insert the code.
549 // @param BB The basic block to copy
550 // @param VMap A map returning for any old value its new equivalent. This
551 // is used to update the operands of the statements.
552 // For new statements a relation old->new is inserted in this
553 // map.
554 void copyBB(BasicBlock *BB, DominatorTree *DT) {
555 Function *F = Builder.GetInsertBlock()->getParent();
556 LLVMContext &Context = F->getContext();
557 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser8ae9aca2011-09-04 11:45:22 +0000558 "polly." + BB->getNameStr()
559 + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000560 F);
561 Builder.CreateBr(CopyBB);
562 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
563 Builder.SetInsertPoint(CopyBB);
564
565 // Create two maps that store the mapping from the original instructions of
566 // the old basic block to their copies in the new basic block. Those maps
567 // are basic block local.
568 //
569 // As vector code generation is supported there is one map for scalar values
570 // and one for vector values.
571 //
572 // In case we just do scalar code generation, the vectorMap is not used and
573 // the scalarMap has just one dimension, which contains the mapping.
574 //
575 // In case vector code generation is done, an instruction may either appear
576 // in the vector map once (as it is calculating >vectorwidth< values at a
577 // time. Or (if the values are calculated using scalar operations), it
578 // appears once in every dimension of the scalarMap.
579 VectorValueMapT scalarBlockMap(getVectorSize());
580 ValueMapT vectorBlockMap;
581
582 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
583 II != IE; ++II)
584 for (int i = 0; i < getVectorSize(); i++) {
585 if (isVectorBlock())
586 VMap = ValueMaps[i];
587
588 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
589 scalarBlockMap, i, getVectorSize());
590 }
591 }
592};
593
594/// Class to generate LLVM-IR that calculates the value of a clast_expr.
595class ClastExpCodeGen {
596 IRBuilder<> &Builder;
597 const CharMapT *IVS;
598
Tobias Grosser55927aa2011-07-18 09:53:32 +0000599 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000600 CharMapT::const_iterator I = IVS->find(e->name);
601
602 if (I != IVS->end())
603 return Builder.CreateSExtOrBitCast(I->second, Ty);
604 else
605 llvm_unreachable("Clast name not found");
606 }
607
Tobias Grosser55927aa2011-07-18 09:53:32 +0000608 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000609 APInt a = APInt_from_MPZ(e->val);
610
611 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
612 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
613
614 if (e->var) {
615 Value *var = codegen(e->var, Ty);
616 return Builder.CreateMul(ConstOne, var);
617 }
618
619 return ConstOne;
620 }
621
Tobias Grosser55927aa2011-07-18 09:53:32 +0000622 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000623 Value *LHS = codegen(e->LHS, Ty);
624
625 APInt RHS_AP = APInt_from_MPZ(e->RHS);
626
627 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
628 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
629
630 switch (e->type) {
631 case clast_bin_mod:
632 return Builder.CreateSRem(LHS, RHS);
633 case clast_bin_fdiv:
634 {
635 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
636 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
637 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
638 One = Builder.CreateZExtOrBitCast(One, Ty);
639 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
640 Value *Sum1 = Builder.CreateSub(LHS, RHS);
641 Value *Sum2 = Builder.CreateAdd(Sum1, One);
642 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
643 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
644 return Builder.CreateSDiv(Dividend, RHS);
645 }
646 case clast_bin_cdiv:
647 {
648 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
649 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
650 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
651 One = Builder.CreateZExtOrBitCast(One, Ty);
652 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
653 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
654 Value *Sum2 = Builder.CreateSub(Sum1, One);
655 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
656 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
657 return Builder.CreateSDiv(Dividend, RHS);
658 }
659 case clast_bin_div:
660 return Builder.CreateSDiv(LHS, RHS);
661 default:
662 llvm_unreachable("Unknown clast binary expression type");
663 };
664 }
665
Tobias Grosser55927aa2011-07-18 09:53:32 +0000666 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000667 assert(( r->type == clast_red_min
668 || r->type == clast_red_max
669 || r->type == clast_red_sum)
670 && "Clast reduction type not supported");
671 Value *old = codegen(r->elts[0], Ty);
672
673 for (int i=1; i < r->n; ++i) {
674 Value *exprValue = codegen(r->elts[i], Ty);
675
676 switch (r->type) {
677 case clast_red_min:
678 {
679 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
680 old = Builder.CreateSelect(cmp, old, exprValue);
681 break;
682 }
683 case clast_red_max:
684 {
685 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
686 old = Builder.CreateSelect(cmp, old, exprValue);
687 break;
688 }
689 case clast_red_sum:
690 old = Builder.CreateAdd(old, exprValue);
691 break;
692 default:
693 llvm_unreachable("Clast unknown reduction type");
694 }
695 }
696
697 return old;
698 }
699
700public:
701
702 // A generator for clast expressions.
703 //
704 // @param B The IRBuilder that defines where the code to calculate the
705 // clast expressions should be inserted.
706 // @param IVMAP A Map that translates strings describing the induction
707 // variables to the Values* that represent these variables
708 // on the LLVM side.
709 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
710
711 // Generates code to calculate a given clast expression.
712 //
713 // @param e The expression to calculate.
714 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000715 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000716 switch(e->type) {
717 case clast_expr_name:
718 return codegen((const clast_name *)e, Ty);
719 case clast_expr_term:
720 return codegen((const clast_term *)e, Ty);
721 case clast_expr_bin:
722 return codegen((const clast_binary *)e, Ty);
723 case clast_expr_red:
724 return codegen((const clast_reduction *)e, Ty);
725 default:
726 llvm_unreachable("Unknown clast expression!");
727 }
728 }
729
730 // @brief Reset the CharMap.
731 //
732 // This function is called to reset the CharMap to new one, while generating
733 // OpenMP code.
734 void setIVS(CharMapT *IVSNew) {
735 IVS = IVSNew;
736 }
737
738};
739
740class ClastStmtCodeGen {
741 // The Scop we code generate.
742 Scop *S;
743 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000744 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000745 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000746 Dependences *DP;
747 TargetData *TD;
748
749 // The Builder specifies the current location to code generate at.
750 IRBuilder<> &Builder;
751
752 // Map the Values from the old code to their counterparts in the new code.
753 ValueMapT ValueMap;
754
755 // clastVars maps from the textual representation of a clast variable to its
756 // current *Value. clast variables are scheduling variables, original
757 // induction variables or parameters. They are used either in loop bounds or
758 // to define the statement instance that is executed.
759 //
760 // for (s = 0; s < n + 3; ++i)
761 // for (t = s; t < m; ++j)
762 // Stmt(i = s + 3 * m, j = t);
763 //
764 // {s,t,i,j,n,m} is the set of clast variables in this clast.
765 CharMapT *clastVars;
766
767 // Codegenerator for clast expressions.
768 ClastExpCodeGen ExpGen;
769
770 // Do we currently generate parallel code?
771 bool parallelCodeGeneration;
772
773 std::vector<std::string> parallelLoops;
774
775public:
776
777 const std::vector<std::string> &getParallelLoops() {
778 return parallelLoops;
779 }
780
781 protected:
782 void codegen(const clast_assignment *a) {
783 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
784 TD->getIntPtrType(Builder.getContext()));
785 }
786
787 void codegen(const clast_assignment *a, ScopStmt *Statement,
788 unsigned Dimension, int vectorDim,
789 std::vector<ValueMapT> *VectorVMap = 0) {
790 Value *RHS = ExpGen.codegen(a->RHS,
791 TD->getIntPtrType(Builder.getContext()));
792
793 assert(!a->LHS && "Statement assignments do not have left hand side");
794 const PHINode *PN;
795 PN = Statement->getInductionVariableForDimension(Dimension);
796 const Value *V = PN;
797
Tobias Grosser75805372011-04-29 06:27:02 +0000798 if (VectorVMap)
799 (*VectorVMap)[vectorDim][V] = RHS;
800
801 ValueMap[V] = RHS;
802 }
803
804 void codegenSubstitutions(const clast_stmt *Assignment,
805 ScopStmt *Statement, int vectorDim = 0,
806 std::vector<ValueMapT> *VectorVMap = 0) {
807 int Dimension = 0;
808
809 while (Assignment) {
810 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
811 && "Substitions are expected to be assignments");
812 codegen((const clast_assignment *)Assignment, Statement, Dimension,
813 vectorDim, VectorVMap);
814 Assignment = Assignment->next;
815 Dimension++;
816 }
817 }
818
819 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
820 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
821 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
822 BasicBlock *BB = Statement->getBasicBlock();
823
824 if (u->substitutions)
825 codegenSubstitutions(u->substitutions, Statement);
826
827 int vectorDimensions = IVS ? IVS->size() : 1;
828
829 VectorValueMapT VectorValueMap(vectorDimensions);
830
831 if (IVS) {
832 assert (u->substitutions && "Substitutions expected!");
833 int i = 0;
834 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
835 II != IE; ++II) {
836 (*clastVars)[iterator] = *II;
837 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
838 i++;
839 }
840 }
841
842 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
843 scatteringDomain);
844 Generator.copyBB(BB, DT);
845 }
846
847 void codegen(const clast_block *b) {
848 if (b->body)
849 codegen(b->body);
850 }
851
852 /// @brief Create a classical sequential loop.
853 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
854 Value *upperBound = 0) {
855 APInt Stride = APInt_from_MPZ(f->stride);
856 PHINode *IV;
857 Value *IncrementedIV;
858 BasicBlock *AfterBB;
859 // The value of lowerbound and upperbound will be supplied, if this
860 // function is called while generating OpenMP code. Otherwise get
861 // the values.
862 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
863 && "Either give both bounds or none");
864 if (lowerBound == 0 || upperBound == 0) {
865 lowerBound = ExpGen.codegen(f->LB,
866 TD->getIntPtrType(Builder.getContext()));
867 upperBound = ExpGen.codegen(f->UB,
868 TD->getIntPtrType(Builder.getContext()));
869 }
870 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
871 IncrementedIV, DT);
872
873 // Add loop iv to symbols.
874 (*clastVars)[f->iterator] = IV;
875
876 if (f->body)
877 codegen(f->body);
878
879 // Loop is finished, so remove its iv from the live symbols.
880 clastVars->erase(f->iterator);
881
882 BasicBlock *HeaderBB = *pred_begin(AfterBB);
883 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
884 Builder.CreateBr(HeaderBB);
885 IV->addIncoming(IncrementedIV, LastBodyBB);
886 Builder.SetInsertPoint(AfterBB);
887 }
888
Tobias Grosser75805372011-04-29 06:27:02 +0000889 /// @brief Add a new definition of an openmp subfunction.
890 Function* addOpenMPSubfunction(Module *M) {
891 Function *F = Builder.GetInsertBlock()->getParent();
892 const std::string &Name = F->getNameStr() + ".omp_subfn";
893
Tobias Grosser851b96e2011-07-12 12:42:54 +0000894 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000895 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
896 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000897 // Do not run any polly pass on the new function.
898 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000899
900 Function::arg_iterator AI = FN->arg_begin();
901 AI->setName("omp.userContext");
902
903 return FN;
904 }
905
906 /// @brief Add values to the OpenMP structure.
907 ///
908 /// Create the subfunction structure and add the values from the list.
909 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
910 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000911 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000912
913 // Create the structure.
914 for (unsigned i = 0; i < OMPDataVals.size(); i++)
915 structMembers.push_back(OMPDataVals[i]->getType());
916
Tobias Grosser75805372011-04-29 06:27:02 +0000917 StructType *structTy = StructType::get(Builder.getContext(),
918 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000919 // Store the values into the structure.
920 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
921 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
922 Value *storeAddr = Builder.CreateStructGEP(structData, i);
923 Builder.CreateStore(OMPDataVals[i], storeAddr);
924 }
925
926 return structData;
927 }
928
929 /// @brief Create OpenMP structure values.
930 ///
931 /// Create a list of values that has to be stored into the subfuncition
932 /// structure.
933 SetVector<Value*> createOpenMPStructValues() {
934 SetVector<Value*> OMPDataVals;
935
936 // Push the clast variables available in the clastVars.
937 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
938 I != E; I++)
939 OMPDataVals.insert(I->second);
940
941 // Push the base addresses of memory references.
942 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
943 ScopStmt *Stmt = *SI;
944 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
945 E = Stmt->memacc_end(); I != E; ++I) {
946 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
947 OMPDataVals.insert((BaseAddr));
948 }
949 }
950
951 return OMPDataVals;
952 }
953
954 /// @brief Extract the values from the subfunction parameter.
955 ///
956 /// Extract the values from the subfunction parameter and update the clast
957 /// variables to point to the new values.
958 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
959 SetVector<Value*> OMPDataVals,
960 Value *userContext) {
961 // Extract the clast variables.
962 unsigned i = 0;
963 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
964 I != E; I++) {
965 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
966 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
967 i++;
968 }
969
970 // Extract the base addresses of memory references.
971 for (unsigned j = i; j < OMPDataVals.size(); j++) {
972 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
973 Value *baseAddr = OMPDataVals[j];
974 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
975 }
976
977 }
978
979 /// @brief Add body to the subfunction.
980 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
981 Value *structData,
982 SetVector<Value*> OMPDataVals) {
983 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
984 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000985 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +0000986
987 // Store the previous basic block.
988 BasicBlock *PrevBB = Builder.GetInsertBlock();
989
990 // Create basic blocks.
991 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
992 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
993 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
994 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
995 FN);
996
997 DT->addNewBlock(HeaderBB, PrevBB);
998 DT->addNewBlock(ExitBB, HeaderBB);
999 DT->addNewBlock(checkNextBB, HeaderBB);
1000 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1001
1002 // Fill up basic block HeaderBB.
1003 Builder.SetInsertPoint(HeaderBB);
1004 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1005 "omp.lowerBoundPtr");
1006 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1007 "omp.upperBoundPtr");
1008 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1009 structData->getType(),
1010 "omp.userContext");
1011
1012 CharMapT clastVarsOMP;
1013 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1014
1015 Builder.CreateBr(checkNextBB);
1016
1017 // Add code to check if another set of iterations will be executed.
1018 Builder.SetInsertPoint(checkNextBB);
1019 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1020 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1021 lowerBoundPtr, upperBoundPtr);
1022 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1023 "omp.hasNextScheduleBlock");
1024 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1025
1026 // Add code to to load the iv bounds for this set of iterations.
1027 Builder.SetInsertPoint(loadIVBoundsBB);
1028 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1029 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1030
1031 // Subtract one as the upper bound provided by openmp is a < comparison
1032 // whereas the codegenForSequential function creates a <= comparison.
1033 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1034 "omp.upperBoundAdjusted");
1035
1036 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1037 CharMapT *oldClastVars = clastVars;
1038 clastVars = &clastVarsOMP;
1039 ExpGen.setIVS(&clastVarsOMP);
1040
1041 codegenForSequential(f, lowerBound, upperBound);
1042
1043 // Restore the old clastVars.
1044 clastVars = oldClastVars;
1045 ExpGen.setIVS(oldClastVars);
1046
1047 Builder.CreateBr(checkNextBB);
1048
1049 // Add code to terminate this openmp subfunction.
1050 Builder.SetInsertPoint(ExitBB);
1051 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1052 Builder.CreateCall(endnowaitFunction);
1053 Builder.CreateRetVoid();
1054
1055 // Restore the builder back to previous basic block.
1056 Builder.SetInsertPoint(PrevBB);
1057 }
1058
1059 /// @brief Create an OpenMP parallel for loop.
1060 ///
1061 /// This loop reflects a loop as if it would have been created by an OpenMP
1062 /// statement.
1063 void codegenForOpenMP(const clast_for *f) {
1064 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001065 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001066
1067 Function *SubFunction = addOpenMPSubfunction(M);
1068 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1069 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1070
1071 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1072
1073 // Create call for GOMP_parallel_loop_runtime_start.
1074 Value *subfunctionParam = Builder.CreateBitCast(structData,
1075 Builder.getInt8PtrTy(),
1076 "omp_data");
1077
1078 Value *numberOfThreads = Builder.getInt32(0);
1079 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1080 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1081
1082 // Add one as the upper bound provided by openmp is a < comparison
1083 // whereas the codegenForSequential function creates a <= comparison.
1084 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1085 APInt APStride = APInt_from_MPZ(f->stride);
1086 Value *stride = ConstantInt::get(intPtrTy,
1087 APStride.zext(intPtrTy->getBitWidth()));
1088
1089 SmallVector<Value *, 6> Arguments;
1090 Arguments.push_back(SubFunction);
1091 Arguments.push_back(subfunctionParam);
1092 Arguments.push_back(numberOfThreads);
1093 Arguments.push_back(lowerBound);
1094 Arguments.push_back(upperBound);
1095 Arguments.push_back(stride);
1096
1097 Function *parallelStartFunction =
1098 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001099 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001100
1101 // Create call to the subfunction.
1102 Builder.CreateCall(SubFunction, subfunctionParam);
1103
1104 // Create call for GOMP_parallel_end.
1105 Function *FN = M->getFunction("GOMP_parallel_end");
1106 Builder.CreateCall(FN);
1107 }
1108
1109 bool isInnermostLoop(const clast_for *f) {
1110 const clast_stmt *stmt = f->body;
1111
1112 while (stmt) {
1113 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1114 return false;
1115
1116 stmt = stmt->next;
1117 }
1118
1119 return true;
1120 }
1121
1122 /// @brief Get the number of loop iterations for this loop.
1123 /// @param f The clast for loop to check.
1124 int getNumberOfIterations(const clast_for *f) {
1125 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1126 isl_set *tmp = isl_set_copy(loopDomain);
1127
1128 // Calculate a map similar to the identity map, but with the last input
1129 // and output dimension not related.
1130 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1131 isl_dim *dim = isl_set_get_dim(loopDomain);
1132 dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1);
1133 dim = isl_dim_map_from_set(dim);
1134 isl_map *identity = isl_map_identity(dim);
1135 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1136 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1137
1138 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1139 map = isl_map_intersect(map, identity);
1140
1141 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001142 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001143 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1144
1145 isl_set *elements = isl_map_range(sub);
1146
Tobias Grosserc532f122011-08-25 08:40:59 +00001147 if (!isl_set_is_singleton(elements)) {
1148 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001149 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001150 }
Tobias Grosser75805372011-04-29 06:27:02 +00001151
1152 isl_point *p = isl_set_sample_point(elements);
1153
1154 isl_int v;
1155 isl_int_init(v);
1156 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1157 int numberIterations = isl_int_get_si(v);
1158 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001159 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001160
1161 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1162 }
1163
1164 /// @brief Create vector instructions for this loop.
1165 void codegenForVector(const clast_for *f) {
1166 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1167 int vectorWidth = getNumberOfIterations(f);
1168
1169 Value *LB = ExpGen.codegen(f->LB,
1170 TD->getIntPtrType(Builder.getContext()));
1171
1172 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001173 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001174 Stride = Stride.zext(LoopIVType->getBitWidth());
1175 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1176
1177 std::vector<Value*> IVS(vectorWidth);
1178 IVS[0] = LB;
1179
1180 for (int i = 1; i < vectorWidth; i++)
1181 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1182
1183 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1184
1185 // Add loop iv to symbols.
1186 (*clastVars)[f->iterator] = LB;
1187
1188 const clast_stmt *stmt = f->body;
1189
1190 while (stmt) {
1191 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1192 scatteringDomain);
1193 stmt = stmt->next;
1194 }
1195
1196 // Loop is finished, so remove its iv from the live symbols.
1197 clastVars->erase(f->iterator);
1198 }
1199
1200 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001201 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001202 && (-1 != getNumberOfIterations(f))
1203 && (getNumberOfIterations(f) <= 16)) {
1204 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001205 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001206 parallelCodeGeneration = true;
1207 parallelLoops.push_back(f->iterator);
1208 codegenForOpenMP(f);
1209 parallelCodeGeneration = false;
1210 } else
1211 codegenForSequential(f);
1212 }
1213
1214 Value *codegen(const clast_equation *eq) {
1215 Value *LHS = ExpGen.codegen(eq->LHS,
1216 TD->getIntPtrType(Builder.getContext()));
1217 Value *RHS = ExpGen.codegen(eq->RHS,
1218 TD->getIntPtrType(Builder.getContext()));
1219 CmpInst::Predicate P;
1220
1221 if (eq->sign == 0)
1222 P = ICmpInst::ICMP_EQ;
1223 else if (eq->sign > 0)
1224 P = ICmpInst::ICMP_SGE;
1225 else
1226 P = ICmpInst::ICMP_SLE;
1227
1228 return Builder.CreateICmp(P, LHS, RHS);
1229 }
1230
1231 void codegen(const clast_guard *g) {
1232 Function *F = Builder.GetInsertBlock()->getParent();
1233 LLVMContext &Context = F->getContext();
1234 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1235 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1236 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1237 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1238
1239 Value *Predicate = codegen(&(g->eq[0]));
1240
1241 for (int i = 1; i < g->n; ++i) {
1242 Value *TmpPredicate = codegen(&(g->eq[i]));
1243 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1244 }
1245
1246 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1247 Builder.SetInsertPoint(ThenBB);
1248
1249 codegen(g->then);
1250
1251 Builder.CreateBr(MergeBB);
1252 Builder.SetInsertPoint(MergeBB);
1253 }
1254
1255 void codegen(const clast_stmt *stmt) {
1256 if (CLAST_STMT_IS_A(stmt, stmt_root))
1257 assert(false && "No second root statement expected");
1258 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1259 codegen((const clast_assignment *)stmt);
1260 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1261 codegen((const clast_user_stmt *)stmt);
1262 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1263 codegen((const clast_block *)stmt);
1264 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1265 codegen((const clast_for *)stmt);
1266 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1267 codegen((const clast_guard *)stmt);
1268
1269 if (stmt->next)
1270 codegen(stmt->next);
1271 }
1272
1273 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001274 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001275
1276 // Create an instruction that specifies the location where the parameters
1277 // are expanded.
1278 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1279 Builder.getInt16Ty(), false, "insertInst",
1280 Builder.GetInsertBlock());
1281
1282 int i = 0;
1283 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1284 PI != PE; ++PI) {
1285 assert(i < names->nb_parameters && "Not enough parameter names");
1286
1287 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001288 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001289
1290 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1291 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1292 (*clastVars)[names->parameters[i]] = V;
1293
1294 ++i;
1295 }
1296 }
1297
1298 public:
1299 void codegen(const clast_root *r) {
1300 clastVars = new CharMapT();
1301 addParameters(r->names);
1302 ExpGen.setIVS(clastVars);
1303
1304 parallelCodeGeneration = false;
1305
1306 const clast_stmt *stmt = (const clast_stmt*) r;
1307 if (stmt->next)
1308 codegen(stmt->next);
1309
1310 delete clastVars;
1311 }
1312
1313 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001314 ScopDetection *sd, Dependences *dp, TargetData *td,
1315 IRBuilder<> &B) :
1316 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1317 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001318
1319};
1320}
1321
1322namespace {
1323class CodeGeneration : public ScopPass {
1324 Region *region;
1325 Scop *S;
1326 DominatorTree *DT;
1327 ScalarEvolution *SE;
1328 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001329 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001330 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001331
1332 std::vector<std::string> parallelLoops;
1333
1334 public:
1335 static char ID;
1336
1337 CodeGeneration() : ScopPass(ID) {}
1338
Tobias Grosser75805372011-04-29 06:27:02 +00001339 // Adding prototypes required if OpenMP is enabled.
1340 void addOpenMPDefinitions(IRBuilder<> &Builder)
1341 {
1342 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1343 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001344 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001345
1346 if (!M->getFunction("GOMP_parallel_end")) {
1347 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1348 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1349 }
1350
1351 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1352 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001353 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001354 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1355 false);
1356 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1357
Tobias Grosser851b96e2011-07-12 12:42:54 +00001358 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001359 args.push_back(FnPtrTy);
1360 args.push_back(Builder.getInt8PtrTy());
1361 args.push_back(Builder.getInt32Ty());
1362 args.push_back(intPtrTy);
1363 args.push_back(intPtrTy);
1364 args.push_back(intPtrTy);
1365
1366 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1367 Function::Create(type, Function::ExternalLinkage,
1368 "GOMP_parallel_loop_runtime_start", M);
1369 }
1370
1371 if (!M->getFunction("GOMP_loop_runtime_next")) {
1372 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1373
Tobias Grosser851b96e2011-07-12 12:42:54 +00001374 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001375 args.push_back(intLongPtrTy);
1376 args.push_back(intLongPtrTy);
1377
1378 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1379 Function::Create(type, Function::ExternalLinkage,
1380 "GOMP_loop_runtime_next", M);
1381 }
1382
1383 if (!M->getFunction("GOMP_loop_end_nowait")) {
1384 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001385 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001386 Function::Create(FT, Function::ExternalLinkage,
1387 "GOMP_loop_end_nowait", M);
1388 }
1389 }
1390
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001391 // Split the entry edge of the region and generate a new basic block on this
1392 // edge. This function also updates ScopInfo and RegionInfo.
1393 //
1394 // @param region The region where the entry edge will be splitted.
1395 BasicBlock *splitEdgeAdvanced(Region *region) {
1396 BasicBlock *newBlock;
1397 BasicBlock *splitBlock;
1398
1399 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1400
1401 if (DT->dominates(region->getEntry(), newBlock)) {
1402 // Update ScopInfo.
1403 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1404 if ((*SI)->getBasicBlock() == newBlock) {
1405 (*SI)->setBasicBlock(newBlock);
1406 break;
1407 }
1408
1409 // Update RegionInfo.
1410 splitBlock = region->getEntry();
1411 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001412 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001413 } else {
1414 RI->setRegionFor(newBlock, region->getParent());
1415 splitBlock = newBlock;
1416 }
1417
1418 return splitBlock;
1419 }
1420
1421 // Create a split block that branches either to the old code or to a new basic
1422 // block where the new code can be inserted.
1423 //
1424 // @param builder A builder that will be set to point to a basic block, where
1425 // the new code can be generated.
1426 // @return The split basic block.
1427 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1428 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1429
1430 splitBlock->setName("polly.enterScop");
1431
1432 Function *function = splitBlock->getParent();
1433 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1434 "polly.start", function);
1435 splitBlock->getTerminator()->eraseFromParent();
1436 builder->SetInsertPoint(splitBlock);
1437 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1438 DT->addNewBlock(startBlock, splitBlock);
1439
1440 // Start code generation here.
1441 builder->SetInsertPoint(startBlock);
1442 return splitBlock;
1443 }
1444
1445 // Merge the control flow of the newly generated code with the existing code.
1446 //
1447 // @param splitBlock The basic block where the control flow was split between
1448 // old and new version of the Scop.
1449 // @param builder An IRBuilder that points to the last instruction of the
1450 // newly generated code.
1451 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1452 BasicBlock *mergeBlock;
1453 Region *R = region;
1454
1455 if (R->getExit()->getSinglePredecessor())
1456 // No splitEdge required. A block with a single predecessor cannot have
1457 // PHI nodes that would complicate life.
1458 mergeBlock = R->getExit();
1459 else {
1460 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1461 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1462 // one predecessor. Hence, mergeBlock is always a newly generated block.
1463 mergeBlock->setName("polly.finalMerge");
1464 R->replaceExit(mergeBlock);
1465 }
1466
1467 builder->CreateBr(mergeBlock);
1468
1469 if (DT->dominates(splitBlock, mergeBlock))
1470 DT->changeImmediateDominator(mergeBlock, splitBlock);
1471 }
1472
Tobias Grosser75805372011-04-29 06:27:02 +00001473 bool runOnScop(Scop &scop) {
1474 S = &scop;
1475 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001476 DT = &getAnalysis<DominatorTree>();
1477 Dependences *DP = &getAnalysis<Dependences>();
1478 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001479 SD = &getAnalysis<ScopDetection>();
1480 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001481 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001482
1483 parallelLoops.clear();
1484
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001485 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001486
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001487 // In the CFG and we generate next to original code of the Scop the
1488 // optimized version. Both the new and the original version of the code
1489 // remain in the CFG. A branch statement decides which version is executed.
1490 // At the moment, we always execute the newly generated version (the old one
1491 // is dead code eliminated by the cleanup passes). Later we may decide to
1492 // execute the new version only under certain conditions. This will be the
1493 // case if we support constructs for which we cannot prove all assumptions
1494 // at compile time.
1495 //
1496 // Before transformation:
1497 //
1498 // bb0
1499 // |
1500 // orig_scop
1501 // |
1502 // bb1
1503 //
1504 // After transformation:
1505 // bb0
1506 // |
1507 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001508 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001509 // | startBlock
1510 // | |
1511 // orig_scop new_scop
1512 // \ /
1513 // \ /
1514 // bb1 (joinBlock)
1515 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001516
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001517 // The builder will be set to startBlock.
1518 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001519
1520 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001521 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001522
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001523 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001524 CloogInfo &C = getAnalysis<CloogInfo>();
1525 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001526
Tobias Grosser75805372011-04-29 06:27:02 +00001527 parallelLoops.insert(parallelLoops.begin(),
1528 CodeGen.getParallelLoops().begin(),
1529 CodeGen.getParallelLoops().end());
1530
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001531 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001532
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001533 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001534 }
1535
1536 virtual void printScop(raw_ostream &OS) const {
1537 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1538 PE = parallelLoops.end(); PI != PE; ++PI)
1539 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1540 }
1541
1542 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1543 AU.addRequired<CloogInfo>();
1544 AU.addRequired<Dependences>();
1545 AU.addRequired<DominatorTree>();
1546 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001547 AU.addRequired<RegionInfo>();
1548 AU.addRequired<ScopDetection>();
1549 AU.addRequired<ScopInfo>();
1550 AU.addRequired<TargetData>();
1551
1552 AU.addPreserved<CloogInfo>();
1553 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001554
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001555 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001556 AU.addPreserved<LoopInfo>();
1557 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001558 AU.addPreserved<ScopDetection>();
1559 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001560
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001561 // FIXME: We do not yet add regions for the newly generated code to the
1562 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001563 AU.addPreserved<RegionInfo>();
1564 AU.addPreserved<TempScopInfo>();
1565 AU.addPreserved<ScopInfo>();
1566 AU.addPreservedID(IndependentBlocksID);
1567 }
1568};
1569}
1570
1571char CodeGeneration::ID = 1;
1572
1573static RegisterPass<CodeGeneration>
1574Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1575
1576Pass* polly::createCodeGenerationPass() {
1577 return new CodeGeneration();
1578}