blob: 9aaff0d8e39c23f6f24b2b234092fd6d72ea2172 [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
Johannes Doerfert5dced262015-12-22 19:08:49 +0000241bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
242 Loop *L = getLoopForInst(Inst);
243 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
244 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion());
245}
246
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000247void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000248 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000249 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000250 // Terminator instructions control the control flow. They are explicitly
251 // expressed in the clast and do not need to be copied.
252 if (Inst->isTerminator())
253 return;
254
Johannes Doerfert5dced262015-12-22 19:08:49 +0000255 // Synthesizable statements will be generated on-demand.
256 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000257 return;
258
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000259 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000260 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000261 // Compute NewLoad before its insertion in BBMap to make the insertion
262 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000263 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000264 return;
265 }
266
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000267 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000268 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000269 return;
270 }
271
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000272 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000273 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000274 return;
275 }
276
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000277 // Skip some special intrinsics for which we do not adjust the semantics to
278 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000279 if (isIgnoredIntrinsic(Inst))
280 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000281
Tobias Grosserbc132602015-09-05 09:56:54 +0000282 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000283}
284
Tobias Grosserbc132602015-09-05 09:56:54 +0000285void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000286 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000287 assert(Stmt.isBlockStmt() &&
288 "Only block statements can be copied by the block generator");
289
290 ValueMapT BBMap;
291
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000292 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000293 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000294}
295
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000296BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000297 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
298 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000299 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000300 return CopyBB;
301}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000302
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000303BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000304 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000305 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000306 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000307 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000308 generateScalarLoads(Stmt, BBMap);
309
Tobias Grosserbc132602015-09-05 09:56:54 +0000310 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000311
312 // After a basic block was copied store all scalars that escape this block in
313 // their alloca.
314 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000315 return CopyBB;
316}
317
318void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000319 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000320 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000321 EntryBB = &CopyBB->getParent()->getEntryBlock();
322
Tobias Grosser91f5b262014-06-04 08:06:40 +0000323 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000324 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000325}
326
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000327Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
328 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000329 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000330 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000331 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000332 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000333 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000334 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000335 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000336 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000337 }
338
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000339 auto Addr = Map[ScalarBase];
340
Tobias Grosserbc132602015-09-05 09:56:54 +0000341 if (GlobalMap.count(Addr))
342 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000343
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000344 return Addr;
345}
346
Tobias Grosserbc132602015-09-05 09:56:54 +0000347Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000348 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000349 return getOrCreatePHIAlloca(Access.getBaseAddr());
350 else
351 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000352}
353
354Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000355 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000356 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000357 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000358 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000359}
360
Tobias Grosserbc132602015-09-05 09:56:54 +0000361Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
362 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000363}
364
Tobias Grosserbc132602015-09-05 09:56:54 +0000365Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
366 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000367}
368
Tobias Grosserbc132602015-09-05 09:56:54 +0000369void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000370 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000371 // If there are escape users we get the alloca for this instruction and put it
372 // in the EscapeMap for later finalization. Lastly, if the instruction was
373 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000374 if (EscapeMap.count(Inst))
375 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000376
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000377 EscapeUserVectorTy EscapeUsers;
378 for (User *U : Inst->users()) {
379
380 // Non-instruction user will never escape.
381 Instruction *UI = dyn_cast<Instruction>(U);
382 if (!UI)
383 continue;
384
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000385 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000386 continue;
387
388 EscapeUsers.push_back(UI);
389 }
390
391 // Exit if no escape uses were found.
392 if (EscapeUsers.empty())
393 return;
394
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000395 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000396 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000397
398 // Remember that this instruction has escape uses and the escape alloca.
399 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000400}
401
Michael Kruse225f0d12015-10-17 21:36:00 +0000402void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
403 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000404 if (MA->isArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000405 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000406
Michael Krusee2bccbb2015-09-18 19:59:43 +0000407 auto *Address = getOrCreateAlloca(*MA);
408 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000409 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000410 }
411}
412
413Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000414 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000415 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000416 // If the value we want to store is an instruction we might have demoted it
417 // in order to make it accessible here. In such a case a reload is
418 // necessary. If it is no instruction it will always be a value that
419 // dominates the current point and we can just use it. In total there are 4
420 // options:
421 // (1) The value is no instruction ==> use the value.
422 // (2) The value is an instruction that was split out of the region prior to
423 // code generation ==> use the instruction as it dominates the region.
424 // (3) The value is an instruction:
425 // (a) The value was defined in the current block, thus a copy is in
426 // the BBMap ==> use the mapped value.
427 // (b) The value was defined in a previous block, thus we demoted it
428 // earlier ==> use the reloaded value.
429 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
430 if (!ScalarValueInst)
431 return ScalarValue;
432
433 if (!R.contains(ScalarValueInst)) {
434 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
435 return /* Case (3a) */ ScalarValueCopy;
436 else
437 return /* Case 2 */ ScalarValue;
438 }
439
440 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
441 return /* Case (3a) */ ScalarValueCopy;
442
Tobias Grosseraff56c82015-09-30 13:36:54 +0000443 if ((Stmt.isBlockStmt() &&
444 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
445 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
446 auto SynthesizedValue = trySynthesizeNewValue(
447 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
448
449 if (SynthesizedValue)
450 return SynthesizedValue;
451 }
452
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000453 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000454 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000455 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000456
457 return ScalarValue;
458}
459
Michael Kruse225f0d12015-10-17 21:36:00 +0000460void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000461 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000462 const Region &R = Stmt.getParent()->getRegion();
463
Michael Kruse225f0d12015-10-17 21:36:00 +0000464 assert(Stmt.isBlockStmt() && "Region statements need to use the "
465 "generateScalarStores() function in the "
466 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000467
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000468 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000469 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000470 continue;
471
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000472 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000473 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000474
Tobias Grosseraff56c82015-09-30 13:36:54 +0000475 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000476 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000477 }
478}
479
Tobias Grosserc0091a72015-08-30 19:19:34 +0000480void BlockGenerator::createScalarInitialization(Scop &S) {
481 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000482 BasicBlock *ExitBB = R.getExit();
483
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000484 // The split block __just before__ the region and optimized region.
485 BasicBlock *SplitBB = R.getEnteringBlock();
486 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
487 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
488
489 // Get the start block of the __optimized__ region.
490 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
491 if (StartBB == R.getEntry())
492 StartBB = SplitBBTerm->getSuccessor(1);
493
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000494 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000495
Tobias Grosserc0091a72015-08-30 19:19:34 +0000496 for (auto &Pair : S.arrays()) {
497 auto &Array = Pair.second;
498 if (Array->getNumberOfDimensions() != 0)
499 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000500 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000501 // For PHI nodes, the only values we need to store are the ones that
502 // reach the PHI node from outside the region. In general there should
503 // only be one such incoming edge and this edge should enter through
504 // 'SplitBB'.
505 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000506
Tobias Grosserc0091a72015-08-30 19:19:34 +0000507 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
508 if (!R.contains(*BI) && *BI != SplitBB)
509 llvm_unreachable("Incoming edges from outside the scop should always "
510 "come from SplitBB");
511
512 int Idx = PHI->getBasicBlockIndex(SplitBB);
513 if (Idx < 0)
514 continue;
515
516 Value *ScalarValue = PHI->getIncomingValue(Idx);
517
Tobias Grosserbc132602015-09-05 09:56:54 +0000518 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000519 continue;
520 }
521
522 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
523
524 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000525 continue;
526
Johannes Doerfert188542f2015-11-09 00:21:21 +0000527 // PHI nodes that are not marked as such in their SAI object are either exit
528 // PHI nodes we model as common scalars but without initialization, or
529 // incoming phi nodes that need to be initialized. Check if the first is the
530 // case for Inst and do not create and initialize memory if so.
531 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
532 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
533 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000534
Tobias Grosserc0091a72015-08-30 19:19:34 +0000535 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000536 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000537 }
538}
539
540void BlockGenerator::createScalarFinalization(Region &R) {
541 // The exit block of the __unoptimized__ region.
542 BasicBlock *ExitBB = R.getExitingBlock();
543 // The merge block __just after__ the region and the optimized region.
544 BasicBlock *MergeBB = R.getExit();
545
546 // The exit block of the __optimized__ region.
547 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
548 if (OptExitBB == ExitBB)
549 OptExitBB = *(++pred_begin(MergeBB));
550
551 Builder.SetInsertPoint(OptExitBB->getTerminator());
552 for (const auto &EscapeMapping : EscapeMap) {
553 // Extract the escaping instruction and the escaping users as well as the
554 // alloca the instruction was demoted to.
555 Instruction *EscapeInst = EscapeMapping.getFirst();
556 const auto &EscapeMappingValue = EscapeMapping.getSecond();
557 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000558 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000559
560 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000561 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000562 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000563 EscapeInstReload =
564 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000565
566 // Create the merge PHI that merges the optimized and unoptimized version.
567 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
568 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000569 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000570
571 // Add the respective values to the merge PHI.
572 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
573 MergePHI->addIncoming(EscapeInst, ExitBB);
574
575 // The information of scalar evolution about the escaping instruction needs
576 // to be revoked so the new merged instruction will be used.
577 if (SE.isSCEVable(EscapeInst->getType()))
578 SE.forgetValue(EscapeInst);
579
580 // Replace all uses of the demoted instruction with the merge PHI.
581 for (Instruction *EUser : EscapeUsers)
582 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
583 }
584}
585
Tobias Grosserffa24462015-10-17 08:54:13 +0000586void BlockGenerator::findOutsideUsers(Scop &S) {
587 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000588 for (auto &Pair : S.arrays()) {
589 auto &Array = Pair.second;
590
591 if (Array->getNumberOfDimensions() != 0)
592 continue;
593
Tobias Grossera535dff2015-12-13 19:59:01 +0000594 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000595 continue;
596
597 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
598
599 if (!Inst)
600 continue;
601
602 // Scop invariant hoisting moves some of the base pointers out of the scop.
603 // We can ignore these, as the invariant load hoisting already registers the
604 // relevant outside users.
605 if (!R.contains(Inst))
606 continue;
607
608 handleOutsideUsers(R, Inst, nullptr);
609 }
610}
611
Tobias Grosser27d742d2015-10-24 17:41:29 +0000612void BlockGenerator::createExitPHINodeMerges(Scop &S) {
613 if (S.hasSingleExitEdge())
614 return;
615
616 Region &R = S.getRegion();
617
618 auto *ExitBB = R.getExitingBlock();
619 auto *MergeBB = R.getExit();
620 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
621 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
622 if (OptExitBB == ExitBB)
623 OptExitBB = *(++pred_begin(MergeBB));
624
625 Builder.SetInsertPoint(OptExitBB->getTerminator());
626
627 for (auto &Pair : S.arrays()) {
628 auto &SAI = Pair.second;
629 auto *Val = SAI->getBasePtr();
630
631 PHINode *PHI = dyn_cast<PHINode>(Val);
632 if (!PHI)
633 continue;
634
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000635 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000636 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000637
638 std::string Name = PHI->getName();
639 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
640 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
641 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
642 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
643 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000644 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000645 MergePHI->addIncoming(Reload, OptExitBB);
646 MergePHI->addIncoming(OriginalValue, ExitBB);
647 int Idx = PHI->getBasicBlockIndex(MergeBB);
648 PHI->setIncomingValue(Idx, MergePHI);
649 }
650}
651
Tobias Grosserffa24462015-10-17 08:54:13 +0000652void BlockGenerator::finalizeSCoP(Scop &S) {
653 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000654 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000655 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000656 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000657}
658
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000659VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000660 std::vector<LoopToScevMapT> &VLTS,
661 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000662 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000663 assert(Schedule && "No statement domain provided");
664}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000665
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000666Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000667 ValueMapT &VectorMap,
668 VectorValueMapT &ScalarMaps,
669 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000670 if (Value *NewValue = VectorMap.lookup(Old))
671 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000672
673 int Width = getVectorWidth();
674
675 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
676
677 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000678 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000679 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000680 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000681
682 VectorMap[Old] = Vector;
683
684 return Vector;
685}
686
687Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
688 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
689 assert(PointerTy && "PointerType expected");
690
691 Type *ScalarType = PointerTy->getElementType();
692 VectorType *VectorType = VectorType::get(ScalarType, Width);
693
694 return PointerType::getUnqual(VectorType);
695}
696
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000697Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000698 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000699 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000700 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000701 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000702 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
703 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
704
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000705 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000706 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
707 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000708 Value *VectorPtr =
709 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
710 LoadInst *VecLoad =
711 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000712 if (!Aligned)
713 VecLoad->setAlignment(8);
714
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000715 if (NegativeStride) {
716 SmallVector<Constant *, 16> Indices;
717 for (int i = VectorWidth - 1; i >= 0; i--)
718 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
719 Constant *SV = llvm::ConstantVector::get(Indices);
720 Value *RevVecLoad = Builder.CreateShuffleVector(
721 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
722 return RevVecLoad;
723 }
724
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000725 return VecLoad;
726}
727
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000728Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000729 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000730 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000731 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000733 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
734 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000735 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
736 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000737 LoadInst *ScalarLoad =
738 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000739
740 if (!Aligned)
741 ScalarLoad->setAlignment(8);
742
Tobias Grosserc14582f2013-02-05 18:01:29 +0000743 Constant *SplatVector = Constant::getNullValue(
744 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000745
Tobias Grosserc14582f2013-02-05 18:01:29 +0000746 Value *VectorLoad = Builder.CreateShuffleVector(
747 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000748 return VectorLoad;
749}
750
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000751Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000752 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000753 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000754 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000755 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000756 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000757 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000758
759 Value *Vector = UndefValue::get(VectorType);
760
761 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000762 Value *NewPointer = generateLocationAccessed(
763 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000764 Value *ScalarLoad =
765 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
766 Vector = Builder.CreateInsertElement(
767 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000768 }
769
770 return Vector;
771}
772
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000773void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000774 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000775 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000776 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
777 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
778 Load->getName() + "_p");
779 return;
780 }
781
Tobias Grosser28736452015-03-23 07:00:36 +0000782 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000784 ScalarMaps[i][Load] =
785 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000786 return;
787 }
788
Tobias Grosser184a4922015-12-15 23:50:01 +0000789 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000790
Tobias Grosser95493982014-04-18 09:46:35 +0000791 // Make sure we have scalar values available to access the pointer to
792 // the data location.
793 extractScalarValues(Load, VectorMap, ScalarMaps);
794
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000795 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000796 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000797 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000798 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000799 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000800 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000801 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000802 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000803 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000804
805 VectorMap[Load] = NewLoad;
806}
807
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000808void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000809 ValueMapT &VectorMap,
810 VectorValueMapT &ScalarMaps) {
811 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000812 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
813 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000814
815 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
816
817 const CastInst *Cast = dyn_cast<CastInst>(Inst);
818 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
819 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
820}
821
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000822void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000823 ValueMapT &VectorMap,
824 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000825 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000826 Value *OpZero = Inst->getOperand(0);
827 Value *OpOne = Inst->getOperand(1);
828
829 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000830 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
831 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000832
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000833 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000834 Inst->getName() + "p_vec");
835 VectorMap[Inst] = NewInst;
836}
837
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000838void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000839 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000840 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000841 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000842
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000843 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000844 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000845 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000846
Tobias Grosser50fd7012014-04-17 23:13:49 +0000847 // Make sure we have scalar values available to access the pointer to
848 // the data location.
849 extractScalarValues(Store, VectorMap, ScalarMaps);
850
Sebastian Popa00a0292012-12-18 07:46:06 +0000851 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000852 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000853 Value *NewPointer = generateLocationAccessed(
854 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000855
Tobias Grosserc14582f2013-02-05 18:01:29 +0000856 Value *VectorPtr =
857 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000858 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
859
860 if (!Aligned)
861 Store->setAlignment(8);
862 } else {
863 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000864 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000865 Value *NewPointer = generateLocationAccessed(
866 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000867 Builder.CreateStore(Scalar, NewPointer);
868 }
869 }
870}
871
872bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
873 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000874 for (Value *Operand : Inst->operands())
875 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000876 return true;
877 return false;
878}
879
880bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
881 ValueMapT &VectorMap,
882 VectorValueMapT &ScalarMaps) {
883 bool HasVectorOperand = false;
884 int VectorWidth = getVectorWidth();
885
Tobias Grosser91f5b262014-06-04 08:06:40 +0000886 for (Value *Operand : Inst->operands()) {
887 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000888
889 if (VecOp == VectorMap.end())
890 continue;
891
892 HasVectorOperand = true;
893 Value *NewVector = VecOp->second;
894
895 for (int i = 0; i < VectorWidth; ++i) {
896 ValueMapT &SM = ScalarMaps[i];
897
898 // If there is one scalar extracted, all scalar elements should have
899 // already been extracted by the code here. So no need to check for the
900 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000901 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000902 break;
903
Tobias Grosser91f5b262014-06-04 08:06:40 +0000904 SM[Operand] =
905 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000906 }
907 }
908
909 return HasVectorOperand;
910}
911
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000912void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000913 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000914 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000915 bool HasVectorOperand;
916 int VectorWidth = getVectorWidth();
917
918 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
919
920 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000921 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000922 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000923
924 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
925 return;
926
927 // Make the result available as vector value.
928 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
929 Value *Vector = UndefValue::get(VectorType);
930
931 for (int i = 0; i < VectorWidth; i++)
932 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
933 Builder.getInt32(i));
934
935 VectorMap[Inst] = Vector;
936}
937
Tobias Grosserbc132602015-09-05 09:56:54 +0000938int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000939
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000940void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000941 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000942 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000943 // Terminator instructions control the control flow. They are explicitly
944 // expressed in the clast and do not need to be copied.
945 if (Inst->isTerminator())
946 return;
947
Johannes Doerfert5dced262015-12-22 19:08:49 +0000948 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000949 return;
950
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000951 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000952 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000953 return;
954 }
955
956 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000957 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000958 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000959 return;
960 }
961
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000962 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000963 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000964 return;
965 }
966
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000967 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000968 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000969 return;
970 }
971
972 // Falltrough: We generate scalar instructions, if we don't know how to
973 // generate vector code.
974 }
975
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000976 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000977}
978
Tobias Grossera69d4f02015-12-15 23:49:58 +0000979void VectorBlockGenerator::generateScalarVectorLoads(
980 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
981 for (MemoryAccess *MA : Stmt) {
982 if (MA->isArrayKind() || MA->isWrite())
983 continue;
984
985 auto *Address = getOrCreateAlloca(*MA);
986 Type *VectorPtrType = getVectorPtrTy(Address, 1);
987 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
988 Address->getName() + "_p_vec_p");
989 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
990 Constant *SplatVector = Constant::getNullValue(
991 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
992
993 Value *VectorVal = Builder.CreateShuffleVector(
994 Val, Val, SplatVector, Address->getName() + "_p_splat");
995 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
996 VectorVal->dump();
997 }
998}
999
1000void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1001 for (MemoryAccess *MA : Stmt) {
1002 if (MA->isArrayKind() || MA->isRead())
1003 continue;
1004
1005 llvm_unreachable("Scalar stores not expected in vector loop");
1006 }
1007}
1008
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001009void VectorBlockGenerator::copyStmt(
1010 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001011 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
1012 "the vector block generator");
1013
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001014 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001015 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1016 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001017 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001018 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001019
1020 // Create two maps that store the mapping from the original instructions of
1021 // the old basic block to their copies in the new basic block. Those maps
1022 // are basic block local.
1023 //
1024 // As vector code generation is supported there is one map for scalar values
1025 // and one for vector values.
1026 //
1027 // In case we just do scalar code generation, the vectorMap is not used and
1028 // the scalarMap has just one dimension, which contains the mapping.
1029 //
1030 // In case vector code generation is done, an instruction may either appear
1031 // in the vector map once (as it is calculating >vectorwidth< values at a
1032 // time. Or (if the values are calculated using scalar operations), it
1033 // appears once in every dimension of the scalarMap.
1034 VectorValueMapT ScalarBlockMap(getVectorWidth());
1035 ValueMapT VectorBlockMap;
1036
Tobias Grossera69d4f02015-12-15 23:49:58 +00001037 generateScalarVectorLoads(Stmt, VectorBlockMap);
1038
Tobias Grosser91f5b262014-06-04 08:06:40 +00001039 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001040 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001041
1042 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001043}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001044
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001045BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1046 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001047
1048 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1049 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1050
1051 if (BBCopyIDom)
1052 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1053
1054 return BBCopyIDom;
1055}
1056
Tobias Grosserbc132602015-09-05 09:56:54 +00001057void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001058 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001059 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001060 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001061
Michael Krused6fb6f12015-11-09 23:07:38 +00001062 Scop *S = Stmt.getParent();
1063
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001064 // Forget all old mappings.
1065 BlockMap.clear();
1066 RegionMaps.clear();
1067 IncompletePHINodeMap.clear();
1068
Michael Kruse225f0d12015-10-17 21:36:00 +00001069 // Collection of all values related to this subregion.
1070 ValueMapT ValueMap;
1071
Johannes Doerfert275a1752015-02-24 16:16:32 +00001072 // The region represented by the statement.
1073 Region *R = Stmt.getRegion();
1074
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001075 // Create a dedicated entry for the region where we can reload all demoted
1076 // inputs.
1077 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001078 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1079 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001080 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001081 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001082
Michael Krusec9937392015-11-09 23:33:40 +00001083 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1084 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001085
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001086 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1087 if (!R->contains(*PI))
1088 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001089
Michael Krused6fb6f12015-11-09 23:07:38 +00001090 // Determine the original exit block of this subregion. If it the exit block
1091 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1092 // We move one block back to find the original block. This only happens if the
1093 // scop required simplification.
1094 // If the whole scop consists of only this non-affine region, then they share
1095 // the same Region object, such that we cannot change the exit of one and not
1096 // the other.
1097 BasicBlock *ExitBB = R->getExit();
1098 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1099 ExitBB = *(++pred_begin(ExitBB));
1100
Johannes Doerfert275a1752015-02-24 16:16:32 +00001101 // Iterate over all blocks in the region in a breadth-first search.
1102 std::deque<BasicBlock *> Blocks;
1103 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001104 Blocks.push_back(EntryBB);
1105 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001106
1107 while (!Blocks.empty()) {
1108 BasicBlock *BB = Blocks.front();
1109 Blocks.pop_front();
1110
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001111 // First split the block and update dominance information.
1112 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001113 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1114
1115 // In order to remap PHI nodes we store also basic block mappings.
1116 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001117
Michael Krusec9937392015-11-09 23:33:40 +00001118 // Get the mapping for this block and initialize it with either the scalar
1119 // loads from the generated entering block (which dominates all blocks of
1120 // this subregion) or the maps of the immediate dominator, if part of the
1121 // subregion. The latter necessarily includes the former.
1122 ValueMapT *InitBBMap;
1123 if (BBCopyIDom) {
1124 assert(RegionMaps.count(BBCopyIDom));
1125 InitBBMap = &RegionMaps[BBCopyIDom];
1126 } else
1127 InitBBMap = &EntryBBMap;
1128 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1129 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001130
Johannes Doerfert275a1752015-02-24 16:16:32 +00001131 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001132 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001133 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001134
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001135 // In order to remap PHI nodes we store also basic block mappings.
1136 BlockMap[BB] = BBCopy;
1137
1138 // Add values to incomplete PHI nodes waiting for this block to be copied.
1139 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001140 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001141 IncompletePHINodeMap[BB].clear();
1142
Johannes Doerfert275a1752015-02-24 16:16:32 +00001143 // And continue with new successors inside the region.
1144 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1145 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1146 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001147
1148 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001149 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001150 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001151 }
1152
1153 // 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 +00001154 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1155 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001156 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001157 BlockMap[R->getExit()] = ExitBBCopy;
1158
Michael Krused6fb6f12015-11-09 23:07:38 +00001159 if (ExitBB == R->getExit())
1160 repairDominance(ExitBB, ExitBBCopy);
1161 else
1162 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001163
1164 // As the block generator doesn't handle control flow we need to add the
1165 // region control flow by hand after all blocks have been copied.
1166 for (BasicBlock *BB : SeenBlocks) {
1167
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001168 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001169 TerminatorInst *TI = BB->getTerminator();
1170 if (isa<UnreachableInst>(TI)) {
1171 while (!BBCopy->empty())
1172 BBCopy->begin()->eraseFromParent();
1173 new UnreachableInst(BBCopy->getContext(), BBCopy);
1174 continue;
1175 }
1176
Johannes Doerfert275a1752015-02-24 16:16:32 +00001177 Instruction *BICopy = BBCopy->getTerminator();
1178
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001179 ValueMapT &RegionMap = RegionMaps[BBCopy];
1180 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1181
Tobias Grosser45e79442015-08-01 09:07:57 +00001182 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001183 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001184 BICopy->eraseFromParent();
1185 }
1186
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001187 // Add counting PHI nodes to all loops in the region that can be used as
1188 // replacement for SCEVs refering to the old loop.
1189 for (BasicBlock *BB : SeenBlocks) {
1190 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001191 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001192 continue;
1193
1194 BasicBlock *BBCopy = BlockMap[BB];
1195 Value *NullVal = Builder.getInt32(0);
1196 PHINode *LoopPHI =
1197 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1198 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1199 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001200 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001201 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1202
1203 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1204 if (!R->contains(PredBB))
1205 continue;
1206 if (L->contains(PredBB))
1207 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1208 else
1209 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1210 }
1211
1212 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1213 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1214 LoopPHI->addIncoming(NullVal, PredBBCopy);
1215
1216 LTS[L] = SE.getUnknown(LoopPHI);
1217 }
1218
Michael Kruse225f0d12015-10-17 21:36:00 +00001219 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001220 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001221
1222 // Write values visible to other statements.
1223 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001224 BlockMap.clear();
1225 RegionMaps.clear();
1226 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001227}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001228
Michael Kruse225f0d12015-10-17 21:36:00 +00001229void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001230 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001231 const Region &R = Stmt.getParent()->getRegion();
1232
Tobias Grosser75296902015-08-21 19:23:21 +00001233 assert(Stmt.getRegion() &&
1234 "Block statements need to use the generateScalarStores() "
1235 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001236
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001237 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001238 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001239 continue;
1240
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001241 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001242 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001243
Michael Kruse225f0d12015-10-17 21:36:00 +00001244 // In case we add the store into an exiting block, we need to restore the
1245 // position for stores in the exit node.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001246 BasicBlock *SavedInsertBB = Builder.GetInsertBlock();
Michael Kruse225f0d12015-10-17 21:36:00 +00001247 auto SavedInsertionPoint = Builder.GetInsertPoint();
Michael Kruse27149cf2015-11-05 16:17:17 +00001248 ValueMapT *LocalBBMap = &BBMap;
Michael Kruse225f0d12015-10-17 21:36:00 +00001249
Tobias Grossera535dff2015-12-13 19:59:01 +00001250 // Scalar writes induced by PHIs must be written in the incoming blocks.
1251 if (MA->isPHIKind() || MA->isExitPHIKind()) {
Michael Kruse225f0d12015-10-17 21:36:00 +00001252 BasicBlock *ExitingBB = ScalarInst->getParent();
1253 BasicBlock *ExitingBBCopy = BlockMap[ExitingBB];
1254 Builder.SetInsertPoint(ExitingBBCopy->getTerminator());
Michael Kruse27149cf2015-11-05 16:17:17 +00001255
1256 // For the incoming blocks, use the block's BBMap instead of the one for
1257 // the entire region.
1258 LocalBBMap = &RegionMaps[ExitingBBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001259 }
1260
Tobias Grosserbc132602015-09-05 09:56:54 +00001261 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001262
Michael Kruse27149cf2015-11-05 16:17:17 +00001263 Val = getNewScalarValue(Val, R, Stmt, LTS, *LocalBBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001264 Builder.CreateStore(Val, Address);
Michael Kruse225f0d12015-10-17 21:36:00 +00001265
1266 // Restore the insertion point if necessary.
Tobias Grossera535dff2015-12-13 19:59:01 +00001267 if (MA->isPHIKind() || MA->isExitPHIKind())
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001268 Builder.SetInsertPoint(SavedInsertBB, SavedInsertionPoint);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001269 }
1270}
1271
1272void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1273 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001274 LoopToScevMapT &LTS) {
1275 Region *StmtR = Stmt.getRegion();
1276
1277 // If the incoming block was not yet copied mark this PHI as incomplete.
1278 // Once the block will be copied the incoming value will be added.
1279 BasicBlock *BBCopy = BlockMap[IncomingBB];
1280 if (!BBCopy) {
1281 assert(StmtR->contains(IncomingBB) &&
1282 "Bad incoming block for PHI in non-affine region");
1283 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1284 return;
1285 }
1286
1287 Value *OpCopy = nullptr;
1288 if (StmtR->contains(IncomingBB)) {
1289 assert(RegionMaps.count(BBCopy) &&
1290 "Incoming PHI block did not have a BBMap");
1291 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1292
1293 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001294
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001295 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001296 auto OldIP = Builder.GetInsertPoint();
1297 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001298 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001299 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001300 } else {
1301
1302 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1303 return;
1304
Tobias Grosserbc132602015-09-05 09:56:54 +00001305 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001306 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1307 BlockMap[IncomingBB]->getTerminator());
1308 }
1309
1310 assert(OpCopy && "Incoming PHI value was not copied properly");
1311 assert(BBCopy && "Incoming PHI block was not copied properly");
1312 PHICopy->addIncoming(OpCopy, BBCopy);
1313}
1314
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001315Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001316 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001317 LoopToScevMapT &LTS) {
1318 unsigned NumIncoming = PHI->getNumIncomingValues();
1319 PHINode *PHICopy =
1320 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1321 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1322 BBMap[PHI] = PHICopy;
1323
1324 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001325 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001326 return PHICopy;
1327}