blob: e44f5ebc4745134d7a4c0d50a7e6405866329737 [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;
88
89// Create a new loop.
90//
91// @param Builder The builder used to create the loop. It also defines the
92// place where to create the loop.
93// @param UB The upper bound of the loop iv.
94// @param Stride The number by which the loop iv is incremented after every
95// iteration.
Tobias Grosser0ac92142012-02-14 14:02:27 +000096static Value *createLoop(IRBuilder<> *Builder, Value *LB, Value *UB,
97 APInt Stride, DominatorTree *DT, Pass *P,
98 BasicBlock **AfterBlock) {
Tobias Grosser75805372011-04-29 06:27:02 +000099 Function *F = Builder->GetInsertBlock()->getParent();
100 LLVMContext &Context = F->getContext();
101
102 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
103 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
104 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000105 BasicBlock *AfterBB = SplitBlock(PreheaderBB, Builder->GetInsertPoint()++, P);
106 AfterBB->setName("polly.loop_after");
Tobias Grosser75805372011-04-29 06:27:02 +0000107
Tobias Grosser0ac92142012-02-14 14:02:27 +0000108 PreheaderBB->getTerminator()->setSuccessor(0, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000109 DT->addNewBlock(HeaderBB, PreheaderBB);
110
Tobias Grosser75805372011-04-29 06:27:02 +0000111 Builder->SetInsertPoint(HeaderBB);
112
113 // Use the type of upper and lower bound.
114 assert(LB->getType() == UB->getType()
115 && "Different types for upper and lower bound.");
116
Tobias Grosser55927aa2011-07-18 09:53:32 +0000117 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000118 assert(LoopIVType && "UB is not integer?");
119
120 // IV
Tobias Grosser0ac92142012-02-14 14:02:27 +0000121 PHINode *IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000122 IV->addIncoming(LB, PreheaderBB);
123
124 // IV increment.
125 Value *StrideValue = ConstantInt::get(LoopIVType,
126 Stride.zext(LoopIVType->getBitWidth()));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000127 Value *IncrementedIV = Builder->CreateAdd(IV, StrideValue,
128 "polly.next_loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000129
130 // Exit condition.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000131 Value *CMP;
Tobias Grosser75805372011-04-29 06:27:02 +0000132 if (AtLeastOnce) { // At least on iteration.
133 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000134 CMP = Builder->CreateICmpNE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000135 } else { // Maybe not executed at all.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000136 CMP = Builder->CreateICmpSLE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000137 }
Tobias Grosser0ac92142012-02-14 14:02:27 +0000138
139 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000140 DT->addNewBlock(BodyBB, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000141
142 Builder->SetInsertPoint(BodyBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000143 Builder->CreateBr(HeaderBB);
144 IV->addIncoming(IncrementedIV, BodyBB);
145 DT->changeImmediateDominator(AfterBB, HeaderBB);
146
147 Builder->SetInsertPoint(BodyBB->begin());
148 *AfterBlock = AfterBB;
149
150 return IV;
Tobias Grosser75805372011-04-29 06:27:02 +0000151}
152
Tobias Grosser642c4112012-03-02 11:27:25 +0000153class IslGenerator;
154
155class IslGenerator {
156public:
157 IslGenerator(IRBuilder<> &Builder) : Builder(Builder) {}
158 Value *generateIslInt(__isl_take isl_int Int);
159 Value *generateIslAff(__isl_take isl_aff *Aff);
160 Value *generateIslPwAff(__isl_take isl_pw_aff *PwAff);
161
162private:
163 typedef struct {
164 Value *Result;
165 class IslGenerator *Generator;
166 } IslGenInfo;
167
168 IRBuilder<> &Builder;
169 static int mergeIslAffValues(__isl_take isl_set *Set,
170 __isl_take isl_aff *Aff, void *User);
171};
172
173Value *IslGenerator::generateIslInt(isl_int Int) {
174 mpz_t IntMPZ;
175 mpz_init(IntMPZ);
176 isl_int_get_gmp(Int, IntMPZ);
177 Value *IntValue = Builder.getInt(APInt_from_MPZ(IntMPZ));
178 mpz_clear(IntMPZ);
179 return IntValue;
180}
181
182Value *IslGenerator::generateIslAff(__isl_take isl_aff *Aff) {
183 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
184 Value *ConstValue;
185 isl_int ConstIsl;
186
187 isl_int_init(ConstIsl);
188 isl_aff_get_constant(Aff, &ConstIsl);
189 ConstValue = generateIslInt(ConstIsl);
190
191 isl_int_clear(ConstIsl);
192 isl_aff_free(Aff);
193
194 return ConstValue;
195}
196
197int IslGenerator::mergeIslAffValues(__isl_take isl_set *Set,
198 __isl_take isl_aff *Aff, void *User) {
199 IslGenInfo *GenInfo = (IslGenInfo *)User;
200
201 assert((GenInfo->Result == NULL) && "Result is already set."
202 "Currently only single isl_aff is supported");
203 assert(isl_set_plain_is_universe(Set)
204 && "Code generation failed because the set is not universe");
205
206 GenInfo->Result = GenInfo->Generator->generateIslAff(Aff);
207
208 isl_set_free(Set);
209 return 0;
210}
211
212Value *IslGenerator::generateIslPwAff(__isl_take isl_pw_aff *PwAff) {
213 IslGenInfo User;
214 User.Result = NULL;
215 User.Generator = this;
216 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &User);
217 assert(User.Result && "Code generation for isl_pw_aff failed");
218
219 isl_pw_aff_free(PwAff);
220 return User.Result;
221}
222
Tobias Grosser55d52082012-03-02 15:20:39 +0000223/// @brief Generate a new basic block for a polyhedral statement.
224///
225/// The only public function exposed is generate().
Tobias Grosser75805372011-04-29 06:27:02 +0000226class BlockGenerator {
Tobias Grosserc941ede2012-03-02 11:26:49 +0000227public:
Tobias Grosser55d52082012-03-02 15:20:39 +0000228 /// @brief Generate a new BasicBlock for a ScopStmt.
229 ///
230 /// @param Builder The LLVM-IR Builder used to generate the statement. The
231 /// code is generated at the location, the Builder points to.
232 /// @param Stmt The statement to code generate.
233 /// @param GlobalMap A map that defines for certain Values referenced from the
234 /// original code new Values they should be replaced with.
235 /// @param P A reference to the pass this function is called from.
236 /// The pass is needed to update other analysis.
237 static void generate(IRBuilder<> &Builder, ScopStmt &Stmt,
238 ValueMapT &GlobalMap, Pass *P) {
239 BlockGenerator Generator(Builder, Stmt, P);
240 Generator.copyBB(GlobalMap);
Tobias Grosserc941ede2012-03-02 11:26:49 +0000241 }
242
Tobias Grosser80998e72012-03-02 11:27:28 +0000243protected:
Tobias Grosser75805372011-04-29 06:27:02 +0000244 IRBuilder<> &Builder;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000245 ScopStmt &Statement;
Tobias Grosser8412cda2012-03-02 11:26:55 +0000246 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000247
Tobias Grosser55d52082012-03-02 15:20:39 +0000248 BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000249
Tobias Grosser55d52082012-03-02 15:20:39 +0000250 /// @brief Get the new version of a Value.
251 ///
252 /// @param Old The old Value.
Tobias Grosser3c2efba2012-03-06 07:38:57 +0000253 /// @param BBMap A mapping from old values to their new values
Tobias Grosser55d52082012-03-02 15:20:39 +0000254 /// (for values recalculated within this basic block).
255 /// @param GlobalMap A mapping from old values to their new values
256 /// (for values recalculated in the new ScoP, but not
257 /// within this basic block).
258 ///
259 /// @returns o The old value, if it is still valid.
260 /// o The new value, if available.
261 /// o NULL, if no value is found.
262 Value *getNewValue(const Value *Old, ValueMapT &BBMap, ValueMapT &GlobalMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000263
Tobias Grosserdf382372012-03-02 15:20:35 +0000264 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
265 ValueMapT &GlobalMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
Raghesh Aloor129e8672011-08-15 02:33:39 +0000267 /// @brief Get the memory access offset to be added to the base address
Tobias Grosser80998e72012-03-02 11:27:28 +0000268 std::vector<Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000269 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000270
Raghesh Aloor62b13122011-08-03 17:02:50 +0000271 /// @brief Get the new operand address according to the changed access in
272 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000273 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
274 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000275 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000276
277 /// @brief Generate the operand address
278 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosserdf382372012-03-02 15:20:35 +0000279 const Value *Pointer, ValueMapT &BBMap,
280 ValueMapT &GlobalMap);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000281
Tobias Grosserdf382372012-03-02 15:20:35 +0000282 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap,
283 ValueMapT &GlobalMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000284
Tobias Grosser55d52082012-03-02 15:20:39 +0000285 /// @brief Copy a single Instruction.
286 ///
287 /// This copies a single Instruction and updates references to old values
288 /// with references to new values, as defined by GlobalMap and BBMap.
289 ///
Tobias Grosser3c2efba2012-03-06 07:38:57 +0000290 /// @param BBMap A mapping from old values to their new values
Tobias Grosser55d52082012-03-02 15:20:39 +0000291 /// (for values recalculated within this basic block).
292 /// @param GlobalMap A mapping from old values to their new values
293 /// (for values recalculated in the new ScoP, but not
294 /// within this basic block).
295 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
Tobias Grosserdf382372012-03-02 15:20:35 +0000296 ValueMapT &GlobalMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000297
Tobias Grosser55d52082012-03-02 15:20:39 +0000298 /// @brief Copy the basic block.
299 ///
300 /// This copies the entire basic block and updates references to old values
301 /// with references to new values, as defined by GlobalMap.
302 ///
303 /// @param GlobalMap A mapping from old values to their new values
304 /// (for values recalculated in the new ScoP, but not
305 /// within this basic block).
306 void copyBB(ValueMapT &GlobalMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000307};
308
Tobias Grosser55d52082012-03-02 15:20:39 +0000309BlockGenerator::BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P):
310 Builder(B), Statement(Stmt), P(P) {}
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000311
Tobias Grosser55d52082012-03-02 15:20:39 +0000312Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
313 ValueMapT &GlobalMap) {
314 const Instruction *Inst = dyn_cast<Instruction>(Old);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000315
Tobias Grosser55d52082012-03-02 15:20:39 +0000316 if (!Inst)
317 return const_cast<Value*>(Old);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000318
Tobias Grosser8367e0c2012-03-02 15:20:31 +0000319 // OldOperand was redefined outside of this BasicBlock.
Tobias Grosser55d52082012-03-02 15:20:39 +0000320 if (GlobalMap.count(Old)) {
321 Value *New = GlobalMap[Old];
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000322
Tobias Grosser55d52082012-03-02 15:20:39 +0000323 if (Old->getType()->getScalarSizeInBits()
324 < New->getType()->getScalarSizeInBits())
325 New = Builder.CreateTruncOrBitCast(New, Old->getType());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000326
Tobias Grosser55d52082012-03-02 15:20:39 +0000327 return New;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000328 }
329
Tobias Grosser8367e0c2012-03-02 15:20:31 +0000330 // OldOperand was recalculated within this BasicBlock.
Tobias Grosser55d52082012-03-02 15:20:39 +0000331 if (BBMap.count(Old)) {
332 return BBMap[Old];
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000333 }
334
Tobias Grosser8367e0c2012-03-02 15:20:31 +0000335 // OldOperand is SCoP invariant.
Tobias Grosser55d52082012-03-02 15:20:39 +0000336 if (!Statement.getParent()->getRegion().contains(Inst->getParent()))
337 return const_cast<Value*>(Old);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000338
Tobias Grosser8367e0c2012-03-02 15:20:31 +0000339 // We could not find any valid new operand.
340 return NULL;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000341}
342
Tobias Grosserdf382372012-03-02 15:20:35 +0000343void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
344 ValueMapT &GlobalMap) {
Tobias Grosser80998e72012-03-02 11:27:28 +0000345 Instruction *NewInst = Inst->clone();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000346
Tobias Grosser80998e72012-03-02 11:27:28 +0000347 // Replace old operands with the new ones.
348 for (Instruction::const_op_iterator OI = Inst->op_begin(),
349 OE = Inst->op_end(); OI != OE; ++OI) {
350 Value *OldOperand = *OI;
Tobias Grosser55d52082012-03-02 15:20:39 +0000351 Value *NewOperand = getNewValue(OldOperand, BBMap, GlobalMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000352
Tobias Grosser80998e72012-03-02 11:27:28 +0000353 if (!NewOperand) {
354 assert(!isa<StoreInst>(NewInst)
355 && "Store instructions are always needed!");
356 delete NewInst;
357 return;
358 }
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000359
Tobias Grosser80998e72012-03-02 11:27:28 +0000360 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000361 }
362
Tobias Grosser80998e72012-03-02 11:27:28 +0000363 Builder.Insert(NewInst);
364 BBMap[Inst] = NewInst;
365
366 if (!NewInst->getType()->isVoidTy())
367 NewInst->setName("p_" + Inst->getName());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000368}
369
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000370std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
371 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
372 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
373 && "Only single dimensional access functions supported");
374
375 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser642c4112012-03-02 11:27:25 +0000376 IslGenerator IslGen(Builder);
377 Value *OffsetValue = IslGen.generateIslPwAff(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000378
379 PointerType *BaseAddressType = dyn_cast<PointerType>(
380 BaseAddress->getType());
381 Type *ArrayTy = BaseAddressType->getElementType();
382 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
383 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
384
385 std::vector<Value*> IndexArray;
386 Value *NullValue = Constant::getNullValue(ArrayElementType);
387 IndexArray.push_back(NullValue);
388 IndexArray.push_back(OffsetValue);
389 return IndexArray;
390}
391
392Value *BlockGenerator::getNewAccessOperand(
393 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
394 *OldOperand, ValueMapT &BBMap) {
395 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
396 BaseAddress);
397 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
398 "p_newarrayidx_");
399 return NewOperand;
400}
401
402Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
403 const Value *Pointer,
Tobias Grosserdf382372012-03-02 15:20:35 +0000404 ValueMapT &BBMap,
405 ValueMapT &GlobalMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000406 MemoryAccess &Access = Statement.getAccessFor(Inst);
407 isl_map *CurrentAccessRelation = Access.getAccessRelation();
408 isl_map *NewAccessRelation = Access.getNewAccessRelation();
409
410 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
411 && "Current and new access function use different spaces");
412
413 Value *NewPointer;
414
415 if (!NewAccessRelation) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000416 NewPointer = getNewValue(Pointer, BBMap, GlobalMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000417 } else {
418 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
419 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
420 BBMap);
421 }
422
423 isl_map_free(CurrentAccessRelation);
424 isl_map_free(NewAccessRelation);
425 return NewPointer;
426}
427
428Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
Tobias Grosserdf382372012-03-02 15:20:35 +0000429 ValueMapT &BBMap,
430 ValueMapT &GlobalMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000431 const Value *Pointer = Load->getPointerOperand();
432 const Instruction *Inst = dyn_cast<Instruction>(Load);
Tobias Grosserdf382372012-03-02 15:20:35 +0000433 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap, GlobalMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000434 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
435 Load->getName() + "_p_scalar_");
436 return ScalarLoad;
437}
438
Tobias Grosser80998e72012-03-02 11:27:28 +0000439void BlockGenerator::copyInstruction(const Instruction *Inst,
Tobias Grosserdf382372012-03-02 15:20:35 +0000440 ValueMapT &BBMap, ValueMapT &GlobalMap) {
Tobias Grosser80998e72012-03-02 11:27:28 +0000441 // Terminator instructions control the control flow. They are explicitly
442 // expressed in the clast and do not need to be copied.
443 if (Inst->isTerminator())
444 return;
445
446 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserdf382372012-03-02 15:20:35 +0000447 BBMap[Load] = generateScalarLoad(Load, BBMap, GlobalMap);
Tobias Grosser80998e72012-03-02 11:27:28 +0000448 return;
449 }
450
Tobias Grosserdf382372012-03-02 15:20:35 +0000451 copyInstScalar(Inst, BBMap, GlobalMap);
Tobias Grosser80998e72012-03-02 11:27:28 +0000452}
453
454
Tobias Grosser55d52082012-03-02 15:20:39 +0000455void BlockGenerator::copyBB(ValueMapT &GlobalMap) {
Tobias Grosser80998e72012-03-02 11:27:28 +0000456 BasicBlock *BB = Statement.getBasicBlock();
457 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
458 Builder.GetInsertPoint(), P);
459 CopyBB->setName("polly.stmt." + BB->getName());
460 Builder.SetInsertPoint(CopyBB->begin());
461
Tobias Grosserdf382372012-03-02 15:20:35 +0000462 ValueMapT BBMap;
Tobias Grosser80998e72012-03-02 11:27:28 +0000463
464 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
465 ++II)
Tobias Grosserdf382372012-03-02 15:20:35 +0000466 copyInstruction(II, BBMap, GlobalMap);
Tobias Grosser80998e72012-03-02 11:27:28 +0000467}
468
Tobias Grosser55d52082012-03-02 15:20:39 +0000469/// @brief Generate a new vector basic block for a polyhedral statement.
470///
471/// The only public function exposed is generate().
Tobias Grosser80998e72012-03-02 11:27:28 +0000472class VectorBlockGenerator : BlockGenerator {
473public:
Tobias Grosser55d52082012-03-02 15:20:39 +0000474 /// @brief Generate a new vector basic block for a ScoPStmt.
475 ///
476 /// This code generation is similar to the normal, scalar code generation,
477 /// except that each instruction is code generated for several vector lanes
478 /// at a time. If possible instructions are issued as actual vector
479 /// instructions, but e.g. for address calculation instructions we currently
480 /// generate scalar instructions for each vector lane.
481 ///
482 /// @param Builder The LLVM-IR Builder used to generate the statement. The
483 /// code is generated at the location, the builder points
484 /// to.
485 /// @param Stmt The statement to code generate.
486 /// @param GlobalMaps A vector of maps that define for certain Values
487 /// referenced from the original code new Values they should
488 /// be replaced with. Each map in the vector of maps is
489 /// used for one vector lane. The number of elements in the
490 /// vector defines the width of the generated vector
491 /// instructions.
492 /// @param P A reference to the pass this function is called from.
493 /// The pass is needed to update other analysis.
494 static void generate(IRBuilder<> &B, ScopStmt &Stmt,
495 VectorValueMapT &GlobalMaps, __isl_keep isl_set *Domain,
496 Pass *P) {
497 VectorBlockGenerator Generator(B, GlobalMaps, Stmt, Domain, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000498 Generator.copyBB();
499 }
500
501private:
Tobias Grosser55d52082012-03-02 15:20:39 +0000502 // This is a vector of global value maps. The first map is used for the first
503 // vector lane, ...
504 // Each map, contains information about Instructions in the old ScoP, which
505 // are recalculated in the new SCoP. When copying the basic block, we replace
506 // all referenes to the old instructions with their recalculated values.
Tobias Grosserdf382372012-03-02 15:20:35 +0000507 VectorValueMapT &GlobalMaps;
Tobias Grosser80998e72012-03-02 11:27:28 +0000508
Tobias Grosser08a82382012-03-02 15:20:24 +0000509 isl_set *Domain;
510
Tobias Grosser55d52082012-03-02 15:20:39 +0000511 VectorBlockGenerator(IRBuilder<> &B, VectorValueMapT &GlobalMaps,
512 ScopStmt &Stmt, __isl_keep isl_set *Domain, Pass *P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000513
514 int getVectorWidth();
515
Tobias Grosser55d52082012-03-02 15:20:39 +0000516 Value *getVectorValue(const Value *Old, ValueMapT &VectorMap,
517 VectorValueMapT &ScalarMaps);
Tobias Grosser80998e72012-03-02 11:27:28 +0000518
519 Type *getVectorPtrTy(const Value *V, int Width);
520
521 /// @brief Load a vector from a set of adjacent scalars
522 ///
523 /// In case a set of scalars is known to be next to each other in memory,
524 /// create a vector load that loads those scalars
525 ///
526 /// %vector_ptr= bitcast double* %p to <4 x double>*
527 /// %vec_full = load <4 x double>* %vector_ptr
528 ///
529 Value *generateStrideOneLoad(const LoadInst *Load, ValueMapT &BBMap);
530
531 /// @brief Load a vector initialized from a single scalar in memory
532 ///
533 /// In case all elements of a vector are initialized to the same
534 /// scalar value, this value is loaded and shuffeled into all elements
535 /// of the vector.
536 ///
537 /// %splat_one = load <1 x double>* %p
538 /// %splat = shufflevector <1 x double> %splat_one, <1 x
539 /// double> %splat_one, <4 x i32> zeroinitializer
540 ///
541 Value *generateStrideZeroLoad(const LoadInst *Load, ValueMapT &BBMap);
542
543 /// @Load a vector from scalars distributed in memory
544 ///
545 /// In case some scalars a distributed randomly in memory. Create a vector
546 /// by loading each scalar and by inserting one after the other into the
547 /// vector.
548 ///
549 /// %scalar_1= load double* %p_1
550 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
551 /// %scalar 2 = load double* %p_2
552 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
553 ///
554 Value *generateUnknownStrideLoad(const LoadInst *Load,
555 VectorValueMapT &ScalarMaps);
556
Tobias Grosser80998e72012-03-02 11:27:28 +0000557 void generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
558 VectorValueMapT &ScalarMaps);
559
Tobias Grosserdf382372012-03-02 15:20:35 +0000560 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &VectorMap,
561 VectorValueMapT &ScalarMaps);
Tobias Grosser80998e72012-03-02 11:27:28 +0000562
Tobias Grosserdf382372012-03-02 15:20:35 +0000563 void copyBinaryInst(const BinaryOperator *Inst, ValueMapT &VectorMap,
564 VectorValueMapT &ScalarMaps);
Tobias Grosser80998e72012-03-02 11:27:28 +0000565
Tobias Grosserdf382372012-03-02 15:20:35 +0000566 void copyStore(const StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser260e86d2012-03-02 15:20:28 +0000567 VectorValueMapT &ScalarMaps);
Tobias Grosser80998e72012-03-02 11:27:28 +0000568
569 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
570
571 void copyInstruction(const Instruction *Inst, ValueMapT &VectorMap,
572 VectorValueMapT &ScalarMaps);
573
Tobias Grosser80998e72012-03-02 11:27:28 +0000574 void copyBB();
575};
576
Tobias Grosser55d52082012-03-02 15:20:39 +0000577VectorBlockGenerator::VectorBlockGenerator(IRBuilder<> &B,
578 VectorValueMapT &GlobalMaps, ScopStmt &Stmt, __isl_keep isl_set *Domain,
579 Pass *P) : BlockGenerator(B, Stmt, P), GlobalMaps(GlobalMaps),
580 Domain(Domain) {
Tobias Grosserdf382372012-03-02 15:20:35 +0000581 assert(GlobalMaps.size() > 1 && "Only one vector lane found");
Tobias Grosser08a82382012-03-02 15:20:24 +0000582 assert(Domain && "No statement domain provided");
Tobias Grosser80998e72012-03-02 11:27:28 +0000583 }
584
Tobias Grosser55d52082012-03-02 15:20:39 +0000585Value *VectorBlockGenerator::getVectorValue(const Value *Old,
586 ValueMapT &VectorMap,
587 VectorValueMapT &ScalarMaps) {
588 if (VectorMap.count(Old))
589 return VectorMap[Old];
Tobias Grosser80998e72012-03-02 11:27:28 +0000590
Tobias Grosserdf382372012-03-02 15:20:35 +0000591 int Width = getVectorWidth();
Tobias Grosser80998e72012-03-02 11:27:28 +0000592
Tobias Grosser55d52082012-03-02 15:20:39 +0000593 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
Tobias Grosser80998e72012-03-02 11:27:28 +0000594
Tobias Grosserdf382372012-03-02 15:20:35 +0000595 for (int Lane = 0; Lane < Width; Lane++)
596 Vector = Builder.CreateInsertElement(Vector,
Tobias Grosser55d52082012-03-02 15:20:39 +0000597 getNewValue(Old,
598 ScalarMaps[Lane],
599 GlobalMaps[Lane]),
Tobias Grosserdf382372012-03-02 15:20:35 +0000600 Builder.getInt32(Lane));
Tobias Grosser80998e72012-03-02 11:27:28 +0000601
Tobias Grosser55d52082012-03-02 15:20:39 +0000602 VectorMap[Old] = Vector;
Tobias Grosserdf382372012-03-02 15:20:35 +0000603
604 return Vector;
Tobias Grosser80998e72012-03-02 11:27:28 +0000605}
606
607Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
608 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
609 assert(PointerTy && "PointerType expected");
610
611 Type *ScalarType = PointerTy->getElementType();
612 VectorType *VectorType = VectorType::get(ScalarType, Width);
613
614 return PointerType::getUnqual(VectorType);
615}
616
617Value *VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
618 ValueMapT &BBMap) {
619 const Value *Pointer = Load->getPointerOperand();
620 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosser55d52082012-03-02 15:20:39 +0000621 Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
Tobias Grosser80998e72012-03-02 11:27:28 +0000622 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
623 "vector_ptr");
624 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
625 Load->getName() + "_p_vec_full");
626 if (!Aligned)
627 VecLoad->setAlignment(8);
628
629 return VecLoad;
630}
631
632Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
633 ValueMapT &BBMap) {
634 const Value *Pointer = Load->getPointerOperand();
635 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosser55d52082012-03-02 15:20:39 +0000636 Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
Tobias Grosser80998e72012-03-02 11:27:28 +0000637 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
638 Load->getName() + "_p_vec_p");
639 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
640 Load->getName() + "_p_splat_one");
641
642 if (!Aligned)
643 ScalarLoad->setAlignment(8);
644
645 Constant *SplatVector =
646 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
647 getVectorWidth()));
648
649 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
650 SplatVector,
651 Load->getName()
652 + "_p_splat");
653 return VectorLoad;
654}
655
656Value *VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
657 VectorValueMapT &ScalarMaps) {
658 int VectorWidth = getVectorWidth();
659 const Value *Pointer = Load->getPointerOperand();
660 VectorType *VectorType = VectorType::get(
661 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
662
663 Value *Vector = UndefValue::get(VectorType);
664
665 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000666 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
Tobias Grosser80998e72012-03-02 11:27:28 +0000667 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
668 Load->getName() + "_p_scalar_");
669 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
670 Builder.getInt32(i),
671 Load->getName() + "_p_vec_");
672 }
673
674 return Vector;
675}
676
677void VectorBlockGenerator::generateLoad(const LoadInst *Load,
678 ValueMapT &VectorMap,
679 VectorValueMapT &ScalarMaps) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000680 Value *NewLoad;
681
682 MemoryAccess &Access = Statement.getAccessFor(Load);
683
Tobias Grosser08a82382012-03-02 15:20:24 +0000684 if (Access.isStrideZero(isl_set_copy(Domain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000685 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Tobias Grosser08a82382012-03-02 15:20:24 +0000686 else if (Access.isStrideOne(isl_set_copy(Domain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000687 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000688 else
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000689 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000690
691 VectorMap[Load] = NewLoad;
692}
693
Tobias Grosser80998e72012-03-02 11:27:28 +0000694void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
Tobias Grosserdf382372012-03-02 15:20:35 +0000695 ValueMapT &VectorMap,
696 VectorValueMapT &ScalarMaps) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000697 int VectorWidth = getVectorWidth();
Tobias Grosser55d52082012-03-02 15:20:39 +0000698 Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap,
699 ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000700
701 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
702
703 const CastInst *Cast = dyn_cast<CastInst>(Inst);
704 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
705 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
706}
707
Tobias Grosser80998e72012-03-02 11:27:28 +0000708void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
Tobias Grosserdf382372012-03-02 15:20:35 +0000709 ValueMapT &VectorMap,
710 VectorValueMapT &ScalarMaps) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000711 Value *OpZero = Inst->getOperand(0);
712 Value *OpOne = Inst->getOperand(1);
713
714 Value *NewOpZero, *NewOpOne;
Tobias Grosser55d52082012-03-02 15:20:39 +0000715 NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps);
716 NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000717
718 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
719 NewOpOne,
720 Inst->getName() + "p_vec");
721 VectorMap[Inst] = NewInst;
722}
723
Tobias Grosserdf382372012-03-02 15:20:35 +0000724void VectorBlockGenerator::copyStore(const StoreInst *Store,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000725 ValueMapT &VectorMap,
Tobias Grosser8927a442012-03-02 11:27:05 +0000726 VectorValueMapT &ScalarMaps) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000727 int VectorWidth = getVectorWidth();
728
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000729 MemoryAccess &Access = Statement.getAccessFor(Store);
730
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000731 const Value *Pointer = Store->getPointerOperand();
Tobias Grosser55d52082012-03-02 15:20:39 +0000732 Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
Tobias Grosserdf382372012-03-02 15:20:35 +0000733 ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000734
Tobias Grosser08a82382012-03-02 15:20:24 +0000735 if (Access.isStrideOne(isl_set_copy(Domain))) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000736 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
Tobias Grosser55d52082012-03-02 15:20:39 +0000737 Value *NewPointer = getNewValue(Pointer, ScalarMaps[0], GlobalMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000738
739 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
740 "vector_ptr");
741 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
742
743 if (!Aligned)
744 Store->setAlignment(8);
745 } else {
746 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
747 Value *Scalar = Builder.CreateExtractElement(Vector,
748 Builder.getInt32(i));
Tobias Grosser55d52082012-03-02 15:20:39 +0000749 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000750 Builder.CreateStore(Scalar, NewPointer);
751 }
752 }
753}
754
Tobias Grosser80998e72012-03-02 11:27:28 +0000755bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
756 ValueMapT &VectorMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000757 for (Instruction::const_op_iterator OI = Inst->op_begin(),
758 OE = Inst->op_end(); OI != OE; ++OI)
759 if (VectorMap.count(*OI))
760 return true;
761 return false;
762}
763
Tobias Grosser80998e72012-03-02 11:27:28 +0000764int VectorBlockGenerator::getVectorWidth() {
Tobias Grosserdf382372012-03-02 15:20:35 +0000765 return GlobalMaps.size();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000766}
767
Tobias Grosser80998e72012-03-02 11:27:28 +0000768void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
Tobias Grosser32152cb2012-03-02 11:27:18 +0000769 ValueMapT &VectorMap,
770 VectorValueMapT &ScalarMaps) {
Tobias Grosser80998e72012-03-02 11:27:28 +0000771 // Terminator instructions control the control flow. They are explicitly
772 // expressed in the clast and do not need to be copied.
773 if (Inst->isTerminator())
774 return;
775
Tobias Grosser32152cb2012-03-02 11:27:18 +0000776 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser80998e72012-03-02 11:27:28 +0000777 generateLoad(Load, VectorMap, ScalarMaps);
Tobias Grosser32152cb2012-03-02 11:27:18 +0000778 return;
779 }
780
781 if (hasVectorOperands(Inst, VectorMap)) {
782 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserdf382372012-03-02 15:20:35 +0000783 copyStore(Store, VectorMap, ScalarMaps);
Tobias Grosser32152cb2012-03-02 11:27:18 +0000784 return;
785 }
786
787 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Tobias Grosserdf382372012-03-02 15:20:35 +0000788 copyUnaryInst(Unary, VectorMap, ScalarMaps);
Tobias Grosser32152cb2012-03-02 11:27:18 +0000789 return;
790 }
791
792 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
Tobias Grosserdf382372012-03-02 15:20:35 +0000793 copyBinaryInst(Binary, VectorMap, ScalarMaps);
Tobias Grosser32152cb2012-03-02 11:27:18 +0000794 return;
795 }
796
797 llvm_unreachable("Cannot issue vector code for this instruction");
798 }
799
800 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Tobias Grosserdf382372012-03-02 15:20:35 +0000801 copyInstScalar(Inst, ScalarMaps[VectorLane], GlobalMaps[VectorLane]);
Tobias Grosser32152cb2012-03-02 11:27:18 +0000802}
803
Tobias Grosser80998e72012-03-02 11:27:28 +0000804void VectorBlockGenerator::copyBB() {
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000805 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000806 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
807 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000808 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000809 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000810
811 // Create two maps that store the mapping from the original instructions of
812 // the old basic block to their copies in the new basic block. Those maps
813 // are basic block local.
814 //
815 // As vector code generation is supported there is one map for scalar values
816 // and one for vector values.
817 //
818 // In case we just do scalar code generation, the vectorMap is not used and
819 // the scalarMap has just one dimension, which contains the mapping.
820 //
821 // In case vector code generation is done, an instruction may either appear
822 // in the vector map once (as it is calculating >vectorwidth< values at a
823 // time. Or (if the values are calculated using scalar operations), it
824 // appears once in every dimension of the scalarMap.
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000825 VectorValueMapT ScalarBlockMap(getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000826 ValueMapT VectorBlockMap;
827
828 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
829 II != IE; ++II)
Tobias Grosserfc1153f2012-03-02 11:27:15 +0000830 copyInstruction(II, VectorBlockMap, ScalarBlockMap);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000831}
832
Tobias Grosser75805372011-04-29 06:27:02 +0000833/// Class to generate LLVM-IR that calculates the value of a clast_expr.
834class ClastExpCodeGen {
835 IRBuilder<> &Builder;
836 const CharMapT *IVS;
837
Tobias Grosserbb137e32012-01-24 16:42:28 +0000838 Value *codegen(const clast_name *e, Type *Ty);
839 Value *codegen(const clast_term *e, Type *Ty);
840 Value *codegen(const clast_binary *e, Type *Ty);
841 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000842public:
843
844 // A generator for clast expressions.
845 //
846 // @param B The IRBuilder that defines where the code to calculate the
847 // clast expressions should be inserted.
848 // @param IVMAP A Map that translates strings describing the induction
849 // variables to the Values* that represent these variables
850 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000851 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000852
853 // Generates code to calculate a given clast expression.
854 //
855 // @param e The expression to calculate.
856 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000857 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859 // @brief Reset the CharMap.
860 //
861 // This function is called to reset the CharMap to new one, while generating
862 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000863 void setIVS(CharMapT *IVSNew);
864};
865
866Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
867 CharMapT::const_iterator I = IVS->find(e->name);
868
869 assert(I != IVS->end() && "Clast name not found");
870
871 return Builder.CreateSExtOrBitCast(I->second, Ty);
872}
873
874Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
875 APInt a = APInt_from_MPZ(e->val);
876
877 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
878 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
879
880 if (!e->var)
881 return ConstOne;
882
883 Value *var = codegen(e->var, Ty);
884 return Builder.CreateMul(ConstOne, var);
885}
886
887Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
888 Value *LHS = codegen(e->LHS, Ty);
889
890 APInt RHS_AP = APInt_from_MPZ(e->RHS);
891
892 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
893 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
894
895 switch (e->type) {
896 case clast_bin_mod:
897 return Builder.CreateSRem(LHS, RHS);
898 case clast_bin_fdiv:
899 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000900 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000901 Value *One = ConstantInt::get(Ty, 1);
902 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000903 Value *Sum1 = Builder.CreateSub(LHS, RHS);
904 Value *Sum2 = Builder.CreateAdd(Sum1, One);
905 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
906 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
907 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000908 }
909 case clast_bin_cdiv:
910 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000911 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
912 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000913 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000914 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
915 Value *Sum2 = Builder.CreateSub(Sum1, One);
916 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
917 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
918 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000919 }
920 case clast_bin_div:
921 return Builder.CreateSDiv(LHS, RHS);
922 };
923
924 llvm_unreachable("Unknown clast binary expression type");
925}
926
927Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
928 assert(( r->type == clast_red_min
929 || r->type == clast_red_max
930 || r->type == clast_red_sum)
931 && "Clast reduction type not supported");
932 Value *old = codegen(r->elts[0], Ty);
933
934 for (int i=1; i < r->n; ++i) {
935 Value *exprValue = codegen(r->elts[i], Ty);
936
937 switch (r->type) {
938 case clast_red_min:
939 {
940 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
941 old = Builder.CreateSelect(cmp, old, exprValue);
942 break;
943 }
944 case clast_red_max:
945 {
946 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
947 old = Builder.CreateSelect(cmp, old, exprValue);
948 break;
949 }
950 case clast_red_sum:
951 old = Builder.CreateAdd(old, exprValue);
952 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000953 }
Tobias Grosser75805372011-04-29 06:27:02 +0000954 }
955
Tobias Grosserbb137e32012-01-24 16:42:28 +0000956 return old;
957}
958
959ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
960 : Builder(B), IVS(IVMap) {}
961
962Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
963 switch(e->type) {
964 case clast_expr_name:
965 return codegen((const clast_name *)e, Ty);
966 case clast_expr_term:
967 return codegen((const clast_term *)e, Ty);
968 case clast_expr_bin:
969 return codegen((const clast_binary *)e, Ty);
970 case clast_expr_red:
971 return codegen((const clast_reduction *)e, Ty);
972 }
973
974 llvm_unreachable("Unknown clast expression!");
975}
976
977void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
978 IVS = IVSNew;
979}
Tobias Grosser75805372011-04-29 06:27:02 +0000980
981class ClastStmtCodeGen {
982 // The Scop we code generate.
983 Scop *S;
984 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000985 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000986 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000987 Dependences *DP;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000988 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000989
990 // The Builder specifies the current location to code generate at.
991 IRBuilder<> &Builder;
992
993 // Map the Values from the old code to their counterparts in the new code.
994 ValueMapT ValueMap;
995
996 // clastVars maps from the textual representation of a clast variable to its
997 // current *Value. clast variables are scheduling variables, original
998 // induction variables or parameters. They are used either in loop bounds or
999 // to define the statement instance that is executed.
1000 //
1001 // for (s = 0; s < n + 3; ++i)
1002 // for (t = s; t < m; ++j)
1003 // Stmt(i = s + 3 * m, j = t);
1004 //
1005 // {s,t,i,j,n,m} is the set of clast variables in this clast.
1006 CharMapT *clastVars;
1007
1008 // Codegenerator for clast expressions.
1009 ClastExpCodeGen ExpGen;
1010
1011 // Do we currently generate parallel code?
1012 bool parallelCodeGeneration;
1013
1014 std::vector<std::string> parallelLoops;
1015
1016public:
1017
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001018 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +00001019
1020 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001021 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +00001022
1023 void codegen(const clast_assignment *a, ScopStmt *Statement,
1024 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001025 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001026
1027 void codegenSubstitutions(const clast_stmt *Assignment,
1028 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001029 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001030
1031 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001032 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001034 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +00001035
1036 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +00001037 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001038 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001039
Tobias Grosser75805372011-04-29 06:27:02 +00001040 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001041 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +00001042
1043 /// @brief Add values to the OpenMP structure.
1044 ///
1045 /// Create the subfunction structure and add the values from the list.
1046 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001047 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +00001048
1049 /// @brief Create OpenMP structure values.
1050 ///
1051 /// Create a list of values that has to be stored into the subfuncition
1052 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001053 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +00001054
1055 /// @brief Extract the values from the subfunction parameter.
1056 ///
1057 /// Extract the values from the subfunction parameter and update the clast
1058 /// variables to point to the new values.
1059 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1060 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001061 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001062
1063 /// @brief Add body to the subfunction.
1064 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1065 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001066 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +00001067
1068 /// @brief Create an OpenMP parallel for loop.
1069 ///
1070 /// This loop reflects a loop as if it would have been created by an OpenMP
1071 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001072 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001073
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001074 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001075
1076 /// @brief Get the number of loop iterations for this loop.
1077 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001078 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001079
1080 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001081 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001082
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001083 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001084
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001085 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +00001086
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001087 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +00001088
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001089 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001090
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001091 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001092
Tobias Grossere9ffea22012-03-15 09:34:48 +00001093 IntegerType *getIntPtrTy();
1094
Tobias Grosser75805372011-04-29 06:27:02 +00001095 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001096 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001097
1098 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001099 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001100 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001101};
1102}
1103
Tobias Grossere9ffea22012-03-15 09:34:48 +00001104IntegerType *ClastStmtCodeGen::getIntPtrTy() {
1105 return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
1106}
1107
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001108const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1109 return parallelLoops;
1110}
1111
1112void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001113 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001114 (*clastVars)[a->LHS] = V;
1115}
1116
1117void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1118 unsigned Dimension, int vectorDim,
1119 std::vector<ValueMapT> *VectorVMap) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001120 Value *RHS = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001121
1122 assert(!a->LHS && "Statement assignments do not have left hand side");
1123 const PHINode *PN;
1124 PN = Statement->getInductionVariableForDimension(Dimension);
1125 const Value *V = PN;
1126
1127 if (VectorVMap)
1128 (*VectorVMap)[vectorDim][V] = RHS;
1129
1130 ValueMap[V] = RHS;
1131}
1132
1133void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1134 ScopStmt *Statement, int vectorDim,
1135 std::vector<ValueMapT> *VectorVMap) {
1136 int Dimension = 0;
1137
1138 while (Assignment) {
1139 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1140 && "Substitions are expected to be assignments");
1141 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1142 vectorDim, VectorVMap);
1143 Assignment = Assignment->next;
1144 Dimension++;
1145 }
1146}
1147
1148void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1149 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001150 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001151 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001152
1153 if (u->substitutions)
1154 codegenSubstitutions(u->substitutions, Statement);
1155
Tobias Grosser80998e72012-03-02 11:27:28 +00001156 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001157
Tobias Grosser80998e72012-03-02 11:27:28 +00001158 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +00001159 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +00001160 return;
1161 }
1162
1163 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001164
1165 if (IVS) {
1166 assert (u->substitutions && "Substitutions expected!");
1167 int i = 0;
1168 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1169 II != IE; ++II) {
1170 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001171 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001172 i++;
1173 }
1174 }
1175
Tobias Grosser55d52082012-03-02 15:20:39 +00001176 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001177}
1178
1179void ClastStmtCodeGen::codegen(const clast_block *b) {
1180 if (b->body)
1181 codegen(b->body);
1182}
1183
1184void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1185 Value *LowerBound,
1186 Value *UpperBound) {
Tobias Grosser0ac92142012-02-14 14:02:27 +00001187 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +00001188 Type *IntPtrTy = getIntPtrTy();
1189 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001190
1191 // The value of lowerbound and upperbound will be supplied, if this
1192 // function is called while generating OpenMP code. Otherwise get
1193 // the values.
1194 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1195
1196 if (LowerBound == 0) {
1197 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1198 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1199 }
1200
Tobias Grosser0ac92142012-02-14 14:02:27 +00001201 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1202 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001203
1204 // Add loop iv to symbols.
1205 (*clastVars)[f->iterator] = IV;
1206
1207 if (f->body)
1208 codegen(f->body);
1209
1210 // Loop is finished, so remove its iv from the live symbols.
1211 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001212 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001213}
1214
1215Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1216 Function *F = Builder.GetInsertBlock()->getParent();
1217 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1218 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1219 Function *FN = Function::Create(FT, Function::InternalLinkage,
1220 F->getName() + ".omp_subfn", M);
1221 // Do not run any polly pass on the new function.
1222 SD->markFunctionAsInvalid(FN);
1223
1224 Function::arg_iterator AI = FN->arg_begin();
1225 AI->setName("omp.userContext");
1226
1227 return FN;
1228}
1229
1230Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1231 Function *SubFunction) {
1232 std::vector<Type*> structMembers;
1233
1234 // Create the structure.
1235 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1236 structMembers.push_back(OMPDataVals[i]->getType());
1237
1238 StructType *structTy = StructType::get(Builder.getContext(),
1239 structMembers);
1240 // Store the values into the structure.
1241 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1242 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1243 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1244 Builder.CreateStore(OMPDataVals[i], storeAddr);
1245 }
1246
1247 return structData;
1248}
1249
1250SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1251 SetVector<Value*> OMPDataVals;
1252
1253 // Push the clast variables available in the clastVars.
1254 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1255 I != E; I++)
1256 OMPDataVals.insert(I->second);
1257
1258 // Push the base addresses of memory references.
1259 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1260 ScopStmt *Stmt = *SI;
1261 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1262 E = Stmt->memacc_end(); I != E; ++I) {
1263 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1264 OMPDataVals.insert((BaseAddr));
1265 }
1266 }
1267
1268 return OMPDataVals;
1269}
1270
1271void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1272 SetVector<Value*> OMPDataVals, Value *userContext) {
1273 // Extract the clast variables.
1274 unsigned i = 0;
1275 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1276 I != E; I++) {
1277 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1278 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1279 i++;
1280 }
1281
1282 // Extract the base addresses of memory references.
1283 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1284 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1285 Value *baseAddr = OMPDataVals[j];
1286 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1287 }
1288}
1289
1290void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1291 const clast_for *f,
1292 Value *structData,
1293 SetVector<Value*> OMPDataVals) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001294 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001295 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1296 LLVMContext &Context = FN->getContext();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001297
1298 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001299 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001300 BasicBlock *PrevBB = Builder.GetInsertBlock();
1301
1302 // Create basic blocks.
1303 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1304 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1305 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1306 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1307 FN);
1308
1309 DT->addNewBlock(HeaderBB, PrevBB);
1310 DT->addNewBlock(ExitBB, HeaderBB);
1311 DT->addNewBlock(checkNextBB, HeaderBB);
1312 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1313
1314 // Fill up basic block HeaderBB.
1315 Builder.SetInsertPoint(HeaderBB);
Tobias Grossere9ffea22012-03-15 09:34:48 +00001316 Value *lowerBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.lowerBoundPtr");
1317 Value *upperBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.upperBoundPtr");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001318 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1319 structData->getType(),
1320 "omp.userContext");
1321
1322 CharMapT clastVarsOMP;
1323 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1324
1325 Builder.CreateBr(checkNextBB);
1326
1327 // Add code to check if another set of iterations will be executed.
1328 Builder.SetInsertPoint(checkNextBB);
1329 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1330 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1331 lowerBoundPtr, upperBoundPtr);
1332 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1333 "omp.hasNextScheduleBlock");
1334 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1335
1336 // Add code to to load the iv bounds for this set of iterations.
1337 Builder.SetInsertPoint(loadIVBoundsBB);
1338 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1339 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1340
1341 // Subtract one as the upper bound provided by openmp is a < comparison
1342 // whereas the codegenForSequential function creates a <= comparison.
Tobias Grossere9ffea22012-03-15 09:34:48 +00001343 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(IntPtrTy, 1),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001344 "omp.upperBoundAdjusted");
1345
1346 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1347 CharMapT *oldClastVars = clastVars;
1348 clastVars = &clastVarsOMP;
1349 ExpGen.setIVS(&clastVarsOMP);
1350
Tobias Grosser0ac92142012-02-14 14:02:27 +00001351 Builder.CreateBr(checkNextBB);
1352 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001353 codegenForSequential(f, lowerBound, upperBound);
1354
1355 // Restore the old clastVars.
1356 clastVars = oldClastVars;
1357 ExpGen.setIVS(oldClastVars);
1358
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001359 // Add code to terminate this openmp subfunction.
1360 Builder.SetInsertPoint(ExitBB);
1361 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1362 Builder.CreateCall(endnowaitFunction);
1363 Builder.CreateRetVoid();
1364
Tobias Grosser0ac92142012-02-14 14:02:27 +00001365 // Restore the previous insert point.
1366 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001367}
1368
Tobias Grosser415245d2012-03-02 15:20:17 +00001369void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001370 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grossere9ffea22012-03-15 09:34:48 +00001371 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001372
1373 Function *SubFunction = addOpenMPSubfunction(M);
1374 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
Tobias Grosser415245d2012-03-02 15:20:17 +00001375 Value *StructData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001376
Tobias Grosser415245d2012-03-02 15:20:17 +00001377 addOpenMPSubfunctionBody(SubFunction, For, StructData, OMPDataVals);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001378
1379 // Create call for GOMP_parallel_loop_runtime_start.
Tobias Grosser415245d2012-03-02 15:20:17 +00001380 Value *SubfunctionParam = Builder.CreateBitCast(StructData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001381 Builder.getInt8PtrTy(),
1382 "omp_data");
1383
Tobias Grosser415245d2012-03-02 15:20:17 +00001384 Value *NumberOfThreads = Builder.getInt32(0);
1385 Value *LowerBound = ExpGen.codegen(For->LB, IntPtrTy);
1386 Value *UpperBound = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001387
1388 // Add one as the upper bound provided by openmp is a < comparison
1389 // whereas the codegenForSequential function creates a <= comparison.
Tobias Grosser415245d2012-03-02 15:20:17 +00001390 UpperBound = Builder.CreateAdd(UpperBound, ConstantInt::get(IntPtrTy, 1));
1391 APInt APStride = APInt_from_MPZ(For->stride);
1392 Value *Stride = ConstantInt::get(IntPtrTy,
1393 APStride.zext(IntPtrTy->getBitWidth()));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001394
Tobias Grosser415245d2012-03-02 15:20:17 +00001395 Value *Arguments[] = { SubFunction, SubfunctionParam, NumberOfThreads,
1396 LowerBound, UpperBound, Stride};
1397 Builder.CreateCall(M->getFunction("GOMP_parallel_loop_runtime_start"),
1398 Arguments);
1399 Builder.CreateCall(SubFunction, SubfunctionParam);
1400 Builder.CreateCall(M->getFunction("GOMP_parallel_end"));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001401}
1402
1403bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1404 const clast_stmt *stmt = f->body;
1405
1406 while (stmt) {
1407 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1408 return false;
1409
1410 stmt = stmt->next;
1411 }
1412
1413 return true;
1414}
1415
1416int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1417 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1418 isl_set *tmp = isl_set_copy(loopDomain);
1419
1420 // Calculate a map similar to the identity map, but with the last input
1421 // and output dimension not related.
1422 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1423 isl_space *Space = isl_set_get_space(loopDomain);
1424 Space = isl_space_drop_outputs(Space,
1425 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1426 Space = isl_space_map_from_set(Space);
1427 isl_map *identity = isl_map_identity(Space);
1428 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1429 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1430
1431 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1432 map = isl_map_intersect(map, identity);
1433
1434 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1435 isl_map *lexmin = isl_map_lexmin(map);
1436 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1437
1438 isl_set *elements = isl_map_range(sub);
1439
1440 if (!isl_set_is_singleton(elements)) {
1441 isl_set_free(elements);
1442 return -1;
1443 }
1444
1445 isl_point *p = isl_set_sample_point(elements);
1446
1447 isl_int v;
1448 isl_int_init(v);
1449 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1450 int numberIterations = isl_int_get_si(v);
1451 isl_int_clear(v);
1452 isl_point_free(p);
1453
1454 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1455}
1456
1457void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1458 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1459 int vectorWidth = getNumberOfIterations(f);
1460
Tobias Grossere9ffea22012-03-15 09:34:48 +00001461 Value *LB = ExpGen.codegen(f->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001462
1463 APInt Stride = APInt_from_MPZ(f->stride);
1464 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1465 Stride = Stride.zext(LoopIVType->getBitWidth());
1466 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1467
1468 std::vector<Value*> IVS(vectorWidth);
1469 IVS[0] = LB;
1470
1471 for (int i = 1; i < vectorWidth; i++)
1472 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1473
1474 isl_set *scatteringDomain =
1475 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1476
1477 // Add loop iv to symbols.
1478 (*clastVars)[f->iterator] = LB;
1479
1480 const clast_stmt *stmt = f->body;
1481
1482 while (stmt) {
1483 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1484 scatteringDomain);
1485 stmt = stmt->next;
1486 }
1487
1488 // Loop is finished, so remove its iv from the live symbols.
1489 isl_set_free(scatteringDomain);
1490 clastVars->erase(f->iterator);
1491}
1492
1493void ClastStmtCodeGen::codegen(const clast_for *f) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001494 if ((Vector || OpenMP) && DP->isParallelFor(f)) {
1495 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1496 && (getNumberOfIterations(f) <= 16)) {
1497 codegenForVector(f);
1498 return;
1499 }
1500
1501 if (OpenMP && !parallelCodeGeneration) {
1502 parallelCodeGeneration = true;
1503 parallelLoops.push_back(f->iterator);
1504 codegenForOpenMP(f);
1505 parallelCodeGeneration = false;
1506 return;
1507 }
1508 }
1509
1510 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001511}
1512
1513Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001514 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
1515 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001516 CmpInst::Predicate P;
1517
1518 if (eq->sign == 0)
1519 P = ICmpInst::ICMP_EQ;
1520 else if (eq->sign > 0)
1521 P = ICmpInst::ICMP_SGE;
1522 else
1523 P = ICmpInst::ICMP_SLE;
1524
1525 return Builder.CreateICmp(P, LHS, RHS);
1526}
1527
1528void ClastStmtCodeGen::codegen(const clast_guard *g) {
1529 Function *F = Builder.GetInsertBlock()->getParent();
1530 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001531
1532 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1533 Builder.GetInsertPoint(), P);
1534 CondBB->setName("polly.cond");
1535 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1536 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001537 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001538
1539 DT->addNewBlock(ThenBB, CondBB);
1540 DT->changeImmediateDominator(MergeBB, CondBB);
1541
1542 CondBB->getTerminator()->eraseFromParent();
1543
1544 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001545
1546 Value *Predicate = codegen(&(g->eq[0]));
1547
1548 for (int i = 1; i < g->n; ++i) {
1549 Value *TmpPredicate = codegen(&(g->eq[i]));
1550 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1551 }
1552
1553 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1554 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001555 Builder.CreateBr(MergeBB);
1556 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001557
1558 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001559
1560 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001561}
1562
1563void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1564 if (CLAST_STMT_IS_A(stmt, stmt_root))
1565 assert(false && "No second root statement expected");
1566 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1567 codegen((const clast_assignment *)stmt);
1568 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1569 codegen((const clast_user_stmt *)stmt);
1570 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1571 codegen((const clast_block *)stmt);
1572 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1573 codegen((const clast_for *)stmt);
1574 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1575 codegen((const clast_guard *)stmt);
1576
1577 if (stmt->next)
1578 codegen(stmt->next);
1579}
1580
1581void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1582 SCEVExpander Rewriter(SE, "polly");
1583
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001584 int i = 0;
1585 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1586 PI != PE; ++PI) {
1587 assert(i < names->nb_parameters && "Not enough parameter names");
1588
1589 const SCEV *Param = *PI;
1590 Type *Ty = Param->getType();
1591
1592 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1593 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1594 (*clastVars)[names->parameters[i]] = V;
1595
1596 ++i;
1597 }
1598}
1599
1600void ClastStmtCodeGen::codegen(const clast_root *r) {
1601 clastVars = new CharMapT();
1602 addParameters(r->names);
1603 ExpGen.setIVS(clastVars);
1604
1605 parallelCodeGeneration = false;
1606
1607 const clast_stmt *stmt = (const clast_stmt*) r;
1608 if (stmt->next)
1609 codegen(stmt->next);
1610
1611 delete clastVars;
1612}
1613
1614ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1615 DominatorTree *dt, ScopDetection *sd,
1616 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001617 IRBuilder<> &B, Pass *P) :
Tobias Grossere9ffea22012-03-15 09:34:48 +00001618 S(scop), SE(se), DT(dt), SD(sd), DP(dp), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001619 ExpGen(Builder, NULL) {}
1620
Tobias Grosser75805372011-04-29 06:27:02 +00001621namespace {
1622class CodeGeneration : public ScopPass {
1623 Region *region;
1624 Scop *S;
1625 DominatorTree *DT;
1626 ScalarEvolution *SE;
1627 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001628 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001629 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001630
1631 std::vector<std::string> parallelLoops;
1632
1633 public:
1634 static char ID;
1635
1636 CodeGeneration() : ScopPass(ID) {}
1637
Tobias Grosserb1c95992012-02-12 12:09:27 +00001638 // Add the declarations needed by the OpenMP function calls that we insert in
1639 // OpenMP mode.
1640 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001641 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001642 IRBuilder<> Builder(M->getContext());
1643 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1644
1645 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001646
1647 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001648 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1649 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001650 }
1651
1652 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001653 Type *Params[] = {
1654 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1655 Builder.getInt8PtrTy(),
1656 false)),
1657 Builder.getInt8PtrTy(),
1658 Builder.getInt32Ty(),
1659 LongTy,
1660 LongTy,
1661 LongTy,
1662 };
Tobias Grosser75805372011-04-29 06:27:02 +00001663
Tobias Grosserd855cc52012-02-12 12:09:32 +00001664 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1665 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001666 }
1667
1668 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001669 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1670 Type *Params[] = {
1671 LongPtrTy,
1672 LongPtrTy,
1673 };
Tobias Grosser75805372011-04-29 06:27:02 +00001674
Tobias Grosserd855cc52012-02-12 12:09:32 +00001675 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1676 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001677 }
1678
1679 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001680 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1681 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001682 }
1683 }
1684
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001685 // Split the entry edge of the region and generate a new basic block on this
1686 // edge. This function also updates ScopInfo and RegionInfo.
1687 //
1688 // @param region The region where the entry edge will be splitted.
1689 BasicBlock *splitEdgeAdvanced(Region *region) {
1690 BasicBlock *newBlock;
1691 BasicBlock *splitBlock;
1692
1693 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1694
1695 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001696 BasicBlock *OldBlock = region->getEntry();
1697 std::string OldName = OldBlock->getName();
1698
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001699 // Update ScopInfo.
1700 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001701 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001702 (*SI)->setBasicBlock(newBlock);
1703 break;
1704 }
1705
1706 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001707 splitBlock = OldBlock;
1708 OldBlock->setName("polly.split");
1709 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001710 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001711 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001712 } else {
1713 RI->setRegionFor(newBlock, region->getParent());
1714 splitBlock = newBlock;
1715 }
1716
1717 return splitBlock;
1718 }
1719
1720 // Create a split block that branches either to the old code or to a new basic
1721 // block where the new code can be inserted.
1722 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001723 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001724 // the new code can be generated.
1725 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001726 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1727 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001728
Tobias Grosserbd608a82012-02-12 12:09:41 +00001729 SplitBlock = splitEdgeAdvanced(region);
1730 SplitBlock->setName("polly.split_new_and_old");
1731 Function *F = SplitBlock->getParent();
1732 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1733 SplitBlock->getTerminator()->eraseFromParent();
1734 Builder->SetInsertPoint(SplitBlock);
1735 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1736 DT->addNewBlock(StartBlock, SplitBlock);
1737 Builder->SetInsertPoint(StartBlock);
1738 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001739 }
1740
1741 // Merge the control flow of the newly generated code with the existing code.
1742 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001743 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001744 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001745 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001746 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001747 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1748 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001749 Region *R = region;
1750
1751 if (R->getExit()->getSinglePredecessor())
1752 // No splitEdge required. A block with a single predecessor cannot have
1753 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001754 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001755 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001756 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001757 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1758 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001759 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001760 }
1761
Tobias Grosserbd608a82012-02-12 12:09:41 +00001762 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001763 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001764
Tobias Grosserbd608a82012-02-12 12:09:41 +00001765 if (DT->dominates(SplitBlock, MergeBlock))
1766 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001767 }
1768
Tobias Grosser75805372011-04-29 06:27:02 +00001769 bool runOnScop(Scop &scop) {
1770 S = &scop;
1771 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001772 DT = &getAnalysis<DominatorTree>();
1773 Dependences *DP = &getAnalysis<Dependences>();
1774 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001775 SD = &getAnalysis<ScopDetection>();
1776 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001777 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001778
1779 parallelLoops.clear();
1780
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001781 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001782
Tobias Grosserb1c95992012-02-12 12:09:27 +00001783 Module *M = region->getEntry()->getParent()->getParent();
1784
Tobias Grosserd855cc52012-02-12 12:09:32 +00001785 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001786
Tobias Grosser5772e652012-02-01 14:23:33 +00001787 // In the CFG the optimized code of the SCoP is generated next to the
1788 // original code. Both the new and the original version of the code remain
1789 // in the CFG. A branch statement decides which version is executed.
1790 // For now, we always execute the new version (the old one is dead code
1791 // eliminated by the cleanup passes). In the future we may decide to execute
1792 // the new version only if certain run time checks succeed. This will be
1793 // useful to support constructs for which we cannot prove all assumptions at
1794 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001795 //
1796 // Before transformation:
1797 //
1798 // bb0
1799 // |
1800 // orig_scop
1801 // |
1802 // bb1
1803 //
1804 // After transformation:
1805 // bb0
1806 // |
1807 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001808 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001809 // | startBlock
1810 // | |
1811 // orig_scop new_scop
1812 // \ /
1813 // \ /
1814 // bb1 (joinBlock)
1815 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001816
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001817 // The builder will be set to startBlock.
1818 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001819 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001820
Tobias Grosser0ac92142012-02-14 14:02:27 +00001821 mergeControlFlow(splitBlock, &builder);
1822 builder.SetInsertPoint(StartBlock->begin());
1823
1824 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001825 CloogInfo &C = getAnalysis<CloogInfo>();
1826 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001827
Tobias Grosser75805372011-04-29 06:27:02 +00001828 parallelLoops.insert(parallelLoops.begin(),
1829 CodeGen.getParallelLoops().begin(),
1830 CodeGen.getParallelLoops().end());
1831
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001832 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001833 }
1834
1835 virtual void printScop(raw_ostream &OS) const {
1836 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1837 PE = parallelLoops.end(); PI != PE; ++PI)
1838 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1839 }
1840
1841 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1842 AU.addRequired<CloogInfo>();
1843 AU.addRequired<Dependences>();
1844 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001845 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001846 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001847 AU.addRequired<ScopDetection>();
1848 AU.addRequired<ScopInfo>();
1849 AU.addRequired<TargetData>();
1850
1851 AU.addPreserved<CloogInfo>();
1852 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001853
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001854 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001855 AU.addPreserved<LoopInfo>();
1856 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001857 AU.addPreserved<ScopDetection>();
1858 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001859
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001860 // FIXME: We do not yet add regions for the newly generated code to the
1861 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001862 AU.addPreserved<RegionInfo>();
1863 AU.addPreserved<TempScopInfo>();
1864 AU.addPreserved<ScopInfo>();
1865 AU.addPreservedID(IndependentBlocksID);
1866 }
1867};
1868}
1869
1870char CodeGeneration::ID = 1;
1871
Tobias Grosser73600b82011-10-08 00:30:40 +00001872INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001873 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +00001874INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1875INITIALIZE_PASS_DEPENDENCY(Dependences)
1876INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1877INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1878INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1879INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1880INITIALIZE_PASS_DEPENDENCY(TargetData)
1881INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001882 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001883
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001884Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001885 return new CodeGeneration();
1886}