blob: a8653bfe866f2dbb558cc2aea60c862ad9aa61b9 [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
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000319 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
320 Value *BaseAddress) {
321 isl_int OffsetMPZ;
322 isl_int_init(OffsetMPZ);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000323
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000324 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
Raghesh Aloor129e8672011-08-15 02:33:39 +0000325 && "Only single dimensional access functions supported");
326
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000327 if (isl_map_plain_is_fixed(AccessRelation, isl_dim_out,
328 0, &OffsetMPZ) == -1)
Raghesh Aloor129e8672011-08-15 02:33:39 +0000329 errs() << "Only fixed value access functions supported\n";
330
331 // Convert the offset from MPZ to Value*.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000332 APInt Offset = APInt_from_MPZ(OffsetMPZ);
333 Value *OffsetValue = ConstantInt::get(Builder.getContext(), Offset);
334 PointerType *BaseAddressType = dyn_cast<PointerType>(
335 BaseAddress->getType());
336 Type *ArrayTy = BaseAddressType->getElementType();
337 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
338 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000339
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000340 std::vector<Value*> IndexArray;
341 Value *NullValue = Constant::getNullValue(ArrayElementType);
342 IndexArray.push_back(NullValue);
343 IndexArray.push_back(OffsetValue);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000344
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000345 isl_int_clear(OffsetMPZ);
346 return IndexArray;
Raghesh Aloor129e8672011-08-15 02:33:39 +0000347 }
348
Raghesh Aloor62b13122011-08-03 17:02:50 +0000349 /// @brief Get the new operand address according to the changed access in
350 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000351 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
352 Value *BaseAddress, const Value *OldOperand,
353 ValueMapT &BBMap) {
354 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
355 BaseAddress);
356 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
Raghesh Aloor129e8672011-08-15 02:33:39 +0000357 "p_newarrayidx_");
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000358 return NewOperand;
Raghesh Aloor62b13122011-08-03 17:02:50 +0000359 }
360
361 /// @brief Generate the operand address
362 Value *generateLocationAccessed(const Instruction *Inst,
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000363 const Value *Pointer, ValueMapT &BBMap ) {
Tobias Grosser5d453812011-10-06 00:04:11 +0000364 MemoryAccess &Access = statement.getAccessFor(Inst);
365 isl_map *CurrentAccessRelation = Access.getAccessRelation();
366 isl_map *NewAccessRelation = Access.getNewAccessRelation();
Raghesh Aloor129e8672011-08-15 02:33:39 +0000367
Tobias Grosser5d453812011-10-06 00:04:11 +0000368 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
Tobias Grosserf5338802011-10-06 00:03:35 +0000369 && "Current and new access function use different spaces");
Raghesh Aloor129e8672011-08-15 02:33:39 +0000370
Tobias Grosser5d453812011-10-06 00:04:11 +0000371 Value *NewPointer;
372
373 if (!NewAccessRelation) {
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000374 NewPointer = getOperand(Pointer, BBMap);
Tobias Grosser5d453812011-10-06 00:04:11 +0000375 } else {
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000376 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
377 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
Tobias Grosser5d453812011-10-06 00:04:11 +0000378 BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000379 }
Raghesh Aloore75e9862011-08-11 08:44:56 +0000380
Tobias Grosser5d453812011-10-06 00:04:11 +0000381 isl_map_free(CurrentAccessRelation);
382 isl_map_free(NewAccessRelation);
383 return NewPointer;
Raghesh Aloor62b13122011-08-03 17:02:50 +0000384 }
385
Tobias Grosser75805372011-04-29 06:27:02 +0000386 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
387 const Value *pointer = load->getPointerOperand();
Raghesh Aloor62b13122011-08-03 17:02:50 +0000388 const Instruction *Inst = dyn_cast<Instruction>(load);
389 Value *newPointer = generateLocationAccessed(Inst, pointer, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000390 Value *scalarLoad = Builder.CreateLoad(newPointer,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000391 load->getName() + "_p_scalar_");
Tobias Grosser75805372011-04-29 06:27:02 +0000392 return scalarLoad;
393 }
394
395 /// @brief Load a value (or several values as a vector) from memory.
396 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
397 VectorValueMapT &scalarMaps, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000398 if (scalarMaps.size() == 1) {
399 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
400 return;
401 }
402
403 Value *newLoad;
404
405 MemoryAccess &Access = statement.getAccessFor(load);
406
407 assert(scatteringDomain && "No scattering domain available");
408
409 if (Access.isStrideZero(scatteringDomain))
410 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
411 else if (Access.isStrideOne(scatteringDomain))
412 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
413 else
414 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
415
416 vectorMap[load] = newLoad;
417 }
418
Tobias Grosserc9215152011-09-04 11:45:52 +0000419 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
420 ValueMapT &VectorMap, int VectorDimension,
421 int VectorWidth) {
422 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
423 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
424
425 if (const CastInst *Cast = dyn_cast<CastInst>(Inst)) {
426 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
427 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand,
428 DestType);
429 } else
430 llvm_unreachable("Can not generate vector code for instruction");
431 return;
432 }
433
Tobias Grosser09c57102011-09-04 11:45:29 +0000434 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser8b00a512011-09-04 11:45:45 +0000435 ValueMapT &vectorMap, int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000436 Value *opZero = Inst->getOperand(0);
437 Value *opOne = Inst->getOperand(1);
438
Tobias Grosser09c57102011-09-04 11:45:29 +0000439 Value *newOpZero, *newOpOne;
440 newOpZero = getOperand(opZero, BBMap, &vectorMap);
441 newOpOne = getOperand(opOne, BBMap, &vectorMap);
442
Tobias Grosser7551c302011-09-04 11:45:41 +0000443 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
444 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000445
446 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
Tobias Grosser7551c302011-09-04 11:45:41 +0000447 newOpOne,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000448 Inst->getName() + "p_vec");
Tobias Grosser7551c302011-09-04 11:45:41 +0000449 vectorMap[Inst] = newInst;
Tobias Grosser09c57102011-09-04 11:45:29 +0000450
451 return;
452 }
453
454 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000455 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
456 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000457 // In vector mode we only generate a store for the first dimension.
458 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000459 return;
460
Tobias Grosser09c57102011-09-04 11:45:29 +0000461 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Tobias Grosser09c57102011-09-04 11:45:29 +0000463 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000464
Tobias Grosser09c57102011-09-04 11:45:29 +0000465 const Value *pointer = store->getPointerOperand();
466 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000467
Tobias Grosser09c57102011-09-04 11:45:29 +0000468 if (Access.isStrideOne(scatteringDomain)) {
469 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
470 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000471
Tobias Grosser09c57102011-09-04 11:45:29 +0000472 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
473 "vector_ptr");
474 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000475
Tobias Grosser09c57102011-09-04 11:45:29 +0000476 if (!Aligned)
477 Store->setAlignment(8);
478 } else {
479 for (unsigned i = 0; i < scalarMaps.size(); i++) {
480 Value *scalar = Builder.CreateExtractElement(vector,
481 Builder.getInt32(i));
482 Value *newPointer = getOperand(pointer, scalarMaps[i]);
483 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000484 }
485 }
486
Tobias Grosser09c57102011-09-04 11:45:29 +0000487 return;
488 }
489
Tobias Grosser7551c302011-09-04 11:45:41 +0000490 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000491 Instruction *NewInst = Inst->clone();
492
Tobias Grosser75805372011-04-29 06:27:02 +0000493 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000494 for (Instruction::const_op_iterator OI = Inst->op_begin(),
495 OE = Inst->op_end(); OI != OE; ++OI) {
496 Value *OldOperand = *OI;
497 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000498
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000499 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000500 assert(!isa<StoreInst>(NewInst)
501 && "Store instructions are always needed!");
502 delete NewInst;
503 return;
504 }
505
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000506 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000507 }
508
509 Builder.Insert(NewInst);
510 BBMap[Inst] = NewInst;
511
512 if (!NewInst->getType()->isVoidTy())
513 NewInst->setName("p_" + Inst->getName());
514 }
515
Tobias Grosser7551c302011-09-04 11:45:41 +0000516 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap) {
517 for (Instruction::const_op_iterator OI = Inst->op_begin(),
518 OE = Inst->op_end(); OI != OE; ++OI)
519 if (VectorMap.count(*OI))
520 return true;
521 return false;
Tobias Grosser09c57102011-09-04 11:45:29 +0000522 }
523
Tobias Grosser75805372011-04-29 06:27:02 +0000524 int getVectorSize() {
525 return ValueMaps.size();
526 }
527
528 bool isVectorBlock() {
529 return getVectorSize() > 1;
530 }
531
Tobias Grosser7551c302011-09-04 11:45:41 +0000532 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
533 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
534 int vectorDimension, int vectorWidth) {
535 // Terminator instructions control the control flow. They are explicitally
536 // expressed in the clast and do not need to be copied.
537 if (Inst->isTerminator())
538 return;
539
540 if (isVectorBlock()) {
541 // If this instruction is already in the vectorMap, a vector instruction
542 // was already issued, that calculates the values of all dimensions. No
543 // need to create any more instructions.
544 if (vectorMap.count(Inst))
545 return;
546 }
547
548 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
549 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
550 return;
551 }
552
553 if (isVectorBlock() && hasVectorOperands(Inst, vectorMap)) {
Tobias Grosserc9215152011-09-04 11:45:52 +0000554 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
555 copyUnaryInst(UnaryInst, BBMap, vectorMap, vectorDimension,
556 vectorWidth);
557 else if
558 (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosser8b00a512011-09-04 11:45:45 +0000559 copyBinInst(binaryInst, BBMap, vectorMap, vectorDimension, vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000560 else if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
561 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
562 vectorWidth);
563 else
564 llvm_unreachable("Cannot issue vector code for this instruction");
565
566 return;
567 }
568
569 copyInstScalar(Inst, BBMap);
570 }
Tobias Grosser75805372011-04-29 06:27:02 +0000571 // Insert a copy of a basic block in the newly generated code.
572 //
573 // @param Builder The builder used to insert the code. It also specifies
574 // where to insert the code.
575 // @param BB The basic block to copy
576 // @param VMap A map returning for any old value its new equivalent. This
577 // is used to update the operands of the statements.
578 // For new statements a relation old->new is inserted in this
579 // map.
580 void copyBB(BasicBlock *BB, DominatorTree *DT) {
581 Function *F = Builder.GetInsertBlock()->getParent();
582 LLVMContext &Context = F->getContext();
583 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000584 "polly." + BB->getName() + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000585 F);
586 Builder.CreateBr(CopyBB);
587 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
588 Builder.SetInsertPoint(CopyBB);
589
590 // Create two maps that store the mapping from the original instructions of
591 // the old basic block to their copies in the new basic block. Those maps
592 // are basic block local.
593 //
594 // As vector code generation is supported there is one map for scalar values
595 // and one for vector values.
596 //
597 // In case we just do scalar code generation, the vectorMap is not used and
598 // the scalarMap has just one dimension, which contains the mapping.
599 //
600 // In case vector code generation is done, an instruction may either appear
601 // in the vector map once (as it is calculating >vectorwidth< values at a
602 // time. Or (if the values are calculated using scalar operations), it
603 // appears once in every dimension of the scalarMap.
604 VectorValueMapT scalarBlockMap(getVectorSize());
605 ValueMapT vectorBlockMap;
606
607 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
608 II != IE; ++II)
609 for (int i = 0; i < getVectorSize(); i++) {
610 if (isVectorBlock())
611 VMap = ValueMaps[i];
612
613 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
614 scalarBlockMap, i, getVectorSize());
615 }
616 }
617};
618
619/// Class to generate LLVM-IR that calculates the value of a clast_expr.
620class ClastExpCodeGen {
621 IRBuilder<> &Builder;
622 const CharMapT *IVS;
623
Tobias Grosser55927aa2011-07-18 09:53:32 +0000624 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000625 CharMapT::const_iterator I = IVS->find(e->name);
626
627 if (I != IVS->end())
628 return Builder.CreateSExtOrBitCast(I->second, Ty);
629 else
630 llvm_unreachable("Clast name not found");
631 }
632
Tobias Grosser55927aa2011-07-18 09:53:32 +0000633 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000634 APInt a = APInt_from_MPZ(e->val);
635
636 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
637 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
638
639 if (e->var) {
640 Value *var = codegen(e->var, Ty);
641 return Builder.CreateMul(ConstOne, var);
642 }
643
644 return ConstOne;
645 }
646
Tobias Grosser55927aa2011-07-18 09:53:32 +0000647 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000648 Value *LHS = codegen(e->LHS, Ty);
649
650 APInt RHS_AP = APInt_from_MPZ(e->RHS);
651
652 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
653 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
654
655 switch (e->type) {
656 case clast_bin_mod:
657 return Builder.CreateSRem(LHS, RHS);
658 case clast_bin_fdiv:
659 {
660 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
661 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
662 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
663 One = Builder.CreateZExtOrBitCast(One, Ty);
664 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
665 Value *Sum1 = Builder.CreateSub(LHS, RHS);
666 Value *Sum2 = Builder.CreateAdd(Sum1, One);
667 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
668 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
669 return Builder.CreateSDiv(Dividend, RHS);
670 }
671 case clast_bin_cdiv:
672 {
673 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
674 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
675 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
676 One = Builder.CreateZExtOrBitCast(One, Ty);
677 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
678 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
679 Value *Sum2 = Builder.CreateSub(Sum1, One);
680 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
681 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
682 return Builder.CreateSDiv(Dividend, RHS);
683 }
684 case clast_bin_div:
685 return Builder.CreateSDiv(LHS, RHS);
686 default:
687 llvm_unreachable("Unknown clast binary expression type");
688 };
689 }
690
Tobias Grosser55927aa2011-07-18 09:53:32 +0000691 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000692 assert(( r->type == clast_red_min
693 || r->type == clast_red_max
694 || r->type == clast_red_sum)
695 && "Clast reduction type not supported");
696 Value *old = codegen(r->elts[0], Ty);
697
698 for (int i=1; i < r->n; ++i) {
699 Value *exprValue = codegen(r->elts[i], Ty);
700
701 switch (r->type) {
702 case clast_red_min:
703 {
704 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
705 old = Builder.CreateSelect(cmp, old, exprValue);
706 break;
707 }
708 case clast_red_max:
709 {
710 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
711 old = Builder.CreateSelect(cmp, old, exprValue);
712 break;
713 }
714 case clast_red_sum:
715 old = Builder.CreateAdd(old, exprValue);
716 break;
717 default:
718 llvm_unreachable("Clast unknown reduction type");
719 }
720 }
721
722 return old;
723 }
724
725public:
726
727 // A generator for clast expressions.
728 //
729 // @param B The IRBuilder that defines where the code to calculate the
730 // clast expressions should be inserted.
731 // @param IVMAP A Map that translates strings describing the induction
732 // variables to the Values* that represent these variables
733 // on the LLVM side.
734 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
735
736 // Generates code to calculate a given clast expression.
737 //
738 // @param e The expression to calculate.
739 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000740 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000741 switch(e->type) {
742 case clast_expr_name:
743 return codegen((const clast_name *)e, Ty);
744 case clast_expr_term:
745 return codegen((const clast_term *)e, Ty);
746 case clast_expr_bin:
747 return codegen((const clast_binary *)e, Ty);
748 case clast_expr_red:
749 return codegen((const clast_reduction *)e, Ty);
750 default:
751 llvm_unreachable("Unknown clast expression!");
752 }
753 }
754
755 // @brief Reset the CharMap.
756 //
757 // This function is called to reset the CharMap to new one, while generating
758 // OpenMP code.
759 void setIVS(CharMapT *IVSNew) {
760 IVS = IVSNew;
761 }
762
763};
764
765class ClastStmtCodeGen {
766 // The Scop we code generate.
767 Scop *S;
768 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000769 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000770 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000771 Dependences *DP;
772 TargetData *TD;
773
774 // The Builder specifies the current location to code generate at.
775 IRBuilder<> &Builder;
776
777 // Map the Values from the old code to their counterparts in the new code.
778 ValueMapT ValueMap;
779
780 // clastVars maps from the textual representation of a clast variable to its
781 // current *Value. clast variables are scheduling variables, original
782 // induction variables or parameters. They are used either in loop bounds or
783 // to define the statement instance that is executed.
784 //
785 // for (s = 0; s < n + 3; ++i)
786 // for (t = s; t < m; ++j)
787 // Stmt(i = s + 3 * m, j = t);
788 //
789 // {s,t,i,j,n,m} is the set of clast variables in this clast.
790 CharMapT *clastVars;
791
792 // Codegenerator for clast expressions.
793 ClastExpCodeGen ExpGen;
794
795 // Do we currently generate parallel code?
796 bool parallelCodeGeneration;
797
798 std::vector<std::string> parallelLoops;
799
800public:
801
802 const std::vector<std::string> &getParallelLoops() {
803 return parallelLoops;
804 }
805
806 protected:
807 void codegen(const clast_assignment *a) {
808 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
809 TD->getIntPtrType(Builder.getContext()));
810 }
811
812 void codegen(const clast_assignment *a, ScopStmt *Statement,
813 unsigned Dimension, int vectorDim,
814 std::vector<ValueMapT> *VectorVMap = 0) {
815 Value *RHS = ExpGen.codegen(a->RHS,
816 TD->getIntPtrType(Builder.getContext()));
817
818 assert(!a->LHS && "Statement assignments do not have left hand side");
819 const PHINode *PN;
820 PN = Statement->getInductionVariableForDimension(Dimension);
821 const Value *V = PN;
822
Tobias Grosser75805372011-04-29 06:27:02 +0000823 if (VectorVMap)
824 (*VectorVMap)[vectorDim][V] = RHS;
825
826 ValueMap[V] = RHS;
827 }
828
829 void codegenSubstitutions(const clast_stmt *Assignment,
830 ScopStmt *Statement, int vectorDim = 0,
831 std::vector<ValueMapT> *VectorVMap = 0) {
832 int Dimension = 0;
833
834 while (Assignment) {
835 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
836 && "Substitions are expected to be assignments");
837 codegen((const clast_assignment *)Assignment, Statement, Dimension,
838 vectorDim, VectorVMap);
839 Assignment = Assignment->next;
840 Dimension++;
841 }
842 }
843
844 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
845 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
846 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
847 BasicBlock *BB = Statement->getBasicBlock();
848
849 if (u->substitutions)
850 codegenSubstitutions(u->substitutions, Statement);
851
852 int vectorDimensions = IVS ? IVS->size() : 1;
853
854 VectorValueMapT VectorValueMap(vectorDimensions);
855
856 if (IVS) {
857 assert (u->substitutions && "Substitutions expected!");
858 int i = 0;
859 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
860 II != IE; ++II) {
861 (*clastVars)[iterator] = *II;
862 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
863 i++;
864 }
865 }
866
867 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
868 scatteringDomain);
869 Generator.copyBB(BB, DT);
870 }
871
872 void codegen(const clast_block *b) {
873 if (b->body)
874 codegen(b->body);
875 }
876
877 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000878 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
879 Value *UpperBound = 0) {
880 APInt Stride;
Tobias Grosser75805372011-04-29 06:27:02 +0000881 PHINode *IV;
882 Value *IncrementedIV;
Tobias Grosser545bc312011-12-06 10:48:27 +0000883 BasicBlock *AfterBB, *HeaderBB, *LastBodyBB;
884 Type *IntPtrTy;
885
886 Stride = APInt_from_MPZ(f->stride);
887 IntPtrTy = TD->getIntPtrType(Builder.getContext());
888
Tobias Grosser75805372011-04-29 06:27:02 +0000889 // The value of lowerbound and upperbound will be supplied, if this
890 // function is called while generating OpenMP code. Otherwise get
891 // the values.
Tobias Grosser545bc312011-12-06 10:48:27 +0000892 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
893
894 if (LowerBound == 0) {
895 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
896 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
Tobias Grosser75805372011-04-29 06:27:02 +0000897 }
Tobias Grosser545bc312011-12-06 10:48:27 +0000898
899 createLoop(&Builder, LowerBound, UpperBound, Stride, IV, AfterBB,
Tobias Grosser75805372011-04-29 06:27:02 +0000900 IncrementedIV, DT);
901
902 // Add loop iv to symbols.
903 (*clastVars)[f->iterator] = IV;
904
905 if (f->body)
906 codegen(f->body);
907
908 // Loop is finished, so remove its iv from the live symbols.
909 clastVars->erase(f->iterator);
910
Tobias Grosser545bc312011-12-06 10:48:27 +0000911 HeaderBB = *pred_begin(AfterBB);
912 LastBodyBB = Builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000913 Builder.CreateBr(HeaderBB);
914 IV->addIncoming(IncrementedIV, LastBodyBB);
915 Builder.SetInsertPoint(AfterBB);
916 }
917
Tobias Grosser75805372011-04-29 06:27:02 +0000918 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000919 Function *addOpenMPSubfunction(Module *M) {
Tobias Grosser75805372011-04-29 06:27:02 +0000920 Function *F = Builder.GetInsertBlock()->getParent();
Tobias Grosser851b96e2011-07-12 12:42:54 +0000921 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000922 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000923 Function *FN = Function::Create(FT, Function::InternalLinkage,
924 F->getName() + ".omp_subfn", M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000925 // Do not run any polly pass on the new function.
926 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928 Function::arg_iterator AI = FN->arg_begin();
929 AI->setName("omp.userContext");
930
931 return FN;
932 }
933
934 /// @brief Add values to the OpenMP structure.
935 ///
936 /// Create the subfunction structure and add the values from the list.
937 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
938 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000939 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000940
941 // Create the structure.
942 for (unsigned i = 0; i < OMPDataVals.size(); i++)
943 structMembers.push_back(OMPDataVals[i]->getType());
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945 StructType *structTy = StructType::get(Builder.getContext(),
946 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000947 // Store the values into the structure.
948 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
949 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
950 Value *storeAddr = Builder.CreateStructGEP(structData, i);
951 Builder.CreateStore(OMPDataVals[i], storeAddr);
952 }
953
954 return structData;
955 }
956
957 /// @brief Create OpenMP structure values.
958 ///
959 /// Create a list of values that has to be stored into the subfuncition
960 /// structure.
961 SetVector<Value*> createOpenMPStructValues() {
962 SetVector<Value*> OMPDataVals;
963
964 // Push the clast variables available in the clastVars.
965 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
966 I != E; I++)
967 OMPDataVals.insert(I->second);
968
969 // Push the base addresses of memory references.
970 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
971 ScopStmt *Stmt = *SI;
972 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
973 E = Stmt->memacc_end(); I != E; ++I) {
974 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
975 OMPDataVals.insert((BaseAddr));
976 }
977 }
978
979 return OMPDataVals;
980 }
981
982 /// @brief Extract the values from the subfunction parameter.
983 ///
984 /// Extract the values from the subfunction parameter and update the clast
985 /// variables to point to the new values.
986 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
987 SetVector<Value*> OMPDataVals,
988 Value *userContext) {
989 // Extract the clast variables.
990 unsigned i = 0;
991 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
992 I != E; I++) {
993 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
994 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
995 i++;
996 }
997
998 // Extract the base addresses of memory references.
999 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1000 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1001 Value *baseAddr = OMPDataVals[j];
1002 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1003 }
1004
1005 }
1006
1007 /// @brief Add body to the subfunction.
1008 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1009 Value *structData,
1010 SetVector<Value*> OMPDataVals) {
1011 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1012 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001013 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
1015 // Store the previous basic block.
1016 BasicBlock *PrevBB = Builder.GetInsertBlock();
1017
1018 // Create basic blocks.
1019 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1020 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1021 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1022 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1023 FN);
1024
1025 DT->addNewBlock(HeaderBB, PrevBB);
1026 DT->addNewBlock(ExitBB, HeaderBB);
1027 DT->addNewBlock(checkNextBB, HeaderBB);
1028 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1029
1030 // Fill up basic block HeaderBB.
1031 Builder.SetInsertPoint(HeaderBB);
1032 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1033 "omp.lowerBoundPtr");
1034 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1035 "omp.upperBoundPtr");
1036 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1037 structData->getType(),
1038 "omp.userContext");
1039
1040 CharMapT clastVarsOMP;
1041 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1042
1043 Builder.CreateBr(checkNextBB);
1044
1045 // Add code to check if another set of iterations will be executed.
1046 Builder.SetInsertPoint(checkNextBB);
1047 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1048 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1049 lowerBoundPtr, upperBoundPtr);
1050 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1051 "omp.hasNextScheduleBlock");
1052 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1053
1054 // Add code to to load the iv bounds for this set of iterations.
1055 Builder.SetInsertPoint(loadIVBoundsBB);
1056 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1057 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1058
1059 // Subtract one as the upper bound provided by openmp is a < comparison
1060 // whereas the codegenForSequential function creates a <= comparison.
1061 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1062 "omp.upperBoundAdjusted");
1063
1064 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1065 CharMapT *oldClastVars = clastVars;
1066 clastVars = &clastVarsOMP;
1067 ExpGen.setIVS(&clastVarsOMP);
1068
1069 codegenForSequential(f, lowerBound, upperBound);
1070
1071 // Restore the old clastVars.
1072 clastVars = oldClastVars;
1073 ExpGen.setIVS(oldClastVars);
1074
1075 Builder.CreateBr(checkNextBB);
1076
1077 // Add code to terminate this openmp subfunction.
1078 Builder.SetInsertPoint(ExitBB);
1079 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1080 Builder.CreateCall(endnowaitFunction);
1081 Builder.CreateRetVoid();
1082
1083 // Restore the builder back to previous basic block.
1084 Builder.SetInsertPoint(PrevBB);
1085 }
1086
1087 /// @brief Create an OpenMP parallel for loop.
1088 ///
1089 /// This loop reflects a loop as if it would have been created by an OpenMP
1090 /// statement.
1091 void codegenForOpenMP(const clast_for *f) {
1092 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001093 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001094
1095 Function *SubFunction = addOpenMPSubfunction(M);
1096 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1097 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1098
1099 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1100
1101 // Create call for GOMP_parallel_loop_runtime_start.
1102 Value *subfunctionParam = Builder.CreateBitCast(structData,
1103 Builder.getInt8PtrTy(),
1104 "omp_data");
1105
1106 Value *numberOfThreads = Builder.getInt32(0);
1107 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1108 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1109
1110 // Add one as the upper bound provided by openmp is a < comparison
1111 // whereas the codegenForSequential function creates a <= comparison.
1112 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1113 APInt APStride = APInt_from_MPZ(f->stride);
1114 Value *stride = ConstantInt::get(intPtrTy,
1115 APStride.zext(intPtrTy->getBitWidth()));
1116
1117 SmallVector<Value *, 6> Arguments;
1118 Arguments.push_back(SubFunction);
1119 Arguments.push_back(subfunctionParam);
1120 Arguments.push_back(numberOfThreads);
1121 Arguments.push_back(lowerBound);
1122 Arguments.push_back(upperBound);
1123 Arguments.push_back(stride);
1124
1125 Function *parallelStartFunction =
1126 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001127 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001128
1129 // Create call to the subfunction.
1130 Builder.CreateCall(SubFunction, subfunctionParam);
1131
1132 // Create call for GOMP_parallel_end.
1133 Function *FN = M->getFunction("GOMP_parallel_end");
1134 Builder.CreateCall(FN);
1135 }
1136
1137 bool isInnermostLoop(const clast_for *f) {
1138 const clast_stmt *stmt = f->body;
1139
1140 while (stmt) {
1141 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1142 return false;
1143
1144 stmt = stmt->next;
1145 }
1146
1147 return true;
1148 }
1149
1150 /// @brief Get the number of loop iterations for this loop.
1151 /// @param f The clast for loop to check.
1152 int getNumberOfIterations(const clast_for *f) {
1153 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1154 isl_set *tmp = isl_set_copy(loopDomain);
1155
1156 // Calculate a map similar to the identity map, but with the last input
1157 // and output dimension not related.
1158 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001159 isl_space *Space = isl_set_get_space(loopDomain);
1160 Space = isl_space_drop_outputs(Space,
1161 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1162 Space = isl_space_map_from_set(Space);
1163 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001164 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1165 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1166
1167 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1168 map = isl_map_intersect(map, identity);
1169
1170 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001171 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001172 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1173
1174 isl_set *elements = isl_map_range(sub);
1175
Tobias Grosserc532f122011-08-25 08:40:59 +00001176 if (!isl_set_is_singleton(elements)) {
1177 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001178 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001179 }
Tobias Grosser75805372011-04-29 06:27:02 +00001180
1181 isl_point *p = isl_set_sample_point(elements);
1182
1183 isl_int v;
1184 isl_int_init(v);
1185 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1186 int numberIterations = isl_int_get_si(v);
1187 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001188 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001189
1190 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1191 }
1192
1193 /// @brief Create vector instructions for this loop.
1194 void codegenForVector(const clast_for *f) {
1195 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1196 int vectorWidth = getNumberOfIterations(f);
1197
1198 Value *LB = ExpGen.codegen(f->LB,
1199 TD->getIntPtrType(Builder.getContext()));
1200
1201 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001202 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001203 Stride = Stride.zext(LoopIVType->getBitWidth());
1204 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1205
1206 std::vector<Value*> IVS(vectorWidth);
1207 IVS[0] = LB;
1208
1209 for (int i = 1; i < vectorWidth; i++)
1210 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1211
1212 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1213
1214 // Add loop iv to symbols.
1215 (*clastVars)[f->iterator] = LB;
1216
1217 const clast_stmt *stmt = f->body;
1218
1219 while (stmt) {
1220 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1221 scatteringDomain);
1222 stmt = stmt->next;
1223 }
1224
1225 // Loop is finished, so remove its iv from the live symbols.
1226 clastVars->erase(f->iterator);
1227 }
1228
1229 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001230 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001231 && (-1 != getNumberOfIterations(f))
1232 && (getNumberOfIterations(f) <= 16)) {
1233 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001234 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001235 parallelCodeGeneration = true;
1236 parallelLoops.push_back(f->iterator);
1237 codegenForOpenMP(f);
1238 parallelCodeGeneration = false;
1239 } else
1240 codegenForSequential(f);
1241 }
1242
1243 Value *codegen(const clast_equation *eq) {
1244 Value *LHS = ExpGen.codegen(eq->LHS,
1245 TD->getIntPtrType(Builder.getContext()));
1246 Value *RHS = ExpGen.codegen(eq->RHS,
1247 TD->getIntPtrType(Builder.getContext()));
1248 CmpInst::Predicate P;
1249
1250 if (eq->sign == 0)
1251 P = ICmpInst::ICMP_EQ;
1252 else if (eq->sign > 0)
1253 P = ICmpInst::ICMP_SGE;
1254 else
1255 P = ICmpInst::ICMP_SLE;
1256
1257 return Builder.CreateICmp(P, LHS, RHS);
1258 }
1259
1260 void codegen(const clast_guard *g) {
1261 Function *F = Builder.GetInsertBlock()->getParent();
1262 LLVMContext &Context = F->getContext();
1263 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1264 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1265 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1266 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1267
1268 Value *Predicate = codegen(&(g->eq[0]));
1269
1270 for (int i = 1; i < g->n; ++i) {
1271 Value *TmpPredicate = codegen(&(g->eq[i]));
1272 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1273 }
1274
1275 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1276 Builder.SetInsertPoint(ThenBB);
1277
1278 codegen(g->then);
1279
1280 Builder.CreateBr(MergeBB);
1281 Builder.SetInsertPoint(MergeBB);
1282 }
1283
1284 void codegen(const clast_stmt *stmt) {
1285 if (CLAST_STMT_IS_A(stmt, stmt_root))
1286 assert(false && "No second root statement expected");
1287 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1288 codegen((const clast_assignment *)stmt);
1289 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1290 codegen((const clast_user_stmt *)stmt);
1291 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1292 codegen((const clast_block *)stmt);
1293 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1294 codegen((const clast_for *)stmt);
1295 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1296 codegen((const clast_guard *)stmt);
1297
1298 if (stmt->next)
1299 codegen(stmt->next);
1300 }
1301
1302 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001303 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001304
1305 // Create an instruction that specifies the location where the parameters
1306 // are expanded.
1307 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1308 Builder.getInt16Ty(), false, "insertInst",
1309 Builder.GetInsertBlock());
1310
1311 int i = 0;
1312 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1313 PI != PE; ++PI) {
1314 assert(i < names->nb_parameters && "Not enough parameter names");
1315
1316 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001317 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001318
1319 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1320 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1321 (*clastVars)[names->parameters[i]] = V;
1322
1323 ++i;
1324 }
1325 }
1326
1327 public:
1328 void codegen(const clast_root *r) {
1329 clastVars = new CharMapT();
1330 addParameters(r->names);
1331 ExpGen.setIVS(clastVars);
1332
1333 parallelCodeGeneration = false;
1334
1335 const clast_stmt *stmt = (const clast_stmt*) r;
1336 if (stmt->next)
1337 codegen(stmt->next);
1338
1339 delete clastVars;
1340 }
1341
1342 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001343 ScopDetection *sd, Dependences *dp, TargetData *td,
1344 IRBuilder<> &B) :
1345 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1346 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001347
1348};
1349}
1350
1351namespace {
1352class CodeGeneration : public ScopPass {
1353 Region *region;
1354 Scop *S;
1355 DominatorTree *DT;
1356 ScalarEvolution *SE;
1357 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001358 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001359 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001360
1361 std::vector<std::string> parallelLoops;
1362
1363 public:
1364 static char ID;
1365
1366 CodeGeneration() : ScopPass(ID) {}
1367
Tobias Grosser75805372011-04-29 06:27:02 +00001368 // Adding prototypes required if OpenMP is enabled.
1369 void addOpenMPDefinitions(IRBuilder<> &Builder)
1370 {
1371 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1372 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001373 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001374
1375 if (!M->getFunction("GOMP_parallel_end")) {
1376 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1377 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1378 }
1379
1380 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1381 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001382 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001383 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1384 false);
1385 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1386
Tobias Grosser851b96e2011-07-12 12:42:54 +00001387 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001388 args.push_back(FnPtrTy);
1389 args.push_back(Builder.getInt8PtrTy());
1390 args.push_back(Builder.getInt32Ty());
1391 args.push_back(intPtrTy);
1392 args.push_back(intPtrTy);
1393 args.push_back(intPtrTy);
1394
1395 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1396 Function::Create(type, Function::ExternalLinkage,
1397 "GOMP_parallel_loop_runtime_start", M);
1398 }
1399
1400 if (!M->getFunction("GOMP_loop_runtime_next")) {
1401 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1402
Tobias Grosser851b96e2011-07-12 12:42:54 +00001403 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001404 args.push_back(intLongPtrTy);
1405 args.push_back(intLongPtrTy);
1406
1407 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1408 Function::Create(type, Function::ExternalLinkage,
1409 "GOMP_loop_runtime_next", M);
1410 }
1411
1412 if (!M->getFunction("GOMP_loop_end_nowait")) {
1413 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001414 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001415 Function::Create(FT, Function::ExternalLinkage,
1416 "GOMP_loop_end_nowait", M);
1417 }
1418 }
1419
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001420 // Split the entry edge of the region and generate a new basic block on this
1421 // edge. This function also updates ScopInfo and RegionInfo.
1422 //
1423 // @param region The region where the entry edge will be splitted.
1424 BasicBlock *splitEdgeAdvanced(Region *region) {
1425 BasicBlock *newBlock;
1426 BasicBlock *splitBlock;
1427
1428 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1429
1430 if (DT->dominates(region->getEntry(), newBlock)) {
1431 // Update ScopInfo.
1432 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1433 if ((*SI)->getBasicBlock() == newBlock) {
1434 (*SI)->setBasicBlock(newBlock);
1435 break;
1436 }
1437
1438 // Update RegionInfo.
1439 splitBlock = region->getEntry();
1440 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001441 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001442 } else {
1443 RI->setRegionFor(newBlock, region->getParent());
1444 splitBlock = newBlock;
1445 }
1446
1447 return splitBlock;
1448 }
1449
1450 // Create a split block that branches either to the old code or to a new basic
1451 // block where the new code can be inserted.
1452 //
1453 // @param builder A builder that will be set to point to a basic block, where
1454 // the new code can be generated.
1455 // @return The split basic block.
1456 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1457 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1458
1459 splitBlock->setName("polly.enterScop");
1460
1461 Function *function = splitBlock->getParent();
1462 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1463 "polly.start", function);
1464 splitBlock->getTerminator()->eraseFromParent();
1465 builder->SetInsertPoint(splitBlock);
1466 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1467 DT->addNewBlock(startBlock, splitBlock);
1468
1469 // Start code generation here.
1470 builder->SetInsertPoint(startBlock);
1471 return splitBlock;
1472 }
1473
1474 // Merge the control flow of the newly generated code with the existing code.
1475 //
1476 // @param splitBlock The basic block where the control flow was split between
1477 // old and new version of the Scop.
1478 // @param builder An IRBuilder that points to the last instruction of the
1479 // newly generated code.
1480 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1481 BasicBlock *mergeBlock;
1482 Region *R = region;
1483
1484 if (R->getExit()->getSinglePredecessor())
1485 // No splitEdge required. A block with a single predecessor cannot have
1486 // PHI nodes that would complicate life.
1487 mergeBlock = R->getExit();
1488 else {
1489 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1490 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1491 // one predecessor. Hence, mergeBlock is always a newly generated block.
1492 mergeBlock->setName("polly.finalMerge");
1493 R->replaceExit(mergeBlock);
1494 }
1495
1496 builder->CreateBr(mergeBlock);
1497
1498 if (DT->dominates(splitBlock, mergeBlock))
1499 DT->changeImmediateDominator(mergeBlock, splitBlock);
1500 }
1501
Tobias Grosser75805372011-04-29 06:27:02 +00001502 bool runOnScop(Scop &scop) {
1503 S = &scop;
1504 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001505 DT = &getAnalysis<DominatorTree>();
1506 Dependences *DP = &getAnalysis<Dependences>();
1507 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001508 SD = &getAnalysis<ScopDetection>();
1509 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001510 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001511
1512 parallelLoops.clear();
1513
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001514 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001515
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001516 // In the CFG and we generate next to original code of the Scop the
1517 // optimized version. Both the new and the original version of the code
1518 // remain in the CFG. A branch statement decides which version is executed.
1519 // At the moment, we always execute the newly generated version (the old one
1520 // is dead code eliminated by the cleanup passes). Later we may decide to
1521 // execute the new version only under certain conditions. This will be the
1522 // case if we support constructs for which we cannot prove all assumptions
1523 // at compile time.
1524 //
1525 // Before transformation:
1526 //
1527 // bb0
1528 // |
1529 // orig_scop
1530 // |
1531 // bb1
1532 //
1533 // After transformation:
1534 // bb0
1535 // |
1536 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001537 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001538 // | startBlock
1539 // | |
1540 // orig_scop new_scop
1541 // \ /
1542 // \ /
1543 // bb1 (joinBlock)
1544 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001545
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001546 // The builder will be set to startBlock.
1547 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001548
1549 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001550 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001551
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001552 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001553 CloogInfo &C = getAnalysis<CloogInfo>();
1554 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001555
Tobias Grosser75805372011-04-29 06:27:02 +00001556 parallelLoops.insert(parallelLoops.begin(),
1557 CodeGen.getParallelLoops().begin(),
1558 CodeGen.getParallelLoops().end());
1559
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001560 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001561
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001562 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001563 }
1564
1565 virtual void printScop(raw_ostream &OS) const {
1566 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1567 PE = parallelLoops.end(); PI != PE; ++PI)
1568 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1569 }
1570
1571 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1572 AU.addRequired<CloogInfo>();
1573 AU.addRequired<Dependences>();
1574 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001575 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001576 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001577 AU.addRequired<ScopDetection>();
1578 AU.addRequired<ScopInfo>();
1579 AU.addRequired<TargetData>();
1580
1581 AU.addPreserved<CloogInfo>();
1582 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001583
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001584 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001585 AU.addPreserved<LoopInfo>();
1586 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001587 AU.addPreserved<ScopDetection>();
1588 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001589
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001590 // FIXME: We do not yet add regions for the newly generated code to the
1591 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001592 AU.addPreserved<RegionInfo>();
1593 AU.addPreserved<TempScopInfo>();
1594 AU.addPreserved<ScopInfo>();
1595 AU.addPreservedID(IndependentBlocksID);
1596 }
1597};
1598}
1599
1600char CodeGeneration::ID = 1;
1601
Tobias Grosser73600b82011-10-08 00:30:40 +00001602INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1603 "Polly - Create LLVM-IR form SCoPs", false, false)
1604INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1605INITIALIZE_PASS_DEPENDENCY(Dependences)
1606INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1607INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1608INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1609INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1610INITIALIZE_PASS_DEPENDENCY(TargetData)
1611INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1612 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001613
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001614Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001615 return new CodeGeneration();
1616}