blob: c9bea7f8b7a0b05c6da7f5193e94ea38717f18d9 [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
Tobias Grosser75805372011-04-29 06:27:02 +000025#include "polly/Cloog.h"
Tobias Grosser67707b72011-10-23 20:59:40 +000026#include "polly/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000027#include "polly/Dependences.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000028#include "polly/LinkAllPasses.h"
Tobias Grosser75805372011-04-29 06:27:02 +000029#include "polly/ScopInfo.h"
30#include "polly/TempScopInfo.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000031#include "polly/Support/GICHelper.h"
32
33#include "llvm/Module.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/IRBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Target/TargetData.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042
43#define CLOOG_INT_GMP 1
44#include "cloog/cloog.h"
45#include "cloog/isl/cloog.h"
46
Raghesh Aloora71989c2011-12-28 02:48:26 +000047#include "isl/aff.h"
48
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <vector>
50#include <utility>
51
52using namespace polly;
53using namespace llvm;
54
55struct isl_set;
56
57namespace polly {
58
Tobias Grosser67707b72011-10-23 20:59:40 +000059bool EnablePollyVector;
60
61static cl::opt<bool, true>
Tobias Grosser75805372011-04-29 06:27:02 +000062Vector("enable-polly-vector",
63 cl::desc("Enable polly vector code generation"), cl::Hidden,
Tobias Grosser67707b72011-10-23 20:59:40 +000064 cl::location(EnablePollyVector), cl::init(false));
Tobias Grosser75805372011-04-29 06:27:02 +000065
66static cl::opt<bool>
67OpenMP("enable-polly-openmp",
68 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
69 cl::value_desc("OpenMP code generation enabled if true"),
70 cl::init(false));
71
72static cl::opt<bool>
73AtLeastOnce("enable-polly-atLeastOnce",
74 cl::desc("Give polly the hint, that every loop is executed at least"
75 "once"), cl::Hidden,
76 cl::value_desc("OpenMP code generation enabled if true"),
77 cl::init(false));
78
79static cl::opt<bool>
80Aligned("enable-polly-aligned",
81 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
82 cl::value_desc("OpenMP code generation enabled if true"),
83 cl::init(false));
84
Tobias Grosser75805372011-04-29 06:27:02 +000085typedef DenseMap<const Value*, Value*> ValueMapT;
86typedef DenseMap<const char*, Value*> CharMapT;
87typedef std::vector<ValueMapT> VectorValueMapT;
Raghesh Aloora71989c2011-12-28 02:48:26 +000088typedef struct {
Raghesh Aloora71989c2011-12-28 02:48:26 +000089 Value *Result;
90 IRBuilder<> *Builder;
91}IslPwAffUserInfo;
Tobias Grosser75805372011-04-29 06:27:02 +000092
93// Create a new loop.
94//
95// @param Builder The builder used to create the loop. It also defines the
96// place where to create the loop.
97// @param UB The upper bound of the loop iv.
98// @param Stride The number by which the loop iv is incremented after every
99// iteration.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000100static Value *createLoop(IRBuilder<> *Builder, Value *LB, Value *UB,
101 APInt Stride, DominatorTree *DT, Pass *P,
102 BasicBlock **AfterBlock) {
Tobias Grosser75805372011-04-29 06:27:02 +0000103 Function *F = Builder->GetInsertBlock()->getParent();
104 LLVMContext &Context = F->getContext();
105
106 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
107 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
108 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000109 BasicBlock *AfterBB = SplitBlock(PreheaderBB, Builder->GetInsertPoint()++, P);
110 AfterBB->setName("polly.loop_after");
Tobias Grosser75805372011-04-29 06:27:02 +0000111
Tobias Grosser0ac92142012-02-14 14:02:27 +0000112 PreheaderBB->getTerminator()->setSuccessor(0, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000113 DT->addNewBlock(HeaderBB, PreheaderBB);
114
Tobias Grosser75805372011-04-29 06:27:02 +0000115 Builder->SetInsertPoint(HeaderBB);
116
117 // Use the type of upper and lower bound.
118 assert(LB->getType() == UB->getType()
119 && "Different types for upper and lower bound.");
120
Tobias Grosser55927aa2011-07-18 09:53:32 +0000121 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000122 assert(LoopIVType && "UB is not integer?");
123
124 // IV
Tobias Grosser0ac92142012-02-14 14:02:27 +0000125 PHINode *IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000126 IV->addIncoming(LB, PreheaderBB);
127
128 // IV increment.
129 Value *StrideValue = ConstantInt::get(LoopIVType,
130 Stride.zext(LoopIVType->getBitWidth()));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000131 Value *IncrementedIV = Builder->CreateAdd(IV, StrideValue,
132 "polly.next_loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000133
134 // Exit condition.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000135 Value *CMP;
Tobias Grosser75805372011-04-29 06:27:02 +0000136 if (AtLeastOnce) { // At least on iteration.
137 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000138 CMP = Builder->CreateICmpNE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000139 } else { // Maybe not executed at all.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000140 CMP = Builder->CreateICmpSLE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000141 }
Tobias Grosser0ac92142012-02-14 14:02:27 +0000142
143 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000144 DT->addNewBlock(BodyBB, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000145
146 Builder->SetInsertPoint(BodyBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000147 Builder->CreateBr(HeaderBB);
148 IV->addIncoming(IncrementedIV, BodyBB);
149 DT->changeImmediateDominator(AfterBB, HeaderBB);
150
151 Builder->SetInsertPoint(BodyBB->begin());
152 *AfterBlock = AfterBB;
153
154 return IV;
Tobias Grosser75805372011-04-29 06:27:02 +0000155}
156
157class BlockGenerator {
158 IRBuilder<> &Builder;
159 ValueMapT &VMap;
160 VectorValueMapT &ValueMaps;
161 Scop &S;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000162 ScopStmt &Statement;
163 isl_set *ScatteringDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000164
165public:
166 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000167 ScopStmt &Stmt, __isl_keep isl_set *domain);
Tobias Grosser75805372011-04-29 06:27:02 +0000168
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000169 const Region &getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000170
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000171 Value *makeVectorOperand(Value *operand, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000172
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000173 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000174 ValueMapT *VectorMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000175
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000176 Type *getVectorPtrTy(const Value *V, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000177
178 /// @brief Load a vector from a set of adjacent scalars
179 ///
180 /// In case a set of scalars is known to be next to each other in memory,
181 /// create a vector load that loads those scalars
182 ///
183 /// %vector_ptr= bitcast double* %p to <4 x double>*
184 /// %vec_full = load <4 x double>* %vector_ptr
185 ///
186 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000187 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000188
189 /// @brief Load a vector initialized from a single scalar in memory
190 ///
191 /// In case all elements of a vector are initialized to the same
192 /// scalar value, this value is loaded and shuffeled into all elements
193 /// of the vector.
194 ///
195 /// %splat_one = load <1 x double>* %p
196 /// %splat = shufflevector <1 x double> %splat_one, <1 x
197 /// double> %splat_one, <4 x i32> zeroinitializer
198 ///
199 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000200 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000201
202 /// @Load a vector from scalars distributed in memory
203 ///
204 /// In case some scalars a distributed randomly in memory. Create a vector
205 /// by loading each scalar and by inserting one after the other into the
206 /// vector.
207 ///
208 /// %scalar_1= load double* %p_1
209 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
210 /// %scalar 2 = load double* %p_2
211 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
212 ///
213 Value *generateUnknownStrideLoad(const LoadInst *load,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000214 VectorValueMapT &scalarMaps, int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000215
Raghesh Aloora71989c2011-12-28 02:48:26 +0000216 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000217 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000218
219 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000220 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000221
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000222 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000223
Raghesh Aloor129e8672011-08-15 02:33:39 +0000224 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000225 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000226 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000227
Raghesh Aloor62b13122011-08-03 17:02:50 +0000228 /// @brief Get the new operand address according to the changed access in
229 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000230 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
231 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000232 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000233
234 /// @brief Generate the operand address
235 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000236 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000237
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000238 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000239
240 /// @brief Load a value (or several values as a vector) from memory.
241 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000242 VectorValueMapT &scalarMaps, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000243
Tobias Grosserc9215152011-09-04 11:45:52 +0000244 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
245 ValueMapT &VectorMap, int VectorDimension,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000246 int VectorWidth);
Tobias Grosserc9215152011-09-04 11:45:52 +0000247
Tobias Grosser09c57102011-09-04 11:45:29 +0000248 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000249 ValueMapT &vectorMap, int vectorDimension, int vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000250
251 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000252 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000253 int vectorDimension, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000254
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000255 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000256
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000257 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000258
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000259 int getVectorSize();
Tobias Grosser75805372011-04-29 06:27:02 +0000260
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000261 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000262
Tobias Grosser7551c302011-09-04 11:45:41 +0000263 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
264 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000265 int vectorDimension, int vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000266
Tobias Grosser75805372011-04-29 06:27:02 +0000267 // Insert a copy of a basic block in the newly generated code.
268 //
269 // @param Builder The builder used to insert the code. It also specifies
270 // where to insert the code.
271 // @param BB The basic block to copy
272 // @param VMap A map returning for any old value its new equivalent. This
273 // is used to update the operands of the statements.
274 // For new statements a relation old->new is inserted in this
275 // map.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000276 void copyBB(BasicBlock *BB, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000277};
278
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000279BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
280 VectorValueMapT &vmaps, ScopStmt &Stmt,
281 __isl_keep isl_set *domain)
282 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
283 Statement(Stmt), ScatteringDomain(domain) {}
284
285const Region &BlockGenerator::getRegion() {
286 return S.getRegion();
287}
288
289Value *BlockGenerator::makeVectorOperand(Value *Operand, int VectorWidth) {
290 if (Operand->getType()->isVectorTy())
291 return Operand;
292
293 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
294 Value *Vector = UndefValue::get(VectorType);
295 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
296
297 std::vector<Constant*> Splat;
298
299 for (int i = 0; i < VectorWidth; i++)
300 Splat.push_back (Builder.getInt32(0));
301
302 Constant *SplatVector = ConstantVector::get(Splat);
303
304 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
305}
306
307Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
308 ValueMapT *VectorMap) {
309 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
310
311 if (!OpInst)
312 return const_cast<Value*>(OldOperand);
313
314 if (VectorMap && VectorMap->count(OldOperand))
315 return (*VectorMap)[OldOperand];
316
317 // IVS and Parameters.
318 if (VMap.count(OldOperand)) {
319 Value *NewOperand = VMap[OldOperand];
320
321 // Insert a cast if types are different
322 if (OldOperand->getType()->getScalarSizeInBits()
323 < NewOperand->getType()->getScalarSizeInBits())
324 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
325 OldOperand->getType());
326
327 return NewOperand;
328 }
329
330 // Instructions calculated in the current BB.
331 if (BBMap.count(OldOperand)) {
332 return BBMap[OldOperand];
333 }
334
335 // Ignore instructions that are referencing ops in the old BB. These
336 // instructions are unused. They where replace by new ones during
337 // createIndependentBlocks().
338 if (getRegion().contains(OpInst->getParent()))
339 return NULL;
340
341 return const_cast<Value*>(OldOperand);
342}
343
344Type *BlockGenerator::getVectorPtrTy(const Value *Val, int VectorWidth) {
345 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
346 assert(PointerTy && "PointerType expected");
347
348 Type *ScalarType = PointerTy->getElementType();
349 VectorType *VectorType = VectorType::get(ScalarType, VectorWidth);
350
351 return PointerType::getUnqual(VectorType);
352}
353
354Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
355 ValueMapT &BBMap, int Size) {
356 const Value *Pointer = Load->getPointerOperand();
357 Type *VectorPtrType = getVectorPtrTy(Pointer, Size);
358 Value *NewPointer = getOperand(Pointer, BBMap);
359 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
360 "vector_ptr");
361 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
362 Load->getName() + "_p_vec_full");
363 if (!Aligned)
364 VecLoad->setAlignment(8);
365
366 return VecLoad;
367}
368
369Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
370 ValueMapT &BBMap, int Size) {
371 const Value *Pointer = Load->getPointerOperand();
372 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
373 Value *NewPointer = getOperand(Pointer, BBMap);
374 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
375 Load->getName() + "_p_vec_p");
376 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
377 Load->getName() + "_p_splat_one");
378
379 if (!Aligned)
380 ScalarLoad->setAlignment(8);
381
Tobias Grossere5b423252012-01-24 16:42:25 +0000382 Constant *SplatVector =
383 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(), Size));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000384
385 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
386 SplatVector,
387 Load->getName()
388 + "_p_splat");
389 return VectorLoad;
390}
391
392Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
393 VectorValueMapT &ScalarMaps,
394 int Size) {
395 const Value *Pointer = Load->getPointerOperand();
396 VectorType *VectorType = VectorType::get(
397 dyn_cast<PointerType>(Pointer->getType())->getElementType(), Size);
398
399 Value *Vector = UndefValue::get(VectorType);
400
401 for (int i = 0; i < Size; i++) {
402 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
403 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
404 Load->getName() + "_p_scalar_");
405 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
406 Builder.getInt32(i),
407 Load->getName() + "_p_vec_");
408 }
409
410 return Vector;
411}
412
413Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
414 IslPwAffUserInfo *UserInfo) {
415 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
416
417 IRBuilder<> *Builder = UserInfo->Builder;
418
419 isl_int OffsetIsl;
420 mpz_t OffsetMPZ;
421
422 isl_int_init(OffsetIsl);
423 mpz_init(OffsetMPZ);
424 isl_aff_get_constant(Aff, &OffsetIsl);
425 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
426
427 Value *OffsetValue = NULL;
428 APInt Offset = APInt_from_MPZ(OffsetMPZ);
429 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
430
431 mpz_clear(OffsetMPZ);
432 isl_int_clear(OffsetIsl);
433 isl_aff_free(Aff);
434
435 return OffsetValue;
436}
437
438int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
439 __isl_take isl_aff *Aff, void *User) {
440 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
441
442 assert((UserInfo->Result == NULL) && "Result is already set."
443 "Currently only single isl_aff is supported");
444 assert(isl_set_plain_is_universe(Set)
445 && "Code generation failed because the set is not universe");
446
447 UserInfo->Result = islAffToValue(Aff, UserInfo);
448
449 isl_set_free(Set);
450 return 0;
451}
452
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000453Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000454 IslPwAffUserInfo UserInfo;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000455 UserInfo.Result = NULL;
456 UserInfo.Builder = &Builder;
457 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
458 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
459
460 isl_pw_aff_free(PwAff);
461 return UserInfo.Result;
462}
463
464std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
465 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
466 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
467 && "Only single dimensional access functions supported");
468
469 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000470 Value *OffsetValue = islPwAffToValue(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000471
472 PointerType *BaseAddressType = dyn_cast<PointerType>(
473 BaseAddress->getType());
474 Type *ArrayTy = BaseAddressType->getElementType();
475 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
476 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
477
478 std::vector<Value*> IndexArray;
479 Value *NullValue = Constant::getNullValue(ArrayElementType);
480 IndexArray.push_back(NullValue);
481 IndexArray.push_back(OffsetValue);
482 return IndexArray;
483}
484
485Value *BlockGenerator::getNewAccessOperand(
486 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
487 *OldOperand, ValueMapT &BBMap) {
488 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
489 BaseAddress);
490 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
491 "p_newarrayidx_");
492 return NewOperand;
493}
494
495Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
496 const Value *Pointer,
497 ValueMapT &BBMap ) {
498 MemoryAccess &Access = Statement.getAccessFor(Inst);
499 isl_map *CurrentAccessRelation = Access.getAccessRelation();
500 isl_map *NewAccessRelation = Access.getNewAccessRelation();
501
502 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
503 && "Current and new access function use different spaces");
504
505 Value *NewPointer;
506
507 if (!NewAccessRelation) {
508 NewPointer = getOperand(Pointer, BBMap);
509 } else {
510 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
511 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
512 BBMap);
513 }
514
515 isl_map_free(CurrentAccessRelation);
516 isl_map_free(NewAccessRelation);
517 return NewPointer;
518}
519
520Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
521 ValueMapT &BBMap) {
522 const Value *Pointer = Load->getPointerOperand();
523 const Instruction *Inst = dyn_cast<Instruction>(Load);
524 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
525 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
526 Load->getName() + "_p_scalar_");
527 return ScalarLoad;
528}
529
530void BlockGenerator::generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
531 VectorValueMapT &ScalarMaps,
532 int VectorWidth) {
533 if (ScalarMaps.size() == 1) {
534 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
535 return;
536 }
537
538 Value *NewLoad;
539
540 MemoryAccess &Access = Statement.getAccessFor(Load);
541
542 assert(ScatteringDomain && "No scattering domain available");
543
544 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
545 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0], VectorWidth);
546 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
547 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0], VectorWidth);
548 else
549 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps, VectorWidth);
550
551 VectorMap[Load] = NewLoad;
552}
553
554void BlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
555 ValueMapT &BBMap, ValueMapT &VectorMap,
556 int VectorDimension, int VectorWidth) {
557 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
558 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
559
560 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
561
562 const CastInst *Cast = dyn_cast<CastInst>(Inst);
563 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
564 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
565}
566
567void BlockGenerator::copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
568 ValueMapT &VectorMap, int VectorDimension,
569 int VectorWidth) {
570 Value *OpZero = Inst->getOperand(0);
571 Value *OpOne = Inst->getOperand(1);
572
573 Value *NewOpZero, *NewOpOne;
574 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
575 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
576
577 NewOpZero = makeVectorOperand(NewOpZero, VectorWidth);
578 NewOpOne = makeVectorOperand(NewOpOne, VectorWidth);
579
580 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
581 NewOpOne,
582 Inst->getName() + "p_vec");
583 VectorMap[Inst] = NewInst;
584}
585
586void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
587 ValueMapT &VectorMap,
588 VectorValueMapT &ScalarMaps,
589 int VectorDimension, int VectorWidth) {
590 // In vector mode we only generate a store for the first dimension.
591 if (VectorDimension > 0)
592 return;
593
594 MemoryAccess &Access = Statement.getAccessFor(Store);
595
596 assert(ScatteringDomain && "No scattering domain available");
597
598 const Value *Pointer = Store->getPointerOperand();
599 Value *Vector = getOperand(Store->getValueOperand(), BBMap, &VectorMap);
600
601 if (Access.isStrideOne(isl_set_copy(ScatteringDomain))) {
602 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
603 Value *NewPointer = getOperand(Pointer, BBMap, &VectorMap);
604
605 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
606 "vector_ptr");
607 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
608
609 if (!Aligned)
610 Store->setAlignment(8);
611 } else {
612 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
613 Value *Scalar = Builder.CreateExtractElement(Vector,
614 Builder.getInt32(i));
615 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
616 Builder.CreateStore(Scalar, NewPointer);
617 }
618 }
619}
620
621void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
622 Instruction *NewInst = Inst->clone();
623
624 // Replace old operands with the new ones.
625 for (Instruction::const_op_iterator OI = Inst->op_begin(),
626 OE = Inst->op_end(); OI != OE; ++OI) {
627 Value *OldOperand = *OI;
628 Value *NewOperand = getOperand(OldOperand, BBMap);
629
630 if (!NewOperand) {
631 assert(!isa<StoreInst>(NewInst)
632 && "Store instructions are always needed!");
633 delete NewInst;
634 return;
635 }
636
637 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
638 }
639
640 Builder.Insert(NewInst);
641 BBMap[Inst] = NewInst;
642
643 if (!NewInst->getType()->isVoidTy())
644 NewInst->setName("p_" + Inst->getName());
645}
646
647bool BlockGenerator::hasVectorOperands(const Instruction *Inst,
648 ValueMapT &VectorMap) {
649 for (Instruction::const_op_iterator OI = Inst->op_begin(),
650 OE = Inst->op_end(); OI != OE; ++OI)
651 if (VectorMap.count(*OI))
652 return true;
653 return false;
654}
655
656int BlockGenerator::getVectorSize() {
657 return ValueMaps.size();
658}
659
660bool BlockGenerator::isVectorBlock() {
661 return getVectorSize() > 1;
662}
663
664void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
665 ValueMapT &VectorMap,
666 VectorValueMapT &ScalarMaps,
667 int VectorDimension, int VectorWidth) {
668 // Terminator instructions control the control flow. They are explicitally
669 // expressed in the clast and do not need to be copied.
670 if (Inst->isTerminator())
671 return;
672
673 if (isVectorBlock()) {
674 // If this instruction is already in the vectorMap, a vector instruction
675 // was already issued, that calculates the values of all dimensions. No
676 // need to create any more instructions.
677 if (VectorMap.count(Inst))
678 return;
679 }
680
681 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
682 generateLoad(Load, VectorMap, ScalarMaps, VectorWidth);
683 return;
684 }
685
686 if (isVectorBlock() && hasVectorOperands(Inst, VectorMap)) {
687 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
688 copyUnaryInst(UnaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
689 else if
690 (const BinaryOperator *BinaryInst = dyn_cast<BinaryOperator>(Inst))
691 copyBinInst(BinaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
692 else if (const StoreInst *Store = dyn_cast<StoreInst>(Inst))
693 copyVectorStore(Store, BBMap, VectorMap, ScalarMaps, VectorDimension,
694 VectorWidth);
695 else
696 llvm_unreachable("Cannot issue vector code for this instruction");
697
698 return;
699 }
700
701 copyInstScalar(Inst, BBMap);
702}
703
Tobias Grosser0ac92142012-02-14 14:02:27 +0000704void BlockGenerator::copyBB(BasicBlock *BB, Pass *P) {
705 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
706 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000707 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000708 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000709
710 // Create two maps that store the mapping from the original instructions of
711 // the old basic block to their copies in the new basic block. Those maps
712 // are basic block local.
713 //
714 // As vector code generation is supported there is one map for scalar values
715 // and one for vector values.
716 //
717 // In case we just do scalar code generation, the vectorMap is not used and
718 // the scalarMap has just one dimension, which contains the mapping.
719 //
720 // In case vector code generation is done, an instruction may either appear
721 // in the vector map once (as it is calculating >vectorwidth< values at a
722 // time. Or (if the values are calculated using scalar operations), it
723 // appears once in every dimension of the scalarMap.
724 VectorValueMapT ScalarBlockMap(getVectorSize());
725 ValueMapT VectorBlockMap;
726
727 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
728 II != IE; ++II)
729 for (int i = 0; i < getVectorSize(); i++) {
730 if (isVectorBlock())
731 VMap = ValueMaps[i];
732
733 copyInstruction(II, ScalarBlockMap[i], VectorBlockMap,
734 ScalarBlockMap, i, getVectorSize());
735 }
736}
737
Tobias Grosser75805372011-04-29 06:27:02 +0000738/// Class to generate LLVM-IR that calculates the value of a clast_expr.
739class ClastExpCodeGen {
740 IRBuilder<> &Builder;
741 const CharMapT *IVS;
742
Tobias Grosserbb137e32012-01-24 16:42:28 +0000743 Value *codegen(const clast_name *e, Type *Ty);
744 Value *codegen(const clast_term *e, Type *Ty);
745 Value *codegen(const clast_binary *e, Type *Ty);
746 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000747public:
748
749 // A generator for clast expressions.
750 //
751 // @param B The IRBuilder that defines where the code to calculate the
752 // clast expressions should be inserted.
753 // @param IVMAP A Map that translates strings describing the induction
754 // variables to the Values* that represent these variables
755 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000756 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000757
758 // Generates code to calculate a given clast expression.
759 //
760 // @param e The expression to calculate.
761 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000762 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000763
764 // @brief Reset the CharMap.
765 //
766 // This function is called to reset the CharMap to new one, while generating
767 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000768 void setIVS(CharMapT *IVSNew);
769};
770
771Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
772 CharMapT::const_iterator I = IVS->find(e->name);
773
774 assert(I != IVS->end() && "Clast name not found");
775
776 return Builder.CreateSExtOrBitCast(I->second, Ty);
777}
778
779Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
780 APInt a = APInt_from_MPZ(e->val);
781
782 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
783 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
784
785 if (!e->var)
786 return ConstOne;
787
788 Value *var = codegen(e->var, Ty);
789 return Builder.CreateMul(ConstOne, var);
790}
791
792Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
793 Value *LHS = codegen(e->LHS, Ty);
794
795 APInt RHS_AP = APInt_from_MPZ(e->RHS);
796
797 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
798 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
799
800 switch (e->type) {
801 case clast_bin_mod:
802 return Builder.CreateSRem(LHS, RHS);
803 case clast_bin_fdiv:
804 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000805 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000806 Value *One = ConstantInt::get(Ty, 1);
807 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000808 Value *Sum1 = Builder.CreateSub(LHS, RHS);
809 Value *Sum2 = Builder.CreateAdd(Sum1, One);
810 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
811 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
812 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000813 }
814 case clast_bin_cdiv:
815 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000816 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
817 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000818 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000819 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
820 Value *Sum2 = Builder.CreateSub(Sum1, One);
821 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
822 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
823 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000824 }
825 case clast_bin_div:
826 return Builder.CreateSDiv(LHS, RHS);
827 };
828
829 llvm_unreachable("Unknown clast binary expression type");
830}
831
832Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
833 assert(( r->type == clast_red_min
834 || r->type == clast_red_max
835 || r->type == clast_red_sum)
836 && "Clast reduction type not supported");
837 Value *old = codegen(r->elts[0], Ty);
838
839 for (int i=1; i < r->n; ++i) {
840 Value *exprValue = codegen(r->elts[i], Ty);
841
842 switch (r->type) {
843 case clast_red_min:
844 {
845 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
846 old = Builder.CreateSelect(cmp, old, exprValue);
847 break;
848 }
849 case clast_red_max:
850 {
851 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
852 old = Builder.CreateSelect(cmp, old, exprValue);
853 break;
854 }
855 case clast_red_sum:
856 old = Builder.CreateAdd(old, exprValue);
857 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000858 }
Tobias Grosser75805372011-04-29 06:27:02 +0000859 }
860
Tobias Grosserbb137e32012-01-24 16:42:28 +0000861 return old;
862}
863
864ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
865 : Builder(B), IVS(IVMap) {}
866
867Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
868 switch(e->type) {
869 case clast_expr_name:
870 return codegen((const clast_name *)e, Ty);
871 case clast_expr_term:
872 return codegen((const clast_term *)e, Ty);
873 case clast_expr_bin:
874 return codegen((const clast_binary *)e, Ty);
875 case clast_expr_red:
876 return codegen((const clast_reduction *)e, Ty);
877 }
878
879 llvm_unreachable("Unknown clast expression!");
880}
881
882void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
883 IVS = IVSNew;
884}
Tobias Grosser75805372011-04-29 06:27:02 +0000885
886class ClastStmtCodeGen {
887 // The Scop we code generate.
888 Scop *S;
889 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000890 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000891 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000892 Dependences *DP;
893 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000894 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000895
896 // The Builder specifies the current location to code generate at.
897 IRBuilder<> &Builder;
898
899 // Map the Values from the old code to their counterparts in the new code.
900 ValueMapT ValueMap;
901
902 // clastVars maps from the textual representation of a clast variable to its
903 // current *Value. clast variables are scheduling variables, original
904 // induction variables or parameters. They are used either in loop bounds or
905 // to define the statement instance that is executed.
906 //
907 // for (s = 0; s < n + 3; ++i)
908 // for (t = s; t < m; ++j)
909 // Stmt(i = s + 3 * m, j = t);
910 //
911 // {s,t,i,j,n,m} is the set of clast variables in this clast.
912 CharMapT *clastVars;
913
914 // Codegenerator for clast expressions.
915 ClastExpCodeGen ExpGen;
916
917 // Do we currently generate parallel code?
918 bool parallelCodeGeneration;
919
920 std::vector<std::string> parallelLoops;
921
922public:
923
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000924 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000925
926 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000927 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000928
929 void codegen(const clast_assignment *a, ScopStmt *Statement,
930 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000931 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000932
933 void codegenSubstitutions(const clast_stmt *Assignment,
934 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000935 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000936
937 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000938 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000939
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000940 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000941
942 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000943 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000944 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000945
Tobias Grosser75805372011-04-29 06:27:02 +0000946 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000947 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000948
949 /// @brief Add values to the OpenMP structure.
950 ///
951 /// Create the subfunction structure and add the values from the list.
952 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000953 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000954
955 /// @brief Create OpenMP structure values.
956 ///
957 /// Create a list of values that has to be stored into the subfuncition
958 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000959 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000960
961 /// @brief Extract the values from the subfunction parameter.
962 ///
963 /// Extract the values from the subfunction parameter and update the clast
964 /// variables to point to the new values.
965 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
966 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000967 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000968
969 /// @brief Add body to the subfunction.
970 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
971 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000972 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000973
974 /// @brief Create an OpenMP parallel for loop.
975 ///
976 /// This loop reflects a loop as if it would have been created by an OpenMP
977 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000978 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000979
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000980 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000981
982 /// @brief Get the number of loop iterations for this loop.
983 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000985
986 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000987 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000988
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000989 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000990
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000993 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000995 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000997 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
999 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001000 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001001
1002 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001003 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001004 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001005};
1006}
1007
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001008const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1009 return parallelLoops;
1010}
1011
1012void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1013 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1014 (*clastVars)[a->LHS] = V;
1015}
1016
1017void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1018 unsigned Dimension, int vectorDim,
1019 std::vector<ValueMapT> *VectorVMap) {
1020 Value *RHS = ExpGen.codegen(a->RHS,
1021 TD->getIntPtrType(Builder.getContext()));
1022
1023 assert(!a->LHS && "Statement assignments do not have left hand side");
1024 const PHINode *PN;
1025 PN = Statement->getInductionVariableForDimension(Dimension);
1026 const Value *V = PN;
1027
1028 if (VectorVMap)
1029 (*VectorVMap)[vectorDim][V] = RHS;
1030
1031 ValueMap[V] = RHS;
1032}
1033
1034void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1035 ScopStmt *Statement, int vectorDim,
1036 std::vector<ValueMapT> *VectorVMap) {
1037 int Dimension = 0;
1038
1039 while (Assignment) {
1040 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1041 && "Substitions are expected to be assignments");
1042 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1043 vectorDim, VectorVMap);
1044 Assignment = Assignment->next;
1045 Dimension++;
1046 }
1047}
1048
1049void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1050 std::vector<Value*> *IVS , const char *iterator,
1051 isl_set *scatteringDomain) {
1052 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
1053 BasicBlock *BB = Statement->getBasicBlock();
1054
1055 if (u->substitutions)
1056 codegenSubstitutions(u->substitutions, Statement);
1057
1058 int vectorDimensions = IVS ? IVS->size() : 1;
1059
1060 VectorValueMapT VectorValueMap(vectorDimensions);
1061
1062 if (IVS) {
1063 assert (u->substitutions && "Substitutions expected!");
1064 int i = 0;
1065 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1066 II != IE; ++II) {
1067 (*clastVars)[iterator] = *II;
1068 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
1069 i++;
1070 }
1071 }
1072
1073 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
1074 scatteringDomain);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001075 Generator.copyBB(BB, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001076}
1077
1078void ClastStmtCodeGen::codegen(const clast_block *b) {
1079 if (b->body)
1080 codegen(b->body);
1081}
1082
1083void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1084 Value *LowerBound,
1085 Value *UpperBound) {
1086 APInt Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +00001087 BasicBlock *AfterBB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001088 Type *IntPtrTy;
1089
1090 Stride = APInt_from_MPZ(f->stride);
1091 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1092
1093 // The value of lowerbound and upperbound will be supplied, if this
1094 // function is called while generating OpenMP code. Otherwise get
1095 // the values.
1096 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1097
1098 if (LowerBound == 0) {
1099 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1100 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1101 }
1102
Tobias Grosser0ac92142012-02-14 14:02:27 +00001103 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1104 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001105
1106 // Add loop iv to symbols.
1107 (*clastVars)[f->iterator] = IV;
1108
1109 if (f->body)
1110 codegen(f->body);
1111
1112 // Loop is finished, so remove its iv from the live symbols.
1113 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001114 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001115}
1116
1117Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1118 Function *F = Builder.GetInsertBlock()->getParent();
1119 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1120 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1121 Function *FN = Function::Create(FT, Function::InternalLinkage,
1122 F->getName() + ".omp_subfn", M);
1123 // Do not run any polly pass on the new function.
1124 SD->markFunctionAsInvalid(FN);
1125
1126 Function::arg_iterator AI = FN->arg_begin();
1127 AI->setName("omp.userContext");
1128
1129 return FN;
1130}
1131
1132Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1133 Function *SubFunction) {
1134 std::vector<Type*> structMembers;
1135
1136 // Create the structure.
1137 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1138 structMembers.push_back(OMPDataVals[i]->getType());
1139
1140 StructType *structTy = StructType::get(Builder.getContext(),
1141 structMembers);
1142 // Store the values into the structure.
1143 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1144 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1145 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1146 Builder.CreateStore(OMPDataVals[i], storeAddr);
1147 }
1148
1149 return structData;
1150}
1151
1152SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1153 SetVector<Value*> OMPDataVals;
1154
1155 // Push the clast variables available in the clastVars.
1156 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1157 I != E; I++)
1158 OMPDataVals.insert(I->second);
1159
1160 // Push the base addresses of memory references.
1161 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1162 ScopStmt *Stmt = *SI;
1163 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1164 E = Stmt->memacc_end(); I != E; ++I) {
1165 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1166 OMPDataVals.insert((BaseAddr));
1167 }
1168 }
1169
1170 return OMPDataVals;
1171}
1172
1173void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1174 SetVector<Value*> OMPDataVals, Value *userContext) {
1175 // Extract the clast variables.
1176 unsigned i = 0;
1177 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1178 I != E; I++) {
1179 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1180 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1181 i++;
1182 }
1183
1184 // Extract the base addresses of memory references.
1185 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1186 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1187 Value *baseAddr = OMPDataVals[j];
1188 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1189 }
1190}
1191
1192void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1193 const clast_for *f,
1194 Value *structData,
1195 SetVector<Value*> OMPDataVals) {
1196 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1197 LLVMContext &Context = FN->getContext();
1198 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1199
1200 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001201 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001202 BasicBlock *PrevBB = Builder.GetInsertBlock();
1203
1204 // Create basic blocks.
1205 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1206 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1207 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1208 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1209 FN);
1210
1211 DT->addNewBlock(HeaderBB, PrevBB);
1212 DT->addNewBlock(ExitBB, HeaderBB);
1213 DT->addNewBlock(checkNextBB, HeaderBB);
1214 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1215
1216 // Fill up basic block HeaderBB.
1217 Builder.SetInsertPoint(HeaderBB);
1218 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1219 "omp.lowerBoundPtr");
1220 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1221 "omp.upperBoundPtr");
1222 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1223 structData->getType(),
1224 "omp.userContext");
1225
1226 CharMapT clastVarsOMP;
1227 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1228
1229 Builder.CreateBr(checkNextBB);
1230
1231 // Add code to check if another set of iterations will be executed.
1232 Builder.SetInsertPoint(checkNextBB);
1233 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1234 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1235 lowerBoundPtr, upperBoundPtr);
1236 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1237 "omp.hasNextScheduleBlock");
1238 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1239
1240 // Add code to to load the iv bounds for this set of iterations.
1241 Builder.SetInsertPoint(loadIVBoundsBB);
1242 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1243 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1244
1245 // Subtract one as the upper bound provided by openmp is a < comparison
1246 // whereas the codegenForSequential function creates a <= comparison.
1247 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1248 "omp.upperBoundAdjusted");
1249
1250 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1251 CharMapT *oldClastVars = clastVars;
1252 clastVars = &clastVarsOMP;
1253 ExpGen.setIVS(&clastVarsOMP);
1254
Tobias Grosser0ac92142012-02-14 14:02:27 +00001255 Builder.CreateBr(checkNextBB);
1256 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001257 codegenForSequential(f, lowerBound, upperBound);
1258
1259 // Restore the old clastVars.
1260 clastVars = oldClastVars;
1261 ExpGen.setIVS(oldClastVars);
1262
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001263 // Add code to terminate this openmp subfunction.
1264 Builder.SetInsertPoint(ExitBB);
1265 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1266 Builder.CreateCall(endnowaitFunction);
1267 Builder.CreateRetVoid();
1268
Tobias Grosser0ac92142012-02-14 14:02:27 +00001269 // Restore the previous insert point.
1270 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001271}
1272
1273void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1274 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1275 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1276
1277 Function *SubFunction = addOpenMPSubfunction(M);
1278 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1279 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1280
1281 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1282
1283 // Create call for GOMP_parallel_loop_runtime_start.
1284 Value *subfunctionParam = Builder.CreateBitCast(structData,
1285 Builder.getInt8PtrTy(),
1286 "omp_data");
1287
1288 Value *numberOfThreads = Builder.getInt32(0);
1289 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1290 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1291
1292 // Add one as the upper bound provided by openmp is a < comparison
1293 // whereas the codegenForSequential function creates a <= comparison.
1294 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1295 APInt APStride = APInt_from_MPZ(f->stride);
1296 Value *stride = ConstantInt::get(intPtrTy,
1297 APStride.zext(intPtrTy->getBitWidth()));
1298
1299 SmallVector<Value *, 6> Arguments;
1300 Arguments.push_back(SubFunction);
1301 Arguments.push_back(subfunctionParam);
1302 Arguments.push_back(numberOfThreads);
1303 Arguments.push_back(lowerBound);
1304 Arguments.push_back(upperBound);
1305 Arguments.push_back(stride);
1306
1307 Function *parallelStartFunction =
1308 M->getFunction("GOMP_parallel_loop_runtime_start");
1309 Builder.CreateCall(parallelStartFunction, Arguments);
1310
1311 // Create call to the subfunction.
1312 Builder.CreateCall(SubFunction, subfunctionParam);
1313
1314 // Create call for GOMP_parallel_end.
1315 Function *FN = M->getFunction("GOMP_parallel_end");
1316 Builder.CreateCall(FN);
1317}
1318
1319bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1320 const clast_stmt *stmt = f->body;
1321
1322 while (stmt) {
1323 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1324 return false;
1325
1326 stmt = stmt->next;
1327 }
1328
1329 return true;
1330}
1331
1332int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1333 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1334 isl_set *tmp = isl_set_copy(loopDomain);
1335
1336 // Calculate a map similar to the identity map, but with the last input
1337 // and output dimension not related.
1338 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1339 isl_space *Space = isl_set_get_space(loopDomain);
1340 Space = isl_space_drop_outputs(Space,
1341 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1342 Space = isl_space_map_from_set(Space);
1343 isl_map *identity = isl_map_identity(Space);
1344 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1345 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1346
1347 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1348 map = isl_map_intersect(map, identity);
1349
1350 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1351 isl_map *lexmin = isl_map_lexmin(map);
1352 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1353
1354 isl_set *elements = isl_map_range(sub);
1355
1356 if (!isl_set_is_singleton(elements)) {
1357 isl_set_free(elements);
1358 return -1;
1359 }
1360
1361 isl_point *p = isl_set_sample_point(elements);
1362
1363 isl_int v;
1364 isl_int_init(v);
1365 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1366 int numberIterations = isl_int_get_si(v);
1367 isl_int_clear(v);
1368 isl_point_free(p);
1369
1370 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1371}
1372
1373void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1374 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1375 int vectorWidth = getNumberOfIterations(f);
1376
1377 Value *LB = ExpGen.codegen(f->LB,
1378 TD->getIntPtrType(Builder.getContext()));
1379
1380 APInt Stride = APInt_from_MPZ(f->stride);
1381 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1382 Stride = Stride.zext(LoopIVType->getBitWidth());
1383 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1384
1385 std::vector<Value*> IVS(vectorWidth);
1386 IVS[0] = LB;
1387
1388 for (int i = 1; i < vectorWidth; i++)
1389 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1390
1391 isl_set *scatteringDomain =
1392 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1393
1394 // Add loop iv to symbols.
1395 (*clastVars)[f->iterator] = LB;
1396
1397 const clast_stmt *stmt = f->body;
1398
1399 while (stmt) {
1400 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1401 scatteringDomain);
1402 stmt = stmt->next;
1403 }
1404
1405 // Loop is finished, so remove its iv from the live symbols.
1406 isl_set_free(scatteringDomain);
1407 clastVars->erase(f->iterator);
1408}
1409
1410void ClastStmtCodeGen::codegen(const clast_for *f) {
1411 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
1412 && (-1 != getNumberOfIterations(f))
1413 && (getNumberOfIterations(f) <= 16)) {
1414 codegenForVector(f);
1415 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
1416 parallelCodeGeneration = true;
1417 parallelLoops.push_back(f->iterator);
1418 codegenForOpenMP(f);
1419 parallelCodeGeneration = false;
1420 } else
1421 codegenForSequential(f);
1422}
1423
1424Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1425 Value *LHS = ExpGen.codegen(eq->LHS,
1426 TD->getIntPtrType(Builder.getContext()));
1427 Value *RHS = ExpGen.codegen(eq->RHS,
1428 TD->getIntPtrType(Builder.getContext()));
1429 CmpInst::Predicate P;
1430
1431 if (eq->sign == 0)
1432 P = ICmpInst::ICMP_EQ;
1433 else if (eq->sign > 0)
1434 P = ICmpInst::ICMP_SGE;
1435 else
1436 P = ICmpInst::ICMP_SLE;
1437
1438 return Builder.CreateICmp(P, LHS, RHS);
1439}
1440
1441void ClastStmtCodeGen::codegen(const clast_guard *g) {
1442 Function *F = Builder.GetInsertBlock()->getParent();
1443 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001444
1445 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1446 Builder.GetInsertPoint(), P);
1447 CondBB->setName("polly.cond");
1448 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1449 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001450 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001451
1452 DT->addNewBlock(ThenBB, CondBB);
1453 DT->changeImmediateDominator(MergeBB, CondBB);
1454
1455 CondBB->getTerminator()->eraseFromParent();
1456
1457 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001458
1459 Value *Predicate = codegen(&(g->eq[0]));
1460
1461 for (int i = 1; i < g->n; ++i) {
1462 Value *TmpPredicate = codegen(&(g->eq[i]));
1463 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1464 }
1465
1466 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1467 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001468 Builder.CreateBr(MergeBB);
1469 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001470
1471 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001472
1473 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001474}
1475
1476void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1477 if (CLAST_STMT_IS_A(stmt, stmt_root))
1478 assert(false && "No second root statement expected");
1479 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1480 codegen((const clast_assignment *)stmt);
1481 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1482 codegen((const clast_user_stmt *)stmt);
1483 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1484 codegen((const clast_block *)stmt);
1485 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1486 codegen((const clast_for *)stmt);
1487 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1488 codegen((const clast_guard *)stmt);
1489
1490 if (stmt->next)
1491 codegen(stmt->next);
1492}
1493
1494void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1495 SCEVExpander Rewriter(SE, "polly");
1496
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001497 int i = 0;
1498 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1499 PI != PE; ++PI) {
1500 assert(i < names->nb_parameters && "Not enough parameter names");
1501
1502 const SCEV *Param = *PI;
1503 Type *Ty = Param->getType();
1504
1505 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1506 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1507 (*clastVars)[names->parameters[i]] = V;
1508
1509 ++i;
1510 }
1511}
1512
1513void ClastStmtCodeGen::codegen(const clast_root *r) {
1514 clastVars = new CharMapT();
1515 addParameters(r->names);
1516 ExpGen.setIVS(clastVars);
1517
1518 parallelCodeGeneration = false;
1519
1520 const clast_stmt *stmt = (const clast_stmt*) r;
1521 if (stmt->next)
1522 codegen(stmt->next);
1523
1524 delete clastVars;
1525}
1526
1527ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1528 DominatorTree *dt, ScopDetection *sd,
1529 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001530 IRBuilder<> &B, Pass *P) :
1531 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001532 ExpGen(Builder, NULL) {}
1533
Tobias Grosser75805372011-04-29 06:27:02 +00001534namespace {
1535class CodeGeneration : public ScopPass {
1536 Region *region;
1537 Scop *S;
1538 DominatorTree *DT;
1539 ScalarEvolution *SE;
1540 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001541 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001542 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001543
1544 std::vector<std::string> parallelLoops;
1545
1546 public:
1547 static char ID;
1548
1549 CodeGeneration() : ScopPass(ID) {}
1550
Tobias Grosserb1c95992012-02-12 12:09:27 +00001551 // Add the declarations needed by the OpenMP function calls that we insert in
1552 // OpenMP mode.
1553 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001554 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001555 IRBuilder<> Builder(M->getContext());
1556 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1557
1558 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001559
1560 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001561 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1562 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001563 }
1564
1565 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001566 Type *Params[] = {
1567 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1568 Builder.getInt8PtrTy(),
1569 false)),
1570 Builder.getInt8PtrTy(),
1571 Builder.getInt32Ty(),
1572 LongTy,
1573 LongTy,
1574 LongTy,
1575 };
Tobias Grosser75805372011-04-29 06:27:02 +00001576
Tobias Grosserd855cc52012-02-12 12:09:32 +00001577 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1578 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001579 }
1580
1581 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001582 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1583 Type *Params[] = {
1584 LongPtrTy,
1585 LongPtrTy,
1586 };
Tobias Grosser75805372011-04-29 06:27:02 +00001587
Tobias Grosserd855cc52012-02-12 12:09:32 +00001588 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1589 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001590 }
1591
1592 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001593 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1594 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001595 }
1596 }
1597
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001598 // Split the entry edge of the region and generate a new basic block on this
1599 // edge. This function also updates ScopInfo and RegionInfo.
1600 //
1601 // @param region The region where the entry edge will be splitted.
1602 BasicBlock *splitEdgeAdvanced(Region *region) {
1603 BasicBlock *newBlock;
1604 BasicBlock *splitBlock;
1605
1606 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1607
1608 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001609 BasicBlock *OldBlock = region->getEntry();
1610 std::string OldName = OldBlock->getName();
1611
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001612 // Update ScopInfo.
1613 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001614 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001615 (*SI)->setBasicBlock(newBlock);
1616 break;
1617 }
1618
1619 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001620 splitBlock = OldBlock;
1621 OldBlock->setName("polly.split");
1622 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001623 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001624 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001625 } else {
1626 RI->setRegionFor(newBlock, region->getParent());
1627 splitBlock = newBlock;
1628 }
1629
1630 return splitBlock;
1631 }
1632
1633 // Create a split block that branches either to the old code or to a new basic
1634 // block where the new code can be inserted.
1635 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001636 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001637 // the new code can be generated.
1638 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001639 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1640 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001641
Tobias Grosserbd608a82012-02-12 12:09:41 +00001642 SplitBlock = splitEdgeAdvanced(region);
1643 SplitBlock->setName("polly.split_new_and_old");
1644 Function *F = SplitBlock->getParent();
1645 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1646 SplitBlock->getTerminator()->eraseFromParent();
1647 Builder->SetInsertPoint(SplitBlock);
1648 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1649 DT->addNewBlock(StartBlock, SplitBlock);
1650 Builder->SetInsertPoint(StartBlock);
1651 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001652 }
1653
1654 // Merge the control flow of the newly generated code with the existing code.
1655 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001656 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001657 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001658 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001659 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001660 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1661 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001662 Region *R = region;
1663
1664 if (R->getExit()->getSinglePredecessor())
1665 // No splitEdge required. A block with a single predecessor cannot have
1666 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001667 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001668 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001669 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1671 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001672 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001673 }
1674
Tobias Grosserbd608a82012-02-12 12:09:41 +00001675 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001676 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001677
Tobias Grosserbd608a82012-02-12 12:09:41 +00001678 if (DT->dominates(SplitBlock, MergeBlock))
1679 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001680 }
1681
Tobias Grosser75805372011-04-29 06:27:02 +00001682 bool runOnScop(Scop &scop) {
1683 S = &scop;
1684 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001685 DT = &getAnalysis<DominatorTree>();
1686 Dependences *DP = &getAnalysis<Dependences>();
1687 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001688 SD = &getAnalysis<ScopDetection>();
1689 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001690 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001691
1692 parallelLoops.clear();
1693
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001694 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001695
Tobias Grosserb1c95992012-02-12 12:09:27 +00001696 Module *M = region->getEntry()->getParent()->getParent();
1697
Tobias Grosserd855cc52012-02-12 12:09:32 +00001698 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001699
Tobias Grosser5772e652012-02-01 14:23:33 +00001700 // In the CFG the optimized code of the SCoP is generated next to the
1701 // original code. Both the new and the original version of the code remain
1702 // in the CFG. A branch statement decides which version is executed.
1703 // For now, we always execute the new version (the old one is dead code
1704 // eliminated by the cleanup passes). In the future we may decide to execute
1705 // the new version only if certain run time checks succeed. This will be
1706 // useful to support constructs for which we cannot prove all assumptions at
1707 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001708 //
1709 // Before transformation:
1710 //
1711 // bb0
1712 // |
1713 // orig_scop
1714 // |
1715 // bb1
1716 //
1717 // After transformation:
1718 // bb0
1719 // |
1720 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001721 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001722 // | startBlock
1723 // | |
1724 // orig_scop new_scop
1725 // \ /
1726 // \ /
1727 // bb1 (joinBlock)
1728 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001729
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001730 // The builder will be set to startBlock.
1731 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001732 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001733
Tobias Grosser0ac92142012-02-14 14:02:27 +00001734 mergeControlFlow(splitBlock, &builder);
1735 builder.SetInsertPoint(StartBlock->begin());
1736
1737 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001738 CloogInfo &C = getAnalysis<CloogInfo>();
1739 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001740
Tobias Grosser75805372011-04-29 06:27:02 +00001741 parallelLoops.insert(parallelLoops.begin(),
1742 CodeGen.getParallelLoops().begin(),
1743 CodeGen.getParallelLoops().end());
1744
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001745 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001746 }
1747
1748 virtual void printScop(raw_ostream &OS) const {
1749 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1750 PE = parallelLoops.end(); PI != PE; ++PI)
1751 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1752 }
1753
1754 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1755 AU.addRequired<CloogInfo>();
1756 AU.addRequired<Dependences>();
1757 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001758 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001759 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001760 AU.addRequired<ScopDetection>();
1761 AU.addRequired<ScopInfo>();
1762 AU.addRequired<TargetData>();
1763
1764 AU.addPreserved<CloogInfo>();
1765 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001766
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001767 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001768 AU.addPreserved<LoopInfo>();
1769 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001770 AU.addPreserved<ScopDetection>();
1771 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001772
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001773 // FIXME: We do not yet add regions for the newly generated code to the
1774 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001775 AU.addPreserved<RegionInfo>();
1776 AU.addPreserved<TempScopInfo>();
1777 AU.addPreserved<ScopInfo>();
1778 AU.addPreservedID(IndependentBlocksID);
1779 }
1780};
1781}
1782
1783char CodeGeneration::ID = 1;
1784
Tobias Grosser73600b82011-10-08 00:30:40 +00001785INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1786 "Polly - Create LLVM-IR form SCoPs", false, false)
1787INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1788INITIALIZE_PASS_DEPENDENCY(Dependences)
1789INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1790INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1791INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1792INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1793INITIALIZE_PASS_DEPENDENCY(TargetData)
1794INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1795 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001796
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001797Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001798 return new CodeGeneration();
1799}