blob: 17613cbfbda11a3416b4440c22926dab93c32220 [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 {
805 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
806 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
807 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
808 One = Builder.CreateZExtOrBitCast(One, Ty);
809 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
810 Value *Sum1 = Builder.CreateSub(LHS, RHS);
811 Value *Sum2 = Builder.CreateAdd(Sum1, One);
812 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
813 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
814 return Builder.CreateSDiv(Dividend, RHS);
815 }
816 case clast_bin_cdiv:
817 {
818 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
819 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
820 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
821 One = Builder.CreateZExtOrBitCast(One, Ty);
822 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
823 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
824 Value *Sum2 = Builder.CreateSub(Sum1, One);
825 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
826 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
827 return Builder.CreateSDiv(Dividend, RHS);
828 }
829 case clast_bin_div:
830 return Builder.CreateSDiv(LHS, RHS);
831 };
832
833 llvm_unreachable("Unknown clast binary expression type");
834}
835
836Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
837 assert(( r->type == clast_red_min
838 || r->type == clast_red_max
839 || r->type == clast_red_sum)
840 && "Clast reduction type not supported");
841 Value *old = codegen(r->elts[0], Ty);
842
843 for (int i=1; i < r->n; ++i) {
844 Value *exprValue = codegen(r->elts[i], Ty);
845
846 switch (r->type) {
847 case clast_red_min:
848 {
849 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
850 old = Builder.CreateSelect(cmp, old, exprValue);
851 break;
852 }
853 case clast_red_max:
854 {
855 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
856 old = Builder.CreateSelect(cmp, old, exprValue);
857 break;
858 }
859 case clast_red_sum:
860 old = Builder.CreateAdd(old, exprValue);
861 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000862 }
Tobias Grosser75805372011-04-29 06:27:02 +0000863 }
864
Tobias Grosserbb137e32012-01-24 16:42:28 +0000865 return old;
866}
867
868ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
869 : Builder(B), IVS(IVMap) {}
870
871Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
872 switch(e->type) {
873 case clast_expr_name:
874 return codegen((const clast_name *)e, Ty);
875 case clast_expr_term:
876 return codegen((const clast_term *)e, Ty);
877 case clast_expr_bin:
878 return codegen((const clast_binary *)e, Ty);
879 case clast_expr_red:
880 return codegen((const clast_reduction *)e, Ty);
881 }
882
883 llvm_unreachable("Unknown clast expression!");
884}
885
886void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
887 IVS = IVSNew;
888}
Tobias Grosser75805372011-04-29 06:27:02 +0000889
890class ClastStmtCodeGen {
891 // The Scop we code generate.
892 Scop *S;
893 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000894 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000895 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000896 Dependences *DP;
897 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000898 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000899
900 // The Builder specifies the current location to code generate at.
901 IRBuilder<> &Builder;
902
903 // Map the Values from the old code to their counterparts in the new code.
904 ValueMapT ValueMap;
905
906 // clastVars maps from the textual representation of a clast variable to its
907 // current *Value. clast variables are scheduling variables, original
908 // induction variables or parameters. They are used either in loop bounds or
909 // to define the statement instance that is executed.
910 //
911 // for (s = 0; s < n + 3; ++i)
912 // for (t = s; t < m; ++j)
913 // Stmt(i = s + 3 * m, j = t);
914 //
915 // {s,t,i,j,n,m} is the set of clast variables in this clast.
916 CharMapT *clastVars;
917
918 // Codegenerator for clast expressions.
919 ClastExpCodeGen ExpGen;
920
921 // Do we currently generate parallel code?
922 bool parallelCodeGeneration;
923
924 std::vector<std::string> parallelLoops;
925
926public:
927
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000928 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000929
930 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000931 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000932
933 void codegen(const clast_assignment *a, ScopStmt *Statement,
934 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000935 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000936
937 void codegenSubstitutions(const clast_stmt *Assignment,
938 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000939 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000940
941 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000942 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000943
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000944 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000945
946 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000947 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000948 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000949
Tobias Grosser75805372011-04-29 06:27:02 +0000950 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000951 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000952
953 /// @brief Add values to the OpenMP structure.
954 ///
955 /// Create the subfunction structure and add the values from the list.
956 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000957 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000958
959 /// @brief Create OpenMP structure values.
960 ///
961 /// Create a list of values that has to be stored into the subfuncition
962 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000963 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000964
965 /// @brief Extract the values from the subfunction parameter.
966 ///
967 /// Extract the values from the subfunction parameter and update the clast
968 /// variables to point to the new values.
969 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
970 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000971 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000972
973 /// @brief Add body to the subfunction.
974 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
975 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000976 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000977
978 /// @brief Create an OpenMP parallel for loop.
979 ///
980 /// This loop reflects a loop as if it would have been created by an OpenMP
981 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000982 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000985
986 /// @brief Get the number of loop iterations for this loop.
987 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000988 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000989
990 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000993 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000995 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000997 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000999 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001000
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001001 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001002
1003 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001004 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001005
1006 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001007 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001008 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001009};
1010}
1011
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001012const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1013 return parallelLoops;
1014}
1015
1016void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1017 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1018 (*clastVars)[a->LHS] = V;
1019}
1020
1021void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1022 unsigned Dimension, int vectorDim,
1023 std::vector<ValueMapT> *VectorVMap) {
1024 Value *RHS = ExpGen.codegen(a->RHS,
1025 TD->getIntPtrType(Builder.getContext()));
1026
1027 assert(!a->LHS && "Statement assignments do not have left hand side");
1028 const PHINode *PN;
1029 PN = Statement->getInductionVariableForDimension(Dimension);
1030 const Value *V = PN;
1031
1032 if (VectorVMap)
1033 (*VectorVMap)[vectorDim][V] = RHS;
1034
1035 ValueMap[V] = RHS;
1036}
1037
1038void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1039 ScopStmt *Statement, int vectorDim,
1040 std::vector<ValueMapT> *VectorVMap) {
1041 int Dimension = 0;
1042
1043 while (Assignment) {
1044 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1045 && "Substitions are expected to be assignments");
1046 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1047 vectorDim, VectorVMap);
1048 Assignment = Assignment->next;
1049 Dimension++;
1050 }
1051}
1052
1053void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1054 std::vector<Value*> *IVS , const char *iterator,
1055 isl_set *scatteringDomain) {
1056 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
1057 BasicBlock *BB = Statement->getBasicBlock();
1058
1059 if (u->substitutions)
1060 codegenSubstitutions(u->substitutions, Statement);
1061
1062 int vectorDimensions = IVS ? IVS->size() : 1;
1063
1064 VectorValueMapT VectorValueMap(vectorDimensions);
1065
1066 if (IVS) {
1067 assert (u->substitutions && "Substitutions expected!");
1068 int i = 0;
1069 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1070 II != IE; ++II) {
1071 (*clastVars)[iterator] = *II;
1072 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
1073 i++;
1074 }
1075 }
1076
1077 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
1078 scatteringDomain);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001079 Generator.copyBB(BB, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001080}
1081
1082void ClastStmtCodeGen::codegen(const clast_block *b) {
1083 if (b->body)
1084 codegen(b->body);
1085}
1086
1087void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1088 Value *LowerBound,
1089 Value *UpperBound) {
1090 APInt Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +00001091 BasicBlock *AfterBB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001092 Type *IntPtrTy;
1093
1094 Stride = APInt_from_MPZ(f->stride);
1095 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1096
1097 // The value of lowerbound and upperbound will be supplied, if this
1098 // function is called while generating OpenMP code. Otherwise get
1099 // the values.
1100 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1101
1102 if (LowerBound == 0) {
1103 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1104 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1105 }
1106
Tobias Grosser0ac92142012-02-14 14:02:27 +00001107 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1108 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001109
1110 // Add loop iv to symbols.
1111 (*clastVars)[f->iterator] = IV;
1112
1113 if (f->body)
1114 codegen(f->body);
1115
1116 // Loop is finished, so remove its iv from the live symbols.
1117 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001118 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001119}
1120
1121Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1122 Function *F = Builder.GetInsertBlock()->getParent();
1123 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1124 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1125 Function *FN = Function::Create(FT, Function::InternalLinkage,
1126 F->getName() + ".omp_subfn", M);
1127 // Do not run any polly pass on the new function.
1128 SD->markFunctionAsInvalid(FN);
1129
1130 Function::arg_iterator AI = FN->arg_begin();
1131 AI->setName("omp.userContext");
1132
1133 return FN;
1134}
1135
1136Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1137 Function *SubFunction) {
1138 std::vector<Type*> structMembers;
1139
1140 // Create the structure.
1141 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1142 structMembers.push_back(OMPDataVals[i]->getType());
1143
1144 StructType *structTy = StructType::get(Builder.getContext(),
1145 structMembers);
1146 // Store the values into the structure.
1147 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1148 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1149 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1150 Builder.CreateStore(OMPDataVals[i], storeAddr);
1151 }
1152
1153 return structData;
1154}
1155
1156SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1157 SetVector<Value*> OMPDataVals;
1158
1159 // Push the clast variables available in the clastVars.
1160 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1161 I != E; I++)
1162 OMPDataVals.insert(I->second);
1163
1164 // Push the base addresses of memory references.
1165 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1166 ScopStmt *Stmt = *SI;
1167 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1168 E = Stmt->memacc_end(); I != E; ++I) {
1169 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1170 OMPDataVals.insert((BaseAddr));
1171 }
1172 }
1173
1174 return OMPDataVals;
1175}
1176
1177void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1178 SetVector<Value*> OMPDataVals, Value *userContext) {
1179 // Extract the clast variables.
1180 unsigned i = 0;
1181 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1182 I != E; I++) {
1183 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1184 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1185 i++;
1186 }
1187
1188 // Extract the base addresses of memory references.
1189 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1190 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1191 Value *baseAddr = OMPDataVals[j];
1192 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1193 }
1194}
1195
1196void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1197 const clast_for *f,
1198 Value *structData,
1199 SetVector<Value*> OMPDataVals) {
1200 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1201 LLVMContext &Context = FN->getContext();
1202 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1203
1204 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001205 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001206 BasicBlock *PrevBB = Builder.GetInsertBlock();
1207
1208 // Create basic blocks.
1209 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1210 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1211 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1212 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1213 FN);
1214
1215 DT->addNewBlock(HeaderBB, PrevBB);
1216 DT->addNewBlock(ExitBB, HeaderBB);
1217 DT->addNewBlock(checkNextBB, HeaderBB);
1218 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1219
1220 // Fill up basic block HeaderBB.
1221 Builder.SetInsertPoint(HeaderBB);
1222 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1223 "omp.lowerBoundPtr");
1224 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1225 "omp.upperBoundPtr");
1226 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1227 structData->getType(),
1228 "omp.userContext");
1229
1230 CharMapT clastVarsOMP;
1231 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1232
1233 Builder.CreateBr(checkNextBB);
1234
1235 // Add code to check if another set of iterations will be executed.
1236 Builder.SetInsertPoint(checkNextBB);
1237 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1238 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1239 lowerBoundPtr, upperBoundPtr);
1240 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1241 "omp.hasNextScheduleBlock");
1242 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1243
1244 // Add code to to load the iv bounds for this set of iterations.
1245 Builder.SetInsertPoint(loadIVBoundsBB);
1246 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1247 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1248
1249 // Subtract one as the upper bound provided by openmp is a < comparison
1250 // whereas the codegenForSequential function creates a <= comparison.
1251 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1252 "omp.upperBoundAdjusted");
1253
1254 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1255 CharMapT *oldClastVars = clastVars;
1256 clastVars = &clastVarsOMP;
1257 ExpGen.setIVS(&clastVarsOMP);
1258
Tobias Grosser0ac92142012-02-14 14:02:27 +00001259 Builder.CreateBr(checkNextBB);
1260 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001261 codegenForSequential(f, lowerBound, upperBound);
1262
1263 // Restore the old clastVars.
1264 clastVars = oldClastVars;
1265 ExpGen.setIVS(oldClastVars);
1266
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001267 // Add code to terminate this openmp subfunction.
1268 Builder.SetInsertPoint(ExitBB);
1269 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1270 Builder.CreateCall(endnowaitFunction);
1271 Builder.CreateRetVoid();
1272
Tobias Grosser0ac92142012-02-14 14:02:27 +00001273 // Restore the previous insert point.
1274 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001275}
1276
1277void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1278 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1279 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1280
1281 Function *SubFunction = addOpenMPSubfunction(M);
1282 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1283 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1284
1285 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1286
1287 // Create call for GOMP_parallel_loop_runtime_start.
1288 Value *subfunctionParam = Builder.CreateBitCast(structData,
1289 Builder.getInt8PtrTy(),
1290 "omp_data");
1291
1292 Value *numberOfThreads = Builder.getInt32(0);
1293 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1294 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1295
1296 // Add one as the upper bound provided by openmp is a < comparison
1297 // whereas the codegenForSequential function creates a <= comparison.
1298 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1299 APInt APStride = APInt_from_MPZ(f->stride);
1300 Value *stride = ConstantInt::get(intPtrTy,
1301 APStride.zext(intPtrTy->getBitWidth()));
1302
1303 SmallVector<Value *, 6> Arguments;
1304 Arguments.push_back(SubFunction);
1305 Arguments.push_back(subfunctionParam);
1306 Arguments.push_back(numberOfThreads);
1307 Arguments.push_back(lowerBound);
1308 Arguments.push_back(upperBound);
1309 Arguments.push_back(stride);
1310
1311 Function *parallelStartFunction =
1312 M->getFunction("GOMP_parallel_loop_runtime_start");
1313 Builder.CreateCall(parallelStartFunction, Arguments);
1314
1315 // Create call to the subfunction.
1316 Builder.CreateCall(SubFunction, subfunctionParam);
1317
1318 // Create call for GOMP_parallel_end.
1319 Function *FN = M->getFunction("GOMP_parallel_end");
1320 Builder.CreateCall(FN);
1321}
1322
1323bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1324 const clast_stmt *stmt = f->body;
1325
1326 while (stmt) {
1327 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1328 return false;
1329
1330 stmt = stmt->next;
1331 }
1332
1333 return true;
1334}
1335
1336int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1337 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1338 isl_set *tmp = isl_set_copy(loopDomain);
1339
1340 // Calculate a map similar to the identity map, but with the last input
1341 // and output dimension not related.
1342 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1343 isl_space *Space = isl_set_get_space(loopDomain);
1344 Space = isl_space_drop_outputs(Space,
1345 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1346 Space = isl_space_map_from_set(Space);
1347 isl_map *identity = isl_map_identity(Space);
1348 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1349 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1350
1351 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1352 map = isl_map_intersect(map, identity);
1353
1354 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1355 isl_map *lexmin = isl_map_lexmin(map);
1356 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1357
1358 isl_set *elements = isl_map_range(sub);
1359
1360 if (!isl_set_is_singleton(elements)) {
1361 isl_set_free(elements);
1362 return -1;
1363 }
1364
1365 isl_point *p = isl_set_sample_point(elements);
1366
1367 isl_int v;
1368 isl_int_init(v);
1369 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1370 int numberIterations = isl_int_get_si(v);
1371 isl_int_clear(v);
1372 isl_point_free(p);
1373
1374 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1375}
1376
1377void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1378 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1379 int vectorWidth = getNumberOfIterations(f);
1380
1381 Value *LB = ExpGen.codegen(f->LB,
1382 TD->getIntPtrType(Builder.getContext()));
1383
1384 APInt Stride = APInt_from_MPZ(f->stride);
1385 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1386 Stride = Stride.zext(LoopIVType->getBitWidth());
1387 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1388
1389 std::vector<Value*> IVS(vectorWidth);
1390 IVS[0] = LB;
1391
1392 for (int i = 1; i < vectorWidth; i++)
1393 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1394
1395 isl_set *scatteringDomain =
1396 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1397
1398 // Add loop iv to symbols.
1399 (*clastVars)[f->iterator] = LB;
1400
1401 const clast_stmt *stmt = f->body;
1402
1403 while (stmt) {
1404 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1405 scatteringDomain);
1406 stmt = stmt->next;
1407 }
1408
1409 // Loop is finished, so remove its iv from the live symbols.
1410 isl_set_free(scatteringDomain);
1411 clastVars->erase(f->iterator);
1412}
1413
1414void ClastStmtCodeGen::codegen(const clast_for *f) {
1415 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
1416 && (-1 != getNumberOfIterations(f))
1417 && (getNumberOfIterations(f) <= 16)) {
1418 codegenForVector(f);
1419 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
1420 parallelCodeGeneration = true;
1421 parallelLoops.push_back(f->iterator);
1422 codegenForOpenMP(f);
1423 parallelCodeGeneration = false;
1424 } else
1425 codegenForSequential(f);
1426}
1427
1428Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1429 Value *LHS = ExpGen.codegen(eq->LHS,
1430 TD->getIntPtrType(Builder.getContext()));
1431 Value *RHS = ExpGen.codegen(eq->RHS,
1432 TD->getIntPtrType(Builder.getContext()));
1433 CmpInst::Predicate P;
1434
1435 if (eq->sign == 0)
1436 P = ICmpInst::ICMP_EQ;
1437 else if (eq->sign > 0)
1438 P = ICmpInst::ICMP_SGE;
1439 else
1440 P = ICmpInst::ICMP_SLE;
1441
1442 return Builder.CreateICmp(P, LHS, RHS);
1443}
1444
1445void ClastStmtCodeGen::codegen(const clast_guard *g) {
1446 Function *F = Builder.GetInsertBlock()->getParent();
1447 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001448
1449 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1450 Builder.GetInsertPoint(), P);
1451 CondBB->setName("polly.cond");
1452 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1453 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001454 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001455
1456 DT->addNewBlock(ThenBB, CondBB);
1457 DT->changeImmediateDominator(MergeBB, CondBB);
1458
1459 CondBB->getTerminator()->eraseFromParent();
1460
1461 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001462
1463 Value *Predicate = codegen(&(g->eq[0]));
1464
1465 for (int i = 1; i < g->n; ++i) {
1466 Value *TmpPredicate = codegen(&(g->eq[i]));
1467 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1468 }
1469
1470 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1471 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001472 Builder.CreateBr(MergeBB);
1473 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001474
1475 codegen(g->then);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001476}
1477
1478void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1479 if (CLAST_STMT_IS_A(stmt, stmt_root))
1480 assert(false && "No second root statement expected");
1481 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1482 codegen((const clast_assignment *)stmt);
1483 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1484 codegen((const clast_user_stmt *)stmt);
1485 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1486 codegen((const clast_block *)stmt);
1487 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1488 codegen((const clast_for *)stmt);
1489 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1490 codegen((const clast_guard *)stmt);
1491
1492 if (stmt->next)
1493 codegen(stmt->next);
1494}
1495
1496void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1497 SCEVExpander Rewriter(SE, "polly");
1498
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001499 int i = 0;
1500 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1501 PI != PE; ++PI) {
1502 assert(i < names->nb_parameters && "Not enough parameter names");
1503
1504 const SCEV *Param = *PI;
1505 Type *Ty = Param->getType();
1506
1507 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1508 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1509 (*clastVars)[names->parameters[i]] = V;
1510
1511 ++i;
1512 }
1513}
1514
1515void ClastStmtCodeGen::codegen(const clast_root *r) {
1516 clastVars = new CharMapT();
1517 addParameters(r->names);
1518 ExpGen.setIVS(clastVars);
1519
1520 parallelCodeGeneration = false;
1521
1522 const clast_stmt *stmt = (const clast_stmt*) r;
1523 if (stmt->next)
1524 codegen(stmt->next);
1525
1526 delete clastVars;
1527}
1528
1529ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1530 DominatorTree *dt, ScopDetection *sd,
1531 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001532 IRBuilder<> &B, Pass *P) :
1533 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001534 ExpGen(Builder, NULL) {}
1535
Tobias Grosser75805372011-04-29 06:27:02 +00001536namespace {
1537class CodeGeneration : public ScopPass {
1538 Region *region;
1539 Scop *S;
1540 DominatorTree *DT;
1541 ScalarEvolution *SE;
1542 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001543 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001544 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001545
1546 std::vector<std::string> parallelLoops;
1547
1548 public:
1549 static char ID;
1550
1551 CodeGeneration() : ScopPass(ID) {}
1552
Tobias Grosserb1c95992012-02-12 12:09:27 +00001553 // Add the declarations needed by the OpenMP function calls that we insert in
1554 // OpenMP mode.
1555 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001556 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001557 IRBuilder<> Builder(M->getContext());
1558 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1559
1560 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001561
1562 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001563 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1564 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001565 }
1566
1567 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001568 Type *Params[] = {
1569 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1570 Builder.getInt8PtrTy(),
1571 false)),
1572 Builder.getInt8PtrTy(),
1573 Builder.getInt32Ty(),
1574 LongTy,
1575 LongTy,
1576 LongTy,
1577 };
Tobias Grosser75805372011-04-29 06:27:02 +00001578
Tobias Grosserd855cc52012-02-12 12:09:32 +00001579 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1580 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001581 }
1582
1583 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001584 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1585 Type *Params[] = {
1586 LongPtrTy,
1587 LongPtrTy,
1588 };
Tobias Grosser75805372011-04-29 06:27:02 +00001589
Tobias Grosserd855cc52012-02-12 12:09:32 +00001590 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1591 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001592 }
1593
1594 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001595 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1596 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001597 }
1598 }
1599
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001600 // Split the entry edge of the region and generate a new basic block on this
1601 // edge. This function also updates ScopInfo and RegionInfo.
1602 //
1603 // @param region The region where the entry edge will be splitted.
1604 BasicBlock *splitEdgeAdvanced(Region *region) {
1605 BasicBlock *newBlock;
1606 BasicBlock *splitBlock;
1607
1608 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1609
1610 if (DT->dominates(region->getEntry(), newBlock)) {
1611 // Update ScopInfo.
1612 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1613 if ((*SI)->getBasicBlock() == newBlock) {
1614 (*SI)->setBasicBlock(newBlock);
1615 break;
1616 }
1617
1618 // Update RegionInfo.
1619 splitBlock = region->getEntry();
1620 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001621 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001622 } else {
1623 RI->setRegionFor(newBlock, region->getParent());
1624 splitBlock = newBlock;
1625 }
1626
1627 return splitBlock;
1628 }
1629
1630 // Create a split block that branches either to the old code or to a new basic
1631 // block where the new code can be inserted.
1632 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001633 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001634 // the new code can be generated.
1635 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001636 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1637 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001638
Tobias Grosserbd608a82012-02-12 12:09:41 +00001639 SplitBlock = splitEdgeAdvanced(region);
1640 SplitBlock->setName("polly.split_new_and_old");
1641 Function *F = SplitBlock->getParent();
1642 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1643 SplitBlock->getTerminator()->eraseFromParent();
1644 Builder->SetInsertPoint(SplitBlock);
1645 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1646 DT->addNewBlock(StartBlock, SplitBlock);
1647 Builder->SetInsertPoint(StartBlock);
1648 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001649 }
1650
1651 // Merge the control flow of the newly generated code with the existing code.
1652 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001653 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001654 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001655 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001656 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001657 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1658 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001659 Region *R = region;
1660
1661 if (R->getExit()->getSinglePredecessor())
1662 // No splitEdge required. A block with a single predecessor cannot have
1663 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001664 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001665 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001666 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001667 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1668 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001669 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 }
1671
Tobias Grosserbd608a82012-02-12 12:09:41 +00001672 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001673 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001674
Tobias Grosserbd608a82012-02-12 12:09:41 +00001675 if (DT->dominates(SplitBlock, MergeBlock))
1676 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001677 }
1678
Tobias Grosser75805372011-04-29 06:27:02 +00001679 bool runOnScop(Scop &scop) {
1680 S = &scop;
1681 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001682 DT = &getAnalysis<DominatorTree>();
1683 Dependences *DP = &getAnalysis<Dependences>();
1684 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001685 SD = &getAnalysis<ScopDetection>();
1686 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001687 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001688
1689 parallelLoops.clear();
1690
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001691 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001692
Tobias Grosserb1c95992012-02-12 12:09:27 +00001693 Module *M = region->getEntry()->getParent()->getParent();
1694
Tobias Grosserd855cc52012-02-12 12:09:32 +00001695 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001696
Tobias Grosser5772e652012-02-01 14:23:33 +00001697 // In the CFG the optimized code of the SCoP is generated next to the
1698 // original code. Both the new and the original version of the code remain
1699 // in the CFG. A branch statement decides which version is executed.
1700 // For now, we always execute the new version (the old one is dead code
1701 // eliminated by the cleanup passes). In the future we may decide to execute
1702 // the new version only if certain run time checks succeed. This will be
1703 // useful to support constructs for which we cannot prove all assumptions at
1704 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001705 //
1706 // Before transformation:
1707 //
1708 // bb0
1709 // |
1710 // orig_scop
1711 // |
1712 // bb1
1713 //
1714 // After transformation:
1715 // bb0
1716 // |
1717 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001718 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001719 // | startBlock
1720 // | |
1721 // orig_scop new_scop
1722 // \ /
1723 // \ /
1724 // bb1 (joinBlock)
1725 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001726
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001727 // The builder will be set to startBlock.
1728 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001729 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001730
Tobias Grosser0ac92142012-02-14 14:02:27 +00001731 mergeControlFlow(splitBlock, &builder);
1732 builder.SetInsertPoint(StartBlock->begin());
1733
1734 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001735 CloogInfo &C = getAnalysis<CloogInfo>();
1736 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001737
Tobias Grosser75805372011-04-29 06:27:02 +00001738 parallelLoops.insert(parallelLoops.begin(),
1739 CodeGen.getParallelLoops().begin(),
1740 CodeGen.getParallelLoops().end());
1741
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001742 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001743 }
1744
1745 virtual void printScop(raw_ostream &OS) const {
1746 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1747 PE = parallelLoops.end(); PI != PE; ++PI)
1748 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1749 }
1750
1751 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1752 AU.addRequired<CloogInfo>();
1753 AU.addRequired<Dependences>();
1754 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001755 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001756 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001757 AU.addRequired<ScopDetection>();
1758 AU.addRequired<ScopInfo>();
1759 AU.addRequired<TargetData>();
1760
1761 AU.addPreserved<CloogInfo>();
1762 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001763
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001764 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001765 AU.addPreserved<LoopInfo>();
1766 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001767 AU.addPreserved<ScopDetection>();
1768 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001769
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001770 // FIXME: We do not yet add regions for the newly generated code to the
1771 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001772 AU.addPreserved<RegionInfo>();
1773 AU.addPreserved<TempScopInfo>();
1774 AU.addPreserved<ScopInfo>();
1775 AU.addPreservedID(IndependentBlocksID);
1776 }
1777};
1778}
1779
1780char CodeGeneration::ID = 1;
1781
Tobias Grosser73600b82011-10-08 00:30:40 +00001782INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1783 "Polly - Create LLVM-IR form SCoPs", false, false)
1784INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1785INITIALIZE_PASS_DEPENDENCY(Dependences)
1786INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1787INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1788INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1789INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1790INITIALIZE_PASS_DEPENDENCY(TargetData)
1791INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1792 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001793
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001794Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001795 return new CodeGeneration();
1796}