blob: 430df1363a301811249a931bb367678c675289dc [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ CodeGeneration.cpp - Code generate the Scops. -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The CodeGeneration pass takes a Scop created by ScopInfo and translates it
11// back to LLVM-IR using Cloog.
12//
13// The Scop describes the high level memory behaviour of a control flow region.
14// Transformation passes can update the schedule (execution order) of statements
15// in the Scop. Cloog is used to generate an abstract syntax tree (clast) that
16// reflects the updated execution order. This clast is used to create new
17// LLVM-IR that is computational equivalent to the original control flow region,
18// but executes its code in the new execution order defined by the changed
19// scattering.
20//
21//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "polly-codegen"
24
25#include "polly/LinkAllPasses.h"
26#include "polly/Support/GICHelper.h"
27#include "polly/Support/ScopHelper.h"
28#include "polly/Cloog.h"
Tobias Grosser67707b72011-10-23 20:59:40 +000029#include "polly/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/Dependences.h"
31#include "polly/ScopInfo.h"
32#include "polly/TempScopInfo.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/IRBuilder.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser8c4cfc322011-05-14 19:01:49 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Module.h"
41#include "llvm/ADT/SetVector.h"
42
43#define CLOOG_INT_GMP 1
44#include "cloog/cloog.h"
45#include "cloog/isl/cloog.h"
46
47#include <vector>
48#include <utility>
49
50using namespace polly;
51using namespace llvm;
52
53struct isl_set;
54
55namespace polly {
56
Tobias Grosser67707b72011-10-23 20:59:40 +000057bool EnablePollyVector;
58
59static cl::opt<bool, true>
Tobias Grosser75805372011-04-29 06:27:02 +000060Vector("enable-polly-vector",
61 cl::desc("Enable polly vector code generation"), cl::Hidden,
Tobias Grosser67707b72011-10-23 20:59:40 +000062 cl::location(EnablePollyVector), cl::init(false));
Tobias Grosser75805372011-04-29 06:27:02 +000063
64static cl::opt<bool>
65OpenMP("enable-polly-openmp",
66 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
67 cl::value_desc("OpenMP code generation enabled if true"),
68 cl::init(false));
69
70static cl::opt<bool>
71AtLeastOnce("enable-polly-atLeastOnce",
72 cl::desc("Give polly the hint, that every loop is executed at least"
73 "once"), cl::Hidden,
74 cl::value_desc("OpenMP code generation enabled if true"),
75 cl::init(false));
76
77static cl::opt<bool>
78Aligned("enable-polly-aligned",
79 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
80 cl::value_desc("OpenMP code generation enabled if true"),
81 cl::init(false));
82
Tobias Grosser75805372011-04-29 06:27:02 +000083typedef DenseMap<const Value*, Value*> ValueMapT;
84typedef DenseMap<const char*, Value*> CharMapT;
85typedef std::vector<ValueMapT> VectorValueMapT;
86
87// Create a new loop.
88//
89// @param Builder The builder used to create the loop. It also defines the
90// place where to create the loop.
91// @param UB The upper bound of the loop iv.
92// @param Stride The number by which the loop iv is incremented after every
93// iteration.
94static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
95 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
96 DominatorTree *DT) {
97 Function *F = Builder->GetInsertBlock()->getParent();
98 LLVMContext &Context = F->getContext();
99
100 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
101 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
102 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
103 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
104
105 Builder->CreateBr(HeaderBB);
106 DT->addNewBlock(HeaderBB, PreheaderBB);
107
108 Builder->SetInsertPoint(BodyBB);
109
110 Builder->SetInsertPoint(HeaderBB);
111
112 // Use the type of upper and lower bound.
113 assert(LB->getType() == UB->getType()
114 && "Different types for upper and lower bound.");
115
Tobias Grosser55927aa2011-07-18 09:53:32 +0000116 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000117 assert(LoopIVType && "UB is not integer?");
118
119 // IV
120 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
121 IV->addIncoming(LB, PreheaderBB);
122
123 // IV increment.
124 Value *StrideValue = ConstantInt::get(LoopIVType,
125 Stride.zext(LoopIVType->getBitWidth()));
126 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
127
128 // Exit condition.
129 if (AtLeastOnce) { // At least on iteration.
130 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
131 Value *CMP = Builder->CreateICmpEQ(IV, UB);
132 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
133 } else { // Maybe not executed at all.
134 Value *CMP = Builder->CreateICmpSLE(IV, UB);
135 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
136 }
137 DT->addNewBlock(BodyBB, HeaderBB);
138 DT->addNewBlock(AfterBB, HeaderBB);
139
140 Builder->SetInsertPoint(BodyBB);
141}
142
143class BlockGenerator {
144 IRBuilder<> &Builder;
145 ValueMapT &VMap;
146 VectorValueMapT &ValueMaps;
147 Scop &S;
148 ScopStmt &statement;
149 isl_set *scatteringDomain;
150
151public:
152 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
153 ScopStmt &Stmt, isl_set *domain)
154 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
155 statement(Stmt), scatteringDomain(domain) {}
156
157 const Region &getRegion() {
158 return S.getRegion();
159 }
160
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000161 Value *makeVectorOperand(Value *operand, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000162 if (operand->getType()->isVectorTy())
163 return operand;
164
165 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
166 Value *vector = UndefValue::get(vectorType);
167 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
168
169 std::vector<Constant*> splat;
170
171 for (int i = 0; i < vectorWidth; i++)
172 splat.push_back (Builder.getInt32(0));
173
174 Constant *splatVector = ConstantVector::get(splat);
175
176 return Builder.CreateShuffleVector(vector, vector, splatVector);
177 }
178
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000179 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000180 ValueMapT *VectorMap = 0) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000181 const Instruction *OpInst = dyn_cast<Instruction>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000182
183 if (!OpInst)
Raghesh Aloor490c5982011-08-08 08:34:16 +0000184 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000185
Raghesh Aloor490c5982011-08-08 08:34:16 +0000186 if (VectorMap && VectorMap->count(oldOperand))
187 return (*VectorMap)[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000188
189 // IVS and Parameters.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000190 if (VMap.count(oldOperand)) {
191 Value *NewOperand = VMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000192
193 // Insert a cast if types are different
Raghesh Aloor490c5982011-08-08 08:34:16 +0000194 if (oldOperand->getType()->getScalarSizeInBits()
Tobias Grosser75805372011-04-29 06:27:02 +0000195 < NewOperand->getType()->getScalarSizeInBits())
196 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000197 oldOperand->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000198
199 return NewOperand;
200 }
201
202 // Instructions calculated in the current BB.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000203 if (BBMap.count(oldOperand)) {
204 return BBMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000205 }
206
207 // Ignore instructions that are referencing ops in the old BB. These
208 // instructions are unused. They where replace by new ones during
209 // createIndependentBlocks().
210 if (getRegion().contains(OpInst->getParent()))
211 return NULL;
212
Raghesh Aloor490c5982011-08-08 08:34:16 +0000213 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000214 }
215
Tobias Grosser55927aa2011-07-18 09:53:32 +0000216 Type *getVectorPtrTy(const Value *V, int vectorWidth) {
217 PointerType *pointerType = dyn_cast<PointerType>(V->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000218 assert(pointerType && "PointerType expected");
219
Tobias Grosser55927aa2011-07-18 09:53:32 +0000220 Type *scalarType = pointerType->getElementType();
Tobias Grosser75805372011-04-29 06:27:02 +0000221 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
222
223 return PointerType::getUnqual(vectorType);
224 }
225
226 /// @brief Load a vector from a set of adjacent scalars
227 ///
228 /// In case a set of scalars is known to be next to each other in memory,
229 /// create a vector load that loads those scalars
230 ///
231 /// %vector_ptr= bitcast double* %p to <4 x double>*
232 /// %vec_full = load <4 x double>* %vector_ptr
233 ///
234 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
235 int size) {
236 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000237 Type *vectorPtrType = getVectorPtrTy(pointer, size);
Tobias Grosser75805372011-04-29 06:27:02 +0000238 Value *newPointer = getOperand(pointer, BBMap);
239 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
240 "vector_ptr");
241 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000242 load->getName() + "_p_vec_full");
Tobias Grosser75805372011-04-29 06:27:02 +0000243 if (!Aligned)
244 VecLoad->setAlignment(8);
245
246 return VecLoad;
247 }
248
249 /// @brief Load a vector initialized from a single scalar in memory
250 ///
251 /// In case all elements of a vector are initialized to the same
252 /// scalar value, this value is loaded and shuffeled into all elements
253 /// of the vector.
254 ///
255 /// %splat_one = load <1 x double>* %p
256 /// %splat = shufflevector <1 x double> %splat_one, <1 x
257 /// double> %splat_one, <4 x i32> zeroinitializer
258 ///
259 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
260 int size) {
261 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000262 Type *vectorPtrType = getVectorPtrTy(pointer, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000263 Value *newPointer = getOperand(pointer, BBMap);
264 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000265 load->getName() + "_p_vec_p");
Tobias Grosser75805372011-04-29 06:27:02 +0000266 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000267 load->getName() + "_p_splat_one");
Tobias Grosser75805372011-04-29 06:27:02 +0000268
269 if (!Aligned)
270 scalarLoad->setAlignment(8);
271
272 std::vector<Constant*> splat;
273
274 for (int i = 0; i < size; i++)
275 splat.push_back (Builder.getInt32(0));
276
277 Constant *splatVector = ConstantVector::get(splat);
278
279 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
280 splatVector,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000281 load->getName()
Tobias Grosser75805372011-04-29 06:27:02 +0000282 + "_p_splat");
283 return vectorLoad;
284 }
285
286 /// @Load a vector from scalars distributed in memory
287 ///
288 /// In case some scalars a distributed randomly in memory. Create a vector
289 /// by loading each scalar and by inserting one after the other into the
290 /// vector.
291 ///
292 /// %scalar_1= load double* %p_1
293 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
294 /// %scalar 2 = load double* %p_2
295 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
296 ///
297 Value *generateUnknownStrideLoad(const LoadInst *load,
298 VectorValueMapT &scalarMaps,
299 int size) {
300 const Value *pointer = load->getPointerOperand();
301 VectorType *vectorType = VectorType::get(
302 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
303
304 Value *vector = UndefValue::get(vectorType);
305
306 for (int i = 0; i < size; i++) {
307 Value *newPointer = getOperand(pointer, scalarMaps[i]);
308 Value *scalarLoad = Builder.CreateLoad(newPointer,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000309 load->getName() + "_p_scalar_");
Tobias Grosser75805372011-04-29 06:27:02 +0000310 vector = Builder.CreateInsertElement(vector, scalarLoad,
311 Builder.getInt32(i),
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000312 load->getName() + "_p_vec_");
Tobias Grosser75805372011-04-29 06:27:02 +0000313 }
314
315 return vector;
316 }
317
Raghesh Aloor129e8672011-08-15 02:33:39 +0000318 /// @brief Get the memory access offset to be added to the base address
319 std::vector <Value*> getMemoryAccessIndex(isl_map *accessRelation,
320 Value *baseAddr) {
321 isl_int offsetMPZ;
322 isl_int_init(offsetMPZ);
323
324 assert((isl_map_dim(accessRelation, isl_dim_out) == 1)
325 && "Only single dimensional access functions supported");
326
327 if (isl_map_plain_is_fixed(accessRelation, isl_dim_out,
328 0, &offsetMPZ) == -1)
329 errs() << "Only fixed value access functions supported\n";
330
331 // Convert the offset from MPZ to Value*.
332 APInt offset = APInt_from_MPZ(offsetMPZ);
333 Value *offsetValue = ConstantInt::get(Builder.getContext(), offset);
334 PointerType *baseAddrType = dyn_cast<PointerType>(baseAddr->getType());
335 Type *arrayType = baseAddrType->getElementType();
336 Type *arrayElementType = dyn_cast<ArrayType>(arrayType)->getElementType();
337 offsetValue = Builder.CreateSExtOrBitCast(offsetValue, arrayElementType);
338
339 std::vector<Value*> indexArray;
340 Value *nullValue = Constant::getNullValue(arrayElementType);
341 indexArray.push_back(nullValue);
342 indexArray.push_back(offsetValue);
343
344 isl_int_clear(offsetMPZ);
345 return indexArray;
346 }
347
Raghesh Aloor62b13122011-08-03 17:02:50 +0000348 /// @brief Get the new operand address according to the changed access in
349 /// JSCOP file.
350 Value *getNewAccessOperand(isl_map *newAccessRelation, Value *baseAddr,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000351 const Value *oldOperand, ValueMapT &BBMap) {
Raghesh Aloor129e8672011-08-15 02:33:39 +0000352 std::vector<Value*> indexArray = getMemoryAccessIndex(newAccessRelation,
353 baseAddr);
354 Value *newOperand = Builder.CreateGEP(baseAddr, indexArray,
355 "p_newarrayidx_");
Raghesh Aloor62b13122011-08-03 17:02:50 +0000356 return newOperand;
357 }
358
359 /// @brief Generate the operand address
360 Value *generateLocationAccessed(const Instruction *Inst,
361 const Value *pointer, ValueMapT &BBMap ) {
Tobias Grosser5d453812011-10-06 00:04:11 +0000362 MemoryAccess &Access = statement.getAccessFor(Inst);
363 isl_map *CurrentAccessRelation = Access.getAccessRelation();
364 isl_map *NewAccessRelation = Access.getNewAccessRelation();
Raghesh Aloor129e8672011-08-15 02:33:39 +0000365
Tobias Grosser5d453812011-10-06 00:04:11 +0000366 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
Tobias Grosserf5338802011-10-06 00:03:35 +0000367 && "Current and new access function use different spaces");
Raghesh Aloor129e8672011-08-15 02:33:39 +0000368
Tobias Grosser5d453812011-10-06 00:04:11 +0000369 Value *NewPointer;
370
371 if (!NewAccessRelation) {
372 NewPointer = getOperand(pointer, BBMap);
373 } else {
374 Value *BaseAddr = const_cast<Value*>(Access.getBaseAddr());
375 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddr, pointer,
376 BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000377 }
Raghesh Aloore75e9862011-08-11 08:44:56 +0000378
Tobias Grosser5d453812011-10-06 00:04:11 +0000379 isl_map_free(CurrentAccessRelation);
380 isl_map_free(NewAccessRelation);
381 return NewPointer;
Raghesh Aloor62b13122011-08-03 17:02:50 +0000382 }
383
Tobias Grosser75805372011-04-29 06:27:02 +0000384 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
385 const Value *pointer = load->getPointerOperand();
Raghesh Aloor62b13122011-08-03 17:02:50 +0000386 const Instruction *Inst = dyn_cast<Instruction>(load);
387 Value *newPointer = generateLocationAccessed(Inst, pointer, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000388 Value *scalarLoad = Builder.CreateLoad(newPointer,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000389 load->getName() + "_p_scalar_");
Tobias Grosser75805372011-04-29 06:27:02 +0000390 return scalarLoad;
391 }
392
393 /// @brief Load a value (or several values as a vector) from memory.
394 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
395 VectorValueMapT &scalarMaps, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000396 if (scalarMaps.size() == 1) {
397 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
398 return;
399 }
400
401 Value *newLoad;
402
403 MemoryAccess &Access = statement.getAccessFor(load);
404
405 assert(scatteringDomain && "No scattering domain available");
406
407 if (Access.isStrideZero(scatteringDomain))
408 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
409 else if (Access.isStrideOne(scatteringDomain))
410 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
411 else
412 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
413
414 vectorMap[load] = newLoad;
415 }
416
Tobias Grosserc9215152011-09-04 11:45:52 +0000417 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
418 ValueMapT &VectorMap, int VectorDimension,
419 int VectorWidth) {
420 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
421 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
422
423 if (const CastInst *Cast = dyn_cast<CastInst>(Inst)) {
424 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
425 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand,
426 DestType);
427 } else
428 llvm_unreachable("Can not generate vector code for instruction");
429 return;
430 }
431
Tobias Grosser09c57102011-09-04 11:45:29 +0000432 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser8b00a512011-09-04 11:45:45 +0000433 ValueMapT &vectorMap, int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000434 Value *opZero = Inst->getOperand(0);
435 Value *opOne = Inst->getOperand(1);
436
Tobias Grosser09c57102011-09-04 11:45:29 +0000437 Value *newOpZero, *newOpOne;
438 newOpZero = getOperand(opZero, BBMap, &vectorMap);
439 newOpOne = getOperand(opOne, BBMap, &vectorMap);
440
Tobias Grosser7551c302011-09-04 11:45:41 +0000441 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
442 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000443
444 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
Tobias Grosser7551c302011-09-04 11:45:41 +0000445 newOpOne,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000446 Inst->getName() + "p_vec");
Tobias Grosser7551c302011-09-04 11:45:41 +0000447 vectorMap[Inst] = newInst;
Tobias Grosser09c57102011-09-04 11:45:29 +0000448
449 return;
450 }
451
452 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000453 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
454 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000455 // In vector mode we only generate a store for the first dimension.
456 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000457 return;
458
Tobias Grosser09c57102011-09-04 11:45:29 +0000459 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000460
Tobias Grosser09c57102011-09-04 11:45:29 +0000461 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Tobias Grosser09c57102011-09-04 11:45:29 +0000463 const Value *pointer = store->getPointerOperand();
464 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000465
Tobias Grosser09c57102011-09-04 11:45:29 +0000466 if (Access.isStrideOne(scatteringDomain)) {
467 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
468 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000469
Tobias Grosser09c57102011-09-04 11:45:29 +0000470 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
471 "vector_ptr");
472 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000473
Tobias Grosser09c57102011-09-04 11:45:29 +0000474 if (!Aligned)
475 Store->setAlignment(8);
476 } else {
477 for (unsigned i = 0; i < scalarMaps.size(); i++) {
478 Value *scalar = Builder.CreateExtractElement(vector,
479 Builder.getInt32(i));
480 Value *newPointer = getOperand(pointer, scalarMaps[i]);
481 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000482 }
483 }
484
Tobias Grosser09c57102011-09-04 11:45:29 +0000485 return;
486 }
487
Tobias Grosser7551c302011-09-04 11:45:41 +0000488 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000489 Instruction *NewInst = Inst->clone();
490
Tobias Grosser75805372011-04-29 06:27:02 +0000491 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000492 for (Instruction::const_op_iterator OI = Inst->op_begin(),
493 OE = Inst->op_end(); OI != OE; ++OI) {
494 Value *OldOperand = *OI;
495 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000496
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000497 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000498 assert(!isa<StoreInst>(NewInst)
499 && "Store instructions are always needed!");
500 delete NewInst;
501 return;
502 }
503
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000504 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000505 }
506
507 Builder.Insert(NewInst);
508 BBMap[Inst] = NewInst;
509
510 if (!NewInst->getType()->isVoidTy())
511 NewInst->setName("p_" + Inst->getName());
512 }
513
Tobias Grosser7551c302011-09-04 11:45:41 +0000514 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap) {
515 for (Instruction::const_op_iterator OI = Inst->op_begin(),
516 OE = Inst->op_end(); OI != OE; ++OI)
517 if (VectorMap.count(*OI))
518 return true;
519 return false;
Tobias Grosser09c57102011-09-04 11:45:29 +0000520 }
521
Tobias Grosser75805372011-04-29 06:27:02 +0000522 int getVectorSize() {
523 return ValueMaps.size();
524 }
525
526 bool isVectorBlock() {
527 return getVectorSize() > 1;
528 }
529
Tobias Grosser7551c302011-09-04 11:45:41 +0000530 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
531 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
532 int vectorDimension, int vectorWidth) {
533 // Terminator instructions control the control flow. They are explicitally
534 // expressed in the clast and do not need to be copied.
535 if (Inst->isTerminator())
536 return;
537
538 if (isVectorBlock()) {
539 // If this instruction is already in the vectorMap, a vector instruction
540 // was already issued, that calculates the values of all dimensions. No
541 // need to create any more instructions.
542 if (vectorMap.count(Inst))
543 return;
544 }
545
546 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
547 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
548 return;
549 }
550
551 if (isVectorBlock() && hasVectorOperands(Inst, vectorMap)) {
Tobias Grosserc9215152011-09-04 11:45:52 +0000552 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
553 copyUnaryInst(UnaryInst, BBMap, vectorMap, vectorDimension,
554 vectorWidth);
555 else if
556 (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosser8b00a512011-09-04 11:45:45 +0000557 copyBinInst(binaryInst, BBMap, vectorMap, vectorDimension, vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000558 else if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
559 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
560 vectorWidth);
561 else
562 llvm_unreachable("Cannot issue vector code for this instruction");
563
564 return;
565 }
566
567 copyInstScalar(Inst, BBMap);
568 }
Tobias Grosser75805372011-04-29 06:27:02 +0000569 // Insert a copy of a basic block in the newly generated code.
570 //
571 // @param Builder The builder used to insert the code. It also specifies
572 // where to insert the code.
573 // @param BB The basic block to copy
574 // @param VMap A map returning for any old value its new equivalent. This
575 // is used to update the operands of the statements.
576 // For new statements a relation old->new is inserted in this
577 // map.
578 void copyBB(BasicBlock *BB, DominatorTree *DT) {
579 Function *F = Builder.GetInsertBlock()->getParent();
580 LLVMContext &Context = F->getContext();
581 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000582 "polly." + BB->getName() + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000583 F);
584 Builder.CreateBr(CopyBB);
585 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
586 Builder.SetInsertPoint(CopyBB);
587
588 // Create two maps that store the mapping from the original instructions of
589 // the old basic block to their copies in the new basic block. Those maps
590 // are basic block local.
591 //
592 // As vector code generation is supported there is one map for scalar values
593 // and one for vector values.
594 //
595 // In case we just do scalar code generation, the vectorMap is not used and
596 // the scalarMap has just one dimension, which contains the mapping.
597 //
598 // In case vector code generation is done, an instruction may either appear
599 // in the vector map once (as it is calculating >vectorwidth< values at a
600 // time. Or (if the values are calculated using scalar operations), it
601 // appears once in every dimension of the scalarMap.
602 VectorValueMapT scalarBlockMap(getVectorSize());
603 ValueMapT vectorBlockMap;
604
605 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
606 II != IE; ++II)
607 for (int i = 0; i < getVectorSize(); i++) {
608 if (isVectorBlock())
609 VMap = ValueMaps[i];
610
611 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
612 scalarBlockMap, i, getVectorSize());
613 }
614 }
615};
616
617/// Class to generate LLVM-IR that calculates the value of a clast_expr.
618class ClastExpCodeGen {
619 IRBuilder<> &Builder;
620 const CharMapT *IVS;
621
Tobias Grosser55927aa2011-07-18 09:53:32 +0000622 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000623 CharMapT::const_iterator I = IVS->find(e->name);
624
625 if (I != IVS->end())
626 return Builder.CreateSExtOrBitCast(I->second, Ty);
627 else
628 llvm_unreachable("Clast name not found");
629 }
630
Tobias Grosser55927aa2011-07-18 09:53:32 +0000631 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000632 APInt a = APInt_from_MPZ(e->val);
633
634 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
635 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
636
637 if (e->var) {
638 Value *var = codegen(e->var, Ty);
639 return Builder.CreateMul(ConstOne, var);
640 }
641
642 return ConstOne;
643 }
644
Tobias Grosser55927aa2011-07-18 09:53:32 +0000645 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000646 Value *LHS = codegen(e->LHS, Ty);
647
648 APInt RHS_AP = APInt_from_MPZ(e->RHS);
649
650 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
651 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
652
653 switch (e->type) {
654 case clast_bin_mod:
655 return Builder.CreateSRem(LHS, RHS);
656 case clast_bin_fdiv:
657 {
658 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / 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.CreateSub(LHS, RHS);
664 Value *Sum2 = Builder.CreateAdd(Sum1, One);
665 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
666 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
667 return Builder.CreateSDiv(Dividend, RHS);
668 }
669 case clast_bin_cdiv:
670 {
671 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
672 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
673 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
674 One = Builder.CreateZExtOrBitCast(One, Ty);
675 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
676 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
677 Value *Sum2 = Builder.CreateSub(Sum1, One);
678 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
679 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
680 return Builder.CreateSDiv(Dividend, RHS);
681 }
682 case clast_bin_div:
683 return Builder.CreateSDiv(LHS, RHS);
684 default:
685 llvm_unreachable("Unknown clast binary expression type");
686 };
687 }
688
Tobias Grosser55927aa2011-07-18 09:53:32 +0000689 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000690 assert(( r->type == clast_red_min
691 || r->type == clast_red_max
692 || r->type == clast_red_sum)
693 && "Clast reduction type not supported");
694 Value *old = codegen(r->elts[0], Ty);
695
696 for (int i=1; i < r->n; ++i) {
697 Value *exprValue = codegen(r->elts[i], Ty);
698
699 switch (r->type) {
700 case clast_red_min:
701 {
702 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
703 old = Builder.CreateSelect(cmp, old, exprValue);
704 break;
705 }
706 case clast_red_max:
707 {
708 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
709 old = Builder.CreateSelect(cmp, old, exprValue);
710 break;
711 }
712 case clast_red_sum:
713 old = Builder.CreateAdd(old, exprValue);
714 break;
715 default:
716 llvm_unreachable("Clast unknown reduction type");
717 }
718 }
719
720 return old;
721 }
722
723public:
724
725 // A generator for clast expressions.
726 //
727 // @param B The IRBuilder that defines where the code to calculate the
728 // clast expressions should be inserted.
729 // @param IVMAP A Map that translates strings describing the induction
730 // variables to the Values* that represent these variables
731 // on the LLVM side.
732 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
733
734 // Generates code to calculate a given clast expression.
735 //
736 // @param e The expression to calculate.
737 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000738 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000739 switch(e->type) {
740 case clast_expr_name:
741 return codegen((const clast_name *)e, Ty);
742 case clast_expr_term:
743 return codegen((const clast_term *)e, Ty);
744 case clast_expr_bin:
745 return codegen((const clast_binary *)e, Ty);
746 case clast_expr_red:
747 return codegen((const clast_reduction *)e, Ty);
748 default:
749 llvm_unreachable("Unknown clast expression!");
750 }
751 }
752
753 // @brief Reset the CharMap.
754 //
755 // This function is called to reset the CharMap to new one, while generating
756 // OpenMP code.
757 void setIVS(CharMapT *IVSNew) {
758 IVS = IVSNew;
759 }
760
761};
762
763class ClastStmtCodeGen {
764 // The Scop we code generate.
765 Scop *S;
766 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000767 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000768 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000769 Dependences *DP;
770 TargetData *TD;
771
772 // The Builder specifies the current location to code generate at.
773 IRBuilder<> &Builder;
774
775 // Map the Values from the old code to their counterparts in the new code.
776 ValueMapT ValueMap;
777
778 // clastVars maps from the textual representation of a clast variable to its
779 // current *Value. clast variables are scheduling variables, original
780 // induction variables or parameters. They are used either in loop bounds or
781 // to define the statement instance that is executed.
782 //
783 // for (s = 0; s < n + 3; ++i)
784 // for (t = s; t < m; ++j)
785 // Stmt(i = s + 3 * m, j = t);
786 //
787 // {s,t,i,j,n,m} is the set of clast variables in this clast.
788 CharMapT *clastVars;
789
790 // Codegenerator for clast expressions.
791 ClastExpCodeGen ExpGen;
792
793 // Do we currently generate parallel code?
794 bool parallelCodeGeneration;
795
796 std::vector<std::string> parallelLoops;
797
798public:
799
800 const std::vector<std::string> &getParallelLoops() {
801 return parallelLoops;
802 }
803
804 protected:
805 void codegen(const clast_assignment *a) {
806 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
807 TD->getIntPtrType(Builder.getContext()));
808 }
809
810 void codegen(const clast_assignment *a, ScopStmt *Statement,
811 unsigned Dimension, int vectorDim,
812 std::vector<ValueMapT> *VectorVMap = 0) {
813 Value *RHS = ExpGen.codegen(a->RHS,
814 TD->getIntPtrType(Builder.getContext()));
815
816 assert(!a->LHS && "Statement assignments do not have left hand side");
817 const PHINode *PN;
818 PN = Statement->getInductionVariableForDimension(Dimension);
819 const Value *V = PN;
820
Tobias Grosser75805372011-04-29 06:27:02 +0000821 if (VectorVMap)
822 (*VectorVMap)[vectorDim][V] = RHS;
823
824 ValueMap[V] = RHS;
825 }
826
827 void codegenSubstitutions(const clast_stmt *Assignment,
828 ScopStmt *Statement, int vectorDim = 0,
829 std::vector<ValueMapT> *VectorVMap = 0) {
830 int Dimension = 0;
831
832 while (Assignment) {
833 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
834 && "Substitions are expected to be assignments");
835 codegen((const clast_assignment *)Assignment, Statement, Dimension,
836 vectorDim, VectorVMap);
837 Assignment = Assignment->next;
838 Dimension++;
839 }
840 }
841
842 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
843 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
844 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
845 BasicBlock *BB = Statement->getBasicBlock();
846
847 if (u->substitutions)
848 codegenSubstitutions(u->substitutions, Statement);
849
850 int vectorDimensions = IVS ? IVS->size() : 1;
851
852 VectorValueMapT VectorValueMap(vectorDimensions);
853
854 if (IVS) {
855 assert (u->substitutions && "Substitutions expected!");
856 int i = 0;
857 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
858 II != IE; ++II) {
859 (*clastVars)[iterator] = *II;
860 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
861 i++;
862 }
863 }
864
865 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
866 scatteringDomain);
867 Generator.copyBB(BB, DT);
868 }
869
870 void codegen(const clast_block *b) {
871 if (b->body)
872 codegen(b->body);
873 }
874
875 /// @brief Create a classical sequential loop.
876 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
877 Value *upperBound = 0) {
878 APInt Stride = APInt_from_MPZ(f->stride);
879 PHINode *IV;
880 Value *IncrementedIV;
881 BasicBlock *AfterBB;
882 // The value of lowerbound and upperbound will be supplied, if this
883 // function is called while generating OpenMP code. Otherwise get
884 // the values.
885 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
886 && "Either give both bounds or none");
887 if (lowerBound == 0 || upperBound == 0) {
888 lowerBound = ExpGen.codegen(f->LB,
889 TD->getIntPtrType(Builder.getContext()));
890 upperBound = ExpGen.codegen(f->UB,
891 TD->getIntPtrType(Builder.getContext()));
892 }
893 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
894 IncrementedIV, DT);
895
896 // Add loop iv to symbols.
897 (*clastVars)[f->iterator] = IV;
898
899 if (f->body)
900 codegen(f->body);
901
902 // Loop is finished, so remove its iv from the live symbols.
903 clastVars->erase(f->iterator);
904
905 BasicBlock *HeaderBB = *pred_begin(AfterBB);
906 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
907 Builder.CreateBr(HeaderBB);
908 IV->addIncoming(IncrementedIV, LastBodyBB);
909 Builder.SetInsertPoint(AfterBB);
910 }
911
Tobias Grosser75805372011-04-29 06:27:02 +0000912 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000913 Function *addOpenMPSubfunction(Module *M) {
Tobias Grosser75805372011-04-29 06:27:02 +0000914 Function *F = Builder.GetInsertBlock()->getParent();
Tobias Grosser851b96e2011-07-12 12:42:54 +0000915 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000916 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000917 Function *FN = Function::Create(FT, Function::InternalLinkage,
918 F->getName() + ".omp_subfn", M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000919 // Do not run any polly pass on the new function.
920 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000921
922 Function::arg_iterator AI = FN->arg_begin();
923 AI->setName("omp.userContext");
924
925 return FN;
926 }
927
928 /// @brief Add values to the OpenMP structure.
929 ///
930 /// Create the subfunction structure and add the values from the list.
931 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
932 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000933 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000934
935 // Create the structure.
936 for (unsigned i = 0; i < OMPDataVals.size(); i++)
937 structMembers.push_back(OMPDataVals[i]->getType());
938
Tobias Grosser75805372011-04-29 06:27:02 +0000939 StructType *structTy = StructType::get(Builder.getContext(),
940 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000941 // Store the values into the structure.
942 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
943 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
944 Value *storeAddr = Builder.CreateStructGEP(structData, i);
945 Builder.CreateStore(OMPDataVals[i], storeAddr);
946 }
947
948 return structData;
949 }
950
951 /// @brief Create OpenMP structure values.
952 ///
953 /// Create a list of values that has to be stored into the subfuncition
954 /// structure.
955 SetVector<Value*> createOpenMPStructValues() {
956 SetVector<Value*> OMPDataVals;
957
958 // Push the clast variables available in the clastVars.
959 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
960 I != E; I++)
961 OMPDataVals.insert(I->second);
962
963 // Push the base addresses of memory references.
964 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
965 ScopStmt *Stmt = *SI;
966 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
967 E = Stmt->memacc_end(); I != E; ++I) {
968 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
969 OMPDataVals.insert((BaseAddr));
970 }
971 }
972
973 return OMPDataVals;
974 }
975
976 /// @brief Extract the values from the subfunction parameter.
977 ///
978 /// Extract the values from the subfunction parameter and update the clast
979 /// variables to point to the new values.
980 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
981 SetVector<Value*> OMPDataVals,
982 Value *userContext) {
983 // Extract the clast variables.
984 unsigned i = 0;
985 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
986 I != E; I++) {
987 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
988 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
989 i++;
990 }
991
992 // Extract the base addresses of memory references.
993 for (unsigned j = i; j < OMPDataVals.size(); j++) {
994 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
995 Value *baseAddr = OMPDataVals[j];
996 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
997 }
998
999 }
1000
1001 /// @brief Add body to the subfunction.
1002 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1003 Value *structData,
1004 SetVector<Value*> OMPDataVals) {
1005 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1006 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001007 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001008
1009 // Store the previous basic block.
1010 BasicBlock *PrevBB = Builder.GetInsertBlock();
1011
1012 // Create basic blocks.
1013 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1014 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1015 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1016 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1017 FN);
1018
1019 DT->addNewBlock(HeaderBB, PrevBB);
1020 DT->addNewBlock(ExitBB, HeaderBB);
1021 DT->addNewBlock(checkNextBB, HeaderBB);
1022 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1023
1024 // Fill up basic block HeaderBB.
1025 Builder.SetInsertPoint(HeaderBB);
1026 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1027 "omp.lowerBoundPtr");
1028 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1029 "omp.upperBoundPtr");
1030 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1031 structData->getType(),
1032 "omp.userContext");
1033
1034 CharMapT clastVarsOMP;
1035 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1036
1037 Builder.CreateBr(checkNextBB);
1038
1039 // Add code to check if another set of iterations will be executed.
1040 Builder.SetInsertPoint(checkNextBB);
1041 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1042 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1043 lowerBoundPtr, upperBoundPtr);
1044 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1045 "omp.hasNextScheduleBlock");
1046 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1047
1048 // Add code to to load the iv bounds for this set of iterations.
1049 Builder.SetInsertPoint(loadIVBoundsBB);
1050 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1051 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1052
1053 // Subtract one as the upper bound provided by openmp is a < comparison
1054 // whereas the codegenForSequential function creates a <= comparison.
1055 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1056 "omp.upperBoundAdjusted");
1057
1058 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1059 CharMapT *oldClastVars = clastVars;
1060 clastVars = &clastVarsOMP;
1061 ExpGen.setIVS(&clastVarsOMP);
1062
1063 codegenForSequential(f, lowerBound, upperBound);
1064
1065 // Restore the old clastVars.
1066 clastVars = oldClastVars;
1067 ExpGen.setIVS(oldClastVars);
1068
1069 Builder.CreateBr(checkNextBB);
1070
1071 // Add code to terminate this openmp subfunction.
1072 Builder.SetInsertPoint(ExitBB);
1073 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1074 Builder.CreateCall(endnowaitFunction);
1075 Builder.CreateRetVoid();
1076
1077 // Restore the builder back to previous basic block.
1078 Builder.SetInsertPoint(PrevBB);
1079 }
1080
1081 /// @brief Create an OpenMP parallel for loop.
1082 ///
1083 /// This loop reflects a loop as if it would have been created by an OpenMP
1084 /// statement.
1085 void codegenForOpenMP(const clast_for *f) {
1086 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001087 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001088
1089 Function *SubFunction = addOpenMPSubfunction(M);
1090 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1091 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1092
1093 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1094
1095 // Create call for GOMP_parallel_loop_runtime_start.
1096 Value *subfunctionParam = Builder.CreateBitCast(structData,
1097 Builder.getInt8PtrTy(),
1098 "omp_data");
1099
1100 Value *numberOfThreads = Builder.getInt32(0);
1101 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1102 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1103
1104 // Add one as the upper bound provided by openmp is a < comparison
1105 // whereas the codegenForSequential function creates a <= comparison.
1106 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1107 APInt APStride = APInt_from_MPZ(f->stride);
1108 Value *stride = ConstantInt::get(intPtrTy,
1109 APStride.zext(intPtrTy->getBitWidth()));
1110
1111 SmallVector<Value *, 6> Arguments;
1112 Arguments.push_back(SubFunction);
1113 Arguments.push_back(subfunctionParam);
1114 Arguments.push_back(numberOfThreads);
1115 Arguments.push_back(lowerBound);
1116 Arguments.push_back(upperBound);
1117 Arguments.push_back(stride);
1118
1119 Function *parallelStartFunction =
1120 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001121 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001122
1123 // Create call to the subfunction.
1124 Builder.CreateCall(SubFunction, subfunctionParam);
1125
1126 // Create call for GOMP_parallel_end.
1127 Function *FN = M->getFunction("GOMP_parallel_end");
1128 Builder.CreateCall(FN);
1129 }
1130
1131 bool isInnermostLoop(const clast_for *f) {
1132 const clast_stmt *stmt = f->body;
1133
1134 while (stmt) {
1135 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1136 return false;
1137
1138 stmt = stmt->next;
1139 }
1140
1141 return true;
1142 }
1143
1144 /// @brief Get the number of loop iterations for this loop.
1145 /// @param f The clast for loop to check.
1146 int getNumberOfIterations(const clast_for *f) {
1147 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1148 isl_set *tmp = isl_set_copy(loopDomain);
1149
1150 // Calculate a map similar to the identity map, but with the last input
1151 // and output dimension not related.
1152 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001153 isl_space *Space = isl_set_get_space(loopDomain);
1154 Space = isl_space_drop_outputs(Space,
1155 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1156 Space = isl_space_map_from_set(Space);
1157 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001158 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1159 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1160
1161 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1162 map = isl_map_intersect(map, identity);
1163
1164 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001165 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001166 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1167
1168 isl_set *elements = isl_map_range(sub);
1169
Tobias Grosserc532f122011-08-25 08:40:59 +00001170 if (!isl_set_is_singleton(elements)) {
1171 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001172 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001173 }
Tobias Grosser75805372011-04-29 06:27:02 +00001174
1175 isl_point *p = isl_set_sample_point(elements);
1176
1177 isl_int v;
1178 isl_int_init(v);
1179 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1180 int numberIterations = isl_int_get_si(v);
1181 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001182 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001183
1184 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1185 }
1186
1187 /// @brief Create vector instructions for this loop.
1188 void codegenForVector(const clast_for *f) {
1189 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1190 int vectorWidth = getNumberOfIterations(f);
1191
1192 Value *LB = ExpGen.codegen(f->LB,
1193 TD->getIntPtrType(Builder.getContext()));
1194
1195 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001196 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001197 Stride = Stride.zext(LoopIVType->getBitWidth());
1198 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1199
1200 std::vector<Value*> IVS(vectorWidth);
1201 IVS[0] = LB;
1202
1203 for (int i = 1; i < vectorWidth; i++)
1204 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1205
1206 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1207
1208 // Add loop iv to symbols.
1209 (*clastVars)[f->iterator] = LB;
1210
1211 const clast_stmt *stmt = f->body;
1212
1213 while (stmt) {
1214 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1215 scatteringDomain);
1216 stmt = stmt->next;
1217 }
1218
1219 // Loop is finished, so remove its iv from the live symbols.
1220 clastVars->erase(f->iterator);
1221 }
1222
1223 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001224 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001225 && (-1 != getNumberOfIterations(f))
1226 && (getNumberOfIterations(f) <= 16)) {
1227 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001228 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001229 parallelCodeGeneration = true;
1230 parallelLoops.push_back(f->iterator);
1231 codegenForOpenMP(f);
1232 parallelCodeGeneration = false;
1233 } else
1234 codegenForSequential(f);
1235 }
1236
1237 Value *codegen(const clast_equation *eq) {
1238 Value *LHS = ExpGen.codegen(eq->LHS,
1239 TD->getIntPtrType(Builder.getContext()));
1240 Value *RHS = ExpGen.codegen(eq->RHS,
1241 TD->getIntPtrType(Builder.getContext()));
1242 CmpInst::Predicate P;
1243
1244 if (eq->sign == 0)
1245 P = ICmpInst::ICMP_EQ;
1246 else if (eq->sign > 0)
1247 P = ICmpInst::ICMP_SGE;
1248 else
1249 P = ICmpInst::ICMP_SLE;
1250
1251 return Builder.CreateICmp(P, LHS, RHS);
1252 }
1253
1254 void codegen(const clast_guard *g) {
1255 Function *F = Builder.GetInsertBlock()->getParent();
1256 LLVMContext &Context = F->getContext();
1257 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1258 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1259 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1260 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1261
1262 Value *Predicate = codegen(&(g->eq[0]));
1263
1264 for (int i = 1; i < g->n; ++i) {
1265 Value *TmpPredicate = codegen(&(g->eq[i]));
1266 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1267 }
1268
1269 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1270 Builder.SetInsertPoint(ThenBB);
1271
1272 codegen(g->then);
1273
1274 Builder.CreateBr(MergeBB);
1275 Builder.SetInsertPoint(MergeBB);
1276 }
1277
1278 void codegen(const clast_stmt *stmt) {
1279 if (CLAST_STMT_IS_A(stmt, stmt_root))
1280 assert(false && "No second root statement expected");
1281 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1282 codegen((const clast_assignment *)stmt);
1283 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1284 codegen((const clast_user_stmt *)stmt);
1285 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1286 codegen((const clast_block *)stmt);
1287 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1288 codegen((const clast_for *)stmt);
1289 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1290 codegen((const clast_guard *)stmt);
1291
1292 if (stmt->next)
1293 codegen(stmt->next);
1294 }
1295
1296 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001297 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001298
1299 // Create an instruction that specifies the location where the parameters
1300 // are expanded.
1301 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1302 Builder.getInt16Ty(), false, "insertInst",
1303 Builder.GetInsertBlock());
1304
1305 int i = 0;
1306 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1307 PI != PE; ++PI) {
1308 assert(i < names->nb_parameters && "Not enough parameter names");
1309
1310 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001311 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001312
1313 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1314 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1315 (*clastVars)[names->parameters[i]] = V;
1316
1317 ++i;
1318 }
1319 }
1320
1321 public:
1322 void codegen(const clast_root *r) {
1323 clastVars = new CharMapT();
1324 addParameters(r->names);
1325 ExpGen.setIVS(clastVars);
1326
1327 parallelCodeGeneration = false;
1328
1329 const clast_stmt *stmt = (const clast_stmt*) r;
1330 if (stmt->next)
1331 codegen(stmt->next);
1332
1333 delete clastVars;
1334 }
1335
1336 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001337 ScopDetection *sd, Dependences *dp, TargetData *td,
1338 IRBuilder<> &B) :
1339 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1340 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001341
1342};
1343}
1344
1345namespace {
1346class CodeGeneration : public ScopPass {
1347 Region *region;
1348 Scop *S;
1349 DominatorTree *DT;
1350 ScalarEvolution *SE;
1351 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001352 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001353 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001354
1355 std::vector<std::string> parallelLoops;
1356
1357 public:
1358 static char ID;
1359
1360 CodeGeneration() : ScopPass(ID) {}
1361
Tobias Grosser75805372011-04-29 06:27:02 +00001362 // Adding prototypes required if OpenMP is enabled.
1363 void addOpenMPDefinitions(IRBuilder<> &Builder)
1364 {
1365 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1366 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001367 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001368
1369 if (!M->getFunction("GOMP_parallel_end")) {
1370 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1371 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1372 }
1373
1374 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1375 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001376 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001377 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1378 false);
1379 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1380
Tobias Grosser851b96e2011-07-12 12:42:54 +00001381 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001382 args.push_back(FnPtrTy);
1383 args.push_back(Builder.getInt8PtrTy());
1384 args.push_back(Builder.getInt32Ty());
1385 args.push_back(intPtrTy);
1386 args.push_back(intPtrTy);
1387 args.push_back(intPtrTy);
1388
1389 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1390 Function::Create(type, Function::ExternalLinkage,
1391 "GOMP_parallel_loop_runtime_start", M);
1392 }
1393
1394 if (!M->getFunction("GOMP_loop_runtime_next")) {
1395 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1396
Tobias Grosser851b96e2011-07-12 12:42:54 +00001397 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001398 args.push_back(intLongPtrTy);
1399 args.push_back(intLongPtrTy);
1400
1401 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1402 Function::Create(type, Function::ExternalLinkage,
1403 "GOMP_loop_runtime_next", M);
1404 }
1405
1406 if (!M->getFunction("GOMP_loop_end_nowait")) {
1407 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001408 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001409 Function::Create(FT, Function::ExternalLinkage,
1410 "GOMP_loop_end_nowait", M);
1411 }
1412 }
1413
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001414 // Split the entry edge of the region and generate a new basic block on this
1415 // edge. This function also updates ScopInfo and RegionInfo.
1416 //
1417 // @param region The region where the entry edge will be splitted.
1418 BasicBlock *splitEdgeAdvanced(Region *region) {
1419 BasicBlock *newBlock;
1420 BasicBlock *splitBlock;
1421
1422 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1423
1424 if (DT->dominates(region->getEntry(), newBlock)) {
1425 // Update ScopInfo.
1426 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1427 if ((*SI)->getBasicBlock() == newBlock) {
1428 (*SI)->setBasicBlock(newBlock);
1429 break;
1430 }
1431
1432 // Update RegionInfo.
1433 splitBlock = region->getEntry();
1434 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001435 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001436 } else {
1437 RI->setRegionFor(newBlock, region->getParent());
1438 splitBlock = newBlock;
1439 }
1440
1441 return splitBlock;
1442 }
1443
1444 // Create a split block that branches either to the old code or to a new basic
1445 // block where the new code can be inserted.
1446 //
1447 // @param builder A builder that will be set to point to a basic block, where
1448 // the new code can be generated.
1449 // @return The split basic block.
1450 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1451 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1452
1453 splitBlock->setName("polly.enterScop");
1454
1455 Function *function = splitBlock->getParent();
1456 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1457 "polly.start", function);
1458 splitBlock->getTerminator()->eraseFromParent();
1459 builder->SetInsertPoint(splitBlock);
1460 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1461 DT->addNewBlock(startBlock, splitBlock);
1462
1463 // Start code generation here.
1464 builder->SetInsertPoint(startBlock);
1465 return splitBlock;
1466 }
1467
1468 // Merge the control flow of the newly generated code with the existing code.
1469 //
1470 // @param splitBlock The basic block where the control flow was split between
1471 // old and new version of the Scop.
1472 // @param builder An IRBuilder that points to the last instruction of the
1473 // newly generated code.
1474 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1475 BasicBlock *mergeBlock;
1476 Region *R = region;
1477
1478 if (R->getExit()->getSinglePredecessor())
1479 // No splitEdge required. A block with a single predecessor cannot have
1480 // PHI nodes that would complicate life.
1481 mergeBlock = R->getExit();
1482 else {
1483 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1484 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1485 // one predecessor. Hence, mergeBlock is always a newly generated block.
1486 mergeBlock->setName("polly.finalMerge");
1487 R->replaceExit(mergeBlock);
1488 }
1489
1490 builder->CreateBr(mergeBlock);
1491
1492 if (DT->dominates(splitBlock, mergeBlock))
1493 DT->changeImmediateDominator(mergeBlock, splitBlock);
1494 }
1495
Tobias Grosser75805372011-04-29 06:27:02 +00001496 bool runOnScop(Scop &scop) {
1497 S = &scop;
1498 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001499 DT = &getAnalysis<DominatorTree>();
1500 Dependences *DP = &getAnalysis<Dependences>();
1501 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001502 SD = &getAnalysis<ScopDetection>();
1503 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001504 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001505
1506 parallelLoops.clear();
1507
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001508 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001509
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001510 // In the CFG and we generate next to original code of the Scop the
1511 // optimized version. Both the new and the original version of the code
1512 // remain in the CFG. A branch statement decides which version is executed.
1513 // At the moment, we always execute the newly generated version (the old one
1514 // is dead code eliminated by the cleanup passes). Later we may decide to
1515 // execute the new version only under certain conditions. This will be the
1516 // case if we support constructs for which we cannot prove all assumptions
1517 // at compile time.
1518 //
1519 // Before transformation:
1520 //
1521 // bb0
1522 // |
1523 // orig_scop
1524 // |
1525 // bb1
1526 //
1527 // After transformation:
1528 // bb0
1529 // |
1530 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001531 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001532 // | startBlock
1533 // | |
1534 // orig_scop new_scop
1535 // \ /
1536 // \ /
1537 // bb1 (joinBlock)
1538 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001539
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001540 // The builder will be set to startBlock.
1541 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001542
1543 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001544 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001545
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001546 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001547 CloogInfo &C = getAnalysis<CloogInfo>();
1548 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001549
Tobias Grosser75805372011-04-29 06:27:02 +00001550 parallelLoops.insert(parallelLoops.begin(),
1551 CodeGen.getParallelLoops().begin(),
1552 CodeGen.getParallelLoops().end());
1553
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001554 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001555
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001556 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001557 }
1558
1559 virtual void printScop(raw_ostream &OS) const {
1560 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1561 PE = parallelLoops.end(); PI != PE; ++PI)
1562 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1563 }
1564
1565 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1566 AU.addRequired<CloogInfo>();
1567 AU.addRequired<Dependences>();
1568 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001569 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001570 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001571 AU.addRequired<ScopDetection>();
1572 AU.addRequired<ScopInfo>();
1573 AU.addRequired<TargetData>();
1574
1575 AU.addPreserved<CloogInfo>();
1576 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001577
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001578 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001579 AU.addPreserved<LoopInfo>();
1580 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001581 AU.addPreserved<ScopDetection>();
1582 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001583
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001584 // FIXME: We do not yet add regions for the newly generated code to the
1585 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001586 AU.addPreserved<RegionInfo>();
1587 AU.addPreserved<TempScopInfo>();
1588 AU.addPreserved<ScopInfo>();
1589 AU.addPreservedID(IndependentBlocksID);
1590 }
1591};
1592}
1593
1594char CodeGeneration::ID = 1;
1595
Tobias Grosser73600b82011-10-08 00:30:40 +00001596INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1597 "Polly - Create LLVM-IR form SCoPs", false, false)
1598INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1599INITIALIZE_PASS_DEPENDENCY(Dependences)
1600INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1601INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1602INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1603INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1604INITIALIZE_PASS_DEPENDENCY(TargetData)
1605INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1606 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001607
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001608Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001609 return new CodeGeneration();
1610}