blob: d17d1666adf9c88a663102933702f551202f73c8 [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 Grosser86bc93a2015-09-06 08:47:57 +000020#include "polly/CodeGen/RuntimeDebugBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000021#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000022#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000023#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000024#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000025#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000026#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000027#include "llvm/Analysis/ScalarEvolution.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"
Tobias Grosser1b9d25a2015-09-27 11:17:22 +000031#include "llvm/Transforms/Utils/Local.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000032#include "isl/aff.h"
33#include "isl/ast.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000034#include "isl/ast_build.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "isl/set.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000036#include <deque>
37
Hongbin Zheng3b11a162012-04-25 13:16:49 +000038using namespace llvm;
39using namespace polly;
40
Tobias Grosser878aba42014-10-22 23:22:41 +000041static cl::opt<bool> Aligned("enable-polly-aligned",
42 cl::desc("Assumed aligned memory accesses."),
43 cl::Hidden, cl::init(false), cl::ZeroOrMore,
44 cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000045
Tobias Grosser86bc93a2015-09-06 08:47:57 +000046static cl::opt<bool> DebugPrinting(
47 "polly-codegen-add-debug-printing",
48 cl::desc("Add printf calls that show the values loaded/stored."),
49 cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
50
Tobias Grosserdcc3b432015-08-04 13:54:20 +000051bool polly::canSynthesize(const Value *V, const llvm::LoopInfo *LI,
Tobias Grosserecfe21b2013-03-20 18:03:18 +000052 ScalarEvolution *SE, const Region *R) {
Tobias Grosserdcc3b432015-08-04 13:54:20 +000053 if (!V || !SE->isSCEVable(V->getType()))
Tobias Grosserecfe21b2013-03-20 18:03:18 +000054 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000055
Tobias Grosserdcc3b432015-08-04 13:54:20 +000056 if (const SCEV *Scev = SE->getSCEV(const_cast<Value *>(V)))
Tobias Grosser683b8e42014-11-30 14:33:31 +000057 if (!isa<SCEVCouldNotCompute>(Scev))
58 if (!hasScalarDepsInsideRegion(Scev, R))
59 return true;
60
61 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000062}
63
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000064bool polly::isIgnoredIntrinsic(const Value *V) {
65 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
66 switch (IT->getIntrinsicID()) {
67 // Lifetime markers are supported/ignored.
68 case llvm::Intrinsic::lifetime_start:
69 case llvm::Intrinsic::lifetime_end:
70 // Invariant markers are supported/ignored.
71 case llvm::Intrinsic::invariant_start:
72 case llvm::Intrinsic::invariant_end:
73 // Some misc annotations are supported/ignored.
74 case llvm::Intrinsic::var_annotation:
75 case llvm::Intrinsic::ptr_annotation:
76 case llvm::Intrinsic::annotation:
77 case llvm::Intrinsic::donothing:
78 case llvm::Intrinsic::assume:
79 case llvm::Intrinsic::expect:
Tobias Grossere83a3962015-08-30 16:57:20 +000080 // Some debug info intrisics are supported/ignored.
81 case llvm::Intrinsic::dbg_value:
82 case llvm::Intrinsic::dbg_declare:
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000083 return true;
84 default:
85 break;
86 }
87 }
88 return false;
89}
90
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000091BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
92 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000093 ScalarAllocaMapTy &ScalarMap,
94 ScalarAllocaMapTy &PHIOpMap,
95 EscapeUsersAllocaMapTy &EscapeMap,
Tobias Grosserf4bb7a62015-10-04 10:18:32 +000096 ValueMapT &GlobalMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000097 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000098 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
99 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
Tobias Grosserbc132602015-09-05 09:56:54 +0000100 EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000101
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000102Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, const Value *Old,
103 ValueMapT &BBMap,
104 LoopToScevMapT &LTS,
105 Loop *L) const {
Tobias Grosser683b8e42014-11-30 14:33:31 +0000106 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000107 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000108 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000109 const SCEV *NewScev = apply(Scev, LTS, SE);
Tobias Grosserf4bb7a62015-10-04 10:18:32 +0000110 llvm::ValueToValueMap VTV;
Sebastian Pop637b23d2013-02-15 20:56:01 +0000111 VTV.insert(BBMap.begin(), BBMap.end());
112 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Johannes Doerferte69e1142015-08-18 11:56:00 +0000113
114 Scop &S = *Stmt.getParent();
115 const DataLayout &DL =
116 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
117 auto IP = Builder.GetInsertPoint();
118
119 assert(IP != Builder.GetInsertBlock()->end() &&
Tobias Grosser45e79442015-08-01 09:07:57 +0000120 "Only instructions can be insert points for SCEVExpander");
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000121 Value *Expanded = expandCodeFor(S, SE, DL, "polly", NewScev,
122 Old->getType(), IP, &VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000123
124 BBMap[Old] = Expanded;
125 return Expanded;
126 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000127 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000128
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000129 return nullptr;
130}
131
132Value *BlockGenerator::getNewValue(ScopStmt &Stmt, const Value *Old,
133 ValueMapT &BBMap, LoopToScevMapT &LTS,
134 Loop *L) const {
135 // We assume constants never change.
136 // This avoids map lookups for many calls to this function.
137 if (isa<Constant>(Old))
138 return const_cast<Value *>(Old);
139
140 if (Value *New = GlobalMap.lookup(Old)) {
141 if (Value *NewRemapped = GlobalMap.lookup(New))
142 New = NewRemapped;
143 if (Old->getType()->getScalarSizeInBits() <
144 New->getType()->getScalarSizeInBits())
145 New = Builder.CreateTruncOrBitCast(New, Old->getType());
146
147 return New;
148 }
149
150 if (Value *New = BBMap.lookup(Old))
151 return New;
152
153 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
154 return New;
155
Tobias Grosser16371ac2014-11-05 20:48:56 +0000156 // A scop-constant value defined by a global or a function parameter.
157 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
158 return const_cast<Value *>(Old);
159
160 // A scop-constant value defined by an instruction executed outside the scop.
161 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000162 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000163 return const_cast<Value *>(Old);
164
165 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000166 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000167 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000168}
169
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000170void BlockGenerator::copyInstScalar(ScopStmt &Stmt, const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000171 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000172 // We do not generate debug intrinsics as we did not investigate how to
173 // copy them correctly. At the current state, they just crash the code
174 // generation as the meta-data operands are not correctly copied.
175 if (isa<DbgInfoIntrinsic>(Inst))
176 return;
177
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000178 Instruction *NewInst = Inst->clone();
179
180 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000181 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000182 Value *NewOperand =
183 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000184
185 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000186 assert(!isa<StoreInst>(NewInst) &&
187 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000188 delete NewInst;
189 return;
190 }
191
192 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
193 }
194
195 Builder.Insert(NewInst);
196 BBMap[Inst] = NewInst;
197
198 if (!NewInst->getType()->isVoidTy())
199 NewInst->setName("p_" + Inst->getName());
200}
201
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000202Value *BlockGenerator::generateLocationAccessed(
203 ScopStmt &Stmt, const Instruction *Inst, const Value *Pointer,
Tobias Grosserbc132602015-09-05 09:56:54 +0000204 ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000205 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000206
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000207 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000208
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000209 if (AccessExpr) {
210 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000211 auto Address = ExprBuilder->create(AccessExpr);
212
213 // Cast the address of this memory access to a pointer type that has the
214 // same element type as the original access, but uses the address space of
215 // the newly generated pointer.
216 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
217 auto NewPtrTy = Address->getType();
218 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
219 NewPtrTy->getPointerAddressSpace());
220
221 if (OldPtrTy != NewPtrTy) {
222 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
223 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
224 "Pointer types to elements with different size found");
225 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
226 }
227 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000228 }
229
Tobias Grosserbc132602015-09-05 09:56:54 +0000230 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000231}
232
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000233Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000234 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000235}
236
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000237Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000238 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000239 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000240 if (Value *PreloadLoad = GlobalMap.lookup(Load))
241 return PreloadLoad;
242
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000243 const Value *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000244 Value *NewPointer =
245 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000246 Value *ScalarLoad = Builder.CreateAlignedLoad(
247 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000248
249 if (DebugPrinting)
250 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
251 ": ", ScalarLoad, "\n");
252
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000253 return ScalarLoad;
254}
255
Tobias Grosserc186ac72015-08-11 08:13:15 +0000256void BlockGenerator::generateScalarStore(ScopStmt &Stmt, const StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000257 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000258 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000259 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000260 Value *NewPointer =
261 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
262 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
263 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000264
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000265 if (DebugPrinting)
266 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
267 ": ", ValueOperand, "\n");
268
Tobias Grosserc186ac72015-08-11 08:13:15 +0000269 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000270}
271
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000272void BlockGenerator::copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000273 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000274 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000275
276 // First check for possible scalar dependences for this instruction.
Tobias Grosserbc132602015-09-05 09:56:54 +0000277 generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000278
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000279 // Terminator instructions control the control flow. They are explicitly
280 // expressed in the clast and do not need to be copied.
281 if (Inst->isTerminator())
282 return;
283
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000284 Loop *L = getLoopForInst(Inst);
285 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
286 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000287 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000288 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000289 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000290
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000291 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000292 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000293 // Compute NewLoad before its insertion in BBMap to make the insertion
294 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000295 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000296 return;
297 }
298
299 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000300 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000301 return;
302 }
303
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000304 if (const PHINode *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000305 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000306 return;
307 }
308
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000309 // Skip some special intrinsics for which we do not adjust the semantics to
310 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000311 if (isIgnoredIntrinsic(Inst))
312 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000313
Tobias Grosserbc132602015-09-05 09:56:54 +0000314 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000315}
316
Tobias Grosserbc132602015-09-05 09:56:54 +0000317void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000318 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000319 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();
Tobias Grosserbc132602015-09-05 09:56:54 +0000325 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000326}
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,
Tobias Grosserbc132602015-09-05 09:56:54 +0000336 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000337 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000338 BasicBlock *CopyBB = splitBB(BB);
Tobias Grosserbc132602015-09-05 09:56:54 +0000339 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000340 return CopyBB;
341}
342
343void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000344 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000345 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000346 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)
Tobias Grosserbc132602015-09-05 09:56:54 +0000350 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
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.
Tobias Grosseraff56c82015-09-30 13:36:54 +0000355 generateScalarStores(Stmt, BB, LTS, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000356
357 const Region &R = Stmt.getParent()->getRegion();
358 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000359 handleOutsideUsers(R, &Inst, BBMap[&Inst]);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000360}
361
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000362Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
363 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000364 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000365 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000366 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000367 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000368 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000369 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000370 NewAddr->insertBefore(EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000371 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000372 }
373
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000374 auto Addr = Map[ScalarBase];
375
Tobias Grosserbc132602015-09-05 09:56:54 +0000376 if (GlobalMap.count(Addr))
377 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000378
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000379 return Addr;
380}
381
Tobias Grosserbc132602015-09-05 09:56:54 +0000382Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000383 if (Access.getScopArrayInfo()->isPHI())
Tobias Grosserbc132602015-09-05 09:56:54 +0000384 return getOrCreatePHIAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000385 else
Tobias Grosserbc132602015-09-05 09:56:54 +0000386 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000387}
388
Tobias Grosserbc132602015-09-05 09:56:54 +0000389Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
390 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000391}
392
Tobias Grosserbc132602015-09-05 09:56:54 +0000393Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
394 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000395}
396
Tobias Grosserbc132602015-09-05 09:56:54 +0000397void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosserb09455d2015-09-18 06:01:11 +0000398 Value *InstCopy, Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000399 // If there are escape users we get the alloca for this instruction and put it
400 // in the EscapeMap for later finalization. Lastly, if the instruction was
401 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000402 if (EscapeMap.count(Inst))
403 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000404
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000405 EscapeUserVectorTy EscapeUsers;
406 for (User *U : Inst->users()) {
407
408 // Non-instruction user will never escape.
409 Instruction *UI = dyn_cast<Instruction>(U);
410 if (!UI)
411 continue;
412
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000413 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000414 continue;
415
416 EscapeUsers.push_back(UI);
417 }
418
419 // Exit if no escape uses were found.
420 if (EscapeUsers.empty())
421 return;
422
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000423 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000424 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000425
426 // Remember that this instruction has escape uses and the escape alloca.
427 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000428}
429
430void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
431 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000432 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
Michael Krusee2bccbb2015-09-18 19:59:43 +0000438 for (MemoryAccess *MA : *MAL) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000439 if (MA->isExplicit() || !MA->isRead())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000440 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000441
Michael Krusee2bccbb2015-09-18 19:59:43 +0000442 auto *Address = getOrCreateAlloca(*MA);
443 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000444 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000445 }
446}
447
448Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000449 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000450 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000451 // If the value we want to store is an instruction we might have demoted it
452 // in order to make it accessible here. In such a case a reload is
453 // necessary. If it is no instruction it will always be a value that
454 // dominates the current point and we can just use it. In total there are 4
455 // options:
456 // (1) The value is no instruction ==> use the value.
457 // (2) The value is an instruction that was split out of the region prior to
458 // code generation ==> use the instruction as it dominates the region.
459 // (3) The value is an instruction:
460 // (a) The value was defined in the current block, thus a copy is in
461 // the BBMap ==> use the mapped value.
462 // (b) The value was defined in a previous block, thus we demoted it
463 // earlier ==> use the reloaded value.
464 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
465 if (!ScalarValueInst)
466 return ScalarValue;
467
468 if (!R.contains(ScalarValueInst)) {
469 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
470 return /* Case (3a) */ ScalarValueCopy;
471 else
472 return /* Case 2 */ ScalarValue;
473 }
474
475 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
476 return /* Case (3a) */ ScalarValueCopy;
477
Tobias Grosseraff56c82015-09-30 13:36:54 +0000478 if ((Stmt.isBlockStmt() &&
479 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
480 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
481 auto SynthesizedValue = trySynthesizeNewValue(
482 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
483
484 if (SynthesizedValue)
485 return SynthesizedValue;
486 }
487
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000488 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000489 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000490 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000491
492 return ScalarValue;
493}
494
495void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000496 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000497 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000498 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) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000505 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000506 continue;
507
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000508 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000509 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000510
Tobias Grosseraff56c82015-09-30 13:36:54 +0000511 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000512 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000513 }
514}
515
Tobias Grosserc0091a72015-08-30 19:19:34 +0000516void BlockGenerator::createScalarInitialization(Scop &S) {
517 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000518 // The split block __just before__ the region and optimized region.
519 BasicBlock *SplitBB = R.getEnteringBlock();
520 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
521 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
522
523 // Get the start block of the __optimized__ region.
524 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
525 if (StartBB == R.getEntry())
526 StartBB = SplitBBTerm->getSuccessor(1);
527
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000528 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000529
Tobias Grosserc0091a72015-08-30 19:19:34 +0000530 for (auto &Pair : S.arrays()) {
531 auto &Array = Pair.second;
532 if (Array->getNumberOfDimensions() != 0)
533 continue;
534 if (Array->isPHI()) {
535 // For PHI nodes, the only values we need to store are the ones that
536 // reach the PHI node from outside the region. In general there should
537 // only be one such incoming edge and this edge should enter through
538 // 'SplitBB'.
539 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000540
Tobias Grosserc0091a72015-08-30 19:19:34 +0000541 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
542 if (!R.contains(*BI) && *BI != SplitBB)
543 llvm_unreachable("Incoming edges from outside the scop should always "
544 "come from SplitBB");
545
546 int Idx = PHI->getBasicBlockIndex(SplitBB);
547 if (Idx < 0)
548 continue;
549
550 Value *ScalarValue = PHI->getIncomingValue(Idx);
551
Tobias Grosserbc132602015-09-05 09:56:54 +0000552 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000553 continue;
554 }
555
556 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
557
558 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000559 continue;
560
Johannes Doerfert717b8662015-09-08 21:44:27 +0000561 // PHI nodes that are not marked as such in their SAI object are exit PHI
562 // nodes we model as common scalars but do not need to initialize.
563 if (Inst && isa<PHINode>(Inst))
564 continue;
565
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000566 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000567 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000568 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000569 }
570}
571
572void BlockGenerator::createScalarFinalization(Region &R) {
573 // The exit block of the __unoptimized__ region.
574 BasicBlock *ExitBB = R.getExitingBlock();
575 // The merge block __just after__ the region and the optimized region.
576 BasicBlock *MergeBB = R.getExit();
577
578 // The exit block of the __optimized__ region.
579 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
580 if (OptExitBB == ExitBB)
581 OptExitBB = *(++pred_begin(MergeBB));
582
583 Builder.SetInsertPoint(OptExitBB->getTerminator());
584 for (const auto &EscapeMapping : EscapeMap) {
585 // Extract the escaping instruction and the escaping users as well as the
586 // alloca the instruction was demoted to.
587 Instruction *EscapeInst = EscapeMapping.getFirst();
588 const auto &EscapeMappingValue = EscapeMapping.getSecond();
589 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000590 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000591
592 // Reload the demoted instruction in the optimized version of the SCoP.
593 Instruction *EscapeInstReload =
594 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
595
596 // Create the merge PHI that merges the optimized and unoptimized version.
597 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
598 EscapeInst->getName() + ".merge");
599 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
600
601 // Add the respective values to the merge PHI.
602 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
603 MergePHI->addIncoming(EscapeInst, ExitBB);
604
605 // The information of scalar evolution about the escaping instruction needs
606 // to be revoked so the new merged instruction will be used.
607 if (SE.isSCEVable(EscapeInst->getType()))
608 SE.forgetValue(EscapeInst);
609
610 // Replace all uses of the demoted instruction with the merge PHI.
611 for (Instruction *EUser : EscapeUsers)
612 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
613 }
614}
615
Tobias Grosser655a4572015-08-30 17:32:39 +0000616void BlockGenerator::finalizeSCoP(Scop &S) {
Johannes Doerfert717b8662015-09-08 21:44:27 +0000617
618 // Handle PHI nodes that were in the original exit and are now
619 // moved into the region exiting block.
620 if (!S.hasSingleExitEdge()) {
621 for (Instruction &I : *S.getRegion().getExitingBlock()) {
622 PHINode *PHI = dyn_cast<PHINode>(&I);
623 if (!PHI)
624 break;
625
626 assert(PHI->getNumUses() == 1);
627 assert(ScalarMap.count(PHI->user_back()));
628
629 handleOutsideUsers(S.getRegion(), PHI, nullptr,
630 ScalarMap[PHI->user_back()]);
631 }
632 }
633
Tobias Grosserc0091a72015-08-30 19:19:34 +0000634 createScalarInitialization(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000635 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000636}
637
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000638VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000639 std::vector<LoopToScevMapT> &VLTS,
640 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000641 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000642 assert(Schedule && "No statement domain provided");
643}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000644
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000645Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, const Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000646 ValueMapT &VectorMap,
647 VectorValueMapT &ScalarMaps,
648 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000649 if (Value *NewValue = VectorMap.lookup(Old))
650 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000651
652 int Width = getVectorWidth();
653
654 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
655
656 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000657 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000658 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000659 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000660
661 VectorMap[Old] = Vector;
662
663 return Vector;
664}
665
666Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
667 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
668 assert(PointerTy && "PointerType expected");
669
670 Type *ScalarType = PointerTy->getElementType();
671 VectorType *VectorType = VectorType::get(ScalarType, Width);
672
673 return PointerType::getUnqual(VectorType);
674}
675
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000676Value *VectorBlockGenerator::generateStrideOneLoad(
677 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000678 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000679 unsigned VectorWidth = getVectorWidth();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000680 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000681 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
682 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
683
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000684 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000685 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
686 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000687 Value *VectorPtr =
688 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
689 LoadInst *VecLoad =
690 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000691 if (!Aligned)
692 VecLoad->setAlignment(8);
693
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000694 if (NegativeStride) {
695 SmallVector<Constant *, 16> Indices;
696 for (int i = VectorWidth - 1; i >= 0; i--)
697 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
698 Constant *SV = llvm::ConstantVector::get(Indices);
699 Value *RevVecLoad = Builder.CreateShuffleVector(
700 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
701 return RevVecLoad;
702 }
703
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000704 return VecLoad;
705}
706
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000707Value *VectorBlockGenerator::generateStrideZeroLoad(
708 ScopStmt &Stmt, const LoadInst *Load, ValueMapT &BBMap,
709 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000710 const Value *Pointer = Load->getPointerOperand();
711 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000712 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
713 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000714 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
715 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000716 LoadInst *ScalarLoad =
717 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000718
719 if (!Aligned)
720 ScalarLoad->setAlignment(8);
721
Tobias Grosserc14582f2013-02-05 18:01:29 +0000722 Constant *SplatVector = Constant::getNullValue(
723 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000724
Tobias Grosserc14582f2013-02-05 18:01:29 +0000725 Value *VectorLoad = Builder.CreateShuffleVector(
726 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000727 return VectorLoad;
728}
729
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000730Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000731 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
732 __isl_keep isl_id_to_ast_expr *NewAccesses
733
734 ) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000735 int VectorWidth = getVectorWidth();
736 const Value *Pointer = Load->getPointerOperand();
737 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000738 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000739
740 Value *Vector = UndefValue::get(VectorType);
741
742 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000743 Value *NewPointer = generateLocationAccessed(
744 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000745 Value *ScalarLoad =
746 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
747 Vector = Builder.CreateInsertElement(
748 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000749 }
750
751 return Vector;
752}
753
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000754void VectorBlockGenerator::generateLoad(
755 ScopStmt &Stmt, const LoadInst *Load, ValueMapT &VectorMap,
756 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000757 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
758 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
759 Load->getName() + "_p");
760 return;
761 }
762
Tobias Grosser28736452015-03-23 07:00:36 +0000763 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000764 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000765 ScalarMaps[i][Load] =
766 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000767 return;
768 }
769
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000770 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000771
Tobias Grosser95493982014-04-18 09:46:35 +0000772 // Make sure we have scalar values available to access the pointer to
773 // the data location.
774 extractScalarValues(Load, VectorMap, ScalarMaps);
775
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000776 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000777 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000778 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000779 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000780 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000781 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000782 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000784 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000785
786 VectorMap[Load] = NewLoad;
787}
788
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000789void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt,
790 const UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000791 ValueMapT &VectorMap,
792 VectorValueMapT &ScalarMaps) {
793 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000794 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
795 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000796
797 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
798
799 const CastInst *Cast = dyn_cast<CastInst>(Inst);
800 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
801 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
802}
803
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000804void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt,
805 const BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806 ValueMapT &VectorMap,
807 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000808 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000809 Value *OpZero = Inst->getOperand(0);
810 Value *OpOne = Inst->getOperand(1);
811
812 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000813 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
814 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000815
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000816 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000817 Inst->getName() + "p_vec");
818 VectorMap[Inst] = NewInst;
819}
820
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000821void VectorBlockGenerator::copyStore(
822 ScopStmt &Stmt, const StoreInst *Store, ValueMapT &VectorMap,
823 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000824 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000825
826 const Value *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000827 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000828 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829
Tobias Grosser50fd7012014-04-17 23:13:49 +0000830 // Make sure we have scalar values available to access the pointer to
831 // the data location.
832 extractScalarValues(Store, VectorMap, ScalarMaps);
833
Sebastian Popa00a0292012-12-18 07:46:06 +0000834 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000835 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000836 Value *NewPointer = generateLocationAccessed(
837 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000838
Tobias Grosserc14582f2013-02-05 18:01:29 +0000839 Value *VectorPtr =
840 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000841 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
842
843 if (!Aligned)
844 Store->setAlignment(8);
845 } else {
846 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000847 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000848 Value *NewPointer = generateLocationAccessed(
849 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000850 Builder.CreateStore(Scalar, NewPointer);
851 }
852 }
853}
854
855bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
856 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000857 for (Value *Operand : Inst->operands())
858 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000859 return true;
860 return false;
861}
862
863bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
864 ValueMapT &VectorMap,
865 VectorValueMapT &ScalarMaps) {
866 bool HasVectorOperand = false;
867 int VectorWidth = getVectorWidth();
868
Tobias Grosser91f5b262014-06-04 08:06:40 +0000869 for (Value *Operand : Inst->operands()) {
870 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000871
872 if (VecOp == VectorMap.end())
873 continue;
874
875 HasVectorOperand = true;
876 Value *NewVector = VecOp->second;
877
878 for (int i = 0; i < VectorWidth; ++i) {
879 ValueMapT &SM = ScalarMaps[i];
880
881 // If there is one scalar extracted, all scalar elements should have
882 // already been extracted by the code here. So no need to check for the
883 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000884 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000885 break;
886
Tobias Grosser91f5b262014-06-04 08:06:40 +0000887 SM[Operand] =
888 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889 }
890 }
891
892 return HasVectorOperand;
893}
894
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000895void VectorBlockGenerator::copyInstScalarized(
896 ScopStmt &Stmt, const Instruction *Inst, ValueMapT &VectorMap,
897 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000898 bool HasVectorOperand;
899 int VectorWidth = getVectorWidth();
900
901 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
902
903 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000904 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000905 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000906
907 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
908 return;
909
910 // Make the result available as vector value.
911 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
912 Value *Vector = UndefValue::get(VectorType);
913
914 for (int i = 0; i < VectorWidth; i++)
915 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
916 Builder.getInt32(i));
917
918 VectorMap[Inst] = Vector;
919}
920
Tobias Grosserbc132602015-09-05 09:56:54 +0000921int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000922
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000923void VectorBlockGenerator::copyInstruction(
924 ScopStmt &Stmt, const Instruction *Inst, ValueMapT &VectorMap,
925 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000926 // Terminator instructions control the control flow. They are explicitly
927 // expressed in the clast and do not need to be copied.
928 if (Inst->isTerminator())
929 return;
930
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000931 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000932 return;
933
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000934 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000935 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000936 return;
937 }
938
939 if (hasVectorOperands(Inst, VectorMap)) {
940 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000941 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000942 return;
943 }
944
945 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000946 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000947 return;
948 }
949
950 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000951 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000952 return;
953 }
954
955 // Falltrough: We generate scalar instructions, if we don't know how to
956 // generate vector code.
957 }
958
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000959 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000960}
961
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000962void VectorBlockGenerator::copyStmt(
963 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000964 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
965 "the vector block generator");
966
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000967 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000968 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000969 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000970 CopyBB->setName("polly.stmt." + BB->getName());
971 Builder.SetInsertPoint(CopyBB->begin());
972
973 // Create two maps that store the mapping from the original instructions of
974 // the old basic block to their copies in the new basic block. Those maps
975 // are basic block local.
976 //
977 // As vector code generation is supported there is one map for scalar values
978 // and one for vector values.
979 //
980 // In case we just do scalar code generation, the vectorMap is not used and
981 // the scalarMap has just one dimension, which contains the mapping.
982 //
983 // In case vector code generation is done, an instruction may either appear
984 // in the vector map once (as it is calculating >vectorwidth< values at a
985 // time. Or (if the values are calculated using scalar operations), it
986 // appears once in every dimension of the scalarMap.
987 VectorValueMapT ScalarBlockMap(getVectorWidth());
988 ValueMapT VectorBlockMap;
989
Tobias Grosser91f5b262014-06-04 08:06:40 +0000990 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000991 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000992}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000993
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000994BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
995 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000996
997 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
998 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
999
1000 if (BBCopyIDom)
1001 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1002
1003 return BBCopyIDom;
1004}
1005
Tobias Grosserbc132602015-09-05 09:56:54 +00001006void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001007 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001008 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001009 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001010
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001011 // Forget all old mappings.
1012 BlockMap.clear();
1013 RegionMaps.clear();
1014 IncompletePHINodeMap.clear();
1015
Johannes Doerfert275a1752015-02-24 16:16:32 +00001016 // The region represented by the statement.
1017 Region *R = Stmt.getRegion();
1018
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001019 // Create a dedicated entry for the region where we can reload all demoted
1020 // inputs.
1021 BasicBlock *EntryBB = R->getEntry();
1022 BasicBlock *EntryBBCopy =
1023 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
1024 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1025 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001026
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001027 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1028 if (!R->contains(*PI))
1029 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001030
1031 // Iterate over all blocks in the region in a breadth-first search.
1032 std::deque<BasicBlock *> Blocks;
1033 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001034 Blocks.push_back(EntryBB);
1035 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001036
1037 while (!Blocks.empty()) {
1038 BasicBlock *BB = Blocks.front();
1039 Blocks.pop_front();
1040
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001041 // First split the block and update dominance information.
1042 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001043 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1044
1045 // In order to remap PHI nodes we store also basic block mappings.
1046 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001047
1048 // Get the mapping for this block and initialize it with the mapping
1049 // available at its immediate dominator (in the new region).
1050 ValueMapT &RegionMap = RegionMaps[BBCopy];
1051 RegionMap = RegionMaps[BBCopyIDom];
1052
Johannes Doerfert275a1752015-02-24 16:16:32 +00001053 // Copy the block with the BlockGenerator.
Tobias Grosserbc132602015-09-05 09:56:54 +00001054 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001055
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001056 // In order to remap PHI nodes we store also basic block mappings.
1057 BlockMap[BB] = BBCopy;
1058
1059 // Add values to incomplete PHI nodes waiting for this block to be copied.
1060 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001061 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001062 IncompletePHINodeMap[BB].clear();
1063
Johannes Doerfert275a1752015-02-24 16:16:32 +00001064 // And continue with new successors inside the region.
1065 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1066 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1067 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001068 }
1069
1070 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001071 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001072 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001073 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001074 BlockMap[R->getExit()] = ExitBBCopy;
1075
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001076 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001077
1078 // As the block generator doesn't handle control flow we need to add the
1079 // region control flow by hand after all blocks have been copied.
1080 for (BasicBlock *BB : SeenBlocks) {
1081
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001082 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001083 TerminatorInst *TI = BB->getTerminator();
1084 if (isa<UnreachableInst>(TI)) {
1085 while (!BBCopy->empty())
1086 BBCopy->begin()->eraseFromParent();
1087 new UnreachableInst(BBCopy->getContext(), BBCopy);
1088 continue;
1089 }
1090
Johannes Doerfert275a1752015-02-24 16:16:32 +00001091 Instruction *BICopy = BBCopy->getTerminator();
1092
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001093 ValueMapT &RegionMap = RegionMaps[BBCopy];
1094 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1095
Tobias Grosser45e79442015-08-01 09:07:57 +00001096 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001097 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001098 BICopy->eraseFromParent();
1099 }
1100
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001101 // Add counting PHI nodes to all loops in the region that can be used as
1102 // replacement for SCEVs refering to the old loop.
1103 for (BasicBlock *BB : SeenBlocks) {
1104 Loop *L = LI.getLoopFor(BB);
1105 if (L == nullptr || L->getHeader() != BB)
1106 continue;
1107
1108 BasicBlock *BBCopy = BlockMap[BB];
1109 Value *NullVal = Builder.getInt32(0);
1110 PHINode *LoopPHI =
1111 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1112 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1113 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1114 LoopPHI->insertBefore(BBCopy->begin());
1115 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1116
1117 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1118 if (!R->contains(PredBB))
1119 continue;
1120 if (L->contains(PredBB))
1121 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1122 else
1123 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1124 }
1125
1126 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1127 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1128 LoopPHI->addIncoming(NullVal, PredBBCopy);
1129
1130 LTS[L] = SE.getUnknown(LoopPHI);
1131 }
1132
Johannes Doerfert275a1752015-02-24 16:16:32 +00001133 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001134 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001135}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001136
1137void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1138 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +00001139 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001140
1141 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1142 // phi is copied it will reload all inputs from outside the region, hence
1143 // we do not need to generate code for the read access of the operands of a
1144 // PHI.
1145 if (isa<PHINode>(Inst))
1146 return;
1147
Tobias Grosserbc132602015-09-05 09:56:54 +00001148 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001149}
1150
1151void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +00001152 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001153 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001154 const Region &R = Stmt.getParent()->getRegion();
1155
Tobias Grosser75296902015-08-21 19:23:21 +00001156 assert(Stmt.getRegion() &&
1157 "Block statements need to use the generateScalarStores() "
1158 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001159
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001160 for (MemoryAccess *MA : Stmt) {
1161
Michael Kruse8d0b7342015-09-25 21:21:00 +00001162 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001163 continue;
1164
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001165 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001166
Tobias Grosser62139132015-08-02 16:17:41 +00001167 // Only generate accesses that belong to this basic block.
1168 if (ScalarInst->getParent() != BB)
1169 continue;
1170
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001171 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001172
Tobias Grosserbc132602015-09-05 09:56:54 +00001173 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001174
Tobias Grosseraff56c82015-09-30 13:36:54 +00001175 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001176 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001177 }
1178}
1179
1180void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1181 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001182 LoopToScevMapT &LTS) {
1183 Region *StmtR = Stmt.getRegion();
1184
1185 // If the incoming block was not yet copied mark this PHI as incomplete.
1186 // Once the block will be copied the incoming value will be added.
1187 BasicBlock *BBCopy = BlockMap[IncomingBB];
1188 if (!BBCopy) {
1189 assert(StmtR->contains(IncomingBB) &&
1190 "Bad incoming block for PHI in non-affine region");
1191 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1192 return;
1193 }
1194
1195 Value *OpCopy = nullptr;
1196 if (StmtR->contains(IncomingBB)) {
1197 assert(RegionMaps.count(BBCopy) &&
1198 "Incoming PHI block did not have a BBMap");
1199 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1200
1201 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Tobias Grosserbc132602015-09-05 09:56:54 +00001202 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001203 } else {
1204
1205 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1206 return;
1207
Tobias Grosserbc132602015-09-05 09:56:54 +00001208 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001209 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1210 BlockMap[IncomingBB]->getTerminator());
1211 }
1212
1213 assert(OpCopy && "Incoming PHI value was not copied properly");
1214 assert(BBCopy && "Incoming PHI block was not copied properly");
1215 PHICopy->addIncoming(OpCopy, BBCopy);
1216}
1217
1218Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, const PHINode *PHI,
1219 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001220 LoopToScevMapT &LTS) {
1221 unsigned NumIncoming = PHI->getNumIncomingValues();
1222 PHINode *PHICopy =
1223 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1224 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1225 BBMap[PHI] = PHICopy;
1226
1227 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001228 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001229 return PHICopy;
1230}