blob: 224ce4016af5c6744a2206731b3d1771f30b04b1 [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 Grosser32152cb2012-03-02 11:27:18 +0000269 void copyVectorInstruction(const Instruction *Inst, ValueMapT &VectorMap,
270 VectorValueMapT &ScalarMaps);
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000271 void copyInstruction(const Instruction *Inst, ValueMapT &VectorMap,
272 VectorValueMapT &ScalarMaps);
Tobias Grosser7551c302011-09-04 11:45:41 +0000273
Tobias Grosser75805372011-04-29 06:27:02 +0000274 // Insert a copy of a basic block in the newly generated code.
275 //
276 // @param Builder The builder used to insert the code. It also specifies
277 // where to insert the code.
Tobias Grosser75805372011-04-29 06:27:02 +0000278 // @param VMap A map returning for any old value its new equivalent. This
279 // is used to update the operands of the statements.
280 // For new statements a relation old->new is inserted in this
281 // map.
Tobias Grosser8412cda2012-03-02 11:26:55 +0000282 void copyBB();
Tobias Grosser75805372011-04-29 06:27:02 +0000283};
284
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000285BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
286 VectorValueMapT &vmaps, ScopStmt &Stmt,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000287 __isl_keep isl_set *domain, Pass *P)
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000288 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
Tobias Grosser8412cda2012-03-02 11:26:55 +0000289 Statement(Stmt), ScatteringDomain(domain), P(P) {}
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000290
291const Region &BlockGenerator::getRegion() {
292 return S.getRegion();
293}
294
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000295Value *BlockGenerator::makeVectorOperand(Value *Operand) {
296 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000297 if (Operand->getType()->isVectorTy())
298 return Operand;
299
300 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
301 Value *Vector = UndefValue::get(VectorType);
302 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
303
304 std::vector<Constant*> Splat;
305
306 for (int i = 0; i < VectorWidth; i++)
307 Splat.push_back (Builder.getInt32(0));
308
309 Constant *SplatVector = ConstantVector::get(Splat);
310
311 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
312}
313
314Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
315 ValueMapT *VectorMap) {
316 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
317
318 if (!OpInst)
319 return const_cast<Value*>(OldOperand);
320
321 if (VectorMap && VectorMap->count(OldOperand))
322 return (*VectorMap)[OldOperand];
323
324 // IVS and Parameters.
325 if (VMap.count(OldOperand)) {
326 Value *NewOperand = VMap[OldOperand];
327
328 // Insert a cast if types are different
329 if (OldOperand->getType()->getScalarSizeInBits()
330 < NewOperand->getType()->getScalarSizeInBits())
331 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
332 OldOperand->getType());
333
334 return NewOperand;
335 }
336
337 // Instructions calculated in the current BB.
338 if (BBMap.count(OldOperand)) {
339 return BBMap[OldOperand];
340 }
341
342 // Ignore instructions that are referencing ops in the old BB. These
343 // instructions are unused. They where replace by new ones during
344 // createIndependentBlocks().
345 if (getRegion().contains(OpInst->getParent()))
346 return NULL;
347
348 return const_cast<Value*>(OldOperand);
349}
350
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000351Type *BlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000352 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
353 assert(PointerTy && "PointerType expected");
354
355 Type *ScalarType = PointerTy->getElementType();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000356 VectorType *VectorType = VectorType::get(ScalarType, Width);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000357
358 return PointerType::getUnqual(VectorType);
359}
360
361Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000362 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000363 const Value *Pointer = Load->getPointerOperand();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000364 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000365 Value *NewPointer = getOperand(Pointer, BBMap);
366 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
367 "vector_ptr");
368 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
369 Load->getName() + "_p_vec_full");
370 if (!Aligned)
371 VecLoad->setAlignment(8);
372
373 return VecLoad;
374}
375
376Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000377 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000378 const Value *Pointer = Load->getPointerOperand();
379 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
380 Value *NewPointer = getOperand(Pointer, BBMap);
381 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
382 Load->getName() + "_p_vec_p");
383 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
384 Load->getName() + "_p_splat_one");
385
386 if (!Aligned)
387 ScalarLoad->setAlignment(8);
388
Tobias Grossere5b423252012-01-24 16:42:25 +0000389 Constant *SplatVector =
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000390 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
391 getVectorWidth()));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000392
393 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
394 SplatVector,
395 Load->getName()
396 + "_p_splat");
397 return VectorLoad;
398}
399
400Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000401 VectorValueMapT &ScalarMaps) {
402 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000403 const Value *Pointer = Load->getPointerOperand();
404 VectorType *VectorType = VectorType::get(
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000405 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000406
407 Value *Vector = UndefValue::get(VectorType);
408
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000409 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000410 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
411 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
412 Load->getName() + "_p_scalar_");
413 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
414 Builder.getInt32(i),
415 Load->getName() + "_p_vec_");
416 }
417
418 return Vector;
419}
420
421Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
422 IslPwAffUserInfo *UserInfo) {
423 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
424
425 IRBuilder<> *Builder = UserInfo->Builder;
426
427 isl_int OffsetIsl;
428 mpz_t OffsetMPZ;
429
430 isl_int_init(OffsetIsl);
431 mpz_init(OffsetMPZ);
432 isl_aff_get_constant(Aff, &OffsetIsl);
433 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
434
435 Value *OffsetValue = NULL;
436 APInt Offset = APInt_from_MPZ(OffsetMPZ);
437 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
438
439 mpz_clear(OffsetMPZ);
440 isl_int_clear(OffsetIsl);
441 isl_aff_free(Aff);
442
443 return OffsetValue;
444}
445
446int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
447 __isl_take isl_aff *Aff, void *User) {
448 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
449
450 assert((UserInfo->Result == NULL) && "Result is already set."
451 "Currently only single isl_aff is supported");
452 assert(isl_set_plain_is_universe(Set)
453 && "Code generation failed because the set is not universe");
454
455 UserInfo->Result = islAffToValue(Aff, UserInfo);
456
457 isl_set_free(Set);
458 return 0;
459}
460
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000461Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000462 IslPwAffUserInfo UserInfo;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000463 UserInfo.Result = NULL;
464 UserInfo.Builder = &Builder;
465 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
466 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
467
468 isl_pw_aff_free(PwAff);
469 return UserInfo.Result;
470}
471
472std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
473 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
474 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
475 && "Only single dimensional access functions supported");
476
477 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000478 Value *OffsetValue = islPwAffToValue(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000479
480 PointerType *BaseAddressType = dyn_cast<PointerType>(
481 BaseAddress->getType());
482 Type *ArrayTy = BaseAddressType->getElementType();
483 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
484 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
485
486 std::vector<Value*> IndexArray;
487 Value *NullValue = Constant::getNullValue(ArrayElementType);
488 IndexArray.push_back(NullValue);
489 IndexArray.push_back(OffsetValue);
490 return IndexArray;
491}
492
493Value *BlockGenerator::getNewAccessOperand(
494 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
495 *OldOperand, ValueMapT &BBMap) {
496 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
497 BaseAddress);
498 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
499 "p_newarrayidx_");
500 return NewOperand;
501}
502
503Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
504 const Value *Pointer,
505 ValueMapT &BBMap ) {
506 MemoryAccess &Access = Statement.getAccessFor(Inst);
507 isl_map *CurrentAccessRelation = Access.getAccessRelation();
508 isl_map *NewAccessRelation = Access.getNewAccessRelation();
509
510 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
511 && "Current and new access function use different spaces");
512
513 Value *NewPointer;
514
515 if (!NewAccessRelation) {
516 NewPointer = getOperand(Pointer, BBMap);
517 } else {
518 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
519 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
520 BBMap);
521 }
522
523 isl_map_free(CurrentAccessRelation);
524 isl_map_free(NewAccessRelation);
525 return NewPointer;
526}
527
528Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
529 ValueMapT &BBMap) {
530 const Value *Pointer = Load->getPointerOperand();
531 const Instruction *Inst = dyn_cast<Instruction>(Load);
532 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
533 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
534 Load->getName() + "_p_scalar_");
535 return ScalarLoad;
536}
537
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000538void BlockGenerator::generateVectorLoad(const LoadInst *Load,
539 ValueMapT &VectorMap,
540 VectorValueMapT &ScalarMaps) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000541 Value *NewLoad;
542
543 MemoryAccess &Access = Statement.getAccessFor(Load);
544
545 assert(ScatteringDomain && "No scattering domain available");
546
547 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000548 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000549 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000550 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000551 else
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000552 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000553
554 VectorMap[Load] = NewLoad;
555}
556
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000557void BlockGenerator::copyVectorUnaryInst(const UnaryInstruction *Inst,
558 ValueMapT &BBMap,
559 ValueMapT &VectorMap) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000560 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000561 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000562 NewOperand = makeVectorOperand(NewOperand);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000563
564 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
565
566 const CastInst *Cast = dyn_cast<CastInst>(Inst);
567 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
568 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
569}
570
Tobias Grosser8b4bf8b2012-03-02 11:27:11 +0000571void BlockGenerator::copyVectorBinInst(const BinaryOperator *Inst,
572 ValueMapT &BBMap, ValueMapT &VectorMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000573 Value *OpZero = Inst->getOperand(0);
574 Value *OpOne = Inst->getOperand(1);
575
576 Value *NewOpZero, *NewOpOne;
577 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
578 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
579
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000580 NewOpZero = makeVectorOperand(NewOpZero);
581 NewOpOne = makeVectorOperand(NewOpOne);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000582
583 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
584 NewOpOne,
585 Inst->getName() + "p_vec");
586 VectorMap[Inst] = NewInst;
587}
588
589void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
590 ValueMapT &VectorMap,
Tobias Grosser8927a442012-03-02 11:27:05 +0000591 VectorValueMapT &ScalarMaps) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000592 int VectorWidth = getVectorWidth();
593
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000594 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
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000656int BlockGenerator::getVectorWidth() {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000657 return ValueMaps.size();
658}
659
660bool BlockGenerator::isVectorBlock() {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000661 return getVectorWidth() > 1;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000662}
663
Tobias Grosser32152cb2012-03-02 11:27:18 +0000664void BlockGenerator::copyVectorInstruction(const Instruction *Inst,
665 ValueMapT &VectorMap,
666 VectorValueMapT &ScalarMaps) {
667 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
668 generateVectorLoad(Load, VectorMap, ScalarMaps);
669 return;
670 }
671
672 if (hasVectorOperands(Inst, VectorMap)) {
673 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
674 copyVectorStore(Store, ScalarMaps[0], VectorMap, ScalarMaps);
675 return;
676 }
677
678 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
679 copyVectorUnaryInst(Unary, ScalarMaps[0], VectorMap);
680 return;
681 }
682
683 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
684 copyVectorBinInst(Binary, ScalarMaps[0], VectorMap);
685 return;
686 }
687
688 llvm_unreachable("Cannot issue vector code for this instruction");
689 }
690
691 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
692 copyInstScalar(Inst, ScalarMaps[VectorLane]);
693}
694
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000695void BlockGenerator::copyInstruction(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000696 ValueMapT &VectorMap,
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000697 VectorValueMapT &ScalarMaps) {
Tobias Grosserb35d9c12012-03-02 11:27:08 +0000698 // Terminator instructions control the control flow. They are explicitly
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000699 // expressed in the clast and do not need to be copied.
700 if (Inst->isTerminator())
701 return;
702
703 if (isVectorBlock()) {
Tobias Grosser32152cb2012-03-02 11:27:18 +0000704 copyVectorInstruction(Inst, VectorMap, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000705 return;
706 }
707
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000708 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
709 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
710 return;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000711 }
712
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000713 copyInstScalar(Inst, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000714}
715
Tobias Grosser8412cda2012-03-02 11:26:55 +0000716void BlockGenerator::copyBB() {
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000717 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000718 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
719 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000720 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000721 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000722
723 // Create two maps that store the mapping from the original instructions of
724 // the old basic block to their copies in the new basic block. Those maps
725 // are basic block local.
726 //
727 // As vector code generation is supported there is one map for scalar values
728 // and one for vector values.
729 //
730 // In case we just do scalar code generation, the vectorMap is not used and
731 // the scalarMap has just one dimension, which contains the mapping.
732 //
733 // In case vector code generation is done, an instruction may either appear
734 // in the vector map once (as it is calculating >vectorwidth< values at a
735 // time. Or (if the values are calculated using scalar operations), it
736 // appears once in every dimension of the scalarMap.
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000737 VectorValueMapT ScalarBlockMap(getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000738 ValueMapT VectorBlockMap;
739
740 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
741 II != IE; ++II)
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000742 copyInstruction(II, VectorBlockMap, ScalarBlockMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000743}
744
Tobias Grosser75805372011-04-29 06:27:02 +0000745/// Class to generate LLVM-IR that calculates the value of a clast_expr.
746class ClastExpCodeGen {
747 IRBuilder<> &Builder;
748 const CharMapT *IVS;
749
Tobias Grosserbb137e32012-01-24 16:42:28 +0000750 Value *codegen(const clast_name *e, Type *Ty);
751 Value *codegen(const clast_term *e, Type *Ty);
752 Value *codegen(const clast_binary *e, Type *Ty);
753 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000754public:
755
756 // A generator for clast expressions.
757 //
758 // @param B The IRBuilder that defines where the code to calculate the
759 // clast expressions should be inserted.
760 // @param IVMAP A Map that translates strings describing the induction
761 // variables to the Values* that represent these variables
762 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000763 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000764
765 // Generates code to calculate a given clast expression.
766 //
767 // @param e The expression to calculate.
768 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000769 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000770
771 // @brief Reset the CharMap.
772 //
773 // This function is called to reset the CharMap to new one, while generating
774 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000775 void setIVS(CharMapT *IVSNew);
776};
777
778Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
779 CharMapT::const_iterator I = IVS->find(e->name);
780
781 assert(I != IVS->end() && "Clast name not found");
782
783 return Builder.CreateSExtOrBitCast(I->second, Ty);
784}
785
786Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
787 APInt a = APInt_from_MPZ(e->val);
788
789 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
790 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
791
792 if (!e->var)
793 return ConstOne;
794
795 Value *var = codegen(e->var, Ty);
796 return Builder.CreateMul(ConstOne, var);
797}
798
799Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
800 Value *LHS = codegen(e->LHS, Ty);
801
802 APInt RHS_AP = APInt_from_MPZ(e->RHS);
803
804 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
805 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
806
807 switch (e->type) {
808 case clast_bin_mod:
809 return Builder.CreateSRem(LHS, RHS);
810 case clast_bin_fdiv:
811 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000812 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000813 Value *One = ConstantInt::get(Ty, 1);
814 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000815 Value *Sum1 = Builder.CreateSub(LHS, RHS);
816 Value *Sum2 = Builder.CreateAdd(Sum1, One);
817 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
818 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
819 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000820 }
821 case clast_bin_cdiv:
822 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000823 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
824 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000825 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000826 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
827 Value *Sum2 = Builder.CreateSub(Sum1, One);
828 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
829 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
830 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000831 }
832 case clast_bin_div:
833 return Builder.CreateSDiv(LHS, RHS);
834 };
835
836 llvm_unreachable("Unknown clast binary expression type");
837}
838
839Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
840 assert(( r->type == clast_red_min
841 || r->type == clast_red_max
842 || r->type == clast_red_sum)
843 && "Clast reduction type not supported");
844 Value *old = codegen(r->elts[0], Ty);
845
846 for (int i=1; i < r->n; ++i) {
847 Value *exprValue = codegen(r->elts[i], Ty);
848
849 switch (r->type) {
850 case clast_red_min:
851 {
852 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
853 old = Builder.CreateSelect(cmp, old, exprValue);
854 break;
855 }
856 case clast_red_max:
857 {
858 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
859 old = Builder.CreateSelect(cmp, old, exprValue);
860 break;
861 }
862 case clast_red_sum:
863 old = Builder.CreateAdd(old, exprValue);
864 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000865 }
Tobias Grosser75805372011-04-29 06:27:02 +0000866 }
867
Tobias Grosserbb137e32012-01-24 16:42:28 +0000868 return old;
869}
870
871ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
872 : Builder(B), IVS(IVMap) {}
873
874Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
875 switch(e->type) {
876 case clast_expr_name:
877 return codegen((const clast_name *)e, Ty);
878 case clast_expr_term:
879 return codegen((const clast_term *)e, Ty);
880 case clast_expr_bin:
881 return codegen((const clast_binary *)e, Ty);
882 case clast_expr_red:
883 return codegen((const clast_reduction *)e, Ty);
884 }
885
886 llvm_unreachable("Unknown clast expression!");
887}
888
889void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
890 IVS = IVSNew;
891}
Tobias Grosser75805372011-04-29 06:27:02 +0000892
893class ClastStmtCodeGen {
894 // The Scop we code generate.
895 Scop *S;
896 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000897 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000898 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000899 Dependences *DP;
900 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000901 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000902
903 // The Builder specifies the current location to code generate at.
904 IRBuilder<> &Builder;
905
906 // Map the Values from the old code to their counterparts in the new code.
907 ValueMapT ValueMap;
908
909 // clastVars maps from the textual representation of a clast variable to its
910 // current *Value. clast variables are scheduling variables, original
911 // induction variables or parameters. They are used either in loop bounds or
912 // to define the statement instance that is executed.
913 //
914 // for (s = 0; s < n + 3; ++i)
915 // for (t = s; t < m; ++j)
916 // Stmt(i = s + 3 * m, j = t);
917 //
918 // {s,t,i,j,n,m} is the set of clast variables in this clast.
919 CharMapT *clastVars;
920
921 // Codegenerator for clast expressions.
922 ClastExpCodeGen ExpGen;
923
924 // Do we currently generate parallel code?
925 bool parallelCodeGeneration;
926
927 std::vector<std::string> parallelLoops;
928
929public:
930
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000931 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000932
933 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000934 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000935
936 void codegen(const clast_assignment *a, ScopStmt *Statement,
937 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000938 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000939
940 void codegenSubstitutions(const clast_stmt *Assignment,
941 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000942 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000943
944 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000945 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000946
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000947 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000948
949 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000950 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000951 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000952
Tobias Grosser75805372011-04-29 06:27:02 +0000953 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000954 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000955
956 /// @brief Add values to the OpenMP structure.
957 ///
958 /// Create the subfunction structure and add the values from the list.
959 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000960 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000961
962 /// @brief Create OpenMP structure values.
963 ///
964 /// Create a list of values that has to be stored into the subfuncition
965 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000966 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000967
968 /// @brief Extract the values from the subfunction parameter.
969 ///
970 /// Extract the values from the subfunction parameter and update the clast
971 /// variables to point to the new values.
972 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
973 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000974 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000975
976 /// @brief Add body to the subfunction.
977 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
978 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000979 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000980
981 /// @brief Create an OpenMP parallel for loop.
982 ///
983 /// This loop reflects a loop as if it would have been created by an OpenMP
984 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000985 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000986
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000987 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000988
989 /// @brief Get the number of loop iterations for this loop.
990 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
993 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000994 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000995
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000996 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000997
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000998 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000999
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001000 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001002 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001003
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001004 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001005
1006 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001007 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001008
1009 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001010 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001011 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001012};
1013}
1014
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001015const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1016 return parallelLoops;
1017}
1018
1019void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1020 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1021 (*clastVars)[a->LHS] = V;
1022}
1023
1024void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1025 unsigned Dimension, int vectorDim,
1026 std::vector<ValueMapT> *VectorVMap) {
1027 Value *RHS = ExpGen.codegen(a->RHS,
1028 TD->getIntPtrType(Builder.getContext()));
1029
1030 assert(!a->LHS && "Statement assignments do not have left hand side");
1031 const PHINode *PN;
1032 PN = Statement->getInductionVariableForDimension(Dimension);
1033 const Value *V = PN;
1034
1035 if (VectorVMap)
1036 (*VectorVMap)[vectorDim][V] = RHS;
1037
1038 ValueMap[V] = RHS;
1039}
1040
1041void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1042 ScopStmt *Statement, int vectorDim,
1043 std::vector<ValueMapT> *VectorVMap) {
1044 int Dimension = 0;
1045
1046 while (Assignment) {
1047 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1048 && "Substitions are expected to be assignments");
1049 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1050 vectorDim, VectorVMap);
1051 Assignment = Assignment->next;
1052 Dimension++;
1053 }
1054}
1055
1056void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1057 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001058 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001059 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001060
1061 if (u->substitutions)
1062 codegenSubstitutions(u->substitutions, Statement);
1063
1064 int vectorDimensions = IVS ? IVS->size() : 1;
1065
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001066 VectorValueMapT VectorMap(vectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001067
1068 if (IVS) {
1069 assert (u->substitutions && "Substitutions expected!");
1070 int i = 0;
1071 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1072 II != IE; ++II) {
1073 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001074 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001075 i++;
1076 }
1077 }
1078
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001079 BlockGenerator::generate(Builder, ValueMap, VectorMap, *Statement, Domain, 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) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001415 if ((Vector || OpenMP) && DP->isParallelFor(f)) {
1416 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1417 && (getNumberOfIterations(f) <= 16)) {
1418 codegenForVector(f);
1419 return;
1420 }
1421
1422 if (OpenMP && !parallelCodeGeneration) {
1423 parallelCodeGeneration = true;
1424 parallelLoops.push_back(f->iterator);
1425 codegenForOpenMP(f);
1426 parallelCodeGeneration = false;
1427 return;
1428 }
1429 }
1430
1431 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001432}
1433
1434Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1435 Value *LHS = ExpGen.codegen(eq->LHS,
1436 TD->getIntPtrType(Builder.getContext()));
1437 Value *RHS = ExpGen.codegen(eq->RHS,
1438 TD->getIntPtrType(Builder.getContext()));
1439 CmpInst::Predicate P;
1440
1441 if (eq->sign == 0)
1442 P = ICmpInst::ICMP_EQ;
1443 else if (eq->sign > 0)
1444 P = ICmpInst::ICMP_SGE;
1445 else
1446 P = ICmpInst::ICMP_SLE;
1447
1448 return Builder.CreateICmp(P, LHS, RHS);
1449}
1450
1451void ClastStmtCodeGen::codegen(const clast_guard *g) {
1452 Function *F = Builder.GetInsertBlock()->getParent();
1453 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001454
1455 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1456 Builder.GetInsertPoint(), P);
1457 CondBB->setName("polly.cond");
1458 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1459 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001460 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001461
1462 DT->addNewBlock(ThenBB, CondBB);
1463 DT->changeImmediateDominator(MergeBB, CondBB);
1464
1465 CondBB->getTerminator()->eraseFromParent();
1466
1467 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001468
1469 Value *Predicate = codegen(&(g->eq[0]));
1470
1471 for (int i = 1; i < g->n; ++i) {
1472 Value *TmpPredicate = codegen(&(g->eq[i]));
1473 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1474 }
1475
1476 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1477 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001478 Builder.CreateBr(MergeBB);
1479 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001480
1481 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001482
1483 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001484}
1485
1486void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1487 if (CLAST_STMT_IS_A(stmt, stmt_root))
1488 assert(false && "No second root statement expected");
1489 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1490 codegen((const clast_assignment *)stmt);
1491 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1492 codegen((const clast_user_stmt *)stmt);
1493 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1494 codegen((const clast_block *)stmt);
1495 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1496 codegen((const clast_for *)stmt);
1497 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1498 codegen((const clast_guard *)stmt);
1499
1500 if (stmt->next)
1501 codegen(stmt->next);
1502}
1503
1504void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1505 SCEVExpander Rewriter(SE, "polly");
1506
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001507 int i = 0;
1508 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1509 PI != PE; ++PI) {
1510 assert(i < names->nb_parameters && "Not enough parameter names");
1511
1512 const SCEV *Param = *PI;
1513 Type *Ty = Param->getType();
1514
1515 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1516 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1517 (*clastVars)[names->parameters[i]] = V;
1518
1519 ++i;
1520 }
1521}
1522
1523void ClastStmtCodeGen::codegen(const clast_root *r) {
1524 clastVars = new CharMapT();
1525 addParameters(r->names);
1526 ExpGen.setIVS(clastVars);
1527
1528 parallelCodeGeneration = false;
1529
1530 const clast_stmt *stmt = (const clast_stmt*) r;
1531 if (stmt->next)
1532 codegen(stmt->next);
1533
1534 delete clastVars;
1535}
1536
1537ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1538 DominatorTree *dt, ScopDetection *sd,
1539 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001540 IRBuilder<> &B, Pass *P) :
1541 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001542 ExpGen(Builder, NULL) {}
1543
Tobias Grosser75805372011-04-29 06:27:02 +00001544namespace {
1545class CodeGeneration : public ScopPass {
1546 Region *region;
1547 Scop *S;
1548 DominatorTree *DT;
1549 ScalarEvolution *SE;
1550 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001551 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001552 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001553
1554 std::vector<std::string> parallelLoops;
1555
1556 public:
1557 static char ID;
1558
1559 CodeGeneration() : ScopPass(ID) {}
1560
Tobias Grosserb1c95992012-02-12 12:09:27 +00001561 // Add the declarations needed by the OpenMP function calls that we insert in
1562 // OpenMP mode.
1563 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001564 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001565 IRBuilder<> Builder(M->getContext());
1566 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1567
1568 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001569
1570 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001571 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1572 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001573 }
1574
1575 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001576 Type *Params[] = {
1577 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1578 Builder.getInt8PtrTy(),
1579 false)),
1580 Builder.getInt8PtrTy(),
1581 Builder.getInt32Ty(),
1582 LongTy,
1583 LongTy,
1584 LongTy,
1585 };
Tobias Grosser75805372011-04-29 06:27:02 +00001586
Tobias Grosserd855cc52012-02-12 12:09:32 +00001587 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1588 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001589 }
1590
1591 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001592 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1593 Type *Params[] = {
1594 LongPtrTy,
1595 LongPtrTy,
1596 };
Tobias Grosser75805372011-04-29 06:27:02 +00001597
Tobias Grosserd855cc52012-02-12 12:09:32 +00001598 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1599 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001600 }
1601
1602 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001603 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1604 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001605 }
1606 }
1607
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001608 // Split the entry edge of the region and generate a new basic block on this
1609 // edge. This function also updates ScopInfo and RegionInfo.
1610 //
1611 // @param region The region where the entry edge will be splitted.
1612 BasicBlock *splitEdgeAdvanced(Region *region) {
1613 BasicBlock *newBlock;
1614 BasicBlock *splitBlock;
1615
1616 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1617
1618 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001619 BasicBlock *OldBlock = region->getEntry();
1620 std::string OldName = OldBlock->getName();
1621
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001622 // Update ScopInfo.
1623 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001624 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001625 (*SI)->setBasicBlock(newBlock);
1626 break;
1627 }
1628
1629 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001630 splitBlock = OldBlock;
1631 OldBlock->setName("polly.split");
1632 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001633 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001634 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001635 } else {
1636 RI->setRegionFor(newBlock, region->getParent());
1637 splitBlock = newBlock;
1638 }
1639
1640 return splitBlock;
1641 }
1642
1643 // Create a split block that branches either to the old code or to a new basic
1644 // block where the new code can be inserted.
1645 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001646 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001647 // the new code can be generated.
1648 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001649 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1650 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001651
Tobias Grosserbd608a82012-02-12 12:09:41 +00001652 SplitBlock = splitEdgeAdvanced(region);
1653 SplitBlock->setName("polly.split_new_and_old");
1654 Function *F = SplitBlock->getParent();
1655 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1656 SplitBlock->getTerminator()->eraseFromParent();
1657 Builder->SetInsertPoint(SplitBlock);
1658 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1659 DT->addNewBlock(StartBlock, SplitBlock);
1660 Builder->SetInsertPoint(StartBlock);
1661 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001662 }
1663
1664 // Merge the control flow of the newly generated code with the existing code.
1665 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001666 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001667 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001668 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001669 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001670 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1671 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001672 Region *R = region;
1673
1674 if (R->getExit()->getSinglePredecessor())
1675 // No splitEdge required. A block with a single predecessor cannot have
1676 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001677 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001678 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001679 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001680 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1681 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001682 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001683 }
1684
Tobias Grosserbd608a82012-02-12 12:09:41 +00001685 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001686 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001687
Tobias Grosserbd608a82012-02-12 12:09:41 +00001688 if (DT->dominates(SplitBlock, MergeBlock))
1689 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001690 }
1691
Tobias Grosser75805372011-04-29 06:27:02 +00001692 bool runOnScop(Scop &scop) {
1693 S = &scop;
1694 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001695 DT = &getAnalysis<DominatorTree>();
1696 Dependences *DP = &getAnalysis<Dependences>();
1697 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001698 SD = &getAnalysis<ScopDetection>();
1699 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001700 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001701
1702 parallelLoops.clear();
1703
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001704 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001705
Tobias Grosserb1c95992012-02-12 12:09:27 +00001706 Module *M = region->getEntry()->getParent()->getParent();
1707
Tobias Grosserd855cc52012-02-12 12:09:32 +00001708 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001709
Tobias Grosser5772e652012-02-01 14:23:33 +00001710 // In the CFG the optimized code of the SCoP is generated next to the
1711 // original code. Both the new and the original version of the code remain
1712 // in the CFG. A branch statement decides which version is executed.
1713 // For now, we always execute the new version (the old one is dead code
1714 // eliminated by the cleanup passes). In the future we may decide to execute
1715 // the new version only if certain run time checks succeed. This will be
1716 // useful to support constructs for which we cannot prove all assumptions at
1717 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001718 //
1719 // Before transformation:
1720 //
1721 // bb0
1722 // |
1723 // orig_scop
1724 // |
1725 // bb1
1726 //
1727 // After transformation:
1728 // bb0
1729 // |
1730 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001731 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001732 // | startBlock
1733 // | |
1734 // orig_scop new_scop
1735 // \ /
1736 // \ /
1737 // bb1 (joinBlock)
1738 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001739
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001740 // The builder will be set to startBlock.
1741 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001742 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001743
Tobias Grosser0ac92142012-02-14 14:02:27 +00001744 mergeControlFlow(splitBlock, &builder);
1745 builder.SetInsertPoint(StartBlock->begin());
1746
1747 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001748 CloogInfo &C = getAnalysis<CloogInfo>();
1749 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001750
Tobias Grosser75805372011-04-29 06:27:02 +00001751 parallelLoops.insert(parallelLoops.begin(),
1752 CodeGen.getParallelLoops().begin(),
1753 CodeGen.getParallelLoops().end());
1754
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001755 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001756 }
1757
1758 virtual void printScop(raw_ostream &OS) const {
1759 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1760 PE = parallelLoops.end(); PI != PE; ++PI)
1761 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1762 }
1763
1764 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1765 AU.addRequired<CloogInfo>();
1766 AU.addRequired<Dependences>();
1767 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001768 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001769 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001770 AU.addRequired<ScopDetection>();
1771 AU.addRequired<ScopInfo>();
1772 AU.addRequired<TargetData>();
1773
1774 AU.addPreserved<CloogInfo>();
1775 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001776
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001777 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001778 AU.addPreserved<LoopInfo>();
1779 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001780 AU.addPreserved<ScopDetection>();
1781 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001782
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001783 // FIXME: We do not yet add regions for the newly generated code to the
1784 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001785 AU.addPreserved<RegionInfo>();
1786 AU.addPreserved<TempScopInfo>();
1787 AU.addPreserved<ScopInfo>();
1788 AU.addPreservedID(IndependentBlocksID);
1789 }
1790};
1791}
1792
1793char CodeGeneration::ID = 1;
1794
Tobias Grosser73600b82011-10-08 00:30:40 +00001795INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1796 "Polly - Create LLVM-IR form SCoPs", false, false)
1797INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1798INITIALIZE_PASS_DEPENDENCY(Dependences)
1799INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1800INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1801INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1802INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1803INITIALIZE_PASS_DEPENDENCY(TargetData)
1804INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1805 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001806
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001807Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001808 return new CodeGeneration();
1809}