blob: b29e78471a26675602d4b7c1559faab0d995b670 [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
Hongbin Zheng8a846612012-04-25 13:18:28 +000016#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000017#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000018#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser86bc93a2015-09-06 08:47:57 +000019#include "polly/CodeGen/RuntimeDebugBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000020#include "polly/Options.h"
Tobias Grosser5624d3c2015-12-21 12:38:56 +000021#include "polly/ScopInfo.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 {
Johannes Doerfert42df8d12015-12-22 19:08:01 +000066 if (!SE.isSCEVable(Old->getType()))
67 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000068
Johannes Doerfert42df8d12015-12-22 19:08:01 +000069 const SCEV *Scev = SE.getSCEVAtScope(Old, L);
70 if (!Scev)
71 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000072
Johannes Doerfert42df8d12015-12-22 19:08:01 +000073 if (isa<SCEVCouldNotCompute>(Scev))
74 return nullptr;
Tobias Grossere71c6ab2012-04-27 16:36:14 +000075
Johannes Doerfert42df8d12015-12-22 19:08:01 +000076 const SCEV *NewScev = apply(Scev, LTS, SE);
77 ValueMapT VTV;
78 VTV.insert(BBMap.begin(), BBMap.end());
79 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Tobias Grossere71c6ab2012-04-27 16:36:14 +000080
Johannes Doerfert42df8d12015-12-22 19:08:01 +000081 Scop &S = *Stmt.getParent();
82 const DataLayout &DL =
83 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
84 auto IP = Builder.GetInsertPoint();
85
86 assert(IP != Builder.GetInsertBlock()->end() &&
87 "Only instructions can be insert points for SCEVExpander");
88 Value *Expanded =
89 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV);
90
91 BBMap[Old] = Expanded;
92 return Expanded;
Tobias Grosser33cb9f92015-09-30 11:56:19 +000093}
94
Tobias Grosser2f1acac2015-10-04 10:18:45 +000095Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
96 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000097 // Constants that do not reference any named value can always remain
Michael Kruse5bbc0e12015-12-14 23:41:32 +000098 // unchanged. Handle them early to avoid expensive map lookups. We do not take
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000099 // the fast-path for external constants which are referenced through globals
100 // as these may need to be rewritten when distributing code accross different
101 // LLVM modules.
102 if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000103 return Old;
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000104
Johannes Doerfert28f8ac12015-12-22 19:08:24 +0000105 // Inline asm is like a constant to us.
106 if (isa<InlineAsm>(Old))
107 return Old;
108
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000109 if (Value *New = GlobalMap.lookup(Old)) {
110 if (Value *NewRemapped = GlobalMap.lookup(New))
111 New = NewRemapped;
112 if (Old->getType()->getScalarSizeInBits() <
113 New->getType()->getScalarSizeInBits())
114 New = Builder.CreateTruncOrBitCast(New, Old->getType());
115
116 return New;
117 }
118
119 if (Value *New = BBMap.lookup(Old))
120 return New;
121
122 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
123 return New;
124
Tobias Grosser16371ac2014-11-05 20:48:56 +0000125 // A scop-constant value defined by a global or a function parameter.
126 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000127 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000128
129 // A scop-constant value defined by an instruction executed outside the scop.
130 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000131 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000132 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000133
134 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000135 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000136 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000137}
138
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000139void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000140 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000141 // We do not generate debug intrinsics as we did not investigate how to
142 // copy them correctly. At the current state, they just crash the code
143 // generation as the meta-data operands are not correctly copied.
144 if (isa<DbgInfoIntrinsic>(Inst))
145 return;
146
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000147 Instruction *NewInst = Inst->clone();
148
149 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000150 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000151 Value *NewOperand =
152 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000153
154 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000155 assert(!isa<StoreInst>(NewInst) &&
156 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000157 delete NewInst;
158 return;
159 }
160
161 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
162 }
163
164 Builder.Insert(NewInst);
165 BBMap[Inst] = NewInst;
166
167 if (!NewInst->getType()->isVoidTy())
168 NewInst->setName("p_" + Inst->getName());
169}
170
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000171Value *BlockGenerator::generateLocationAccessed(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000172 ScopStmt &Stmt, const Instruction *Inst, Value *Pointer, ValueMapT &BBMap,
173 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000174 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000175
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000176 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000177
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000178 if (AccessExpr) {
179 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000180 auto Address = ExprBuilder->create(AccessExpr);
181
182 // Cast the address of this memory access to a pointer type that has the
183 // same element type as the original access, but uses the address space of
184 // the newly generated pointer.
185 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
186 auto NewPtrTy = Address->getType();
187 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
188 NewPtrTy->getPointerAddressSpace());
189
190 if (OldPtrTy != NewPtrTy) {
191 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
192 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
193 "Pointer types to elements with different size found");
194 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
195 }
196 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000197 }
198
Tobias Grosserbc132602015-09-05 09:56:54 +0000199 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000200}
201
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000202Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000203 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000204}
205
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000206Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000207 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000208 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000209 if (Value *PreloadLoad = GlobalMap.lookup(Load))
210 return PreloadLoad;
211
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000212 auto *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000213 Value *NewPointer =
214 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000215 Value *ScalarLoad = Builder.CreateAlignedLoad(
216 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000217
218 if (DebugPrinting)
219 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
220 ": ", ScalarLoad, "\n");
221
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000222 return ScalarLoad;
223}
224
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000225void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000226 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000227 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000228 auto *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 Value *NewPointer =
230 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
231 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
232 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000233
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000234 if (DebugPrinting)
235 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
236 ": ", ValueOperand, "\n");
237
Tobias Grosserc186ac72015-08-11 08:13:15 +0000238 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000239}
240
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000241void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000242 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000243 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000244 // Terminator instructions control the control flow. They are explicitly
245 // expressed in the clast and do not need to be copied.
246 if (Inst->isTerminator())
247 return;
248
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000249 Loop *L = getLoopForInst(Inst);
250 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
251 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000252 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000253 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000254 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000255
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000256 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000257 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000258 // Compute NewLoad before its insertion in BBMap to make the insertion
259 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000260 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000261 return;
262 }
263
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000264 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000265 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000266 return;
267 }
268
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000269 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000270 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000271 return;
272 }
273
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000274 // Skip some special intrinsics for which we do not adjust the semantics to
275 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000276 if (isIgnoredIntrinsic(Inst))
277 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000278
Tobias Grosserbc132602015-09-05 09:56:54 +0000279 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000280}
281
Tobias Grosserbc132602015-09-05 09:56:54 +0000282void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000283 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000284 assert(Stmt.isBlockStmt() &&
285 "Only block statements can be copied by the block generator");
286
287 ValueMapT BBMap;
288
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000289 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000290 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000291}
292
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000293BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000294 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
295 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000296 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000297 return CopyBB;
298}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000299
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000300BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000301 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000302 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000303 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000304 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000305 generateScalarLoads(Stmt, BBMap);
306
Tobias Grosserbc132602015-09-05 09:56:54 +0000307 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000308
309 // After a basic block was copied store all scalars that escape this block in
310 // their alloca.
311 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000312 return CopyBB;
313}
314
315void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000316 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000317 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000318 EntryBB = &CopyBB->getParent()->getEntryBlock();
319
Tobias Grosser91f5b262014-06-04 08:06:40 +0000320 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000321 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000322}
323
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000324Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
325 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000326 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000327 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000328 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000329 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000330 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000331 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000332 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000333 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000334 }
335
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000336 auto Addr = Map[ScalarBase];
337
Tobias Grosserbc132602015-09-05 09:56:54 +0000338 if (GlobalMap.count(Addr))
339 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000340
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000341 return Addr;
342}
343
Tobias Grosserbc132602015-09-05 09:56:54 +0000344Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000345 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000346 return getOrCreatePHIAlloca(Access.getBaseAddr());
347 else
348 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000349}
350
351Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000352 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000353 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000354 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000355 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000356}
357
Tobias Grosserbc132602015-09-05 09:56:54 +0000358Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
359 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000360}
361
Tobias Grosserbc132602015-09-05 09:56:54 +0000362Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
363 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000364}
365
Tobias Grosserbc132602015-09-05 09:56:54 +0000366void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000367 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000368 // If there are escape users we get the alloca for this instruction and put it
369 // in the EscapeMap for later finalization. Lastly, if the instruction was
370 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000371 if (EscapeMap.count(Inst))
372 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000373
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000374 EscapeUserVectorTy EscapeUsers;
375 for (User *U : Inst->users()) {
376
377 // Non-instruction user will never escape.
378 Instruction *UI = dyn_cast<Instruction>(U);
379 if (!UI)
380 continue;
381
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000382 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000383 continue;
384
385 EscapeUsers.push_back(UI);
386 }
387
388 // Exit if no escape uses were found.
389 if (EscapeUsers.empty())
390 return;
391
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000392 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000393 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000394
395 // Remember that this instruction has escape uses and the escape alloca.
396 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000397}
398
Michael Kruse225f0d12015-10-17 21:36:00 +0000399void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
400 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000401 if (MA->isArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000402 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000403
Michael Krusee2bccbb2015-09-18 19:59:43 +0000404 auto *Address = getOrCreateAlloca(*MA);
405 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000406 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000407 }
408}
409
410Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000411 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000412 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000413 // If the value we want to store is an instruction we might have demoted it
414 // in order to make it accessible here. In such a case a reload is
415 // necessary. If it is no instruction it will always be a value that
416 // dominates the current point and we can just use it. In total there are 4
417 // options:
418 // (1) The value is no instruction ==> use the value.
419 // (2) The value is an instruction that was split out of the region prior to
420 // code generation ==> use the instruction as it dominates the region.
421 // (3) The value is an instruction:
422 // (a) The value was defined in the current block, thus a copy is in
423 // the BBMap ==> use the mapped value.
424 // (b) The value was defined in a previous block, thus we demoted it
425 // earlier ==> use the reloaded value.
426 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
427 if (!ScalarValueInst)
428 return ScalarValue;
429
430 if (!R.contains(ScalarValueInst)) {
431 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
432 return /* Case (3a) */ ScalarValueCopy;
433 else
434 return /* Case 2 */ ScalarValue;
435 }
436
437 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
438 return /* Case (3a) */ ScalarValueCopy;
439
Tobias Grosseraff56c82015-09-30 13:36:54 +0000440 if ((Stmt.isBlockStmt() &&
441 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
442 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
443 auto SynthesizedValue = trySynthesizeNewValue(
444 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
445
446 if (SynthesizedValue)
447 return SynthesizedValue;
448 }
449
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000450 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000451 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000452 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000453
454 return ScalarValue;
455}
456
Michael Kruse225f0d12015-10-17 21:36:00 +0000457void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000458 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000459 const Region &R = Stmt.getParent()->getRegion();
460
Michael Kruse225f0d12015-10-17 21:36:00 +0000461 assert(Stmt.isBlockStmt() && "Region statements need to use the "
462 "generateScalarStores() function in the "
463 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000464
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000465 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000466 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000467 continue;
468
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000469 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000470 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000471
Tobias Grosseraff56c82015-09-30 13:36:54 +0000472 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000473 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000474 }
475}
476
Tobias Grosserc0091a72015-08-30 19:19:34 +0000477void BlockGenerator::createScalarInitialization(Scop &S) {
478 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000479 BasicBlock *ExitBB = R.getExit();
480
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000481 // The split block __just before__ the region and optimized region.
482 BasicBlock *SplitBB = R.getEnteringBlock();
483 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
484 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
485
486 // Get the start block of the __optimized__ region.
487 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
488 if (StartBB == R.getEntry())
489 StartBB = SplitBBTerm->getSuccessor(1);
490
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000491 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000492
Tobias Grosserc0091a72015-08-30 19:19:34 +0000493 for (auto &Pair : S.arrays()) {
494 auto &Array = Pair.second;
495 if (Array->getNumberOfDimensions() != 0)
496 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000497 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000498 // For PHI nodes, the only values we need to store are the ones that
499 // reach the PHI node from outside the region. In general there should
500 // only be one such incoming edge and this edge should enter through
501 // 'SplitBB'.
502 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000503
Tobias Grosserc0091a72015-08-30 19:19:34 +0000504 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
505 if (!R.contains(*BI) && *BI != SplitBB)
506 llvm_unreachable("Incoming edges from outside the scop should always "
507 "come from SplitBB");
508
509 int Idx = PHI->getBasicBlockIndex(SplitBB);
510 if (Idx < 0)
511 continue;
512
513 Value *ScalarValue = PHI->getIncomingValue(Idx);
514
Tobias Grosserbc132602015-09-05 09:56:54 +0000515 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000516 continue;
517 }
518
519 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
520
521 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000522 continue;
523
Johannes Doerfert188542f2015-11-09 00:21:21 +0000524 // PHI nodes that are not marked as such in their SAI object are either exit
525 // PHI nodes we model as common scalars but without initialization, or
526 // incoming phi nodes that need to be initialized. Check if the first is the
527 // case for Inst and do not create and initialize memory if so.
528 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
529 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
530 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000531
Tobias Grosserc0091a72015-08-30 19:19:34 +0000532 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000533 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000534 }
535}
536
537void BlockGenerator::createScalarFinalization(Region &R) {
538 // The exit block of the __unoptimized__ region.
539 BasicBlock *ExitBB = R.getExitingBlock();
540 // The merge block __just after__ the region and the optimized region.
541 BasicBlock *MergeBB = R.getExit();
542
543 // The exit block of the __optimized__ region.
544 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
545 if (OptExitBB == ExitBB)
546 OptExitBB = *(++pred_begin(MergeBB));
547
548 Builder.SetInsertPoint(OptExitBB->getTerminator());
549 for (const auto &EscapeMapping : EscapeMap) {
550 // Extract the escaping instruction and the escaping users as well as the
551 // alloca the instruction was demoted to.
552 Instruction *EscapeInst = EscapeMapping.getFirst();
553 const auto &EscapeMappingValue = EscapeMapping.getSecond();
554 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000555 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000556
557 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000558 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000559 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000560 EscapeInstReload =
561 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000562
563 // Create the merge PHI that merges the optimized and unoptimized version.
564 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
565 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000566 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000567
568 // Add the respective values to the merge PHI.
569 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
570 MergePHI->addIncoming(EscapeInst, ExitBB);
571
572 // The information of scalar evolution about the escaping instruction needs
573 // to be revoked so the new merged instruction will be used.
574 if (SE.isSCEVable(EscapeInst->getType()))
575 SE.forgetValue(EscapeInst);
576
577 // Replace all uses of the demoted instruction with the merge PHI.
578 for (Instruction *EUser : EscapeUsers)
579 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
580 }
581}
582
Tobias Grosserffa24462015-10-17 08:54:13 +0000583void BlockGenerator::findOutsideUsers(Scop &S) {
584 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000585 for (auto &Pair : S.arrays()) {
586 auto &Array = Pair.second;
587
588 if (Array->getNumberOfDimensions() != 0)
589 continue;
590
Tobias Grossera535dff2015-12-13 19:59:01 +0000591 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000592 continue;
593
594 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
595
596 if (!Inst)
597 continue;
598
599 // Scop invariant hoisting moves some of the base pointers out of the scop.
600 // We can ignore these, as the invariant load hoisting already registers the
601 // relevant outside users.
602 if (!R.contains(Inst))
603 continue;
604
605 handleOutsideUsers(R, Inst, nullptr);
606 }
607}
608
Tobias Grosser27d742d2015-10-24 17:41:29 +0000609void BlockGenerator::createExitPHINodeMerges(Scop &S) {
610 if (S.hasSingleExitEdge())
611 return;
612
613 Region &R = S.getRegion();
614
615 auto *ExitBB = R.getExitingBlock();
616 auto *MergeBB = R.getExit();
617 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
618 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
619 if (OptExitBB == ExitBB)
620 OptExitBB = *(++pred_begin(MergeBB));
621
622 Builder.SetInsertPoint(OptExitBB->getTerminator());
623
624 for (auto &Pair : S.arrays()) {
625 auto &SAI = Pair.second;
626 auto *Val = SAI->getBasePtr();
627
628 PHINode *PHI = dyn_cast<PHINode>(Val);
629 if (!PHI)
630 continue;
631
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000632 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000633 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000634
635 std::string Name = PHI->getName();
636 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
637 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
638 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
639 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
640 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000641 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000642 MergePHI->addIncoming(Reload, OptExitBB);
643 MergePHI->addIncoming(OriginalValue, ExitBB);
644 int Idx = PHI->getBasicBlockIndex(MergeBB);
645 PHI->setIncomingValue(Idx, MergePHI);
646 }
647}
648
Tobias Grosserffa24462015-10-17 08:54:13 +0000649void BlockGenerator::finalizeSCoP(Scop &S) {
650 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000651 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000652 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000653 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000654}
655
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000656VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000657 std::vector<LoopToScevMapT> &VLTS,
658 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000659 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000660 assert(Schedule && "No statement domain provided");
661}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000662
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000663Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000664 ValueMapT &VectorMap,
665 VectorValueMapT &ScalarMaps,
666 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000667 if (Value *NewValue = VectorMap.lookup(Old))
668 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000669
670 int Width = getVectorWidth();
671
672 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
673
674 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000675 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000676 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000677 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000678
679 VectorMap[Old] = Vector;
680
681 return Vector;
682}
683
684Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
685 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
686 assert(PointerTy && "PointerType expected");
687
688 Type *ScalarType = PointerTy->getElementType();
689 VectorType *VectorType = VectorType::get(ScalarType, Width);
690
691 return PointerType::getUnqual(VectorType);
692}
693
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000694Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000695 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000696 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000697 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000698 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000699 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
700 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
701
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000702 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000703 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
704 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000705 Value *VectorPtr =
706 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
707 LoadInst *VecLoad =
708 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000709 if (!Aligned)
710 VecLoad->setAlignment(8);
711
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000712 if (NegativeStride) {
713 SmallVector<Constant *, 16> Indices;
714 for (int i = VectorWidth - 1; i >= 0; i--)
715 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
716 Constant *SV = llvm::ConstantVector::get(Indices);
717 Value *RevVecLoad = Builder.CreateShuffleVector(
718 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
719 return RevVecLoad;
720 }
721
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000722 return VecLoad;
723}
724
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000725Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000726 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000727 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000728 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000729 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000730 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
731 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
733 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000734 LoadInst *ScalarLoad =
735 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000736
737 if (!Aligned)
738 ScalarLoad->setAlignment(8);
739
Tobias Grosserc14582f2013-02-05 18:01:29 +0000740 Constant *SplatVector = Constant::getNullValue(
741 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000742
Tobias Grosserc14582f2013-02-05 18:01:29 +0000743 Value *VectorLoad = Builder.CreateShuffleVector(
744 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000745 return VectorLoad;
746}
747
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000748Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000749 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000750 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000751 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000752 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000753 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000754 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000755
756 Value *Vector = UndefValue::get(VectorType);
757
758 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000759 Value *NewPointer = generateLocationAccessed(
760 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000761 Value *ScalarLoad =
762 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
763 Vector = Builder.CreateInsertElement(
764 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000765 }
766
767 return Vector;
768}
769
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000770void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000771 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000772 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000773 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
774 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
775 Load->getName() + "_p");
776 return;
777 }
778
Tobias Grosser28736452015-03-23 07:00:36 +0000779 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000780 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000781 ScalarMaps[i][Load] =
782 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783 return;
784 }
785
Tobias Grosser184a4922015-12-15 23:50:01 +0000786 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787
Tobias Grosser95493982014-04-18 09:46:35 +0000788 // Make sure we have scalar values available to access the pointer to
789 // the data location.
790 extractScalarValues(Load, VectorMap, ScalarMaps);
791
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000793 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000794 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000795 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000796 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000797 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000798 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000799 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000800 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000801
802 VectorMap[Load] = NewLoad;
803}
804
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000805void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806 ValueMapT &VectorMap,
807 VectorValueMapT &ScalarMaps) {
808 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000809 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
810 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000811
812 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
813
814 const CastInst *Cast = dyn_cast<CastInst>(Inst);
815 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
816 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
817}
818
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000819void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000820 ValueMapT &VectorMap,
821 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000822 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000823 Value *OpZero = Inst->getOperand(0);
824 Value *OpOne = Inst->getOperand(1);
825
826 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000827 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
828 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000830 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000831 Inst->getName() + "p_vec");
832 VectorMap[Inst] = NewInst;
833}
834
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000835void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000836 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000837 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000838 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000839
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000840 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000841 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000842 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000843
Tobias Grosser50fd7012014-04-17 23:13:49 +0000844 // Make sure we have scalar values available to access the pointer to
845 // the data location.
846 extractScalarValues(Store, VectorMap, ScalarMaps);
847
Sebastian Popa00a0292012-12-18 07:46:06 +0000848 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000849 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000850 Value *NewPointer = generateLocationAccessed(
851 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000852
Tobias Grosserc14582f2013-02-05 18:01:29 +0000853 Value *VectorPtr =
854 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000855 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
856
857 if (!Aligned)
858 Store->setAlignment(8);
859 } else {
860 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000861 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000862 Value *NewPointer = generateLocationAccessed(
863 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000864 Builder.CreateStore(Scalar, NewPointer);
865 }
866 }
867}
868
869bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
870 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000871 for (Value *Operand : Inst->operands())
872 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000873 return true;
874 return false;
875}
876
877bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
878 ValueMapT &VectorMap,
879 VectorValueMapT &ScalarMaps) {
880 bool HasVectorOperand = false;
881 int VectorWidth = getVectorWidth();
882
Tobias Grosser91f5b262014-06-04 08:06:40 +0000883 for (Value *Operand : Inst->operands()) {
884 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000885
886 if (VecOp == VectorMap.end())
887 continue;
888
889 HasVectorOperand = true;
890 Value *NewVector = VecOp->second;
891
892 for (int i = 0; i < VectorWidth; ++i) {
893 ValueMapT &SM = ScalarMaps[i];
894
895 // If there is one scalar extracted, all scalar elements should have
896 // already been extracted by the code here. So no need to check for the
897 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000898 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000899 break;
900
Tobias Grosser91f5b262014-06-04 08:06:40 +0000901 SM[Operand] =
902 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000903 }
904 }
905
906 return HasVectorOperand;
907}
908
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000909void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000910 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000911 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000912 bool HasVectorOperand;
913 int VectorWidth = getVectorWidth();
914
915 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
916
917 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000918 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000919 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000920
921 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
922 return;
923
924 // Make the result available as vector value.
925 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
926 Value *Vector = UndefValue::get(VectorType);
927
928 for (int i = 0; i < VectorWidth; i++)
929 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
930 Builder.getInt32(i));
931
932 VectorMap[Inst] = Vector;
933}
934
Tobias Grosserbc132602015-09-05 09:56:54 +0000935int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000936
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000937void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000938 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000939 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000940 // Terminator instructions control the control flow. They are explicitly
941 // expressed in the clast and do not need to be copied.
942 if (Inst->isTerminator())
943 return;
944
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000945 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000946 return;
947
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000948 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000949 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000950 return;
951 }
952
953 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000954 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000955 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000956 return;
957 }
958
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000959 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000960 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000961 return;
962 }
963
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000964 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000965 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000966 return;
967 }
968
969 // Falltrough: We generate scalar instructions, if we don't know how to
970 // generate vector code.
971 }
972
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000973 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000974}
975
Tobias Grossera69d4f02015-12-15 23:49:58 +0000976void VectorBlockGenerator::generateScalarVectorLoads(
977 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
978 for (MemoryAccess *MA : Stmt) {
979 if (MA->isArrayKind() || MA->isWrite())
980 continue;
981
982 auto *Address = getOrCreateAlloca(*MA);
983 Type *VectorPtrType = getVectorPtrTy(Address, 1);
984 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
985 Address->getName() + "_p_vec_p");
986 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
987 Constant *SplatVector = Constant::getNullValue(
988 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
989
990 Value *VectorVal = Builder.CreateShuffleVector(
991 Val, Val, SplatVector, Address->getName() + "_p_splat");
992 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
993 VectorVal->dump();
994 }
995}
996
997void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
998 for (MemoryAccess *MA : Stmt) {
999 if (MA->isArrayKind() || MA->isRead())
1000 continue;
1001
1002 llvm_unreachable("Scalar stores not expected in vector loop");
1003 }
1004}
1005
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001006void VectorBlockGenerator::copyStmt(
1007 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001008 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
1009 "the vector block generator");
1010
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001011 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001012 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1013 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001014 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001015 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001016
1017 // Create two maps that store the mapping from the original instructions of
1018 // the old basic block to their copies in the new basic block. Those maps
1019 // are basic block local.
1020 //
1021 // As vector code generation is supported there is one map for scalar values
1022 // and one for vector values.
1023 //
1024 // In case we just do scalar code generation, the vectorMap is not used and
1025 // the scalarMap has just one dimension, which contains the mapping.
1026 //
1027 // In case vector code generation is done, an instruction may either appear
1028 // in the vector map once (as it is calculating >vectorwidth< values at a
1029 // time. Or (if the values are calculated using scalar operations), it
1030 // appears once in every dimension of the scalarMap.
1031 VectorValueMapT ScalarBlockMap(getVectorWidth());
1032 ValueMapT VectorBlockMap;
1033
Tobias Grossera69d4f02015-12-15 23:49:58 +00001034 generateScalarVectorLoads(Stmt, VectorBlockMap);
1035
Tobias Grosser91f5b262014-06-04 08:06:40 +00001036 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001037 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001038
1039 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001040}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001041
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001042BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1043 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001044
1045 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1046 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1047
1048 if (BBCopyIDom)
1049 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1050
1051 return BBCopyIDom;
1052}
1053
Tobias Grosserbc132602015-09-05 09:56:54 +00001054void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001055 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001056 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001057 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001058
Michael Krused6fb6f12015-11-09 23:07:38 +00001059 Scop *S = Stmt.getParent();
1060
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001061 // Forget all old mappings.
1062 BlockMap.clear();
1063 RegionMaps.clear();
1064 IncompletePHINodeMap.clear();
1065
Michael Kruse225f0d12015-10-17 21:36:00 +00001066 // Collection of all values related to this subregion.
1067 ValueMapT ValueMap;
1068
Johannes Doerfert275a1752015-02-24 16:16:32 +00001069 // The region represented by the statement.
1070 Region *R = Stmt.getRegion();
1071
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001072 // Create a dedicated entry for the region where we can reload all demoted
1073 // inputs.
1074 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001075 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1076 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001077 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001078 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001079
Michael Krusec9937392015-11-09 23:33:40 +00001080 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1081 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001082
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001083 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1084 if (!R->contains(*PI))
1085 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001086
Michael Krused6fb6f12015-11-09 23:07:38 +00001087 // Determine the original exit block of this subregion. If it the exit block
1088 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1089 // We move one block back to find the original block. This only happens if the
1090 // scop required simplification.
1091 // If the whole scop consists of only this non-affine region, then they share
1092 // the same Region object, such that we cannot change the exit of one and not
1093 // the other.
1094 BasicBlock *ExitBB = R->getExit();
1095 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1096 ExitBB = *(++pred_begin(ExitBB));
1097
Johannes Doerfert275a1752015-02-24 16:16:32 +00001098 // Iterate over all blocks in the region in a breadth-first search.
1099 std::deque<BasicBlock *> Blocks;
1100 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001101 Blocks.push_back(EntryBB);
1102 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001103
1104 while (!Blocks.empty()) {
1105 BasicBlock *BB = Blocks.front();
1106 Blocks.pop_front();
1107
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001108 // First split the block and update dominance information.
1109 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001110 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1111
1112 // In order to remap PHI nodes we store also basic block mappings.
1113 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001114
Michael Krusec9937392015-11-09 23:33:40 +00001115 // Get the mapping for this block and initialize it with either the scalar
1116 // loads from the generated entering block (which dominates all blocks of
1117 // this subregion) or the maps of the immediate dominator, if part of the
1118 // subregion. The latter necessarily includes the former.
1119 ValueMapT *InitBBMap;
1120 if (BBCopyIDom) {
1121 assert(RegionMaps.count(BBCopyIDom));
1122 InitBBMap = &RegionMaps[BBCopyIDom];
1123 } else
1124 InitBBMap = &EntryBBMap;
1125 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1126 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001127
Johannes Doerfert275a1752015-02-24 16:16:32 +00001128 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001129 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001130 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001131
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001132 // In order to remap PHI nodes we store also basic block mappings.
1133 BlockMap[BB] = BBCopy;
1134
1135 // Add values to incomplete PHI nodes waiting for this block to be copied.
1136 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001137 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001138 IncompletePHINodeMap[BB].clear();
1139
Johannes Doerfert275a1752015-02-24 16:16:32 +00001140 // And continue with new successors inside the region.
1141 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1142 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1143 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001144
1145 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001146 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001147 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001148 }
1149
1150 // 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 +00001151 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1152 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001153 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001154 BlockMap[R->getExit()] = ExitBBCopy;
1155
Michael Krused6fb6f12015-11-09 23:07:38 +00001156 if (ExitBB == R->getExit())
1157 repairDominance(ExitBB, ExitBBCopy);
1158 else
1159 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001160
1161 // As the block generator doesn't handle control flow we need to add the
1162 // region control flow by hand after all blocks have been copied.
1163 for (BasicBlock *BB : SeenBlocks) {
1164
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001165 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001166 TerminatorInst *TI = BB->getTerminator();
1167 if (isa<UnreachableInst>(TI)) {
1168 while (!BBCopy->empty())
1169 BBCopy->begin()->eraseFromParent();
1170 new UnreachableInst(BBCopy->getContext(), BBCopy);
1171 continue;
1172 }
1173
Johannes Doerfert275a1752015-02-24 16:16:32 +00001174 Instruction *BICopy = BBCopy->getTerminator();
1175
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001176 ValueMapT &RegionMap = RegionMaps[BBCopy];
1177 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1178
Tobias Grosser45e79442015-08-01 09:07:57 +00001179 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001180 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001181 BICopy->eraseFromParent();
1182 }
1183
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001184 // Add counting PHI nodes to all loops in the region that can be used as
1185 // replacement for SCEVs refering to the old loop.
1186 for (BasicBlock *BB : SeenBlocks) {
1187 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001188 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001189 continue;
1190
1191 BasicBlock *BBCopy = BlockMap[BB];
1192 Value *NullVal = Builder.getInt32(0);
1193 PHINode *LoopPHI =
1194 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1195 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1196 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001197 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001198 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1199
1200 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1201 if (!R->contains(PredBB))
1202 continue;
1203 if (L->contains(PredBB))
1204 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1205 else
1206 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1207 }
1208
1209 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1210 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1211 LoopPHI->addIncoming(NullVal, PredBBCopy);
1212
1213 LTS[L] = SE.getUnknown(LoopPHI);
1214 }
1215
Michael Kruse225f0d12015-10-17 21:36:00 +00001216 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001217 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001218
1219 // Write values visible to other statements.
1220 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001221 BlockMap.clear();
1222 RegionMaps.clear();
1223 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001224}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001225
Michael Kruse225f0d12015-10-17 21:36:00 +00001226void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001227 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001228 const Region &R = Stmt.getParent()->getRegion();
1229
Tobias Grosser75296902015-08-21 19:23:21 +00001230 assert(Stmt.getRegion() &&
1231 "Block statements need to use the generateScalarStores() "
1232 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001233
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001234 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001235 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001236 continue;
1237
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001238 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001239 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001240
Michael Kruse225f0d12015-10-17 21:36:00 +00001241 // In case we add the store into an exiting block, we need to restore the
1242 // position for stores in the exit node.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001243 BasicBlock *SavedInsertBB = Builder.GetInsertBlock();
Michael Kruse225f0d12015-10-17 21:36:00 +00001244 auto SavedInsertionPoint = Builder.GetInsertPoint();
Michael Kruse27149cf2015-11-05 16:17:17 +00001245 ValueMapT *LocalBBMap = &BBMap;
Michael Kruse225f0d12015-10-17 21:36:00 +00001246
Tobias Grossera535dff2015-12-13 19:59:01 +00001247 // Scalar writes induced by PHIs must be written in the incoming blocks.
1248 if (MA->isPHIKind() || MA->isExitPHIKind()) {
Michael Kruse225f0d12015-10-17 21:36:00 +00001249 BasicBlock *ExitingBB = ScalarInst->getParent();
1250 BasicBlock *ExitingBBCopy = BlockMap[ExitingBB];
1251 Builder.SetInsertPoint(ExitingBBCopy->getTerminator());
Michael Kruse27149cf2015-11-05 16:17:17 +00001252
1253 // For the incoming blocks, use the block's BBMap instead of the one for
1254 // the entire region.
1255 LocalBBMap = &RegionMaps[ExitingBBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001256 }
1257
Tobias Grosserbc132602015-09-05 09:56:54 +00001258 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001259
Michael Kruse27149cf2015-11-05 16:17:17 +00001260 Val = getNewScalarValue(Val, R, Stmt, LTS, *LocalBBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001261 Builder.CreateStore(Val, Address);
Michael Kruse225f0d12015-10-17 21:36:00 +00001262
1263 // Restore the insertion point if necessary.
Tobias Grossera535dff2015-12-13 19:59:01 +00001264 if (MA->isPHIKind() || MA->isExitPHIKind())
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001265 Builder.SetInsertPoint(SavedInsertBB, SavedInsertionPoint);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001266 }
1267}
1268
1269void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1270 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001271 LoopToScevMapT &LTS) {
1272 Region *StmtR = Stmt.getRegion();
1273
1274 // If the incoming block was not yet copied mark this PHI as incomplete.
1275 // Once the block will be copied the incoming value will be added.
1276 BasicBlock *BBCopy = BlockMap[IncomingBB];
1277 if (!BBCopy) {
1278 assert(StmtR->contains(IncomingBB) &&
1279 "Bad incoming block for PHI in non-affine region");
1280 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1281 return;
1282 }
1283
1284 Value *OpCopy = nullptr;
1285 if (StmtR->contains(IncomingBB)) {
1286 assert(RegionMaps.count(BBCopy) &&
1287 "Incoming PHI block did not have a BBMap");
1288 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1289
1290 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001291
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001292 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001293 auto OldIP = Builder.GetInsertPoint();
1294 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001295 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001296 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001297 } else {
1298
1299 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1300 return;
1301
Tobias Grosserbc132602015-09-05 09:56:54 +00001302 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001303 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1304 BlockMap[IncomingBB]->getTerminator());
1305 }
1306
1307 assert(OpCopy && "Incoming PHI value was not copied properly");
1308 assert(BBCopy && "Incoming PHI block was not copied properly");
1309 PHICopy->addIncoming(OpCopy, BBCopy);
1310}
1311
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001312Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001313 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001314 LoopToScevMapT &LTS) {
1315 unsigned NumIncoming = PHI->getNumIncomingValues();
1316 PHINode *PHICopy =
1317 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1318 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1319 BBMap[PHI] = PHICopy;
1320
1321 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001322 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001323 return PHICopy;
1324}