blob: 22722a5726b35bd37e48110fc424e658399c7af0 [file] [log] [blame]
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
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// This file implements the BlockGenerator and VectorBlockGenerator classes,
11// which generate sequential code and vectorized code for a polyhedral
12// statement, respectively.
13//
14//===----------------------------------------------------------------------===//
15
16#include "polly/ScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000017#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000018#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000019#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000020#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000021#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000022#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000023#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000024#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000025#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000026#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser030237d2014-02-21 15:06:05 +000028#include "llvm/IR/IntrinsicInst.h"
Tobias Grosserc9895062015-03-10 15:24:33 +000029#include "llvm/IR/Module.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000031#include "isl/aff.h"
32#include "isl/ast.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000033#include "isl/ast_build.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "isl/set.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000035#include <deque>
36
Hongbin Zheng3b11a162012-04-25 13:16:49 +000037using namespace llvm;
38using namespace polly;
39
Tobias Grosser878aba42014-10-22 23:22:41 +000040static cl::opt<bool> Aligned("enable-polly-aligned",
41 cl::desc("Assumed aligned memory accesses."),
42 cl::Hidden, cl::init(false), cl::ZeroOrMore,
43 cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000044
Tobias Grosserecfe21b2013-03-20 18:03:18 +000045bool polly::canSynthesize(const Instruction *I, const llvm::LoopInfo *LI,
46 ScalarEvolution *SE, const Region *R) {
Tobias Grosser683b8e42014-11-30 14:33:31 +000047 if (!I || !SE->isSCEVable(I->getType()))
Tobias Grosserecfe21b2013-03-20 18:03:18 +000048 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000049
Tobias Grosser683b8e42014-11-30 14:33:31 +000050 if (const SCEV *Scev = SE->getSCEV(const_cast<Instruction *>(I)))
51 if (!isa<SCEVCouldNotCompute>(Scev))
52 if (!hasScalarDepsInsideRegion(Scev, R))
53 return true;
54
55 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000056}
57
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000058bool polly::isIgnoredIntrinsic(const Value *V) {
59 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
60 switch (IT->getIntrinsicID()) {
61 // Lifetime markers are supported/ignored.
62 case llvm::Intrinsic::lifetime_start:
63 case llvm::Intrinsic::lifetime_end:
64 // Invariant markers are supported/ignored.
65 case llvm::Intrinsic::invariant_start:
66 case llvm::Intrinsic::invariant_end:
67 // Some misc annotations are supported/ignored.
68 case llvm::Intrinsic::var_annotation:
69 case llvm::Intrinsic::ptr_annotation:
70 case llvm::Intrinsic::annotation:
71 case llvm::Intrinsic::donothing:
72 case llvm::Intrinsic::assume:
73 case llvm::Intrinsic::expect:
74 return true;
75 default:
76 break;
77 }
78 }
79 return false;
80}
81
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000082BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
83 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000084 ScalarAllocaMapTy &ScalarMap,
85 ScalarAllocaMapTy &PHIOpMap,
86 EscapeUsersAllocaMapTy &EscapeMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000087 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000088 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
89 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
90 EscapeMap(EscapeMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +000091
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000092Value *BlockGenerator::getNewValue(ScopStmt &Stmt, const Value *Old,
93 ValueMapT &BBMap, ValueMapT &GlobalMap,
94 LoopToScevMapT &LTS, Loop *L) const {
Hongbin Zheng3b11a162012-04-25 13:16:49 +000095 // We assume constants never change.
96 // This avoids map lookups for many calls to this function.
97 if (isa<Constant>(Old))
Tobias Grosserc14582f2013-02-05 18:01:29 +000098 return const_cast<Value *>(Old);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000099
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000100 if (Value *New = GlobalMap.lookup(Old)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000101 if (Old->getType()->getScalarSizeInBits() <
Tobias Grosserd7e58642013-04-10 06:55:45 +0000102 New->getType()->getScalarSizeInBits())
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000103 New = Builder.CreateTruncOrBitCast(New, Old->getType());
104
105 return New;
106 }
107
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000108 if (Value *New = BBMap.lookup(Old))
109 return New;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000110
Tobias Grosser683b8e42014-11-30 14:33:31 +0000111 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000112 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000113 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000114 const SCEV *NewScev = apply(Scev, LTS, SE);
115 ValueToValueMap VTV;
116 VTV.insert(BBMap.begin(), BBMap.end());
117 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Sebastian Pop47d4ee32013-02-15 21:26:53 +0000118 NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
Tobias Grosserc9895062015-03-10 15:24:33 +0000119 SCEVExpander Expander(SE, Stmt.getParent()
120 ->getRegion()
121 .getEntry()
122 ->getParent()
123 ->getParent()
124 ->getDataLayout(),
125 "polly");
Tobias Grosser45e79442015-08-01 09:07:57 +0000126 assert(Builder.GetInsertPoint() != Builder.GetInsertBlock()->end() &&
127 "Only instructions can be insert points for SCEVExpander");
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000128 Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
129 Builder.GetInsertPoint());
130
131 BBMap[Old] = Expanded;
132 return Expanded;
133 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000134 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000135
Tobias Grosser16371ac2014-11-05 20:48:56 +0000136 // A scop-constant value defined by a global or a function parameter.
137 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
138 return const_cast<Value *>(Old);
139
140 // A scop-constant value defined by an instruction executed outside the scop.
141 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000142 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000143 return const_cast<Value *>(Old);
144
145 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000146 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000147 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000148}
149
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000150void BlockGenerator::copyInstScalar(ScopStmt &Stmt, const Instruction *Inst,
151 ValueMapT &BBMap, ValueMapT &GlobalMap,
152 LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000153 // We do not generate debug intrinsics as we did not investigate how to
154 // copy them correctly. At the current state, they just crash the code
155 // generation as the meta-data operands are not correctly copied.
156 if (isa<DbgInfoIntrinsic>(Inst))
157 return;
158
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000159 Instruction *NewInst = Inst->clone();
160
161 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000162 for (Value *OldOperand : Inst->operands()) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000163 Value *NewOperand = getNewValue(Stmt, OldOperand, BBMap, GlobalMap, LTS,
164 getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000165
166 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000167 assert(!isa<StoreInst>(NewInst) &&
168 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000169 delete NewInst;
170 return;
171 }
172
173 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
174 }
175
176 Builder.Insert(NewInst);
177 BBMap[Inst] = NewInst;
178
179 if (!NewInst->getType()->isVoidTy())
180 NewInst->setName("p_" + Inst->getName());
181}
182
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000183Value *BlockGenerator::getNewAccessOperand(ScopStmt &Stmt,
184 const MemoryAccess &MA) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000185 isl_pw_multi_aff *PWAccRel;
186 isl_union_map *Schedule;
Johannes Doerferta63b2572014-08-03 01:51:59 +0000187 isl_ast_expr *Expr;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000188 isl_ast_build *Build = Stmt.getAstBuild();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000189
Johannes Doerferta63b2572014-08-03 01:51:59 +0000190 assert(ExprBuilder && Build &&
191 "Cannot generate new value without IslExprBuilder!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000192
Johannes Doerferta99130f2014-10-13 12:58:03 +0000193 Schedule = isl_ast_build_get_schedule(Build);
194 PWAccRel = MA.applyScheduleToAccessRelation(Schedule);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000195
Johannes Doerferta63b2572014-08-03 01:51:59 +0000196 Expr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
Johannes Doerfertdcb5f1d2014-09-18 11:14:30 +0000197 Expr = isl_ast_expr_address_of(Expr);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000198
199 return ExprBuilder->create(Expr);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000200}
201
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000202Value *BlockGenerator::generateLocationAccessed(
203 ScopStmt &Stmt, const Instruction *Inst, const Value *Pointer,
204 ValueMapT &BBMap, ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
205 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000206
207 Value *NewPointer;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000208 if (MA.hasNewAccessRelation())
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000209 NewPointer = getNewAccessOperand(Stmt, MA);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000210 else
Tobias Grosser369430f2013-03-22 23:42:53 +0000211 NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000212 getNewValue(Stmt, Pointer, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000213
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000214 return NewPointer;
215}
216
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000217Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000218 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000219}
220
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000221Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grossere602a072013-05-07 07:30:56 +0000222 ValueMapT &BBMap,
223 ValueMapT &GlobalMap,
224 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000225 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser7242ad92013-02-22 08:07:06 +0000226 Value *NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000227 generateLocationAccessed(Stmt, Load, Pointer, BBMap, GlobalMap, LTS);
Johannes Doerfert87901452014-10-02 16:22:19 +0000228 Value *ScalarLoad = Builder.CreateAlignedLoad(
229 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000230 return ScalarLoad;
231}
232
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000233Value *BlockGenerator::generateScalarStore(ScopStmt &Stmt,
234 const StoreInst *Store,
Tobias Grossere602a072013-05-07 07:30:56 +0000235 ValueMapT &BBMap,
236 ValueMapT &GlobalMap,
237 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000238 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000239 Value *NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000240 generateLocationAccessed(Stmt, Store, Pointer, BBMap, GlobalMap, LTS);
241 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
242 GlobalMap, LTS, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000243
Johannes Doerfert87901452014-10-02 16:22:19 +0000244 Value *NewStore = Builder.CreateAlignedStore(ValueOperand, NewPointer,
245 Store->getAlignment());
246 return NewStore;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000247}
248
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000249void BlockGenerator::copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
250 ValueMapT &BBMap, ValueMapT &GlobalMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000251 LoopToScevMapT &LTS) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000252
253 // First check for possible scalar dependences for this instruction.
254 generateScalarLoads(Stmt, Inst, BBMap);
255
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000256 // Terminator instructions control the control flow. They are explicitly
257 // expressed in the clast and do not need to be copied.
258 if (Inst->isTerminator())
259 return;
260
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000261 Loop *L = getLoopForInst(Inst);
262 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
263 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
264 Value *NewValue = getNewValue(Stmt, Inst, BBMap, GlobalMap, LTS, L);
265 BBMap[Inst] = NewValue;
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000266 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000267 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000268
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000269 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000270 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000271 // Compute NewLoad before its insertion in BBMap to make the insertion
272 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000273 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000274 return;
275 }
276
277 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000278 Value *NewStore = generateScalarStore(Stmt, Store, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000279 // Compute NewStore before its insertion in BBMap to make the insertion
280 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000281 BBMap[Store] = NewStore;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000282 return;
283 }
284
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000285 if (const PHINode *PHI = dyn_cast<PHINode>(Inst)) {
286 copyPHIInstruction(Stmt, PHI, BBMap, GlobalMap, LTS);
287 return;
288 }
289
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000290 // Skip some special intrinsics for which we do not adjust the semantics to
291 // the new schedule. All others are handled like every other instruction.
292 if (auto *IT = dyn_cast<IntrinsicInst>(Inst)) {
293 switch (IT->getIntrinsicID()) {
294 // Lifetime markers are ignored.
295 case llvm::Intrinsic::lifetime_start:
296 case llvm::Intrinsic::lifetime_end:
297 // Invariant markers are ignored.
298 case llvm::Intrinsic::invariant_start:
299 case llvm::Intrinsic::invariant_end:
300 // Some misc annotations are ignored.
301 case llvm::Intrinsic::var_annotation:
302 case llvm::Intrinsic::ptr_annotation:
303 case llvm::Intrinsic::annotation:
304 case llvm::Intrinsic::donothing:
305 case llvm::Intrinsic::assume:
306 case llvm::Intrinsic::expect:
307 return;
308 default:
309 // Other intrinsics are copied.
310 break;
311 }
312 }
313
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000314 copyInstScalar(Stmt, Inst, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000315}
316
Johannes Doerfert275a1752015-02-24 16:16:32 +0000317void BlockGenerator::copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap,
318 LoopToScevMapT &LTS) {
319 assert(Stmt.isBlockStmt() &&
320 "Only block statements can be copied by the block generator");
321
322 ValueMapT BBMap;
323
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000324 BasicBlock *BB = Stmt.getBasicBlock();
Johannes Doerfert275a1752015-02-24 16:16:32 +0000325 copyBB(Stmt, BB, BBMap, GlobalMap, LTS);
326}
327
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000328BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000329 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000330 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000331 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000332 return CopyBB;
333}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000334
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000335BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
336 ValueMapT &BBMap, ValueMapT &GlobalMap,
337 LoopToScevMapT &LTS) {
338 BasicBlock *CopyBB = splitBB(BB);
339 copyBB(Stmt, BB, CopyBB, BBMap, GlobalMap, LTS);
340 return CopyBB;
341}
342
343void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
344 ValueMapT &BBMap, ValueMapT &GlobalMap,
345 LoopToScevMapT &LTS) {
346 Builder.SetInsertPoint(CopyBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000347 EntryBB = &CopyBB->getParent()->getEntryBlock();
348
Tobias Grosser91f5b262014-06-04 08:06:40 +0000349 for (Instruction &Inst : *BB)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000350 copyInstruction(Stmt, &Inst, BBMap, GlobalMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000351
352 // After a basic block was copied store all scalars that escape this block
353 // in their alloca. First the scalars that have dependences inside the SCoP,
354 // then the ones that might escape the SCoP.
355 generateScalarStores(Stmt, BB, BBMap, GlobalMap);
356
357 const Region &R = Stmt.getParent()->getRegion();
358 for (Instruction &Inst : *BB)
359 handleOutsideUsers(R, &Inst, BBMap[&Inst]);
360}
361
362AllocaInst *BlockGenerator::getOrCreateAlloca(Instruction *ScalarBase,
363 ScalarAllocaMapTy &Map,
364 const char *NameExt,
365 bool *IsNew) {
366
367 // Check if an alloca was cached for the base instruction.
368 AllocaInst *&Addr = Map[ScalarBase];
369
370 // If needed indicate if it was found already or will be created.
371 if (IsNew)
372 *IsNew = (Addr == nullptr);
373
374 // If no alloca was found create one and insert it in the entry block.
375 if (!Addr) {
376 auto *Ty = ScalarBase->getType();
377 Addr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
378 Addr->insertBefore(EntryBB->getFirstInsertionPt());
379 }
380
381 return Addr;
382}
383
384void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
385 Value *InstCopy) {
386 BasicBlock *ExitBB = R.getExit();
387
388 EscapeUserVectorTy EscapeUsers;
389 for (User *U : Inst->users()) {
390
391 // Non-instruction user will never escape.
392 Instruction *UI = dyn_cast<Instruction>(U);
393 if (!UI)
394 continue;
395
396 if (R.contains(UI) && ExitBB != UI->getParent())
397 continue;
398
399 EscapeUsers.push_back(UI);
400 }
401
402 // Exit if no escape uses were found.
403 if (EscapeUsers.empty())
404 return;
405
406 // If there are escape users we get the alloca for this instruction and put
407 // it in the EscapeMap for later finalization. However, if the alloca was not
408 // created by an already handled scalar dependence we have to initialize it
409 // also. Lastly, if the instruction was copied multiple times we already did
410 // this and can exit.
411 if (EscapeMap.count(Inst))
412 return;
413
414 // Get or create an escape alloca for this instruction.
415 bool IsNew;
416 AllocaInst *ScalarAddr =
417 getOrCreateAlloca(Inst, ScalarMap, ".escape", &IsNew);
418
419 // Remember that this instruction has escape uses and the escape alloca.
420 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
421
422 // If the escape alloca was just created store the instruction in there,
423 // otherwise that happened already.
424 if (IsNew) {
425 assert(InstCopy && "Except PHIs every instruction should have a copy!");
426 Builder.CreateStore(InstCopy, ScalarAddr);
427 }
428}
429
430void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
431 const Instruction *Inst,
432 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000433 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000434
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000435 if (!MAL)
436 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000437
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000438 for (MemoryAccess &MA : *MAL) {
439 AllocaInst *Address;
440 if (!MA.isScalar() || !MA.isRead())
441 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000442
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000443 auto Base = cast<Instruction>(MA.getBaseAddr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000444
Tobias Grosser92245222015-07-28 14:53:44 +0000445 if (MA.getScopArrayInfo()->isPHI())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000446 Address = getOrCreateAlloca(Base, PHIOpMap, ".phiops");
447 else
448 Address = getOrCreateAlloca(Base, ScalarMap, ".s2a");
449
450 BBMap[Base] = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000451 }
452}
453
454Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
455 ScalarAllocaMapTy &ReloadMap,
456 ValueMapT &BBMap,
457 ValueMapT &GlobalMap) {
458 // If the value we want to store is an instruction we might have demoted it
459 // in order to make it accessible here. In such a case a reload is
460 // necessary. If it is no instruction it will always be a value that
461 // dominates the current point and we can just use it. In total there are 4
462 // options:
463 // (1) The value is no instruction ==> use the value.
464 // (2) The value is an instruction that was split out of the region prior to
465 // code generation ==> use the instruction as it dominates the region.
466 // (3) The value is an instruction:
467 // (a) The value was defined in the current block, thus a copy is in
468 // the BBMap ==> use the mapped value.
469 // (b) The value was defined in a previous block, thus we demoted it
470 // earlier ==> use the reloaded value.
471 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
472 if (!ScalarValueInst)
473 return ScalarValue;
474
475 if (!R.contains(ScalarValueInst)) {
476 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
477 return /* Case (3a) */ ScalarValueCopy;
478 else
479 return /* Case 2 */ ScalarValue;
480 }
481
482 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
483 return /* Case (3a) */ ScalarValueCopy;
484
485 // Case (3b)
486 assert(ReloadMap.count(ScalarValueInst) &&
487 "ScalarInst not mapped in the block and not in the given reload map!");
488 Value *ReloadAddr = ReloadMap[ScalarValueInst];
489 ScalarValue =
490 Builder.CreateLoad(ReloadAddr, ReloadAddr->getName() + ".reload");
491
492 return ScalarValue;
493}
494
495void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
496 ValueMapT &BBMap,
497 ValueMapT &GlobalMap) {
498 const Region &R = Stmt.getParent()->getRegion();
499
500 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
501 "Region statements need to use the generateScalarStores() "
502 "function in the RegionGenerator");
503
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000504 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000505 if (!MA->isScalar() || MA->isRead())
506 continue;
507
Tobias Grosser92245222015-07-28 14:53:44 +0000508 Instruction *Base = cast<Instruction>(MA->getBaseAddr());
509 Instruction *Inst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000510
Tobias Grosser92245222015-07-28 14:53:44 +0000511 Value *Val = nullptr;
512 AllocaInst *Address = nullptr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000513
Tobias Grosser92245222015-07-28 14:53:44 +0000514 if (MA->getScopArrayInfo()->isPHI()) {
515 PHINode *BasePHI = dyn_cast<PHINode>(Base);
516 int PHIIdx = BasePHI->getBasicBlockIndex(BB);
517 Address = getOrCreateAlloca(Base, PHIOpMap, ".phiops");
518 Val = BasePHI->getIncomingValue(PHIIdx);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000519 } else {
Tobias Grosser92245222015-07-28 14:53:44 +0000520 Address = getOrCreateAlloca(Base, ScalarMap, ".s2a");
521 Val = Inst;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000522 }
Tobias Grosser92245222015-07-28 14:53:44 +0000523 Val = getNewScalarValue(Val, R, ScalarMap, BBMap, GlobalMap);
524 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000525 }
526}
527
528void BlockGenerator::createScalarInitialization(Region &R,
529 ValueMapT &GlobalMap) {
530 // The split block __just before__ the region and optimized region.
531 BasicBlock *SplitBB = R.getEnteringBlock();
532 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
533 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
534
535 // Get the start block of the __optimized__ region.
536 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
537 if (StartBB == R.getEntry())
538 StartBB = SplitBBTerm->getSuccessor(1);
539
540 // For each PHI predecessor outside the region store the incoming operand
541 // value prior to entering the optimized region.
542 Builder.SetInsertPoint(StartBB->getTerminator());
543
544 ScalarAllocaMapTy EmptyMap;
545 for (const auto &PHIOpMapping : PHIOpMap) {
546 const PHINode *PHI = cast<PHINode>(PHIOpMapping.getFirst());
547
548 // Check if this PHI has the split block as predecessor (that is the only
549 // possible predecessor outside the SCoP).
550 int idx = PHI->getBasicBlockIndex(SplitBB);
551 if (idx < 0)
552 continue;
553
554 Value *ScalarValue = PHI->getIncomingValue(idx);
555 ScalarValue =
556 getNewScalarValue(ScalarValue, R, EmptyMap, GlobalMap, GlobalMap);
557
558 // If the split block is the predecessor initialize the PHI operator alloca.
559 Builder.CreateStore(ScalarValue, PHIOpMapping.getSecond());
560 }
561}
562
563void BlockGenerator::createScalarFinalization(Region &R) {
564 // The exit block of the __unoptimized__ region.
565 BasicBlock *ExitBB = R.getExitingBlock();
566 // The merge block __just after__ the region and the optimized region.
567 BasicBlock *MergeBB = R.getExit();
568
569 // The exit block of the __optimized__ region.
570 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
571 if (OptExitBB == ExitBB)
572 OptExitBB = *(++pred_begin(MergeBB));
573
574 Builder.SetInsertPoint(OptExitBB->getTerminator());
575 for (const auto &EscapeMapping : EscapeMap) {
576 // Extract the escaping instruction and the escaping users as well as the
577 // alloca the instruction was demoted to.
578 Instruction *EscapeInst = EscapeMapping.getFirst();
579 const auto &EscapeMappingValue = EscapeMapping.getSecond();
580 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
581 AllocaInst *ScalarAddr = EscapeMappingValue.first;
582
583 // Reload the demoted instruction in the optimized version of the SCoP.
584 Instruction *EscapeInstReload =
585 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
586
587 // Create the merge PHI that merges the optimized and unoptimized version.
588 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
589 EscapeInst->getName() + ".merge");
590 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
591
592 // Add the respective values to the merge PHI.
593 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
594 MergePHI->addIncoming(EscapeInst, ExitBB);
595
596 // The information of scalar evolution about the escaping instruction needs
597 // to be revoked so the new merged instruction will be used.
598 if (SE.isSCEVable(EscapeInst->getType()))
599 SE.forgetValue(EscapeInst);
600
601 // Replace all uses of the demoted instruction with the merge PHI.
602 for (Instruction *EUser : EscapeUsers)
603 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
604 }
605}
606
607void BlockGenerator::finalizeSCoP(Scop &S, ValueMapT &GlobalMap) {
608 createScalarInitialization(S.getRegion(), GlobalMap);
609 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000610}
611
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000612VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
613 VectorValueMapT &GlobalMaps,
614 std::vector<LoopToScevMapT> &VLTS,
615 isl_map *Schedule)
616 : BlockGenerator(BlockGen), GlobalMaps(GlobalMaps), VLTS(VLTS),
617 Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000618 assert(GlobalMaps.size() > 1 && "Only one vector lane found");
619 assert(Schedule && "No statement domain provided");
620}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000621
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000622Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, const Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000623 ValueMapT &VectorMap,
624 VectorValueMapT &ScalarMaps,
625 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000626 if (Value *NewValue = VectorMap.lookup(Old))
627 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000628
629 int Width = getVectorWidth();
630
631 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
632
633 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000634 Vector = Builder.CreateInsertElement(
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000635 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], GlobalMaps[Lane],
636 VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000637 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000638
639 VectorMap[Old] = Vector;
640
641 return Vector;
642}
643
644Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
645 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
646 assert(PointerTy && "PointerType expected");
647
648 Type *ScalarType = PointerTy->getElementType();
649 VectorType *VectorType = VectorType::get(ScalarType, Width);
650
651 return PointerType::getUnqual(VectorType);
652}
653
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000654Value *VectorBlockGenerator::generateStrideOneLoad(
655 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
656 bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000657 unsigned VectorWidth = getVectorWidth();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000658 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000659 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
660 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
661
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000662 Value *NewPointer = nullptr;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000663 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
Johannes Doerfert731685e2014-10-08 17:25:30 +0000664 GlobalMaps[Offset], VLTS[Offset]);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000665 Value *VectorPtr =
666 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
667 LoadInst *VecLoad =
668 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000669 if (!Aligned)
670 VecLoad->setAlignment(8);
671
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000672 if (NegativeStride) {
673 SmallVector<Constant *, 16> Indices;
674 for (int i = VectorWidth - 1; i >= 0; i--)
675 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
676 Constant *SV = llvm::ConstantVector::get(Indices);
677 Value *RevVecLoad = Builder.CreateShuffleVector(
678 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
679 return RevVecLoad;
680 }
681
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000682 return VecLoad;
683}
684
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000685Value *VectorBlockGenerator::generateStrideZeroLoad(ScopStmt &Stmt,
686 const LoadInst *Load,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000687 ValueMapT &BBMap) {
688 const Value *Pointer = Load->getPointerOperand();
689 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000690 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
691 GlobalMaps[0], VLTS[0]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000692 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
693 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000694 LoadInst *ScalarLoad =
695 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000696
697 if (!Aligned)
698 ScalarLoad->setAlignment(8);
699
Tobias Grosserc14582f2013-02-05 18:01:29 +0000700 Constant *SplatVector = Constant::getNullValue(
701 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000702
Tobias Grosserc14582f2013-02-05 18:01:29 +0000703 Value *VectorLoad = Builder.CreateShuffleVector(
704 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000705 return VectorLoad;
706}
707
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000708Value *VectorBlockGenerator::generateUnknownStrideLoad(
709 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000710 int VectorWidth = getVectorWidth();
711 const Value *Pointer = Load->getPointerOperand();
712 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000713 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000714
715 Value *Vector = UndefValue::get(VectorType);
716
717 for (int i = 0; i < VectorWidth; i++) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000718 Value *NewPointer = generateLocationAccessed(
719 Stmt, Load, Pointer, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000720 Value *ScalarLoad =
721 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
722 Vector = Builder.CreateInsertElement(
723 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000724 }
725
726 return Vector;
727}
728
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000729void VectorBlockGenerator::generateLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grossere602a072013-05-07 07:30:56 +0000730 ValueMapT &VectorMap,
731 VectorValueMapT &ScalarMaps) {
Tobias Grosser28736452015-03-23 07:00:36 +0000732 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000733 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000734 ScalarMaps[i][Load] =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000735 generateScalarLoad(Stmt, Load, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000736 return;
737 }
738
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000739 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000740
Tobias Grosser95493982014-04-18 09:46:35 +0000741 // Make sure we have scalar values available to access the pointer to
742 // the data location.
743 extractScalarValues(Load, VectorMap, ScalarMaps);
744
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000745 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000746 if (Access.isStrideZero(isl_map_copy(Schedule)))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000747 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0]);
Sebastian Popa00a0292012-12-18 07:46:06 +0000748 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000749 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000750 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000751 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000752 else
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000753 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000754
755 VectorMap[Load] = NewLoad;
756}
757
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000758void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt,
759 const UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000760 ValueMapT &VectorMap,
761 VectorValueMapT &ScalarMaps) {
762 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000763 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
764 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000765
766 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
767
768 const CastInst *Cast = dyn_cast<CastInst>(Inst);
769 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
770 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
771}
772
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000773void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt,
774 const BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000775 ValueMapT &VectorMap,
776 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000777 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778 Value *OpZero = Inst->getOperand(0);
779 Value *OpOne = Inst->getOperand(1);
780
781 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000782 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
783 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000784
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000785 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000786 Inst->getName() + "p_vec");
787 VectorMap[Inst] = NewInst;
788}
789
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000790void VectorBlockGenerator::copyStore(ScopStmt &Stmt, const StoreInst *Store,
Tobias Grossere602a072013-05-07 07:30:56 +0000791 ValueMapT &VectorMap,
792 VectorValueMapT &ScalarMaps) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000793 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000794
795 const Value *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000796 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000797 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000798
Tobias Grosser50fd7012014-04-17 23:13:49 +0000799 // Make sure we have scalar values available to access the pointer to
800 // the data location.
801 extractScalarValues(Store, VectorMap, ScalarMaps);
802
Sebastian Popa00a0292012-12-18 07:46:06 +0000803 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000804 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000805 Value *NewPointer = generateLocationAccessed(
806 Stmt, Store, Pointer, ScalarMaps[0], GlobalMaps[0], VLTS[0]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000807
Tobias Grosserc14582f2013-02-05 18:01:29 +0000808 Value *VectorPtr =
809 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000810 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
811
812 if (!Aligned)
813 Store->setAlignment(8);
814 } else {
815 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000816 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Johannes Doerfert731685e2014-10-08 17:25:30 +0000817 Value *NewPointer = generateLocationAccessed(
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000818 Stmt, Store, Pointer, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000819 Builder.CreateStore(Scalar, NewPointer);
820 }
821 }
822}
823
824bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
825 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000826 for (Value *Operand : Inst->operands())
827 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000828 return true;
829 return false;
830}
831
832bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
833 ValueMapT &VectorMap,
834 VectorValueMapT &ScalarMaps) {
835 bool HasVectorOperand = false;
836 int VectorWidth = getVectorWidth();
837
Tobias Grosser91f5b262014-06-04 08:06:40 +0000838 for (Value *Operand : Inst->operands()) {
839 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000840
841 if (VecOp == VectorMap.end())
842 continue;
843
844 HasVectorOperand = true;
845 Value *NewVector = VecOp->second;
846
847 for (int i = 0; i < VectorWidth; ++i) {
848 ValueMapT &SM = ScalarMaps[i];
849
850 // If there is one scalar extracted, all scalar elements should have
851 // already been extracted by the code here. So no need to check for the
852 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000853 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000854 break;
855
Tobias Grosser91f5b262014-06-04 08:06:40 +0000856 SM[Operand] =
857 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000858 }
859 }
860
861 return HasVectorOperand;
862}
863
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000864void VectorBlockGenerator::copyInstScalarized(ScopStmt &Stmt,
865 const Instruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866 ValueMapT &VectorMap,
867 VectorValueMapT &ScalarMaps) {
868 bool HasVectorOperand;
869 int VectorWidth = getVectorWidth();
870
871 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
872
873 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000874 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Johannes Doerfert731685e2014-10-08 17:25:30 +0000875 GlobalMaps[VectorLane], VLTS[VectorLane]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000876
877 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
878 return;
879
880 // Make the result available as vector value.
881 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
882 Value *Vector = UndefValue::get(VectorType);
883
884 for (int i = 0; i < VectorWidth; i++)
885 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
886 Builder.getInt32(i));
887
888 VectorMap[Inst] = Vector;
889}
890
Tobias Grosserc14582f2013-02-05 18:01:29 +0000891int VectorBlockGenerator::getVectorWidth() { return GlobalMaps.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000892
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000893void VectorBlockGenerator::copyInstruction(ScopStmt &Stmt,
894 const Instruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000895 ValueMapT &VectorMap,
896 VectorValueMapT &ScalarMaps) {
897 // Terminator instructions control the control flow. They are explicitly
898 // expressed in the clast and do not need to be copied.
899 if (Inst->isTerminator())
900 return;
901
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000902 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000903 return;
904
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000905 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000906 generateLoad(Stmt, Load, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000907 return;
908 }
909
910 if (hasVectorOperands(Inst, VectorMap)) {
911 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000912 copyStore(Stmt, Store, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913 return;
914 }
915
916 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000917 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000918 return;
919 }
920
921 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000922 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000923 return;
924 }
925
926 // Falltrough: We generate scalar instructions, if we don't know how to
927 // generate vector code.
928 }
929
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000930 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000931}
932
Johannes Doerfert275a1752015-02-24 16:16:32 +0000933void VectorBlockGenerator::copyStmt(ScopStmt &Stmt) {
934 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
935 "the vector block generator");
936
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000937 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000938 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000939 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000940 CopyBB->setName("polly.stmt." + BB->getName());
941 Builder.SetInsertPoint(CopyBB->begin());
942
943 // Create two maps that store the mapping from the original instructions of
944 // the old basic block to their copies in the new basic block. Those maps
945 // are basic block local.
946 //
947 // As vector code generation is supported there is one map for scalar values
948 // and one for vector values.
949 //
950 // In case we just do scalar code generation, the vectorMap is not used and
951 // the scalarMap has just one dimension, which contains the mapping.
952 //
953 // In case vector code generation is done, an instruction may either appear
954 // in the vector map once (as it is calculating >vectorwidth< values at a
955 // time. Or (if the values are calculated using scalar operations), it
956 // appears once in every dimension of the scalarMap.
957 VectorValueMapT ScalarBlockMap(getVectorWidth());
958 ValueMapT VectorBlockMap;
959
Tobias Grosser91f5b262014-06-04 08:06:40 +0000960 for (Instruction &Inst : *BB)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000961 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000962}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000963
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000964BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
965 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000966
967 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
968 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
969
970 if (BBCopyIDom)
971 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
972
973 return BBCopyIDom;
974}
975
Johannes Doerfert275a1752015-02-24 16:16:32 +0000976void RegionGenerator::copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap,
977 LoopToScevMapT &LTS) {
978 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +0000979 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +0000980
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000981 // Forget all old mappings.
982 BlockMap.clear();
983 RegionMaps.clear();
984 IncompletePHINodeMap.clear();
985
Johannes Doerfert275a1752015-02-24 16:16:32 +0000986 // The region represented by the statement.
987 Region *R = Stmt.getRegion();
988
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000989 // Create a dedicated entry for the region where we can reload all demoted
990 // inputs.
991 BasicBlock *EntryBB = R->getEntry();
992 BasicBlock *EntryBBCopy =
993 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
994 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
995 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000996
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000997 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
998 if (!R->contains(*PI))
999 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001000
1001 // Iterate over all blocks in the region in a breadth-first search.
1002 std::deque<BasicBlock *> Blocks;
1003 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001004 Blocks.push_back(EntryBB);
1005 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001006
1007 while (!Blocks.empty()) {
1008 BasicBlock *BB = Blocks.front();
1009 Blocks.pop_front();
1010
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001011 // First split the block and update dominance information.
1012 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001013 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1014
1015 // In order to remap PHI nodes we store also basic block mappings.
1016 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001017
1018 // Get the mapping for this block and initialize it with the mapping
1019 // available at its immediate dominator (in the new region).
1020 ValueMapT &RegionMap = RegionMaps[BBCopy];
1021 RegionMap = RegionMaps[BBCopyIDom];
1022
Johannes Doerfert275a1752015-02-24 16:16:32 +00001023 // Copy the block with the BlockGenerator.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001024 copyBB(Stmt, BB, BBCopy, RegionMap, GlobalMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001025
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001026 // In order to remap PHI nodes we store also basic block mappings.
1027 BlockMap[BB] = BBCopy;
1028
1029 // Add values to incomplete PHI nodes waiting for this block to be copied.
1030 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1031 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB,
1032 GlobalMap, LTS);
1033 IncompletePHINodeMap[BB].clear();
1034
Johannes Doerfert275a1752015-02-24 16:16:32 +00001035 // And continue with new successors inside the region.
1036 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1037 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1038 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001039 }
1040
1041 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001042 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001043 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001044 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001045 BlockMap[R->getExit()] = ExitBBCopy;
1046
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001047 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001048
1049 // As the block generator doesn't handle control flow we need to add the
1050 // region control flow by hand after all blocks have been copied.
1051 for (BasicBlock *BB : SeenBlocks) {
1052
1053 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1054
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001055 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerfert275a1752015-02-24 16:16:32 +00001056 Instruction *BICopy = BBCopy->getTerminator();
1057
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001058 ValueMapT &RegionMap = RegionMaps[BBCopy];
1059 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1060
Tobias Grosser45e79442015-08-01 09:07:57 +00001061 Builder.SetInsertPoint(BICopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001062 copyInstScalar(Stmt, BI, RegionMap, GlobalMap, LTS);
1063 BICopy->eraseFromParent();
1064 }
1065
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001066 // Add counting PHI nodes to all loops in the region that can be used as
1067 // replacement for SCEVs refering to the old loop.
1068 for (BasicBlock *BB : SeenBlocks) {
1069 Loop *L = LI.getLoopFor(BB);
1070 if (L == nullptr || L->getHeader() != BB)
1071 continue;
1072
1073 BasicBlock *BBCopy = BlockMap[BB];
1074 Value *NullVal = Builder.getInt32(0);
1075 PHINode *LoopPHI =
1076 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1077 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1078 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1079 LoopPHI->insertBefore(BBCopy->begin());
1080 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1081
1082 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1083 if (!R->contains(PredBB))
1084 continue;
1085 if (L->contains(PredBB))
1086 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1087 else
1088 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1089 }
1090
1091 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1092 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1093 LoopPHI->addIncoming(NullVal, PredBBCopy);
1094
1095 LTS[L] = SE.getUnknown(LoopPHI);
1096 }
1097
1098 // Add all mappings from the region to the global map so outside uses will use
1099 // the copied instructions.
1100 for (auto &BBMap : RegionMaps)
1101 GlobalMap.insert(BBMap.second.begin(), BBMap.second.end());
1102
Johannes Doerfert275a1752015-02-24 16:16:32 +00001103 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001104 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001105}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001106
1107void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1108 const Instruction *Inst,
1109 ValueMapT &BBMap) {
1110
1111 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1112 // phi is copied it will reload all inputs from outside the region, hence
1113 // we do not need to generate code for the read access of the operands of a
1114 // PHI.
1115 if (isa<PHINode>(Inst))
1116 return;
1117
1118 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
1119}
1120
1121void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
1122 ValueMapT &BBMap,
1123 ValueMapT &GlobalMap) {
1124 const Region &R = Stmt.getParent()->getRegion();
1125
1126 Region *StmtR = Stmt.getRegion();
1127 assert(StmtR && "Block statements need to use the generateScalarStores() "
1128 "function in the BlockGenerator");
1129
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001130 for (MemoryAccess *MA : Stmt) {
1131
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001132 if (!MA->isScalar() || MA->isRead())
1133 continue;
1134
1135 Instruction *ScalarBase = cast<Instruction>(MA->getBaseAddr());
1136 Instruction *ScalarInst = MA->getAccessInstruction();
1137 PHINode *ScalarBasePHI = dyn_cast<PHINode>(ScalarBase);
1138
Tobias Grosser62139132015-08-02 16:17:41 +00001139 // Only generate accesses that belong to this basic block.
1140 if (ScalarInst->getParent() != BB)
1141 continue;
1142
Tobias Grosser92245222015-07-28 14:53:44 +00001143 Value *Val = nullptr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001144 AllocaInst *ScalarAddr = nullptr;
1145
Tobias Grosser92245222015-07-28 14:53:44 +00001146 if (MA->getScopArrayInfo()->isPHI()) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001147 int PHIIdx = ScalarBasePHI->getBasicBlockIndex(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001148 ScalarAddr = getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosser92245222015-07-28 14:53:44 +00001149 Val = ScalarBasePHI->getIncomingValue(PHIIdx);
1150 } else {
1151 ScalarAddr = getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
1152 Val = ScalarInst;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001153 }
1154
Tobias Grosser92245222015-07-28 14:53:44 +00001155 Val = getNewScalarValue(Val, R, ScalarMap, BBMap, GlobalMap);
1156 Builder.CreateStore(Val, ScalarAddr);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001157 }
1158}
1159
1160void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1161 PHINode *PHICopy, BasicBlock *IncomingBB,
1162 ValueMapT &GlobalMap,
1163 LoopToScevMapT &LTS) {
1164 Region *StmtR = Stmt.getRegion();
1165
1166 // If the incoming block was not yet copied mark this PHI as incomplete.
1167 // Once the block will be copied the incoming value will be added.
1168 BasicBlock *BBCopy = BlockMap[IncomingBB];
1169 if (!BBCopy) {
1170 assert(StmtR->contains(IncomingBB) &&
1171 "Bad incoming block for PHI in non-affine region");
1172 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1173 return;
1174 }
1175
1176 Value *OpCopy = nullptr;
1177 if (StmtR->contains(IncomingBB)) {
1178 assert(RegionMaps.count(BBCopy) &&
1179 "Incoming PHI block did not have a BBMap");
1180 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1181
1182 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1183 OpCopy =
1184 getNewValue(Stmt, Op, BBCopyMap, GlobalMap, LTS, getLoopForInst(PHI));
1185 } else {
1186
1187 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1188 return;
1189
1190 AllocaInst *PHIOpAddr =
1191 getOrCreateAlloca(const_cast<PHINode *>(PHI), PHIOpMap, ".phiops");
1192 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1193 BlockMap[IncomingBB]->getTerminator());
1194 }
1195
1196 assert(OpCopy && "Incoming PHI value was not copied properly");
1197 assert(BBCopy && "Incoming PHI block was not copied properly");
1198 PHICopy->addIncoming(OpCopy, BBCopy);
1199}
1200
1201Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, const PHINode *PHI,
1202 ValueMapT &BBMap,
1203 ValueMapT &GlobalMap,
1204 LoopToScevMapT &LTS) {
1205 unsigned NumIncoming = PHI->getNumIncomingValues();
1206 PHINode *PHICopy =
1207 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1208 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1209 BBMap[PHI] = PHICopy;
1210
1211 for (unsigned u = 0; u < NumIncoming; u++)
1212 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), GlobalMap,
1213 LTS);
1214 return PHICopy;
1215}