blob: b4364df7fdaafafb87ba260e49c8eefa81b00394 [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
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000051BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
52 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000053 ScalarAllocaMapTy &ScalarMap,
54 ScalarAllocaMapTy &PHIOpMap,
55 EscapeUsersAllocaMapTy &EscapeMap,
Tobias Grosserf4bb7a62015-10-04 10:18:32 +000056 ValueMapT &GlobalMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000057 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000058 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
59 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
Tobias Grosserbc132602015-09-05 09:56:54 +000060 EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +000061
Tobias Grosser2f1acac2015-10-04 10:18:45 +000062Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
Tobias Grosser33cb9f92015-09-30 11:56:19 +000063 ValueMapT &BBMap,
64 LoopToScevMapT &LTS,
65 Loop *L) const {
Tobias Grosser683b8e42014-11-30 14:33:31 +000066 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +000067 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +000068 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +000069 const SCEV *NewScev = apply(Scev, LTS, SE);
Johannes Doerfert09e36972015-10-07 20:17:36 +000070 ValueMapT VTV;
Sebastian Pop637b23d2013-02-15 20:56:01 +000071 VTV.insert(BBMap.begin(), BBMap.end());
72 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Johannes Doerferte69e1142015-08-18 11:56:00 +000073
74 Scop &S = *Stmt.getParent();
75 const DataLayout &DL =
76 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
77 auto IP = Builder.GetInsertPoint();
78
79 assert(IP != Builder.GetInsertBlock()->end() &&
Tobias Grosser45e79442015-08-01 09:07:57 +000080 "Only instructions can be insert points for SCEVExpander");
Johannes Doerfertc0729a32015-09-30 16:52:03 +000081 Value *Expanded = expandCodeFor(S, SE, DL, "polly", NewScev,
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +000082 Old->getType(), &*IP, &VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +000083
84 BBMap[Old] = Expanded;
85 return Expanded;
86 }
Tobias Grosser369430f2013-03-22 23:42:53 +000087 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +000088
Tobias Grosser33cb9f92015-09-30 11:56:19 +000089 return nullptr;
90}
91
Tobias Grosser2f1acac2015-10-04 10:18:45 +000092Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
93 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000094 // Constants that do not reference any named value can always remain
Michael Kruse5bbc0e12015-12-14 23:41:32 +000095 // unchanged. Handle them early to avoid expensive map lookups. We do not take
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000096 // the fast-path for external constants which are referenced through globals
97 // as these may need to be rewritten when distributing code accross different
98 // LLVM modules.
99 if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000100 return Old;
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000101
102 if (Value *New = GlobalMap.lookup(Old)) {
103 if (Value *NewRemapped = GlobalMap.lookup(New))
104 New = NewRemapped;
105 if (Old->getType()->getScalarSizeInBits() <
106 New->getType()->getScalarSizeInBits())
107 New = Builder.CreateTruncOrBitCast(New, Old->getType());
108
109 return New;
110 }
111
112 if (Value *New = BBMap.lookup(Old))
113 return New;
114
115 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
116 return New;
117
Tobias Grosser16371ac2014-11-05 20:48:56 +0000118 // A scop-constant value defined by a global or a function parameter.
119 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000120 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000121
122 // A scop-constant value defined by an instruction executed outside the scop.
123 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000124 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000125 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000126
127 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000128 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000129 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000130}
131
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000132void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000133 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000134 // We do not generate debug intrinsics as we did not investigate how to
135 // copy them correctly. At the current state, they just crash the code
136 // generation as the meta-data operands are not correctly copied.
137 if (isa<DbgInfoIntrinsic>(Inst))
138 return;
139
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000140 Instruction *NewInst = Inst->clone();
141
142 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000143 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000144 Value *NewOperand =
145 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000146
147 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000148 assert(!isa<StoreInst>(NewInst) &&
149 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000150 delete NewInst;
151 return;
152 }
153
154 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
155 }
156
157 Builder.Insert(NewInst);
158 BBMap[Inst] = NewInst;
159
160 if (!NewInst->getType()->isVoidTy())
161 NewInst->setName("p_" + Inst->getName());
162}
163
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000164Value *BlockGenerator::generateLocationAccessed(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000165 ScopStmt &Stmt, const Instruction *Inst, Value *Pointer, ValueMapT &BBMap,
166 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000167 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000168
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000169 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000170
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000171 if (AccessExpr) {
172 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000173 auto Address = ExprBuilder->create(AccessExpr);
174
175 // Cast the address of this memory access to a pointer type that has the
176 // same element type as the original access, but uses the address space of
177 // the newly generated pointer.
178 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
179 auto NewPtrTy = Address->getType();
180 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
181 NewPtrTy->getPointerAddressSpace());
182
183 if (OldPtrTy != NewPtrTy) {
184 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
185 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
186 "Pointer types to elements with different size found");
187 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
188 }
189 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000190 }
191
Tobias Grosserbc132602015-09-05 09:56:54 +0000192 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000193}
194
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000195Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000196 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000197}
198
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000199Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000200 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000201 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000202 if (Value *PreloadLoad = GlobalMap.lookup(Load))
203 return PreloadLoad;
204
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000205 auto *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000206 Value *NewPointer =
207 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000208 Value *ScalarLoad = Builder.CreateAlignedLoad(
209 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000210
211 if (DebugPrinting)
212 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
213 ": ", ScalarLoad, "\n");
214
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000215 return ScalarLoad;
216}
217
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000218void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000219 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000220 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000221 auto *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000222 Value *NewPointer =
223 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
224 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
225 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000226
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000227 if (DebugPrinting)
228 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
229 ": ", ValueOperand, "\n");
230
Tobias Grosserc186ac72015-08-11 08:13:15 +0000231 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000232}
233
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000234void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000235 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000236 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000237 // Terminator instructions control the control flow. They are explicitly
238 // expressed in the clast and do not need to be copied.
239 if (Inst->isTerminator())
240 return;
241
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000242 Loop *L = getLoopForInst(Inst);
243 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
244 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000245 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000246 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000247 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000248
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000249 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000250 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000251 // Compute NewLoad before its insertion in BBMap to make the insertion
252 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000253 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000254 return;
255 }
256
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000257 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000258 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000259 return;
260 }
261
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000262 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000263 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000264 return;
265 }
266
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000267 // Skip some special intrinsics for which we do not adjust the semantics to
268 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000269 if (isIgnoredIntrinsic(Inst))
270 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000271
Tobias Grosserbc132602015-09-05 09:56:54 +0000272 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000273}
274
Tobias Grosserbc132602015-09-05 09:56:54 +0000275void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000276 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000277 assert(Stmt.isBlockStmt() &&
278 "Only block statements can be copied by the block generator");
279
280 ValueMapT BBMap;
281
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000282 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000283 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000284}
285
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000286BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000287 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
288 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000289 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000290 return CopyBB;
291}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000292
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000293BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000294 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000295 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000296 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000297 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000298 generateScalarLoads(Stmt, BBMap);
299
Tobias Grosserbc132602015-09-05 09:56:54 +0000300 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000301
302 // After a basic block was copied store all scalars that escape this block in
303 // their alloca.
304 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000305 return CopyBB;
306}
307
308void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000309 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000310 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000311 EntryBB = &CopyBB->getParent()->getEntryBlock();
312
Tobias Grosser91f5b262014-06-04 08:06:40 +0000313 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000314 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000315}
316
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000317Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
318 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000319 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000320 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000321 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000322 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000323 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000324 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000325 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000326 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000327 }
328
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000329 auto Addr = Map[ScalarBase];
330
Tobias Grosserbc132602015-09-05 09:56:54 +0000331 if (GlobalMap.count(Addr))
332 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000333
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000334 return Addr;
335}
336
Tobias Grosserbc132602015-09-05 09:56:54 +0000337Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000338 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000339 return getOrCreatePHIAlloca(Access.getBaseAddr());
340 else
341 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000342}
343
344Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000345 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000346 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000347 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000348 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000349}
350
Tobias Grosserbc132602015-09-05 09:56:54 +0000351Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
352 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000353}
354
Tobias Grosserbc132602015-09-05 09:56:54 +0000355Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
356 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000357}
358
Tobias Grosserbc132602015-09-05 09:56:54 +0000359void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000360 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000361 // If there are escape users we get the alloca for this instruction and put it
362 // in the EscapeMap for later finalization. Lastly, if the instruction was
363 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000364 if (EscapeMap.count(Inst))
365 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000366
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000367 EscapeUserVectorTy EscapeUsers;
368 for (User *U : Inst->users()) {
369
370 // Non-instruction user will never escape.
371 Instruction *UI = dyn_cast<Instruction>(U);
372 if (!UI)
373 continue;
374
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000375 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000376 continue;
377
378 EscapeUsers.push_back(UI);
379 }
380
381 // Exit if no escape uses were found.
382 if (EscapeUsers.empty())
383 return;
384
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000385 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000386 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000387
388 // Remember that this instruction has escape uses and the escape alloca.
389 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000390}
391
Michael Kruse225f0d12015-10-17 21:36:00 +0000392void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
393 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000394 if (MA->isArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000395 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000396
Michael Krusee2bccbb2015-09-18 19:59:43 +0000397 auto *Address = getOrCreateAlloca(*MA);
398 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000399 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000400 }
401}
402
403Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000404 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000405 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000406 // If the value we want to store is an instruction we might have demoted it
407 // in order to make it accessible here. In such a case a reload is
408 // necessary. If it is no instruction it will always be a value that
409 // dominates the current point and we can just use it. In total there are 4
410 // options:
411 // (1) The value is no instruction ==> use the value.
412 // (2) The value is an instruction that was split out of the region prior to
413 // code generation ==> use the instruction as it dominates the region.
414 // (3) The value is an instruction:
415 // (a) The value was defined in the current block, thus a copy is in
416 // the BBMap ==> use the mapped value.
417 // (b) The value was defined in a previous block, thus we demoted it
418 // earlier ==> use the reloaded value.
419 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
420 if (!ScalarValueInst)
421 return ScalarValue;
422
423 if (!R.contains(ScalarValueInst)) {
424 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
425 return /* Case (3a) */ ScalarValueCopy;
426 else
427 return /* Case 2 */ ScalarValue;
428 }
429
430 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
431 return /* Case (3a) */ ScalarValueCopy;
432
Tobias Grosseraff56c82015-09-30 13:36:54 +0000433 if ((Stmt.isBlockStmt() &&
434 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
435 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
436 auto SynthesizedValue = trySynthesizeNewValue(
437 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
438
439 if (SynthesizedValue)
440 return SynthesizedValue;
441 }
442
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000443 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000444 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000445 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000446
447 return ScalarValue;
448}
449
Michael Kruse225f0d12015-10-17 21:36:00 +0000450void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000451 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000452 const Region &R = Stmt.getParent()->getRegion();
453
Michael Kruse225f0d12015-10-17 21:36:00 +0000454 assert(Stmt.isBlockStmt() && "Region statements need to use the "
455 "generateScalarStores() function in the "
456 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000457
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000458 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000459 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000460 continue;
461
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000462 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000463 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000464
Tobias Grosseraff56c82015-09-30 13:36:54 +0000465 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000466 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000467 }
468}
469
Tobias Grosserc0091a72015-08-30 19:19:34 +0000470void BlockGenerator::createScalarInitialization(Scop &S) {
471 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000472 BasicBlock *ExitBB = R.getExit();
473
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000474 // The split block __just before__ the region and optimized region.
475 BasicBlock *SplitBB = R.getEnteringBlock();
476 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
477 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
478
479 // Get the start block of the __optimized__ region.
480 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
481 if (StartBB == R.getEntry())
482 StartBB = SplitBBTerm->getSuccessor(1);
483
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000484 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000485
Tobias Grosserc0091a72015-08-30 19:19:34 +0000486 for (auto &Pair : S.arrays()) {
487 auto &Array = Pair.second;
488 if (Array->getNumberOfDimensions() != 0)
489 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000490 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000491 // For PHI nodes, the only values we need to store are the ones that
492 // reach the PHI node from outside the region. In general there should
493 // only be one such incoming edge and this edge should enter through
494 // 'SplitBB'.
495 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000496
Tobias Grosserc0091a72015-08-30 19:19:34 +0000497 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
498 if (!R.contains(*BI) && *BI != SplitBB)
499 llvm_unreachable("Incoming edges from outside the scop should always "
500 "come from SplitBB");
501
502 int Idx = PHI->getBasicBlockIndex(SplitBB);
503 if (Idx < 0)
504 continue;
505
506 Value *ScalarValue = PHI->getIncomingValue(Idx);
507
Tobias Grosserbc132602015-09-05 09:56:54 +0000508 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000509 continue;
510 }
511
512 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
513
514 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000515 continue;
516
Johannes Doerfert188542f2015-11-09 00:21:21 +0000517 // PHI nodes that are not marked as such in their SAI object are either exit
518 // PHI nodes we model as common scalars but without initialization, or
519 // incoming phi nodes that need to be initialized. Check if the first is the
520 // case for Inst and do not create and initialize memory if so.
521 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
522 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
523 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000524
Tobias Grosserc0091a72015-08-30 19:19:34 +0000525 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000526 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000527 }
528}
529
530void BlockGenerator::createScalarFinalization(Region &R) {
531 // The exit block of the __unoptimized__ region.
532 BasicBlock *ExitBB = R.getExitingBlock();
533 // The merge block __just after__ the region and the optimized region.
534 BasicBlock *MergeBB = R.getExit();
535
536 // The exit block of the __optimized__ region.
537 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
538 if (OptExitBB == ExitBB)
539 OptExitBB = *(++pred_begin(MergeBB));
540
541 Builder.SetInsertPoint(OptExitBB->getTerminator());
542 for (const auto &EscapeMapping : EscapeMap) {
543 // Extract the escaping instruction and the escaping users as well as the
544 // alloca the instruction was demoted to.
545 Instruction *EscapeInst = EscapeMapping.getFirst();
546 const auto &EscapeMappingValue = EscapeMapping.getSecond();
547 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000548 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000549
550 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000551 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000552 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000553 EscapeInstReload =
554 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000555
556 // Create the merge PHI that merges the optimized and unoptimized version.
557 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
558 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000559 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000560
561 // Add the respective values to the merge PHI.
562 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
563 MergePHI->addIncoming(EscapeInst, ExitBB);
564
565 // The information of scalar evolution about the escaping instruction needs
566 // to be revoked so the new merged instruction will be used.
567 if (SE.isSCEVable(EscapeInst->getType()))
568 SE.forgetValue(EscapeInst);
569
570 // Replace all uses of the demoted instruction with the merge PHI.
571 for (Instruction *EUser : EscapeUsers)
572 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
573 }
574}
575
Tobias Grosserffa24462015-10-17 08:54:13 +0000576void BlockGenerator::findOutsideUsers(Scop &S) {
577 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000578 for (auto &Pair : S.arrays()) {
579 auto &Array = Pair.second;
580
581 if (Array->getNumberOfDimensions() != 0)
582 continue;
583
Tobias Grossera535dff2015-12-13 19:59:01 +0000584 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000585 continue;
586
587 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
588
589 if (!Inst)
590 continue;
591
592 // Scop invariant hoisting moves some of the base pointers out of the scop.
593 // We can ignore these, as the invariant load hoisting already registers the
594 // relevant outside users.
595 if (!R.contains(Inst))
596 continue;
597
598 handleOutsideUsers(R, Inst, nullptr);
599 }
600}
601
Tobias Grosser27d742d2015-10-24 17:41:29 +0000602void BlockGenerator::createExitPHINodeMerges(Scop &S) {
603 if (S.hasSingleExitEdge())
604 return;
605
606 Region &R = S.getRegion();
607
608 auto *ExitBB = R.getExitingBlock();
609 auto *MergeBB = R.getExit();
610 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
611 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
612 if (OptExitBB == ExitBB)
613 OptExitBB = *(++pred_begin(MergeBB));
614
615 Builder.SetInsertPoint(OptExitBB->getTerminator());
616
617 for (auto &Pair : S.arrays()) {
618 auto &SAI = Pair.second;
619 auto *Val = SAI->getBasePtr();
620
621 PHINode *PHI = dyn_cast<PHINode>(Val);
622 if (!PHI)
623 continue;
624
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000625 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000626 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000627
628 std::string Name = PHI->getName();
629 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
630 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
631 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
632 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
633 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000634 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000635 MergePHI->addIncoming(Reload, OptExitBB);
636 MergePHI->addIncoming(OriginalValue, ExitBB);
637 int Idx = PHI->getBasicBlockIndex(MergeBB);
638 PHI->setIncomingValue(Idx, MergePHI);
639 }
640}
641
Tobias Grosserffa24462015-10-17 08:54:13 +0000642void BlockGenerator::finalizeSCoP(Scop &S) {
643 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000644 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000645 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000646 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000647}
648
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000649VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000650 std::vector<LoopToScevMapT> &VLTS,
651 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000652 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000653 assert(Schedule && "No statement domain provided");
654}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000655
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000656Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000657 ValueMapT &VectorMap,
658 VectorValueMapT &ScalarMaps,
659 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000660 if (Value *NewValue = VectorMap.lookup(Old))
661 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000662
663 int Width = getVectorWidth();
664
665 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
666
667 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000668 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000669 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000670 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000671
672 VectorMap[Old] = Vector;
673
674 return Vector;
675}
676
677Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
678 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
679 assert(PointerTy && "PointerType expected");
680
681 Type *ScalarType = PointerTy->getElementType();
682 VectorType *VectorType = VectorType::get(ScalarType, Width);
683
684 return PointerType::getUnqual(VectorType);
685}
686
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000687Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000688 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000689 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000690 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000691 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000692 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
693 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
694
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000695 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000696 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
697 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000698 Value *VectorPtr =
699 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
700 LoadInst *VecLoad =
701 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000702 if (!Aligned)
703 VecLoad->setAlignment(8);
704
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000705 if (NegativeStride) {
706 SmallVector<Constant *, 16> Indices;
707 for (int i = VectorWidth - 1; i >= 0; i--)
708 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
709 Constant *SV = llvm::ConstantVector::get(Indices);
710 Value *RevVecLoad = Builder.CreateShuffleVector(
711 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
712 return RevVecLoad;
713 }
714
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000715 return VecLoad;
716}
717
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000718Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000719 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000720 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000721 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000722 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000723 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
724 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000725 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
726 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000727 LoadInst *ScalarLoad =
728 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000729
730 if (!Aligned)
731 ScalarLoad->setAlignment(8);
732
Tobias Grosserc14582f2013-02-05 18:01:29 +0000733 Constant *SplatVector = Constant::getNullValue(
734 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000735
Tobias Grosserc14582f2013-02-05 18:01:29 +0000736 Value *VectorLoad = Builder.CreateShuffleVector(
737 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000738 return VectorLoad;
739}
740
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000741Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000742 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000743 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000744 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000745 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000746 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000747 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000748
749 Value *Vector = UndefValue::get(VectorType);
750
751 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000752 Value *NewPointer = generateLocationAccessed(
753 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000754 Value *ScalarLoad =
755 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
756 Vector = Builder.CreateInsertElement(
757 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000758 }
759
760 return Vector;
761}
762
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000763void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000764 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000765 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000766 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
767 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
768 Load->getName() + "_p");
769 return;
770 }
771
Tobias Grosser28736452015-03-23 07:00:36 +0000772 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000773 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000774 ScalarMaps[i][Load] =
775 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000776 return;
777 }
778
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000779 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000780
Tobias Grosser95493982014-04-18 09:46:35 +0000781 // Make sure we have scalar values available to access the pointer to
782 // the data location.
783 extractScalarValues(Load, VectorMap, ScalarMaps);
784
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000785 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000786 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000787 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000788 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000789 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000790 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000791 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000793 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000794
795 VectorMap[Load] = NewLoad;
796}
797
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000798void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000799 ValueMapT &VectorMap,
800 VectorValueMapT &ScalarMaps) {
801 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000802 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
803 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000804
805 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
806
807 const CastInst *Cast = dyn_cast<CastInst>(Inst);
808 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
809 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
810}
811
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000812void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000813 ValueMapT &VectorMap,
814 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000815 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000816 Value *OpZero = Inst->getOperand(0);
817 Value *OpOne = Inst->getOperand(1);
818
819 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000820 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
821 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000822
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000823 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000824 Inst->getName() + "p_vec");
825 VectorMap[Inst] = NewInst;
826}
827
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000828void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000829 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000830 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000831 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000832
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000833 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000834 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000835 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000836
Tobias Grosser50fd7012014-04-17 23:13:49 +0000837 // Make sure we have scalar values available to access the pointer to
838 // the data location.
839 extractScalarValues(Store, VectorMap, ScalarMaps);
840
Sebastian Popa00a0292012-12-18 07:46:06 +0000841 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000842 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000843 Value *NewPointer = generateLocationAccessed(
844 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000845
Tobias Grosserc14582f2013-02-05 18:01:29 +0000846 Value *VectorPtr =
847 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000848 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
849
850 if (!Aligned)
851 Store->setAlignment(8);
852 } else {
853 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000854 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000855 Value *NewPointer = generateLocationAccessed(
856 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000857 Builder.CreateStore(Scalar, NewPointer);
858 }
859 }
860}
861
862bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
863 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000864 for (Value *Operand : Inst->operands())
865 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866 return true;
867 return false;
868}
869
870bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
871 ValueMapT &VectorMap,
872 VectorValueMapT &ScalarMaps) {
873 bool HasVectorOperand = false;
874 int VectorWidth = getVectorWidth();
875
Tobias Grosser91f5b262014-06-04 08:06:40 +0000876 for (Value *Operand : Inst->operands()) {
877 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000878
879 if (VecOp == VectorMap.end())
880 continue;
881
882 HasVectorOperand = true;
883 Value *NewVector = VecOp->second;
884
885 for (int i = 0; i < VectorWidth; ++i) {
886 ValueMapT &SM = ScalarMaps[i];
887
888 // If there is one scalar extracted, all scalar elements should have
889 // already been extracted by the code here. So no need to check for the
890 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000891 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000892 break;
893
Tobias Grosser91f5b262014-06-04 08:06:40 +0000894 SM[Operand] =
895 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000896 }
897 }
898
899 return HasVectorOperand;
900}
901
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000902void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000903 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000904 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000905 bool HasVectorOperand;
906 int VectorWidth = getVectorWidth();
907
908 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
909
910 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000911 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000912 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913
914 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
915 return;
916
917 // Make the result available as vector value.
918 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
919 Value *Vector = UndefValue::get(VectorType);
920
921 for (int i = 0; i < VectorWidth; i++)
922 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
923 Builder.getInt32(i));
924
925 VectorMap[Inst] = Vector;
926}
927
Tobias Grosserbc132602015-09-05 09:56:54 +0000928int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000929
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000930void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000931 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000932 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000933 // Terminator instructions control the control flow. They are explicitly
934 // expressed in the clast and do not need to be copied.
935 if (Inst->isTerminator())
936 return;
937
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000938 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000939 return;
940
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000941 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000942 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000943 return;
944 }
945
946 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000947 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000948 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000949 return;
950 }
951
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000952 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000953 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000954 return;
955 }
956
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000957 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000958 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000959 return;
960 }
961
962 // Falltrough: We generate scalar instructions, if we don't know how to
963 // generate vector code.
964 }
965
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000966 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000967}
968
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000969void VectorBlockGenerator::copyStmt(
970 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000971 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
972 "the vector block generator");
973
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000974 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000975 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
976 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000977 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000978 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000979
980 // Create two maps that store the mapping from the original instructions of
981 // the old basic block to their copies in the new basic block. Those maps
982 // are basic block local.
983 //
984 // As vector code generation is supported there is one map for scalar values
985 // and one for vector values.
986 //
987 // In case we just do scalar code generation, the vectorMap is not used and
988 // the scalarMap has just one dimension, which contains the mapping.
989 //
990 // In case vector code generation is done, an instruction may either appear
991 // in the vector map once (as it is calculating >vectorwidth< values at a
992 // time. Or (if the values are calculated using scalar operations), it
993 // appears once in every dimension of the scalarMap.
994 VectorValueMapT ScalarBlockMap(getVectorWidth());
995 ValueMapT VectorBlockMap;
996
Tobias Grosser91f5b262014-06-04 08:06:40 +0000997 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000998 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000999}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001000
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001001BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1002 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001003
1004 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1005 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1006
1007 if (BBCopyIDom)
1008 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1009
1010 return BBCopyIDom;
1011}
1012
Tobias Grosserbc132602015-09-05 09:56:54 +00001013void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001014 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001015 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001016 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001017
Michael Krused6fb6f12015-11-09 23:07:38 +00001018 Scop *S = Stmt.getParent();
1019
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001020 // Forget all old mappings.
1021 BlockMap.clear();
1022 RegionMaps.clear();
1023 IncompletePHINodeMap.clear();
1024
Michael Kruse225f0d12015-10-17 21:36:00 +00001025 // Collection of all values related to this subregion.
1026 ValueMapT ValueMap;
1027
Johannes Doerfert275a1752015-02-24 16:16:32 +00001028 // The region represented by the statement.
1029 Region *R = Stmt.getRegion();
1030
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001031 // Create a dedicated entry for the region where we can reload all demoted
1032 // inputs.
1033 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001034 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1035 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001036 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001037 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001038
Michael Krusec9937392015-11-09 23:33:40 +00001039 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1040 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001041
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001042 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1043 if (!R->contains(*PI))
1044 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001045
Michael Krused6fb6f12015-11-09 23:07:38 +00001046 // Determine the original exit block of this subregion. If it the exit block
1047 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1048 // We move one block back to find the original block. This only happens if the
1049 // scop required simplification.
1050 // If the whole scop consists of only this non-affine region, then they share
1051 // the same Region object, such that we cannot change the exit of one and not
1052 // the other.
1053 BasicBlock *ExitBB = R->getExit();
1054 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1055 ExitBB = *(++pred_begin(ExitBB));
1056
Johannes Doerfert275a1752015-02-24 16:16:32 +00001057 // Iterate over all blocks in the region in a breadth-first search.
1058 std::deque<BasicBlock *> Blocks;
1059 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001060 Blocks.push_back(EntryBB);
1061 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001062
1063 while (!Blocks.empty()) {
1064 BasicBlock *BB = Blocks.front();
1065 Blocks.pop_front();
1066
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001067 // First split the block and update dominance information.
1068 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001069 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1070
1071 // In order to remap PHI nodes we store also basic block mappings.
1072 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001073
Michael Krusec9937392015-11-09 23:33:40 +00001074 // Get the mapping for this block and initialize it with either the scalar
1075 // loads from the generated entering block (which dominates all blocks of
1076 // this subregion) or the maps of the immediate dominator, if part of the
1077 // subregion. The latter necessarily includes the former.
1078 ValueMapT *InitBBMap;
1079 if (BBCopyIDom) {
1080 assert(RegionMaps.count(BBCopyIDom));
1081 InitBBMap = &RegionMaps[BBCopyIDom];
1082 } else
1083 InitBBMap = &EntryBBMap;
1084 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1085 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001086
Johannes Doerfert275a1752015-02-24 16:16:32 +00001087 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001088 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001089 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001090
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001091 // In order to remap PHI nodes we store also basic block mappings.
1092 BlockMap[BB] = BBCopy;
1093
1094 // Add values to incomplete PHI nodes waiting for this block to be copied.
1095 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001096 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001097 IncompletePHINodeMap[BB].clear();
1098
Johannes Doerfert275a1752015-02-24 16:16:32 +00001099 // And continue with new successors inside the region.
1100 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1101 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1102 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001103
1104 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001105 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001106 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001107 }
1108
1109 // Now create a new dedicated region exit block and add it to the region map.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001110 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1111 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001112 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001113 BlockMap[R->getExit()] = ExitBBCopy;
1114
Michael Krused6fb6f12015-11-09 23:07:38 +00001115 if (ExitBB == R->getExit())
1116 repairDominance(ExitBB, ExitBBCopy);
1117 else
1118 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001119
1120 // As the block generator doesn't handle control flow we need to add the
1121 // region control flow by hand after all blocks have been copied.
1122 for (BasicBlock *BB : SeenBlocks) {
1123
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001124 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001125 TerminatorInst *TI = BB->getTerminator();
1126 if (isa<UnreachableInst>(TI)) {
1127 while (!BBCopy->empty())
1128 BBCopy->begin()->eraseFromParent();
1129 new UnreachableInst(BBCopy->getContext(), BBCopy);
1130 continue;
1131 }
1132
Johannes Doerfert275a1752015-02-24 16:16:32 +00001133 Instruction *BICopy = BBCopy->getTerminator();
1134
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001135 ValueMapT &RegionMap = RegionMaps[BBCopy];
1136 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1137
Tobias Grosser45e79442015-08-01 09:07:57 +00001138 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001139 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001140 BICopy->eraseFromParent();
1141 }
1142
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001143 // Add counting PHI nodes to all loops in the region that can be used as
1144 // replacement for SCEVs refering to the old loop.
1145 for (BasicBlock *BB : SeenBlocks) {
1146 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001147 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001148 continue;
1149
1150 BasicBlock *BBCopy = BlockMap[BB];
1151 Value *NullVal = Builder.getInt32(0);
1152 PHINode *LoopPHI =
1153 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1154 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1155 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001156 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001157 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1158
1159 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1160 if (!R->contains(PredBB))
1161 continue;
1162 if (L->contains(PredBB))
1163 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1164 else
1165 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1166 }
1167
1168 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1169 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1170 LoopPHI->addIncoming(NullVal, PredBBCopy);
1171
1172 LTS[L] = SE.getUnknown(LoopPHI);
1173 }
1174
Michael Kruse225f0d12015-10-17 21:36:00 +00001175 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001176 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001177
1178 // Write values visible to other statements.
1179 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001180 BlockMap.clear();
1181 RegionMaps.clear();
1182 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001183}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001184
Michael Kruse225f0d12015-10-17 21:36:00 +00001185void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001186 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001187 const Region &R = Stmt.getParent()->getRegion();
1188
Tobias Grosser75296902015-08-21 19:23:21 +00001189 assert(Stmt.getRegion() &&
1190 "Block statements need to use the generateScalarStores() "
1191 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001192
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001193 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001194 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001195 continue;
1196
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001197 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001198 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001199
Michael Kruse225f0d12015-10-17 21:36:00 +00001200 // In case we add the store into an exiting block, we need to restore the
1201 // position for stores in the exit node.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001202 BasicBlock *SavedInsertBB = Builder.GetInsertBlock();
Michael Kruse225f0d12015-10-17 21:36:00 +00001203 auto SavedInsertionPoint = Builder.GetInsertPoint();
Michael Kruse27149cf2015-11-05 16:17:17 +00001204 ValueMapT *LocalBBMap = &BBMap;
Michael Kruse225f0d12015-10-17 21:36:00 +00001205
Tobias Grossera535dff2015-12-13 19:59:01 +00001206 // Scalar writes induced by PHIs must be written in the incoming blocks.
1207 if (MA->isPHIKind() || MA->isExitPHIKind()) {
Michael Kruse225f0d12015-10-17 21:36:00 +00001208 BasicBlock *ExitingBB = ScalarInst->getParent();
1209 BasicBlock *ExitingBBCopy = BlockMap[ExitingBB];
1210 Builder.SetInsertPoint(ExitingBBCopy->getTerminator());
Michael Kruse27149cf2015-11-05 16:17:17 +00001211
1212 // For the incoming blocks, use the block's BBMap instead of the one for
1213 // the entire region.
1214 LocalBBMap = &RegionMaps[ExitingBBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001215 }
1216
Tobias Grosserbc132602015-09-05 09:56:54 +00001217 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001218
Michael Kruse27149cf2015-11-05 16:17:17 +00001219 Val = getNewScalarValue(Val, R, Stmt, LTS, *LocalBBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001220 Builder.CreateStore(Val, Address);
Michael Kruse225f0d12015-10-17 21:36:00 +00001221
1222 // Restore the insertion point if necessary.
Tobias Grossera535dff2015-12-13 19:59:01 +00001223 if (MA->isPHIKind() || MA->isExitPHIKind())
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001224 Builder.SetInsertPoint(SavedInsertBB, SavedInsertionPoint);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001225 }
1226}
1227
1228void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1229 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001230 LoopToScevMapT &LTS) {
1231 Region *StmtR = Stmt.getRegion();
1232
1233 // If the incoming block was not yet copied mark this PHI as incomplete.
1234 // Once the block will be copied the incoming value will be added.
1235 BasicBlock *BBCopy = BlockMap[IncomingBB];
1236 if (!BBCopy) {
1237 assert(StmtR->contains(IncomingBB) &&
1238 "Bad incoming block for PHI in non-affine region");
1239 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1240 return;
1241 }
1242
1243 Value *OpCopy = nullptr;
1244 if (StmtR->contains(IncomingBB)) {
1245 assert(RegionMaps.count(BBCopy) &&
1246 "Incoming PHI block did not have a BBMap");
1247 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1248
1249 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001250
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001251 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001252 auto OldIP = Builder.GetInsertPoint();
1253 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001254 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001255 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001256 } else {
1257
1258 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1259 return;
1260
Tobias Grosserbc132602015-09-05 09:56:54 +00001261 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001262 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1263 BlockMap[IncomingBB]->getTerminator());
1264 }
1265
1266 assert(OpCopy && "Incoming PHI value was not copied properly");
1267 assert(BBCopy && "Incoming PHI block was not copied properly");
1268 PHICopy->addIncoming(OpCopy, BBCopy);
1269}
1270
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001271Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001272 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001273 LoopToScevMapT &LTS) {
1274 unsigned NumIncoming = PHI->getNumIncomingValues();
1275 PHINode *PHICopy =
1276 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1277 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1278 BBMap[PHI] = PHICopy;
1279
1280 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001281 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001282 return PHICopy;
1283}