blob: 5914d2b25761a9a5f4dbfa18ae4ab246794c17e7 [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 {
Tobias Grosserc941ede2012-03-02 11:26:49 +0000158public:
159 /// @brief Generate code for single basic block.
160 static void generate(IRBuilder<> &B, ValueMapT &ValueMap,
161 VectorValueMapT &VectorMaps, ScopStmt &Stmt,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000162 __isl_keep isl_set *Domain, Pass *P) {
Tobias Grosser8412cda2012-03-02 11:26:55 +0000163 BlockGenerator Generator(B, ValueMap, VectorMaps, Stmt, Domain, P);
164 Generator.copyBB();
Tobias Grosserc941ede2012-03-02 11:26:49 +0000165 }
166
167private:
168 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000169 ScopStmt &Stmt, __isl_keep isl_set *domain, Pass *p);
Tobias Grosserc941ede2012-03-02 11:26:49 +0000170
Tobias Grosser75805372011-04-29 06:27:02 +0000171 IRBuilder<> &Builder;
172 ValueMapT &VMap;
173 VectorValueMapT &ValueMaps;
174 Scop &S;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000175 ScopStmt &Statement;
176 isl_set *ScatteringDomain;
Tobias Grosser8412cda2012-03-02 11:26:55 +0000177 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000178
Tobias Grosser75805372011-04-29 06:27:02 +0000179
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000180 const Region &getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000181
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000182 Value *makeVectorOperand(Value *Operand);
Tobias Grosser75805372011-04-29 06:27:02 +0000183
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000184 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000185 ValueMapT *VectorMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000186
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000187 Type *getVectorPtrTy(const Value *V, int Width);
Tobias Grosser75805372011-04-29 06:27:02 +0000188
189 /// @brief Load a vector from a set of adjacent scalars
190 ///
191 /// In case a set of scalars is known to be next to each other in memory,
192 /// create a vector load that loads those scalars
193 ///
194 /// %vector_ptr= bitcast double* %p to <4 x double>*
195 /// %vec_full = load <4 x double>* %vector_ptr
196 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000197 Value *generateStrideOneLoad(const LoadInst *Load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000198
199 /// @brief Load a vector initialized from a single scalar in memory
200 ///
201 /// In case all elements of a vector are initialized to the same
202 /// scalar value, this value is loaded and shuffeled into all elements
203 /// of the vector.
204 ///
205 /// %splat_one = load <1 x double>* %p
206 /// %splat = shufflevector <1 x double> %splat_one, <1 x
207 /// double> %splat_one, <4 x i32> zeroinitializer
208 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000209 Value *generateStrideZeroLoad(const LoadInst *Load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000210
211 /// @Load a vector from scalars distributed in memory
212 ///
213 /// In case some scalars a distributed randomly in memory. Create a vector
214 /// by loading each scalar and by inserting one after the other into the
215 /// vector.
216 ///
217 /// %scalar_1= load double* %p_1
218 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
219 /// %scalar 2 = load double* %p_2
220 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
221 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000222 Value *generateUnknownStrideLoad(const LoadInst *Load,
223 VectorValueMapT &ScalarMaps);
Tobias Grosser75805372011-04-29 06:27:02 +0000224
Raghesh Aloora71989c2011-12-28 02:48:26 +0000225 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000226 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000227
228 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000229 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000230
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000231 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000232
Raghesh Aloor129e8672011-08-15 02:33:39 +0000233 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000234 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000235 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000236
Raghesh Aloor62b13122011-08-03 17:02:50 +0000237 /// @brief Get the new operand address according to the changed access in
238 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000239 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
240 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000241 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000242
243 /// @brief Generate the operand address
244 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000245 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000246
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000247 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000248
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000249 void generateVectorLoad(const LoadInst *Load, ValueMapT &VectorMap,
250 VectorValueMapT &ScalarMaps);
Tobias Grosser75805372011-04-29 06:27:02 +0000251
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000252 void copyVectorUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
253 ValueMapT &VectorMap);
Tobias Grosserc9215152011-09-04 11:45:52 +0000254
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000255 void copyVectorBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
256 ValueMapT &VectorMap);
Tobias Grosser09c57102011-09-04 11:45:29 +0000257
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000258 void copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
Tobias Grosser8927a442012-03-02 11:27:05 +0000259 ValueMapT &VectorMap, VectorValueMapT &ScalarMaps);
Tobias Grosser75805372011-04-29 06:27:02 +0000260
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000261 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000262
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000263 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000264
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000265 int getVectorWidth();
Tobias Grosser75805372011-04-29 06:27:02 +0000266
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000267 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000268
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000269 void copyInstruction(const Instruction *Inst, ValueMapT &VectorMap,
270 VectorValueMapT &ScalarMaps);
Tobias Grosser7551c302011-09-04 11:45:41 +0000271
Tobias Grosser75805372011-04-29 06:27:02 +0000272 // Insert a copy of a basic block in the newly generated code.
273 //
274 // @param Builder The builder used to insert the code. It also specifies
275 // where to insert the code.
Tobias Grosser75805372011-04-29 06:27:02 +0000276 // @param VMap A map returning for any old value its new equivalent. This
277 // is used to update the operands of the statements.
278 // For new statements a relation old->new is inserted in this
279 // map.
Tobias Grosser8412cda2012-03-02 11:26:55 +0000280 void copyBB();
Tobias Grosser75805372011-04-29 06:27:02 +0000281};
282
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000283BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
284 VectorValueMapT &vmaps, ScopStmt &Stmt,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000285 __isl_keep isl_set *domain, Pass *P)
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000286 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
Tobias Grosser8412cda2012-03-02 11:26:55 +0000287 Statement(Stmt), ScatteringDomain(domain), P(P) {}
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000288
289const Region &BlockGenerator::getRegion() {
290 return S.getRegion();
291}
292
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000293Value *BlockGenerator::makeVectorOperand(Value *Operand) {
294 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000295 if (Operand->getType()->isVectorTy())
296 return Operand;
297
298 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
299 Value *Vector = UndefValue::get(VectorType);
300 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
301
302 std::vector<Constant*> Splat;
303
304 for (int i = 0; i < VectorWidth; i++)
305 Splat.push_back (Builder.getInt32(0));
306
307 Constant *SplatVector = ConstantVector::get(Splat);
308
309 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
310}
311
312Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
313 ValueMapT *VectorMap) {
314 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
315
316 if (!OpInst)
317 return const_cast<Value*>(OldOperand);
318
319 if (VectorMap && VectorMap->count(OldOperand))
320 return (*VectorMap)[OldOperand];
321
322 // IVS and Parameters.
323 if (VMap.count(OldOperand)) {
324 Value *NewOperand = VMap[OldOperand];
325
326 // Insert a cast if types are different
327 if (OldOperand->getType()->getScalarSizeInBits()
328 < NewOperand->getType()->getScalarSizeInBits())
329 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
330 OldOperand->getType());
331
332 return NewOperand;
333 }
334
335 // Instructions calculated in the current BB.
336 if (BBMap.count(OldOperand)) {
337 return BBMap[OldOperand];
338 }
339
340 // Ignore instructions that are referencing ops in the old BB. These
341 // instructions are unused. They where replace by new ones during
342 // createIndependentBlocks().
343 if (getRegion().contains(OpInst->getParent()))
344 return NULL;
345
346 return const_cast<Value*>(OldOperand);
347}
348
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000349Type *BlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000350 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
351 assert(PointerTy && "PointerType expected");
352
353 Type *ScalarType = PointerTy->getElementType();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000354 VectorType *VectorType = VectorType::get(ScalarType, Width);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000355
356 return PointerType::getUnqual(VectorType);
357}
358
359Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000360 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000361 const Value *Pointer = Load->getPointerOperand();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000362 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000363 Value *NewPointer = getOperand(Pointer, BBMap);
364 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
365 "vector_ptr");
366 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
367 Load->getName() + "_p_vec_full");
368 if (!Aligned)
369 VecLoad->setAlignment(8);
370
371 return VecLoad;
372}
373
374Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000375 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000376 const Value *Pointer = Load->getPointerOperand();
377 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
378 Value *NewPointer = getOperand(Pointer, BBMap);
379 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
380 Load->getName() + "_p_vec_p");
381 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
382 Load->getName() + "_p_splat_one");
383
384 if (!Aligned)
385 ScalarLoad->setAlignment(8);
386
Tobias Grossere5b423252012-01-24 16:42:25 +0000387 Constant *SplatVector =
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000388 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
389 getVectorWidth()));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000390
391 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
392 SplatVector,
393 Load->getName()
394 + "_p_splat");
395 return VectorLoad;
396}
397
398Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000399 VectorValueMapT &ScalarMaps) {
400 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000401 const Value *Pointer = Load->getPointerOperand();
402 VectorType *VectorType = VectorType::get(
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000403 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000404
405 Value *Vector = UndefValue::get(VectorType);
406
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000407 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000408 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
409 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
410 Load->getName() + "_p_scalar_");
411 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
412 Builder.getInt32(i),
413 Load->getName() + "_p_vec_");
414 }
415
416 return Vector;
417}
418
419Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
420 IslPwAffUserInfo *UserInfo) {
421 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
422
423 IRBuilder<> *Builder = UserInfo->Builder;
424
425 isl_int OffsetIsl;
426 mpz_t OffsetMPZ;
427
428 isl_int_init(OffsetIsl);
429 mpz_init(OffsetMPZ);
430 isl_aff_get_constant(Aff, &OffsetIsl);
431 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
432
433 Value *OffsetValue = NULL;
434 APInt Offset = APInt_from_MPZ(OffsetMPZ);
435 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
436
437 mpz_clear(OffsetMPZ);
438 isl_int_clear(OffsetIsl);
439 isl_aff_free(Aff);
440
441 return OffsetValue;
442}
443
444int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
445 __isl_take isl_aff *Aff, void *User) {
446 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
447
448 assert((UserInfo->Result == NULL) && "Result is already set."
449 "Currently only single isl_aff is supported");
450 assert(isl_set_plain_is_universe(Set)
451 && "Code generation failed because the set is not universe");
452
453 UserInfo->Result = islAffToValue(Aff, UserInfo);
454
455 isl_set_free(Set);
456 return 0;
457}
458
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000459Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000460 IslPwAffUserInfo UserInfo;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000461 UserInfo.Result = NULL;
462 UserInfo.Builder = &Builder;
463 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
464 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
465
466 isl_pw_aff_free(PwAff);
467 return UserInfo.Result;
468}
469
470std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
471 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
472 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
473 && "Only single dimensional access functions supported");
474
475 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000476 Value *OffsetValue = islPwAffToValue(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000477
478 PointerType *BaseAddressType = dyn_cast<PointerType>(
479 BaseAddress->getType());
480 Type *ArrayTy = BaseAddressType->getElementType();
481 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
482 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
483
484 std::vector<Value*> IndexArray;
485 Value *NullValue = Constant::getNullValue(ArrayElementType);
486 IndexArray.push_back(NullValue);
487 IndexArray.push_back(OffsetValue);
488 return IndexArray;
489}
490
491Value *BlockGenerator::getNewAccessOperand(
492 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
493 *OldOperand, ValueMapT &BBMap) {
494 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
495 BaseAddress);
496 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
497 "p_newarrayidx_");
498 return NewOperand;
499}
500
501Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
502 const Value *Pointer,
503 ValueMapT &BBMap ) {
504 MemoryAccess &Access = Statement.getAccessFor(Inst);
505 isl_map *CurrentAccessRelation = Access.getAccessRelation();
506 isl_map *NewAccessRelation = Access.getNewAccessRelation();
507
508 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
509 && "Current and new access function use different spaces");
510
511 Value *NewPointer;
512
513 if (!NewAccessRelation) {
514 NewPointer = getOperand(Pointer, BBMap);
515 } else {
516 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
517 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
518 BBMap);
519 }
520
521 isl_map_free(CurrentAccessRelation);
522 isl_map_free(NewAccessRelation);
523 return NewPointer;
524}
525
526Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
527 ValueMapT &BBMap) {
528 const Value *Pointer = Load->getPointerOperand();
529 const Instruction *Inst = dyn_cast<Instruction>(Load);
530 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
531 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
532 Load->getName() + "_p_scalar_");
533 return ScalarLoad;
534}
535
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000536void BlockGenerator::generateVectorLoad(const LoadInst *Load,
537 ValueMapT &VectorMap,
538 VectorValueMapT &ScalarMaps) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000539 Value *NewLoad;
540
541 MemoryAccess &Access = Statement.getAccessFor(Load);
542
543 assert(ScatteringDomain && "No scattering domain available");
544
545 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000546 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000547 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000548 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000549 else
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000550 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000551
552 VectorMap[Load] = NewLoad;
553}
554
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000555void BlockGenerator::copyVectorUnaryInst(const UnaryInstruction *Inst,
556 ValueMapT &BBMap,
557 ValueMapT &VectorMap) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000558 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000559 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000560 NewOperand = makeVectorOperand(NewOperand);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000561
562 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
563
564 const CastInst *Cast = dyn_cast<CastInst>(Inst);
565 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
566 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
567}
568
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000569void BlockGenerator::copyVectorBinInst(const BinaryOperator *Inst,
570 ValueMapT &BBMap, ValueMapT &VectorMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000571 Value *OpZero = Inst->getOperand(0);
572 Value *OpOne = Inst->getOperand(1);
573
574 Value *NewOpZero, *NewOpOne;
575 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
576 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
577
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000578 NewOpZero = makeVectorOperand(NewOpZero);
579 NewOpOne = makeVectorOperand(NewOpOne);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000580
581 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
582 NewOpOne,
583 Inst->getName() + "p_vec");
584 VectorMap[Inst] = NewInst;
585}
586
587void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
588 ValueMapT &VectorMap,
Tobias Grosser8927a442012-03-02 11:27:05 +0000589 VectorValueMapT &ScalarMaps) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000590 int VectorWidth = getVectorWidth();
591
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000592 MemoryAccess &Access = Statement.getAccessFor(Store);
593
594 assert(ScatteringDomain && "No scattering domain available");
595
596 const Value *Pointer = Store->getPointerOperand();
597 Value *Vector = getOperand(Store->getValueOperand(), BBMap, &VectorMap);
598
599 if (Access.isStrideOne(isl_set_copy(ScatteringDomain))) {
600 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
601 Value *NewPointer = getOperand(Pointer, BBMap, &VectorMap);
602
603 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
604 "vector_ptr");
605 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
606
607 if (!Aligned)
608 Store->setAlignment(8);
609 } else {
610 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
611 Value *Scalar = Builder.CreateExtractElement(Vector,
612 Builder.getInt32(i));
613 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
614 Builder.CreateStore(Scalar, NewPointer);
615 }
616 }
617}
618
619void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
620 Instruction *NewInst = Inst->clone();
621
622 // Replace old operands with the new ones.
623 for (Instruction::const_op_iterator OI = Inst->op_begin(),
624 OE = Inst->op_end(); OI != OE; ++OI) {
625 Value *OldOperand = *OI;
626 Value *NewOperand = getOperand(OldOperand, BBMap);
627
628 if (!NewOperand) {
629 assert(!isa<StoreInst>(NewInst)
630 && "Store instructions are always needed!");
631 delete NewInst;
632 return;
633 }
634
635 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
636 }
637
638 Builder.Insert(NewInst);
639 BBMap[Inst] = NewInst;
640
641 if (!NewInst->getType()->isVoidTy())
642 NewInst->setName("p_" + Inst->getName());
643}
644
645bool BlockGenerator::hasVectorOperands(const Instruction *Inst,
646 ValueMapT &VectorMap) {
647 for (Instruction::const_op_iterator OI = Inst->op_begin(),
648 OE = Inst->op_end(); OI != OE; ++OI)
649 if (VectorMap.count(*OI))
650 return true;
651 return false;
652}
653
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000654int BlockGenerator::getVectorWidth() {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000655 return ValueMaps.size();
656}
657
658bool BlockGenerator::isVectorBlock() {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000659 return getVectorWidth() > 1;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000660}
661
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000662void BlockGenerator::copyInstruction(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000663 ValueMapT &VectorMap,
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000664 VectorValueMapT &ScalarMaps) {
Tobias Grosserb35d9c12012-03-02 11:27:08 +0000665 // Terminator instructions control the control flow. They are explicitly
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000666 // expressed in the clast and do not need to be copied.
667 if (Inst->isTerminator())
668 return;
669
670 if (isVectorBlock()) {
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000671 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
672 generateVectorLoad(Load, VectorMap, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000673 return;
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000674 }
Tobias Grosser8927a442012-03-02 11:27:05 +0000675
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000676 if (hasVectorOperands(Inst, VectorMap)) {
677 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
678 copyVectorStore(Store, ScalarMaps[0], VectorMap, ScalarMaps);
679 return;
680 }
Tobias Grosser8927a442012-03-02 11:27:05 +0000681
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000682 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
683 copyVectorUnaryInst(Unary, ScalarMaps[0], VectorMap);
684 return;
685 }
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000686
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000687 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
688 copyVectorBinInst(Binary, ScalarMaps[0], VectorMap);
689 return;
690 }
691
692 llvm_unreachable("Cannot issue vector code for this instruction");
693 }
694
695 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
696 copyInstScalar(Inst, ScalarMaps[VectorLane]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000697 return;
698 }
699
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000700 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
701 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
702 return;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000703 }
704
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000705 copyInstScalar(Inst, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000706}
707
Tobias Grosser8412cda2012-03-02 11:26:55 +0000708void BlockGenerator::copyBB() {
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000709 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000710 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
711 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000712 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000713 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000714
715 // Create two maps that store the mapping from the original instructions of
716 // the old basic block to their copies in the new basic block. Those maps
717 // are basic block local.
718 //
719 // As vector code generation is supported there is one map for scalar values
720 // and one for vector values.
721 //
722 // In case we just do scalar code generation, the vectorMap is not used and
723 // the scalarMap has just one dimension, which contains the mapping.
724 //
725 // In case vector code generation is done, an instruction may either appear
726 // in the vector map once (as it is calculating >vectorwidth< values at a
727 // time. Or (if the values are calculated using scalar operations), it
728 // appears once in every dimension of the scalarMap.
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000729 VectorValueMapT ScalarBlockMap(getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000730 ValueMapT VectorBlockMap;
731
732 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
733 II != IE; ++II)
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000734 copyInstruction(II, VectorBlockMap, ScalarBlockMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000735}
736
Tobias Grosser75805372011-04-29 06:27:02 +0000737/// Class to generate LLVM-IR that calculates the value of a clast_expr.
738class ClastExpCodeGen {
739 IRBuilder<> &Builder;
740 const CharMapT *IVS;
741
Tobias Grosserbb137e32012-01-24 16:42:28 +0000742 Value *codegen(const clast_name *e, Type *Ty);
743 Value *codegen(const clast_term *e, Type *Ty);
744 Value *codegen(const clast_binary *e, Type *Ty);
745 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000746public:
747
748 // A generator for clast expressions.
749 //
750 // @param B The IRBuilder that defines where the code to calculate the
751 // clast expressions should be inserted.
752 // @param IVMAP A Map that translates strings describing the induction
753 // variables to the Values* that represent these variables
754 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000755 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757 // Generates code to calculate a given clast expression.
758 //
759 // @param e The expression to calculate.
760 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000761 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000762
763 // @brief Reset the CharMap.
764 //
765 // This function is called to reset the CharMap to new one, while generating
766 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000767 void setIVS(CharMapT *IVSNew);
768};
769
770Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
771 CharMapT::const_iterator I = IVS->find(e->name);
772
773 assert(I != IVS->end() && "Clast name not found");
774
775 return Builder.CreateSExtOrBitCast(I->second, Ty);
776}
777
778Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
779 APInt a = APInt_from_MPZ(e->val);
780
781 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
782 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
783
784 if (!e->var)
785 return ConstOne;
786
787 Value *var = codegen(e->var, Ty);
788 return Builder.CreateMul(ConstOne, var);
789}
790
791Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
792 Value *LHS = codegen(e->LHS, Ty);
793
794 APInt RHS_AP = APInt_from_MPZ(e->RHS);
795
796 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
797 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
798
799 switch (e->type) {
800 case clast_bin_mod:
801 return Builder.CreateSRem(LHS, RHS);
802 case clast_bin_fdiv:
803 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000804 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000805 Value *One = ConstantInt::get(Ty, 1);
806 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000807 Value *Sum1 = Builder.CreateSub(LHS, RHS);
808 Value *Sum2 = Builder.CreateAdd(Sum1, One);
809 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
810 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
811 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000812 }
813 case clast_bin_cdiv:
814 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000815 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
816 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000817 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000818 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
819 Value *Sum2 = Builder.CreateSub(Sum1, One);
820 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
821 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
822 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000823 }
824 case clast_bin_div:
825 return Builder.CreateSDiv(LHS, RHS);
826 };
827
828 llvm_unreachable("Unknown clast binary expression type");
829}
830
831Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
832 assert(( r->type == clast_red_min
833 || r->type == clast_red_max
834 || r->type == clast_red_sum)
835 && "Clast reduction type not supported");
836 Value *old = codegen(r->elts[0], Ty);
837
838 for (int i=1; i < r->n; ++i) {
839 Value *exprValue = codegen(r->elts[i], Ty);
840
841 switch (r->type) {
842 case clast_red_min:
843 {
844 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
845 old = Builder.CreateSelect(cmp, old, exprValue);
846 break;
847 }
848 case clast_red_max:
849 {
850 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
851 old = Builder.CreateSelect(cmp, old, exprValue);
852 break;
853 }
854 case clast_red_sum:
855 old = Builder.CreateAdd(old, exprValue);
856 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000857 }
Tobias Grosser75805372011-04-29 06:27:02 +0000858 }
859
Tobias Grosserbb137e32012-01-24 16:42:28 +0000860 return old;
861}
862
863ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
864 : Builder(B), IVS(IVMap) {}
865
866Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
867 switch(e->type) {
868 case clast_expr_name:
869 return codegen((const clast_name *)e, Ty);
870 case clast_expr_term:
871 return codegen((const clast_term *)e, Ty);
872 case clast_expr_bin:
873 return codegen((const clast_binary *)e, Ty);
874 case clast_expr_red:
875 return codegen((const clast_reduction *)e, Ty);
876 }
877
878 llvm_unreachable("Unknown clast expression!");
879}
880
881void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
882 IVS = IVSNew;
883}
Tobias Grosser75805372011-04-29 06:27:02 +0000884
885class ClastStmtCodeGen {
886 // The Scop we code generate.
887 Scop *S;
888 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000889 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000890 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000891 Dependences *DP;
892 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000893 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000894
895 // The Builder specifies the current location to code generate at.
896 IRBuilder<> &Builder;
897
898 // Map the Values from the old code to their counterparts in the new code.
899 ValueMapT ValueMap;
900
901 // clastVars maps from the textual representation of a clast variable to its
902 // current *Value. clast variables are scheduling variables, original
903 // induction variables or parameters. They are used either in loop bounds or
904 // to define the statement instance that is executed.
905 //
906 // for (s = 0; s < n + 3; ++i)
907 // for (t = s; t < m; ++j)
908 // Stmt(i = s + 3 * m, j = t);
909 //
910 // {s,t,i,j,n,m} is the set of clast variables in this clast.
911 CharMapT *clastVars;
912
913 // Codegenerator for clast expressions.
914 ClastExpCodeGen ExpGen;
915
916 // Do we currently generate parallel code?
917 bool parallelCodeGeneration;
918
919 std::vector<std::string> parallelLoops;
920
921public:
922
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000923 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000924
925 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000926 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928 void codegen(const clast_assignment *a, ScopStmt *Statement,
929 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000930 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000931
932 void codegenSubstitutions(const clast_stmt *Assignment,
933 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000934 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000935
936 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000937 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000938
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000939 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000940
941 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000942 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000943 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000944
Tobias Grosser75805372011-04-29 06:27:02 +0000945 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000946 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000947
948 /// @brief Add values to the OpenMP structure.
949 ///
950 /// Create the subfunction structure and add the values from the list.
951 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000952 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000953
954 /// @brief Create OpenMP structure values.
955 ///
956 /// Create a list of values that has to be stored into the subfuncition
957 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000958 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000959
960 /// @brief Extract the values from the subfunction parameter.
961 ///
962 /// Extract the values from the subfunction parameter and update the clast
963 /// variables to point to the new values.
964 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
965 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000966 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000967
968 /// @brief Add body to the subfunction.
969 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
970 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000971 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000972
973 /// @brief Create an OpenMP parallel for loop.
974 ///
975 /// This loop reflects a loop as if it would have been created by an OpenMP
976 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000977 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000978
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000979 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000980
981 /// @brief Get the number of loop iterations for this loop.
982 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000983 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000984
985 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000986 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000987
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000988 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000990 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000992 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000993
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000994 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000995
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000996 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000997
998 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000999 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001000
1001 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001002 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001003 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001004};
1005}
1006
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001007const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1008 return parallelLoops;
1009}
1010
1011void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1012 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1013 (*clastVars)[a->LHS] = V;
1014}
1015
1016void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1017 unsigned Dimension, int vectorDim,
1018 std::vector<ValueMapT> *VectorVMap) {
1019 Value *RHS = ExpGen.codegen(a->RHS,
1020 TD->getIntPtrType(Builder.getContext()));
1021
1022 assert(!a->LHS && "Statement assignments do not have left hand side");
1023 const PHINode *PN;
1024 PN = Statement->getInductionVariableForDimension(Dimension);
1025 const Value *V = PN;
1026
1027 if (VectorVMap)
1028 (*VectorVMap)[vectorDim][V] = RHS;
1029
1030 ValueMap[V] = RHS;
1031}
1032
1033void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1034 ScopStmt *Statement, int vectorDim,
1035 std::vector<ValueMapT> *VectorVMap) {
1036 int Dimension = 0;
1037
1038 while (Assignment) {
1039 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1040 && "Substitions are expected to be assignments");
1041 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1042 vectorDim, VectorVMap);
1043 Assignment = Assignment->next;
1044 Dimension++;
1045 }
1046}
1047
1048void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1049 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001050 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001051 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001052
1053 if (u->substitutions)
1054 codegenSubstitutions(u->substitutions, Statement);
1055
1056 int vectorDimensions = IVS ? IVS->size() : 1;
1057
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001058 VectorValueMapT VectorMap(vectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001059
1060 if (IVS) {
1061 assert (u->substitutions && "Substitutions expected!");
1062 int i = 0;
1063 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1064 II != IE; ++II) {
1065 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001066 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001067 i++;
1068 }
1069 }
1070
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001071 BlockGenerator::generate(Builder, ValueMap, VectorMap, *Statement, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001072}
1073
1074void ClastStmtCodeGen::codegen(const clast_block *b) {
1075 if (b->body)
1076 codegen(b->body);
1077}
1078
1079void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1080 Value *LowerBound,
1081 Value *UpperBound) {
1082 APInt Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +00001083 BasicBlock *AfterBB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001084 Type *IntPtrTy;
1085
1086 Stride = APInt_from_MPZ(f->stride);
1087 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1088
1089 // The value of lowerbound and upperbound will be supplied, if this
1090 // function is called while generating OpenMP code. Otherwise get
1091 // the values.
1092 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1093
1094 if (LowerBound == 0) {
1095 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1096 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1097 }
1098
Tobias Grosser0ac92142012-02-14 14:02:27 +00001099 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1100 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001101
1102 // Add loop iv to symbols.
1103 (*clastVars)[f->iterator] = IV;
1104
1105 if (f->body)
1106 codegen(f->body);
1107
1108 // Loop is finished, so remove its iv from the live symbols.
1109 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001110 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001111}
1112
1113Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1114 Function *F = Builder.GetInsertBlock()->getParent();
1115 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1116 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1117 Function *FN = Function::Create(FT, Function::InternalLinkage,
1118 F->getName() + ".omp_subfn", M);
1119 // Do not run any polly pass on the new function.
1120 SD->markFunctionAsInvalid(FN);
1121
1122 Function::arg_iterator AI = FN->arg_begin();
1123 AI->setName("omp.userContext");
1124
1125 return FN;
1126}
1127
1128Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1129 Function *SubFunction) {
1130 std::vector<Type*> structMembers;
1131
1132 // Create the structure.
1133 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1134 structMembers.push_back(OMPDataVals[i]->getType());
1135
1136 StructType *structTy = StructType::get(Builder.getContext(),
1137 structMembers);
1138 // Store the values into the structure.
1139 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1140 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1141 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1142 Builder.CreateStore(OMPDataVals[i], storeAddr);
1143 }
1144
1145 return structData;
1146}
1147
1148SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1149 SetVector<Value*> OMPDataVals;
1150
1151 // Push the clast variables available in the clastVars.
1152 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1153 I != E; I++)
1154 OMPDataVals.insert(I->second);
1155
1156 // Push the base addresses of memory references.
1157 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1158 ScopStmt *Stmt = *SI;
1159 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1160 E = Stmt->memacc_end(); I != E; ++I) {
1161 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1162 OMPDataVals.insert((BaseAddr));
1163 }
1164 }
1165
1166 return OMPDataVals;
1167}
1168
1169void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1170 SetVector<Value*> OMPDataVals, Value *userContext) {
1171 // Extract the clast variables.
1172 unsigned i = 0;
1173 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1174 I != E; I++) {
1175 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1176 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1177 i++;
1178 }
1179
1180 // Extract the base addresses of memory references.
1181 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1182 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1183 Value *baseAddr = OMPDataVals[j];
1184 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1185 }
1186}
1187
1188void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1189 const clast_for *f,
1190 Value *structData,
1191 SetVector<Value*> OMPDataVals) {
1192 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1193 LLVMContext &Context = FN->getContext();
1194 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1195
1196 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001197 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001198 BasicBlock *PrevBB = Builder.GetInsertBlock();
1199
1200 // Create basic blocks.
1201 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1202 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1203 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1204 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1205 FN);
1206
1207 DT->addNewBlock(HeaderBB, PrevBB);
1208 DT->addNewBlock(ExitBB, HeaderBB);
1209 DT->addNewBlock(checkNextBB, HeaderBB);
1210 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1211
1212 // Fill up basic block HeaderBB.
1213 Builder.SetInsertPoint(HeaderBB);
1214 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1215 "omp.lowerBoundPtr");
1216 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1217 "omp.upperBoundPtr");
1218 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1219 structData->getType(),
1220 "omp.userContext");
1221
1222 CharMapT clastVarsOMP;
1223 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1224
1225 Builder.CreateBr(checkNextBB);
1226
1227 // Add code to check if another set of iterations will be executed.
1228 Builder.SetInsertPoint(checkNextBB);
1229 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1230 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1231 lowerBoundPtr, upperBoundPtr);
1232 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1233 "omp.hasNextScheduleBlock");
1234 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1235
1236 // Add code to to load the iv bounds for this set of iterations.
1237 Builder.SetInsertPoint(loadIVBoundsBB);
1238 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1239 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1240
1241 // Subtract one as the upper bound provided by openmp is a < comparison
1242 // whereas the codegenForSequential function creates a <= comparison.
1243 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1244 "omp.upperBoundAdjusted");
1245
1246 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1247 CharMapT *oldClastVars = clastVars;
1248 clastVars = &clastVarsOMP;
1249 ExpGen.setIVS(&clastVarsOMP);
1250
Tobias Grosser0ac92142012-02-14 14:02:27 +00001251 Builder.CreateBr(checkNextBB);
1252 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001253 codegenForSequential(f, lowerBound, upperBound);
1254
1255 // Restore the old clastVars.
1256 clastVars = oldClastVars;
1257 ExpGen.setIVS(oldClastVars);
1258
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001259 // Add code to terminate this openmp subfunction.
1260 Builder.SetInsertPoint(ExitBB);
1261 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1262 Builder.CreateCall(endnowaitFunction);
1263 Builder.CreateRetVoid();
1264
Tobias Grosser0ac92142012-02-14 14:02:27 +00001265 // Restore the previous insert point.
1266 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001267}
1268
1269void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1270 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1271 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1272
1273 Function *SubFunction = addOpenMPSubfunction(M);
1274 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1275 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1276
1277 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1278
1279 // Create call for GOMP_parallel_loop_runtime_start.
1280 Value *subfunctionParam = Builder.CreateBitCast(structData,
1281 Builder.getInt8PtrTy(),
1282 "omp_data");
1283
1284 Value *numberOfThreads = Builder.getInt32(0);
1285 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1286 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1287
1288 // Add one as the upper bound provided by openmp is a < comparison
1289 // whereas the codegenForSequential function creates a <= comparison.
1290 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1291 APInt APStride = APInt_from_MPZ(f->stride);
1292 Value *stride = ConstantInt::get(intPtrTy,
1293 APStride.zext(intPtrTy->getBitWidth()));
1294
1295 SmallVector<Value *, 6> Arguments;
1296 Arguments.push_back(SubFunction);
1297 Arguments.push_back(subfunctionParam);
1298 Arguments.push_back(numberOfThreads);
1299 Arguments.push_back(lowerBound);
1300 Arguments.push_back(upperBound);
1301 Arguments.push_back(stride);
1302
1303 Function *parallelStartFunction =
1304 M->getFunction("GOMP_parallel_loop_runtime_start");
1305 Builder.CreateCall(parallelStartFunction, Arguments);
1306
1307 // Create call to the subfunction.
1308 Builder.CreateCall(SubFunction, subfunctionParam);
1309
1310 // Create call for GOMP_parallel_end.
1311 Function *FN = M->getFunction("GOMP_parallel_end");
1312 Builder.CreateCall(FN);
1313}
1314
1315bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1316 const clast_stmt *stmt = f->body;
1317
1318 while (stmt) {
1319 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1320 return false;
1321
1322 stmt = stmt->next;
1323 }
1324
1325 return true;
1326}
1327
1328int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1329 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1330 isl_set *tmp = isl_set_copy(loopDomain);
1331
1332 // Calculate a map similar to the identity map, but with the last input
1333 // and output dimension not related.
1334 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1335 isl_space *Space = isl_set_get_space(loopDomain);
1336 Space = isl_space_drop_outputs(Space,
1337 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1338 Space = isl_space_map_from_set(Space);
1339 isl_map *identity = isl_map_identity(Space);
1340 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1341 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1342
1343 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1344 map = isl_map_intersect(map, identity);
1345
1346 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1347 isl_map *lexmin = isl_map_lexmin(map);
1348 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1349
1350 isl_set *elements = isl_map_range(sub);
1351
1352 if (!isl_set_is_singleton(elements)) {
1353 isl_set_free(elements);
1354 return -1;
1355 }
1356
1357 isl_point *p = isl_set_sample_point(elements);
1358
1359 isl_int v;
1360 isl_int_init(v);
1361 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1362 int numberIterations = isl_int_get_si(v);
1363 isl_int_clear(v);
1364 isl_point_free(p);
1365
1366 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1367}
1368
1369void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1370 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1371 int vectorWidth = getNumberOfIterations(f);
1372
1373 Value *LB = ExpGen.codegen(f->LB,
1374 TD->getIntPtrType(Builder.getContext()));
1375
1376 APInt Stride = APInt_from_MPZ(f->stride);
1377 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1378 Stride = Stride.zext(LoopIVType->getBitWidth());
1379 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1380
1381 std::vector<Value*> IVS(vectorWidth);
1382 IVS[0] = LB;
1383
1384 for (int i = 1; i < vectorWidth; i++)
1385 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1386
1387 isl_set *scatteringDomain =
1388 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1389
1390 // Add loop iv to symbols.
1391 (*clastVars)[f->iterator] = LB;
1392
1393 const clast_stmt *stmt = f->body;
1394
1395 while (stmt) {
1396 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1397 scatteringDomain);
1398 stmt = stmt->next;
1399 }
1400
1401 // Loop is finished, so remove its iv from the live symbols.
1402 isl_set_free(scatteringDomain);
1403 clastVars->erase(f->iterator);
1404}
1405
1406void ClastStmtCodeGen::codegen(const clast_for *f) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001407 if ((Vector || OpenMP) && DP->isParallelFor(f)) {
1408 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1409 && (getNumberOfIterations(f) <= 16)) {
1410 codegenForVector(f);
1411 return;
1412 }
1413
1414 if (OpenMP && !parallelCodeGeneration) {
1415 parallelCodeGeneration = true;
1416 parallelLoops.push_back(f->iterator);
1417 codegenForOpenMP(f);
1418 parallelCodeGeneration = false;
1419 return;
1420 }
1421 }
1422
1423 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001424}
1425
1426Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1427 Value *LHS = ExpGen.codegen(eq->LHS,
1428 TD->getIntPtrType(Builder.getContext()));
1429 Value *RHS = ExpGen.codegen(eq->RHS,
1430 TD->getIntPtrType(Builder.getContext()));
1431 CmpInst::Predicate P;
1432
1433 if (eq->sign == 0)
1434 P = ICmpInst::ICMP_EQ;
1435 else if (eq->sign > 0)
1436 P = ICmpInst::ICMP_SGE;
1437 else
1438 P = ICmpInst::ICMP_SLE;
1439
1440 return Builder.CreateICmp(P, LHS, RHS);
1441}
1442
1443void ClastStmtCodeGen::codegen(const clast_guard *g) {
1444 Function *F = Builder.GetInsertBlock()->getParent();
1445 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001446
1447 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1448 Builder.GetInsertPoint(), P);
1449 CondBB->setName("polly.cond");
1450 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1451 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001452 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001453
1454 DT->addNewBlock(ThenBB, CondBB);
1455 DT->changeImmediateDominator(MergeBB, CondBB);
1456
1457 CondBB->getTerminator()->eraseFromParent();
1458
1459 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001460
1461 Value *Predicate = codegen(&(g->eq[0]));
1462
1463 for (int i = 1; i < g->n; ++i) {
1464 Value *TmpPredicate = codegen(&(g->eq[i]));
1465 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1466 }
1467
1468 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1469 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001470 Builder.CreateBr(MergeBB);
1471 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001472
1473 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001474
1475 Builder.SetInsertPoint(MergeBB->begin());
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)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001611 BasicBlock *OldBlock = region->getEntry();
1612 std::string OldName = OldBlock->getName();
1613
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001614 // Update ScopInfo.
1615 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001616 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001617 (*SI)->setBasicBlock(newBlock);
1618 break;
1619 }
1620
1621 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001622 splitBlock = OldBlock;
1623 OldBlock->setName("polly.split");
1624 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001625 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001626 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001627 } else {
1628 RI->setRegionFor(newBlock, region->getParent());
1629 splitBlock = newBlock;
1630 }
1631
1632 return splitBlock;
1633 }
1634
1635 // Create a split block that branches either to the old code or to a new basic
1636 // block where the new code can be inserted.
1637 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001638 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001639 // the new code can be generated.
1640 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001641 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1642 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001643
Tobias Grosserbd608a82012-02-12 12:09:41 +00001644 SplitBlock = splitEdgeAdvanced(region);
1645 SplitBlock->setName("polly.split_new_and_old");
1646 Function *F = SplitBlock->getParent();
1647 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1648 SplitBlock->getTerminator()->eraseFromParent();
1649 Builder->SetInsertPoint(SplitBlock);
1650 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1651 DT->addNewBlock(StartBlock, SplitBlock);
1652 Builder->SetInsertPoint(StartBlock);
1653 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001654 }
1655
1656 // Merge the control flow of the newly generated code with the existing code.
1657 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001658 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001659 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001660 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001661 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001662 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1663 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001664 Region *R = region;
1665
1666 if (R->getExit()->getSinglePredecessor())
1667 // No splitEdge required. A block with a single predecessor cannot have
1668 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001669 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001671 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001672 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1673 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001674 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001675 }
1676
Tobias Grosserbd608a82012-02-12 12:09:41 +00001677 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001678 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001679
Tobias Grosserbd608a82012-02-12 12:09:41 +00001680 if (DT->dominates(SplitBlock, MergeBlock))
1681 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001682 }
1683
Tobias Grosser75805372011-04-29 06:27:02 +00001684 bool runOnScop(Scop &scop) {
1685 S = &scop;
1686 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001687 DT = &getAnalysis<DominatorTree>();
1688 Dependences *DP = &getAnalysis<Dependences>();
1689 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001690 SD = &getAnalysis<ScopDetection>();
1691 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001692 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001693
1694 parallelLoops.clear();
1695
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001696 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001697
Tobias Grosserb1c95992012-02-12 12:09:27 +00001698 Module *M = region->getEntry()->getParent()->getParent();
1699
Tobias Grosserd855cc52012-02-12 12:09:32 +00001700 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001701
Tobias Grosser5772e652012-02-01 14:23:33 +00001702 // In the CFG the optimized code of the SCoP is generated next to the
1703 // original code. Both the new and the original version of the code remain
1704 // in the CFG. A branch statement decides which version is executed.
1705 // For now, we always execute the new version (the old one is dead code
1706 // eliminated by the cleanup passes). In the future we may decide to execute
1707 // the new version only if certain run time checks succeed. This will be
1708 // useful to support constructs for which we cannot prove all assumptions at
1709 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001710 //
1711 // Before transformation:
1712 //
1713 // bb0
1714 // |
1715 // orig_scop
1716 // |
1717 // bb1
1718 //
1719 // After transformation:
1720 // bb0
1721 // |
1722 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001723 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001724 // | startBlock
1725 // | |
1726 // orig_scop new_scop
1727 // \ /
1728 // \ /
1729 // bb1 (joinBlock)
1730 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001731
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001732 // The builder will be set to startBlock.
1733 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001734 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001735
Tobias Grosser0ac92142012-02-14 14:02:27 +00001736 mergeControlFlow(splitBlock, &builder);
1737 builder.SetInsertPoint(StartBlock->begin());
1738
1739 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001740 CloogInfo &C = getAnalysis<CloogInfo>();
1741 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001742
Tobias Grosser75805372011-04-29 06:27:02 +00001743 parallelLoops.insert(parallelLoops.begin(),
1744 CodeGen.getParallelLoops().begin(),
1745 CodeGen.getParallelLoops().end());
1746
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001747 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001748 }
1749
1750 virtual void printScop(raw_ostream &OS) const {
1751 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1752 PE = parallelLoops.end(); PI != PE; ++PI)
1753 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1754 }
1755
1756 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1757 AU.addRequired<CloogInfo>();
1758 AU.addRequired<Dependences>();
1759 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001760 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001761 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001762 AU.addRequired<ScopDetection>();
1763 AU.addRequired<ScopInfo>();
1764 AU.addRequired<TargetData>();
1765
1766 AU.addPreserved<CloogInfo>();
1767 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001768
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001769 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001770 AU.addPreserved<LoopInfo>();
1771 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001772 AU.addPreserved<ScopDetection>();
1773 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001774
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001775 // FIXME: We do not yet add regions for the newly generated code to the
1776 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001777 AU.addPreserved<RegionInfo>();
1778 AU.addPreserved<TempScopInfo>();
1779 AU.addPreserved<ScopInfo>();
1780 AU.addPreservedID(IndependentBlocksID);
1781 }
1782};
1783}
1784
1785char CodeGeneration::ID = 1;
1786
Tobias Grosser73600b82011-10-08 00:30:40 +00001787INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1788 "Polly - Create LLVM-IR form SCoPs", false, false)
1789INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1790INITIALIZE_PASS_DEPENDENCY(Dependences)
1791INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1792INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1793INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1794INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1795INITIALIZE_PASS_DEPENDENCY(TargetData)
1796INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1797 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001798
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001799Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001800 return new CodeGeneration();
1801}