blob: b7be56eadb55cee0368e8c56826c1ed0de9c3443 [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,
Tobias Grosserd596b372012-03-15 09:34:52 +000097 APInt Stride, Pass *P, BasicBlock **AfterBlock) {
98 DominatorTree &DT = P->getAnalysis<DominatorTree>();
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 Grosserd596b372012-03-15 09:34:52 +0000109 DT.addNewBlock(HeaderBB, PreheaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000110
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 Grosserd596b372012-03-15 09:34:52 +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);
Tobias Grosserd596b372012-03-15 09:34:52 +0000145 DT.changeImmediateDominator(AfterBB, HeaderBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000146
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;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000984 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000985
986 // The Builder specifies the current location to code generate at.
987 IRBuilder<> &Builder;
988
989 // Map the Values from the old code to their counterparts in the new code.
990 ValueMapT ValueMap;
991
992 // clastVars maps from the textual representation of a clast variable to its
993 // current *Value. clast variables are scheduling variables, original
994 // induction variables or parameters. They are used either in loop bounds or
995 // to define the statement instance that is executed.
996 //
997 // for (s = 0; s < n + 3; ++i)
998 // for (t = s; t < m; ++j)
999 // Stmt(i = s + 3 * m, j = t);
1000 //
1001 // {s,t,i,j,n,m} is the set of clast variables in this clast.
1002 CharMapT *clastVars;
1003
1004 // Codegenerator for clast expressions.
1005 ClastExpCodeGen ExpGen;
1006
1007 // Do we currently generate parallel code?
1008 bool parallelCodeGeneration;
1009
1010 std::vector<std::string> parallelLoops;
1011
1012public:
1013
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001014 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +00001015
1016 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001017 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +00001018
1019 void codegen(const clast_assignment *a, ScopStmt *Statement,
1020 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001021 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001022
1023 void codegenSubstitutions(const clast_stmt *Assignment,
1024 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001025 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001026
1027 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001028 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001029
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001030 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +00001031
1032 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +00001033 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001034 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001035
Tobias Grosser75805372011-04-29 06:27:02 +00001036 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001037 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +00001038
1039 /// @brief Add values to the OpenMP structure.
1040 ///
1041 /// Create the subfunction structure and add the values from the list.
1042 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001043 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +00001044
1045 /// @brief Create OpenMP structure values.
1046 ///
1047 /// Create a list of values that has to be stored into the subfuncition
1048 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001049 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +00001050
1051 /// @brief Extract the values from the subfunction parameter.
1052 ///
1053 /// Extract the values from the subfunction parameter and update the clast
1054 /// variables to point to the new values.
1055 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1056 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001057 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +00001058
1059 /// @brief Add body to the subfunction.
1060 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1061 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001062 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +00001063
1064 /// @brief Create an OpenMP parallel for loop.
1065 ///
1066 /// This loop reflects a loop as if it would have been created by an OpenMP
1067 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001068 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001069
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001070 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001071
1072 /// @brief Get the number of loop iterations for this loop.
1073 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001074 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001075
1076 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001077 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001078
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001079 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +00001080
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001081 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +00001082
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001083 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +00001084
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001085 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001086
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001087 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001088
Tobias Grossere9ffea22012-03-15 09:34:48 +00001089 IntegerType *getIntPtrTy();
1090
Tobias Grosser75805372011-04-29 06:27:02 +00001091 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001092 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001093
Tobias Grosserd596b372012-03-15 09:34:52 +00001094 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001095};
1096}
1097
Tobias Grossere9ffea22012-03-15 09:34:48 +00001098IntegerType *ClastStmtCodeGen::getIntPtrTy() {
1099 return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
1100}
1101
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001102const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1103 return parallelLoops;
1104}
1105
1106void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001107 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001108 (*clastVars)[a->LHS] = V;
1109}
1110
1111void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1112 unsigned Dimension, int vectorDim,
1113 std::vector<ValueMapT> *VectorVMap) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001114 Value *RHS = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001115
1116 assert(!a->LHS && "Statement assignments do not have left hand side");
1117 const PHINode *PN;
1118 PN = Statement->getInductionVariableForDimension(Dimension);
1119 const Value *V = PN;
1120
1121 if (VectorVMap)
1122 (*VectorVMap)[vectorDim][V] = RHS;
1123
1124 ValueMap[V] = RHS;
1125}
1126
1127void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1128 ScopStmt *Statement, int vectorDim,
1129 std::vector<ValueMapT> *VectorVMap) {
1130 int Dimension = 0;
1131
1132 while (Assignment) {
1133 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1134 && "Substitions are expected to be assignments");
1135 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1136 vectorDim, VectorVMap);
1137 Assignment = Assignment->next;
1138 Dimension++;
1139 }
1140}
1141
1142void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1143 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001144 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001145 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001146
1147 if (u->substitutions)
1148 codegenSubstitutions(u->substitutions, Statement);
1149
Tobias Grosser80998e72012-03-02 11:27:28 +00001150 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001151
Tobias Grosser80998e72012-03-02 11:27:28 +00001152 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +00001153 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +00001154 return;
1155 }
1156
1157 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001158
1159 if (IVS) {
1160 assert (u->substitutions && "Substitutions expected!");
1161 int i = 0;
1162 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1163 II != IE; ++II) {
1164 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001165 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001166 i++;
1167 }
1168 }
1169
Tobias Grosser55d52082012-03-02 15:20:39 +00001170 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001171}
1172
1173void ClastStmtCodeGen::codegen(const clast_block *b) {
1174 if (b->body)
1175 codegen(b->body);
1176}
1177
1178void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1179 Value *LowerBound,
1180 Value *UpperBound) {
Tobias Grosser0ac92142012-02-14 14:02:27 +00001181 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +00001182 Type *IntPtrTy = getIntPtrTy();
1183 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001184
1185 // The value of lowerbound and upperbound will be supplied, if this
1186 // function is called while generating OpenMP code. Otherwise get
1187 // the values.
1188 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1189
1190 if (LowerBound == 0) {
1191 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1192 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1193 }
1194
Tobias Grosserd596b372012-03-15 09:34:52 +00001195 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, P, &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001196
1197 // Add loop iv to symbols.
1198 (*clastVars)[f->iterator] = IV;
1199
1200 if (f->body)
1201 codegen(f->body);
1202
1203 // Loop is finished, so remove its iv from the live symbols.
1204 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001205 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001206}
1207
1208Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1209 Function *F = Builder.GetInsertBlock()->getParent();
1210 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1211 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1212 Function *FN = Function::Create(FT, Function::InternalLinkage,
1213 F->getName() + ".omp_subfn", M);
1214 // Do not run any polly pass on the new function.
Tobias Grosserd596b372012-03-15 09:34:52 +00001215 P->getAnalysis<ScopDetection>().markFunctionAsInvalid(FN);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001216
1217 Function::arg_iterator AI = FN->arg_begin();
1218 AI->setName("omp.userContext");
1219
1220 return FN;
1221}
1222
1223Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1224 Function *SubFunction) {
1225 std::vector<Type*> structMembers;
1226
1227 // Create the structure.
1228 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1229 structMembers.push_back(OMPDataVals[i]->getType());
1230
1231 StructType *structTy = StructType::get(Builder.getContext(),
1232 structMembers);
1233 // Store the values into the structure.
1234 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1235 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1236 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1237 Builder.CreateStore(OMPDataVals[i], storeAddr);
1238 }
1239
1240 return structData;
1241}
1242
1243SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1244 SetVector<Value*> OMPDataVals;
1245
1246 // Push the clast variables available in the clastVars.
1247 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1248 I != E; I++)
1249 OMPDataVals.insert(I->second);
1250
1251 // Push the base addresses of memory references.
1252 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1253 ScopStmt *Stmt = *SI;
1254 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1255 E = Stmt->memacc_end(); I != E; ++I) {
1256 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1257 OMPDataVals.insert((BaseAddr));
1258 }
1259 }
1260
1261 return OMPDataVals;
1262}
1263
1264void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1265 SetVector<Value*> OMPDataVals, Value *userContext) {
1266 // Extract the clast variables.
1267 unsigned i = 0;
1268 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1269 I != E; I++) {
1270 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1271 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1272 i++;
1273 }
1274
1275 // Extract the base addresses of memory references.
1276 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1277 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1278 Value *baseAddr = OMPDataVals[j];
1279 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1280 }
1281}
1282
1283void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1284 const clast_for *f,
1285 Value *structData,
1286 SetVector<Value*> OMPDataVals) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001287 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001288 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1289 LLVMContext &Context = FN->getContext();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001290
1291 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001292 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001293 BasicBlock *PrevBB = Builder.GetInsertBlock();
1294
1295 // Create basic blocks.
1296 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1297 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1298 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1299 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1300 FN);
1301
Tobias Grosserd596b372012-03-15 09:34:52 +00001302 DominatorTree &DT = P->getAnalysis<DominatorTree>();
1303 DT.addNewBlock(HeaderBB, PrevBB);
1304 DT.addNewBlock(ExitBB, HeaderBB);
1305 DT.addNewBlock(checkNextBB, HeaderBB);
1306 DT.addNewBlock(loadIVBoundsBB, HeaderBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001307
1308 // Fill up basic block HeaderBB.
1309 Builder.SetInsertPoint(HeaderBB);
Tobias Grossere9ffea22012-03-15 09:34:48 +00001310 Value *lowerBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.lowerBoundPtr");
1311 Value *upperBoundPtr = Builder.CreateAlloca(IntPtrTy, 0, "omp.upperBoundPtr");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001312 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1313 structData->getType(),
1314 "omp.userContext");
1315
1316 CharMapT clastVarsOMP;
1317 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1318
1319 Builder.CreateBr(checkNextBB);
1320
1321 // Add code to check if another set of iterations will be executed.
1322 Builder.SetInsertPoint(checkNextBB);
1323 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1324 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1325 lowerBoundPtr, upperBoundPtr);
1326 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1327 "omp.hasNextScheduleBlock");
1328 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1329
1330 // Add code to to load the iv bounds for this set of iterations.
1331 Builder.SetInsertPoint(loadIVBoundsBB);
1332 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1333 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1334
1335 // Subtract one as the upper bound provided by openmp is a < comparison
1336 // whereas the codegenForSequential function creates a <= comparison.
Tobias Grossere9ffea22012-03-15 09:34:48 +00001337 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(IntPtrTy, 1),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001338 "omp.upperBoundAdjusted");
1339
1340 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1341 CharMapT *oldClastVars = clastVars;
1342 clastVars = &clastVarsOMP;
1343 ExpGen.setIVS(&clastVarsOMP);
1344
Tobias Grosser0ac92142012-02-14 14:02:27 +00001345 Builder.CreateBr(checkNextBB);
1346 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001347 codegenForSequential(f, lowerBound, upperBound);
1348
1349 // Restore the old clastVars.
1350 clastVars = oldClastVars;
1351 ExpGen.setIVS(oldClastVars);
1352
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001353 // Add code to terminate this openmp subfunction.
1354 Builder.SetInsertPoint(ExitBB);
1355 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1356 Builder.CreateCall(endnowaitFunction);
1357 Builder.CreateRetVoid();
1358
Tobias Grosser0ac92142012-02-14 14:02:27 +00001359 // Restore the previous insert point.
1360 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001361}
1362
Tobias Grosser415245d2012-03-02 15:20:17 +00001363void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001364 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grossere9ffea22012-03-15 09:34:48 +00001365 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001366
1367 Function *SubFunction = addOpenMPSubfunction(M);
1368 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
Tobias Grosser415245d2012-03-02 15:20:17 +00001369 Value *StructData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001370
Tobias Grosser415245d2012-03-02 15:20:17 +00001371 addOpenMPSubfunctionBody(SubFunction, For, StructData, OMPDataVals);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001372
1373 // Create call for GOMP_parallel_loop_runtime_start.
Tobias Grosser415245d2012-03-02 15:20:17 +00001374 Value *SubfunctionParam = Builder.CreateBitCast(StructData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001375 Builder.getInt8PtrTy(),
1376 "omp_data");
1377
Tobias Grosser415245d2012-03-02 15:20:17 +00001378 Value *NumberOfThreads = Builder.getInt32(0);
1379 Value *LowerBound = ExpGen.codegen(For->LB, IntPtrTy);
1380 Value *UpperBound = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001381
1382 // Add one as the upper bound provided by openmp is a < comparison
1383 // whereas the codegenForSequential function creates a <= comparison.
Tobias Grosser415245d2012-03-02 15:20:17 +00001384 UpperBound = Builder.CreateAdd(UpperBound, ConstantInt::get(IntPtrTy, 1));
1385 APInt APStride = APInt_from_MPZ(For->stride);
1386 Value *Stride = ConstantInt::get(IntPtrTy,
1387 APStride.zext(IntPtrTy->getBitWidth()));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001388
Tobias Grosser415245d2012-03-02 15:20:17 +00001389 Value *Arguments[] = { SubFunction, SubfunctionParam, NumberOfThreads,
1390 LowerBound, UpperBound, Stride};
1391 Builder.CreateCall(M->getFunction("GOMP_parallel_loop_runtime_start"),
1392 Arguments);
1393 Builder.CreateCall(SubFunction, SubfunctionParam);
1394 Builder.CreateCall(M->getFunction("GOMP_parallel_end"));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001395}
1396
1397bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1398 const clast_stmt *stmt = f->body;
1399
1400 while (stmt) {
1401 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1402 return false;
1403
1404 stmt = stmt->next;
1405 }
1406
1407 return true;
1408}
1409
1410int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1411 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1412 isl_set *tmp = isl_set_copy(loopDomain);
1413
1414 // Calculate a map similar to the identity map, but with the last input
1415 // and output dimension not related.
1416 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1417 isl_space *Space = isl_set_get_space(loopDomain);
1418 Space = isl_space_drop_outputs(Space,
1419 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1420 Space = isl_space_map_from_set(Space);
1421 isl_map *identity = isl_map_identity(Space);
1422 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1423 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1424
1425 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1426 map = isl_map_intersect(map, identity);
1427
1428 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1429 isl_map *lexmin = isl_map_lexmin(map);
1430 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1431
1432 isl_set *elements = isl_map_range(sub);
1433
1434 if (!isl_set_is_singleton(elements)) {
1435 isl_set_free(elements);
1436 return -1;
1437 }
1438
1439 isl_point *p = isl_set_sample_point(elements);
1440
1441 isl_int v;
1442 isl_int_init(v);
1443 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1444 int numberIterations = isl_int_get_si(v);
1445 isl_int_clear(v);
1446 isl_point_free(p);
1447
1448 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1449}
1450
Tobias Grosser2da263e2012-03-15 09:34:55 +00001451void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
1452 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
1453 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001454
Tobias Grosser2da263e2012-03-15 09:34:55 +00001455 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001456
Tobias Grosser2da263e2012-03-15 09:34:55 +00001457 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001458 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1459 Stride = Stride.zext(LoopIVType->getBitWidth());
1460 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1461
Tobias Grosser2da263e2012-03-15 09:34:55 +00001462 std::vector<Value*> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001463 IVS[0] = LB;
1464
Tobias Grosser2da263e2012-03-15 09:34:55 +00001465 for (int i = 1; i < VectorWidth; i++)
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001466 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1467
Tobias Grosser00d898d2012-03-15 09:34:58 +00001468 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001469
1470 // Add loop iv to symbols.
Tobias Grosser2da263e2012-03-15 09:34:55 +00001471 (*clastVars)[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001472
Tobias Grosser2da263e2012-03-15 09:34:55 +00001473 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001474
Tobias Grosser2da263e2012-03-15 09:34:55 +00001475 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +00001476 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
1477 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +00001478 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001479 }
1480
1481 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +00001482 isl_set_free(Domain);
Tobias Grosser2da263e2012-03-15 09:34:55 +00001483 clastVars->erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001484}
1485
1486void ClastStmtCodeGen::codegen(const clast_for *f) {
Tobias Grosserd596b372012-03-15 09:34:52 +00001487 if ((Vector || OpenMP) && P->getAnalysis<Dependences>().isParallelFor(f)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001488 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1489 && (getNumberOfIterations(f) <= 16)) {
1490 codegenForVector(f);
1491 return;
1492 }
1493
1494 if (OpenMP && !parallelCodeGeneration) {
1495 parallelCodeGeneration = true;
1496 parallelLoops.push_back(f->iterator);
1497 codegenForOpenMP(f);
1498 parallelCodeGeneration = false;
1499 return;
1500 }
1501 }
1502
1503 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001504}
1505
1506Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +00001507 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
1508 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001509 CmpInst::Predicate P;
1510
1511 if (eq->sign == 0)
1512 P = ICmpInst::ICMP_EQ;
1513 else if (eq->sign > 0)
1514 P = ICmpInst::ICMP_SGE;
1515 else
1516 P = ICmpInst::ICMP_SLE;
1517
1518 return Builder.CreateICmp(P, LHS, RHS);
1519}
1520
1521void ClastStmtCodeGen::codegen(const clast_guard *g) {
1522 Function *F = Builder.GetInsertBlock()->getParent();
1523 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001524
1525 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1526 Builder.GetInsertPoint(), P);
1527 CondBB->setName("polly.cond");
1528 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1529 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001530 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001531
Tobias Grosserd596b372012-03-15 09:34:52 +00001532 DominatorTree &DT = P->getAnalysis<DominatorTree>();
1533 DT.addNewBlock(ThenBB, CondBB);
1534 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001535
1536 CondBB->getTerminator()->eraseFromParent();
1537
1538 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001539
1540 Value *Predicate = codegen(&(g->eq[0]));
1541
1542 for (int i = 1; i < g->n; ++i) {
1543 Value *TmpPredicate = codegen(&(g->eq[i]));
1544 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1545 }
1546
1547 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1548 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001549 Builder.CreateBr(MergeBB);
1550 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001551
1552 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001553
1554 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001555}
1556
1557void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1558 if (CLAST_STMT_IS_A(stmt, stmt_root))
1559 assert(false && "No second root statement expected");
1560 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1561 codegen((const clast_assignment *)stmt);
1562 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1563 codegen((const clast_user_stmt *)stmt);
1564 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1565 codegen((const clast_block *)stmt);
1566 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1567 codegen((const clast_for *)stmt);
1568 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1569 codegen((const clast_guard *)stmt);
1570
1571 if (stmt->next)
1572 codegen(stmt->next);
1573}
1574
1575void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +00001576 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001577
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001578 int i = 0;
1579 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1580 PI != PE; ++PI) {
1581 assert(i < names->nb_parameters && "Not enough parameter names");
1582
1583 const SCEV *Param = *PI;
1584 Type *Ty = Param->getType();
1585
1586 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1587 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1588 (*clastVars)[names->parameters[i]] = V;
1589
1590 ++i;
1591 }
1592}
1593
1594void ClastStmtCodeGen::codegen(const clast_root *r) {
1595 clastVars = new CharMapT();
1596 addParameters(r->names);
1597 ExpGen.setIVS(clastVars);
1598
1599 parallelCodeGeneration = false;
1600
1601 const clast_stmt *stmt = (const clast_stmt*) r;
1602 if (stmt->next)
1603 codegen(stmt->next);
1604
1605 delete clastVars;
1606}
1607
Tobias Grosserd596b372012-03-15 09:34:52 +00001608ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
1609 S(scop), P(P), Builder(B), ExpGen(Builder, NULL) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001610
Tobias Grosser75805372011-04-29 06:27:02 +00001611namespace {
1612class CodeGeneration : public ScopPass {
1613 Region *region;
1614 Scop *S;
1615 DominatorTree *DT;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001616 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001617
1618 std::vector<std::string> parallelLoops;
1619
1620 public:
1621 static char ID;
1622
1623 CodeGeneration() : ScopPass(ID) {}
1624
Tobias Grosserb1c95992012-02-12 12:09:27 +00001625 // Add the declarations needed by the OpenMP function calls that we insert in
1626 // OpenMP mode.
1627 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001628 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001629 IRBuilder<> Builder(M->getContext());
Tobias Grosserd596b372012-03-15 09:34:52 +00001630 Type *LongTy = getAnalysis<TargetData>().getIntPtrType(M->getContext());
Tobias Grosserd855cc52012-02-12 12:09:32 +00001631
1632 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001633
1634 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001635 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1636 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001637 }
1638
1639 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001640 Type *Params[] = {
1641 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1642 Builder.getInt8PtrTy(),
1643 false)),
1644 Builder.getInt8PtrTy(),
1645 Builder.getInt32Ty(),
1646 LongTy,
1647 LongTy,
1648 LongTy,
1649 };
Tobias Grosser75805372011-04-29 06:27:02 +00001650
Tobias Grosserd855cc52012-02-12 12:09:32 +00001651 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1652 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001653 }
1654
1655 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001656 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1657 Type *Params[] = {
1658 LongPtrTy,
1659 LongPtrTy,
1660 };
Tobias Grosser75805372011-04-29 06:27:02 +00001661
Tobias Grosserd855cc52012-02-12 12:09:32 +00001662 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1663 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001664 }
1665
1666 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001667 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1668 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001669 }
1670 }
1671
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001672 // Split the entry edge of the region and generate a new basic block on this
1673 // edge. This function also updates ScopInfo and RegionInfo.
1674 //
1675 // @param region The region where the entry edge will be splitted.
1676 BasicBlock *splitEdgeAdvanced(Region *region) {
1677 BasicBlock *newBlock;
1678 BasicBlock *splitBlock;
1679
1680 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1681
1682 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001683 BasicBlock *OldBlock = region->getEntry();
1684 std::string OldName = OldBlock->getName();
1685
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001686 // Update ScopInfo.
1687 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001688 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001689 (*SI)->setBasicBlock(newBlock);
1690 break;
1691 }
1692
1693 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001694 splitBlock = OldBlock;
1695 OldBlock->setName("polly.split");
1696 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001697 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001698 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001699 } else {
1700 RI->setRegionFor(newBlock, region->getParent());
1701 splitBlock = newBlock;
1702 }
1703
1704 return splitBlock;
1705 }
1706
1707 // Create a split block that branches either to the old code or to a new basic
1708 // block where the new code can be inserted.
1709 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001710 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001711 // the new code can be generated.
1712 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001713 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1714 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001715
Tobias Grosserbd608a82012-02-12 12:09:41 +00001716 SplitBlock = splitEdgeAdvanced(region);
1717 SplitBlock->setName("polly.split_new_and_old");
1718 Function *F = SplitBlock->getParent();
1719 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1720 SplitBlock->getTerminator()->eraseFromParent();
1721 Builder->SetInsertPoint(SplitBlock);
1722 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1723 DT->addNewBlock(StartBlock, SplitBlock);
1724 Builder->SetInsertPoint(StartBlock);
1725 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001726 }
1727
1728 // Merge the control flow of the newly generated code with the existing code.
1729 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001730 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001731 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001732 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001733 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001734 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1735 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001736 Region *R = region;
1737
1738 if (R->getExit()->getSinglePredecessor())
1739 // No splitEdge required. A block with a single predecessor cannot have
1740 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001741 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001742 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001743 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001744 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1745 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001746 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001747 }
1748
Tobias Grosserbd608a82012-02-12 12:09:41 +00001749 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001750 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001751
Tobias Grosserbd608a82012-02-12 12:09:41 +00001752 if (DT->dominates(SplitBlock, MergeBlock))
1753 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001754 }
1755
Tobias Grosser75805372011-04-29 06:27:02 +00001756 bool runOnScop(Scop &scop) {
1757 S = &scop;
1758 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001759 DT = &getAnalysis<DominatorTree>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001760 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001761
1762 parallelLoops.clear();
1763
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001764 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001765
Tobias Grosserb1c95992012-02-12 12:09:27 +00001766 Module *M = region->getEntry()->getParent()->getParent();
1767
Tobias Grosserd855cc52012-02-12 12:09:32 +00001768 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001769
Tobias Grosser5772e652012-02-01 14:23:33 +00001770 // In the CFG the optimized code of the SCoP is generated next to the
1771 // original code. Both the new and the original version of the code remain
1772 // in the CFG. A branch statement decides which version is executed.
1773 // For now, we always execute the new version (the old one is dead code
1774 // eliminated by the cleanup passes). In the future we may decide to execute
1775 // the new version only if certain run time checks succeed. This will be
1776 // useful to support constructs for which we cannot prove all assumptions at
1777 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001778 //
1779 // Before transformation:
1780 //
1781 // bb0
1782 // |
1783 // orig_scop
1784 // |
1785 // bb1
1786 //
1787 // After transformation:
1788 // bb0
1789 // |
1790 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001791 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001792 // | startBlock
1793 // | |
1794 // orig_scop new_scop
1795 // \ /
1796 // \ /
1797 // bb1 (joinBlock)
1798 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001799
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001800 // The builder will be set to startBlock.
1801 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001802 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001803
Tobias Grosser0ac92142012-02-14 14:02:27 +00001804 mergeControlFlow(splitBlock, &builder);
1805 builder.SetInsertPoint(StartBlock->begin());
1806
Tobias Grosserd596b372012-03-15 09:34:52 +00001807 ClastStmtCodeGen CodeGen(S, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001808 CloogInfo &C = getAnalysis<CloogInfo>();
1809 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001810
Tobias Grosser75805372011-04-29 06:27:02 +00001811 parallelLoops.insert(parallelLoops.begin(),
1812 CodeGen.getParallelLoops().begin(),
1813 CodeGen.getParallelLoops().end());
1814
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001815 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001816 }
1817
1818 virtual void printScop(raw_ostream &OS) const {
1819 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1820 PE = parallelLoops.end(); PI != PE; ++PI)
1821 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1822 }
1823
1824 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1825 AU.addRequired<CloogInfo>();
1826 AU.addRequired<Dependences>();
1827 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001828 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001829 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001830 AU.addRequired<ScopDetection>();
1831 AU.addRequired<ScopInfo>();
1832 AU.addRequired<TargetData>();
1833
1834 AU.addPreserved<CloogInfo>();
1835 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001836
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001837 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001838 AU.addPreserved<LoopInfo>();
1839 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001840 AU.addPreserved<ScopDetection>();
1841 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001842
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001843 // FIXME: We do not yet add regions for the newly generated code to the
1844 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001845 AU.addPreserved<RegionInfo>();
1846 AU.addPreserved<TempScopInfo>();
1847 AU.addPreserved<ScopInfo>();
1848 AU.addPreservedID(IndependentBlocksID);
1849 }
1850};
1851}
1852
1853char CodeGeneration::ID = 1;
1854
Tobias Grosser73600b82011-10-08 00:30:40 +00001855INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001856 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +00001857INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1858INITIALIZE_PASS_DEPENDENCY(Dependences)
1859INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1860INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1861INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1862INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1863INITIALIZE_PASS_DEPENDENCY(TargetData)
1864INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001865 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001866
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001867Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001868 return new CodeGeneration();
1869}