blob: 33611e7a9efe9b667af6ac48dfd0f7ad2277e041 [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
Michael Kruse70131d32016-01-27 17:09:17 +0000171Value *
172BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
173 ValueMapT &BBMap, LoopToScevMapT &LTS,
174 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000175 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000176
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000177 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000178
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000179 if (AccessExpr) {
180 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000181 auto Address = ExprBuilder->create(AccessExpr);
182
183 // Cast the address of this memory access to a pointer type that has the
184 // same element type as the original access, but uses the address space of
185 // the newly generated pointer.
186 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
187 auto NewPtrTy = Address->getType();
188 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
189 NewPtrTy->getPointerAddressSpace());
190
191 if (OldPtrTy != NewPtrTy) {
192 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
193 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
194 "Pointer types to elements with different size found");
195 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
196 }
197 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000198 }
199
Michael Kruse70131d32016-01-27 17:09:17 +0000200 return getNewValue(Stmt, Inst.getPointerOperand(), BBMap, LTS,
201 getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000202}
203
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000204Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000205 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000206}
207
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000208Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000209 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000210 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000211 if (Value *PreloadLoad = GlobalMap.lookup(Load))
212 return PreloadLoad;
213
Tobias Grosserbc132602015-09-05 09:56:54 +0000214 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000215 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000216 Value *ScalarLoad = Builder.CreateAlignedLoad(
217 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000218
219 if (DebugPrinting)
220 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
221 ": ", ScalarLoad, "\n");
222
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000223 return ScalarLoad;
224}
225
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000226void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000227 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000228 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000230 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
Tobias Grosserbc132602015-09-05 09:56:54 +0000231 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 Grosser5c7f16b2016-01-24 14:16:59 +0000341 if (auto NewAddr = GlobalMap.lookup(Addr))
342 return NewAddr;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000343
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000344 return Addr;
345}
346
Johannes Doerfert800e17a2016-02-02 14:16:01 +0000347Value *BlockGenerator::getOrCreateAlloca(const 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
Michael Kruse225f0d12015-10-17 21:36:00 +0000413void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000414 ValueMapT &BBMap) {
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000415 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000416
Michael Kruse225f0d12015-10-17 21:36:00 +0000417 assert(Stmt.isBlockStmt() && "Region statements need to use the "
418 "generateScalarStores() function in the "
419 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000420
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000421 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000422 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000423 continue;
424
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000425 Value *Val = MA->getAccessValue();
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000426 if (MA->isAnyPHIKind()) {
427 assert(MA->getIncoming().size() >= 1 &&
428 "Block statements have exactly one exiting block, or multiple but "
429 "with same incoming block and value");
430 assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
431 [&](std::pair<BasicBlock *, Value *> p) -> bool {
432 return p.first == Stmt.getBasicBlock();
433 }) &&
434 "Incoming block must be statement's block");
435 Val = MA->getIncoming()[0].second;
436 }
Tobias Grosserbc132602015-09-05 09:56:54 +0000437 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000438
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000439 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
Tobias Grosser92245222015-07-28 14:53:44 +0000440 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000441 }
442}
443
Tobias Grosserc0091a72015-08-30 19:19:34 +0000444void BlockGenerator::createScalarInitialization(Scop &S) {
445 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000446 BasicBlock *ExitBB = R.getExit();
447
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000448 // The split block __just before__ the region and optimized region.
449 BasicBlock *SplitBB = R.getEnteringBlock();
450 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
451 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
452
453 // Get the start block of the __optimized__ region.
454 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
455 if (StartBB == R.getEntry())
456 StartBB = SplitBBTerm->getSuccessor(1);
457
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000458 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000459
Tobias Grosserc0091a72015-08-30 19:19:34 +0000460 for (auto &Pair : S.arrays()) {
461 auto &Array = Pair.second;
462 if (Array->getNumberOfDimensions() != 0)
463 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000464 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000465 // For PHI nodes, the only values we need to store are the ones that
466 // reach the PHI node from outside the region. In general there should
467 // only be one such incoming edge and this edge should enter through
468 // 'SplitBB'.
469 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000470
Tobias Grosserc0091a72015-08-30 19:19:34 +0000471 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
472 if (!R.contains(*BI) && *BI != SplitBB)
473 llvm_unreachable("Incoming edges from outside the scop should always "
474 "come from SplitBB");
475
476 int Idx = PHI->getBasicBlockIndex(SplitBB);
477 if (Idx < 0)
478 continue;
479
480 Value *ScalarValue = PHI->getIncomingValue(Idx);
481
Tobias Grosserbc132602015-09-05 09:56:54 +0000482 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000483 continue;
484 }
485
486 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
487
488 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000489 continue;
490
Johannes Doerfert188542f2015-11-09 00:21:21 +0000491 // PHI nodes that are not marked as such in their SAI object are either exit
492 // PHI nodes we model as common scalars but without initialization, or
493 // incoming phi nodes that need to be initialized. Check if the first is the
494 // case for Inst and do not create and initialize memory if so.
495 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
496 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
497 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000498
Tobias Grosserc0091a72015-08-30 19:19:34 +0000499 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000500 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000501 }
502}
503
504void BlockGenerator::createScalarFinalization(Region &R) {
505 // The exit block of the __unoptimized__ region.
506 BasicBlock *ExitBB = R.getExitingBlock();
507 // The merge block __just after__ the region and the optimized region.
508 BasicBlock *MergeBB = R.getExit();
509
510 // The exit block of the __optimized__ region.
511 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
512 if (OptExitBB == ExitBB)
513 OptExitBB = *(++pred_begin(MergeBB));
514
515 Builder.SetInsertPoint(OptExitBB->getTerminator());
516 for (const auto &EscapeMapping : EscapeMap) {
517 // Extract the escaping instruction and the escaping users as well as the
518 // alloca the instruction was demoted to.
519 Instruction *EscapeInst = EscapeMapping.getFirst();
520 const auto &EscapeMappingValue = EscapeMapping.getSecond();
521 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000522 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000523
524 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000525 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000526 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000527 EscapeInstReload =
528 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000529
530 // Create the merge PHI that merges the optimized and unoptimized version.
531 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
532 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000533 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000534
535 // Add the respective values to the merge PHI.
536 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
537 MergePHI->addIncoming(EscapeInst, ExitBB);
538
539 // The information of scalar evolution about the escaping instruction needs
540 // to be revoked so the new merged instruction will be used.
541 if (SE.isSCEVable(EscapeInst->getType()))
542 SE.forgetValue(EscapeInst);
543
544 // Replace all uses of the demoted instruction with the merge PHI.
545 for (Instruction *EUser : EscapeUsers)
546 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
547 }
548}
549
Tobias Grosserffa24462015-10-17 08:54:13 +0000550void BlockGenerator::findOutsideUsers(Scop &S) {
551 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000552 for (auto &Pair : S.arrays()) {
553 auto &Array = Pair.second;
554
555 if (Array->getNumberOfDimensions() != 0)
556 continue;
557
Tobias Grossera535dff2015-12-13 19:59:01 +0000558 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000559 continue;
560
561 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
562
563 if (!Inst)
564 continue;
565
566 // Scop invariant hoisting moves some of the base pointers out of the scop.
567 // We can ignore these, as the invariant load hoisting already registers the
568 // relevant outside users.
569 if (!R.contains(Inst))
570 continue;
571
572 handleOutsideUsers(R, Inst, nullptr);
573 }
574}
575
Tobias Grosser27d742d2015-10-24 17:41:29 +0000576void BlockGenerator::createExitPHINodeMerges(Scop &S) {
577 if (S.hasSingleExitEdge())
578 return;
579
580 Region &R = S.getRegion();
581
582 auto *ExitBB = R.getExitingBlock();
583 auto *MergeBB = R.getExit();
584 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
585 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
586 if (OptExitBB == ExitBB)
587 OptExitBB = *(++pred_begin(MergeBB));
588
589 Builder.SetInsertPoint(OptExitBB->getTerminator());
590
591 for (auto &Pair : S.arrays()) {
592 auto &SAI = Pair.second;
593 auto *Val = SAI->getBasePtr();
594
595 PHINode *PHI = dyn_cast<PHINode>(Val);
596 if (!PHI)
597 continue;
598
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000599 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000600 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000601
602 std::string Name = PHI->getName();
603 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
604 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
605 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
606 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
607 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000608 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000609 MergePHI->addIncoming(Reload, OptExitBB);
610 MergePHI->addIncoming(OriginalValue, ExitBB);
611 int Idx = PHI->getBasicBlockIndex(MergeBB);
612 PHI->setIncomingValue(Idx, MergePHI);
613 }
614}
615
Tobias Grosserffa24462015-10-17 08:54:13 +0000616void BlockGenerator::finalizeSCoP(Scop &S) {
617 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000618 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000619 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000620 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000621}
622
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000623VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000624 std::vector<LoopToScevMapT> &VLTS,
625 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000626 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000627 assert(Schedule && "No statement domain provided");
628}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000629
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000630Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000631 ValueMapT &VectorMap,
632 VectorValueMapT &ScalarMaps,
633 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000634 if (Value *NewValue = VectorMap.lookup(Old))
635 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000636
637 int Width = getVectorWidth();
638
639 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
640
641 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000642 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000643 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000644 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000645
646 VectorMap[Old] = Vector;
647
648 return Vector;
649}
650
651Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
652 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
653 assert(PointerTy && "PointerType expected");
654
655 Type *ScalarType = PointerTy->getElementType();
656 VectorType *VectorType = VectorType::get(ScalarType, Width);
657
658 return PointerType::getUnqual(VectorType);
659}
660
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000661Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000662 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000663 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000664 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000665 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000666 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
667 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
668
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000669 Value *NewPointer = nullptr;
Michael Kruse70131d32016-01-27 17:09:17 +0000670 NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
Tobias Grosserbc132602015-09-05 09:56:54 +0000671 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000672 Value *VectorPtr =
673 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
674 LoadInst *VecLoad =
675 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000676 if (!Aligned)
677 VecLoad->setAlignment(8);
678
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000679 if (NegativeStride) {
680 SmallVector<Constant *, 16> Indices;
681 for (int i = VectorWidth - 1; i >= 0; i--)
682 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
683 Constant *SV = llvm::ConstantVector::get(Indices);
684 Value *RevVecLoad = Builder.CreateShuffleVector(
685 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
686 return RevVecLoad;
687 }
688
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000689 return VecLoad;
690}
691
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000692Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000693 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000694 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000695 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000696 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Michael Kruse70131d32016-01-27 17:09:17 +0000697 Value *NewPointer =
698 generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000699 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
700 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000701 LoadInst *ScalarLoad =
702 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000703
704 if (!Aligned)
705 ScalarLoad->setAlignment(8);
706
Tobias Grosserc14582f2013-02-05 18:01:29 +0000707 Constant *SplatVector = Constant::getNullValue(
708 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000709
Tobias Grosserc14582f2013-02-05 18:01:29 +0000710 Value *VectorLoad = Builder.CreateShuffleVector(
711 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000712 return VectorLoad;
713}
714
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000715Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000716 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000717 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000718 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000719 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000720 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000721 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000722
723 Value *Vector = UndefValue::get(VectorType);
724
725 for (int i = 0; i < VectorWidth; i++) {
Michael Kruse70131d32016-01-27 17:09:17 +0000726 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
727 VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000728 Value *ScalarLoad =
729 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
730 Vector = Builder.CreateInsertElement(
731 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732 }
733
734 return Vector;
735}
736
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000737void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000738 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000739 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000740 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
741 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
742 Load->getName() + "_p");
743 return;
744 }
745
Tobias Grosser28736452015-03-23 07:00:36 +0000746 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000747 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000748 ScalarMaps[i][Load] =
749 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000750 return;
751 }
752
Tobias Grosser184a4922015-12-15 23:50:01 +0000753 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000754
Tobias Grosser95493982014-04-18 09:46:35 +0000755 // Make sure we have scalar values available to access the pointer to
756 // the data location.
757 extractScalarValues(Load, VectorMap, ScalarMaps);
758
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000759 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000760 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000761 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000762 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000763 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000764 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000765 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000766 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000767 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000768
769 VectorMap[Load] = NewLoad;
770}
771
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000772void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000773 ValueMapT &VectorMap,
774 VectorValueMapT &ScalarMaps) {
775 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000776 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
777 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778
779 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
780
781 const CastInst *Cast = dyn_cast<CastInst>(Inst);
782 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
783 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
784}
785
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000786void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787 ValueMapT &VectorMap,
788 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000789 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000790 Value *OpZero = Inst->getOperand(0);
791 Value *OpOne = Inst->getOperand(1);
792
793 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000794 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
795 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000796
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000797 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000798 Inst->getName() + "p_vec");
799 VectorMap[Inst] = NewInst;
800}
801
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000802void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000803 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000804 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000805 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000807 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000808 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000809 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000810
Tobias Grosser50fd7012014-04-17 23:13:49 +0000811 // Make sure we have scalar values available to access the pointer to
812 // the data location.
813 extractScalarValues(Store, VectorMap, ScalarMaps);
814
Sebastian Popa00a0292012-12-18 07:46:06 +0000815 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000816 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Michael Kruse70131d32016-01-27 17:09:17 +0000817 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
818 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000819
Tobias Grosserc14582f2013-02-05 18:01:29 +0000820 Value *VectorPtr =
821 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000822 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
823
824 if (!Aligned)
825 Store->setAlignment(8);
826 } else {
827 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000828 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Michael Kruse70131d32016-01-27 17:09:17 +0000829 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
830 VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000831 Builder.CreateStore(Scalar, NewPointer);
832 }
833 }
834}
835
836bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
837 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000838 for (Value *Operand : Inst->operands())
839 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000840 return true;
841 return false;
842}
843
844bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
845 ValueMapT &VectorMap,
846 VectorValueMapT &ScalarMaps) {
847 bool HasVectorOperand = false;
848 int VectorWidth = getVectorWidth();
849
Tobias Grosser91f5b262014-06-04 08:06:40 +0000850 for (Value *Operand : Inst->operands()) {
851 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000852
853 if (VecOp == VectorMap.end())
854 continue;
855
856 HasVectorOperand = true;
857 Value *NewVector = VecOp->second;
858
859 for (int i = 0; i < VectorWidth; ++i) {
860 ValueMapT &SM = ScalarMaps[i];
861
862 // If there is one scalar extracted, all scalar elements should have
863 // already been extracted by the code here. So no need to check for the
864 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000865 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866 break;
867
Tobias Grosser91f5b262014-06-04 08:06:40 +0000868 SM[Operand] =
869 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000870 }
871 }
872
873 return HasVectorOperand;
874}
875
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000876void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000877 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000878 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000879 bool HasVectorOperand;
880 int VectorWidth = getVectorWidth();
881
882 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
883
884 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000885 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000886 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000887
888 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
889 return;
890
891 // Make the result available as vector value.
892 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
893 Value *Vector = UndefValue::get(VectorType);
894
895 for (int i = 0; i < VectorWidth; i++)
896 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
897 Builder.getInt32(i));
898
899 VectorMap[Inst] = Vector;
900}
901
Tobias Grosserbc132602015-09-05 09:56:54 +0000902int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000903
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000904void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000905 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000906 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000907 // Terminator instructions control the control flow. They are explicitly
908 // expressed in the clast and do not need to be copied.
909 if (Inst->isTerminator())
910 return;
911
Johannes Doerfert5dced262015-12-22 19:08:49 +0000912 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000913 return;
914
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000915 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000916 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000917 return;
918 }
919
920 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000921 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000922 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000923 return;
924 }
925
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000926 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000927 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000928 return;
929 }
930
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000931 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000932 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000933 return;
934 }
935
936 // Falltrough: We generate scalar instructions, if we don't know how to
937 // generate vector code.
938 }
939
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000940 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000941}
942
Tobias Grossera69d4f02015-12-15 23:49:58 +0000943void VectorBlockGenerator::generateScalarVectorLoads(
944 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
945 for (MemoryAccess *MA : Stmt) {
946 if (MA->isArrayKind() || MA->isWrite())
947 continue;
948
949 auto *Address = getOrCreateAlloca(*MA);
950 Type *VectorPtrType = getVectorPtrTy(Address, 1);
951 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
952 Address->getName() + "_p_vec_p");
953 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
954 Constant *SplatVector = Constant::getNullValue(
955 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
956
957 Value *VectorVal = Builder.CreateShuffleVector(
958 Val, Val, SplatVector, Address->getName() + "_p_splat");
959 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
960 VectorVal->dump();
961 }
962}
963
964void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
965 for (MemoryAccess *MA : Stmt) {
966 if (MA->isArrayKind() || MA->isRead())
967 continue;
968
969 llvm_unreachable("Scalar stores not expected in vector loop");
970 }
971}
972
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000973void VectorBlockGenerator::copyStmt(
974 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000975 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
976 "the vector block generator");
977
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000978 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000979 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
980 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000981 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000982 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000983
984 // Create two maps that store the mapping from the original instructions of
985 // the old basic block to their copies in the new basic block. Those maps
986 // are basic block local.
987 //
988 // As vector code generation is supported there is one map for scalar values
989 // and one for vector values.
990 //
991 // In case we just do scalar code generation, the vectorMap is not used and
992 // the scalarMap has just one dimension, which contains the mapping.
993 //
994 // In case vector code generation is done, an instruction may either appear
995 // in the vector map once (as it is calculating >vectorwidth< values at a
996 // time. Or (if the values are calculated using scalar operations), it
997 // appears once in every dimension of the scalarMap.
998 VectorValueMapT ScalarBlockMap(getVectorWidth());
999 ValueMapT VectorBlockMap;
1000
Tobias Grossera69d4f02015-12-15 23:49:58 +00001001 generateScalarVectorLoads(Stmt, VectorBlockMap);
1002
Tobias Grosser91f5b262014-06-04 08:06:40 +00001003 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001004 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001005
1006 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001007}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001008
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001009BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1010 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001011
1012 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1013 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1014
1015 if (BBCopyIDom)
1016 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1017
1018 return BBCopyIDom;
1019}
1020
Tobias Grosserbc132602015-09-05 09:56:54 +00001021void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001022 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001023 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001024 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001025
Michael Krused6fb6f12015-11-09 23:07:38 +00001026 Scop *S = Stmt.getParent();
1027
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001028 // Forget all old mappings.
1029 BlockMap.clear();
1030 RegionMaps.clear();
1031 IncompletePHINodeMap.clear();
1032
Michael Kruse225f0d12015-10-17 21:36:00 +00001033 // Collection of all values related to this subregion.
1034 ValueMapT ValueMap;
1035
Johannes Doerfert275a1752015-02-24 16:16:32 +00001036 // The region represented by the statement.
1037 Region *R = Stmt.getRegion();
1038
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001039 // Create a dedicated entry for the region where we can reload all demoted
1040 // inputs.
1041 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001042 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1043 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001044 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001045 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001046
Michael Krusec9937392015-11-09 23:33:40 +00001047 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1048 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001049
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001050 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1051 if (!R->contains(*PI))
1052 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001053
Michael Krused6fb6f12015-11-09 23:07:38 +00001054 // Determine the original exit block of this subregion. If it the exit block
1055 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1056 // We move one block back to find the original block. This only happens if the
1057 // scop required simplification.
1058 // If the whole scop consists of only this non-affine region, then they share
1059 // the same Region object, such that we cannot change the exit of one and not
1060 // the other.
1061 BasicBlock *ExitBB = R->getExit();
1062 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1063 ExitBB = *(++pred_begin(ExitBB));
1064
Johannes Doerfert275a1752015-02-24 16:16:32 +00001065 // Iterate over all blocks in the region in a breadth-first search.
1066 std::deque<BasicBlock *> Blocks;
1067 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001068 Blocks.push_back(EntryBB);
1069 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001070
1071 while (!Blocks.empty()) {
1072 BasicBlock *BB = Blocks.front();
1073 Blocks.pop_front();
1074
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001075 // First split the block and update dominance information.
1076 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001077 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1078
1079 // In order to remap PHI nodes we store also basic block mappings.
1080 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001081
Michael Krusec9937392015-11-09 23:33:40 +00001082 // Get the mapping for this block and initialize it with either the scalar
1083 // loads from the generated entering block (which dominates all blocks of
1084 // this subregion) or the maps of the immediate dominator, if part of the
1085 // subregion. The latter necessarily includes the former.
1086 ValueMapT *InitBBMap;
1087 if (BBCopyIDom) {
1088 assert(RegionMaps.count(BBCopyIDom));
1089 InitBBMap = &RegionMaps[BBCopyIDom];
1090 } else
1091 InitBBMap = &EntryBBMap;
1092 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1093 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001094
Johannes Doerfert275a1752015-02-24 16:16:32 +00001095 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001096 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001097 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001098
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001099 // In order to remap PHI nodes we store also basic block mappings.
1100 BlockMap[BB] = BBCopy;
1101
1102 // Add values to incomplete PHI nodes waiting for this block to be copied.
1103 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001104 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001105 IncompletePHINodeMap[BB].clear();
1106
Johannes Doerfert275a1752015-02-24 16:16:32 +00001107 // And continue with new successors inside the region.
1108 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1109 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1110 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001111
1112 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001113 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001114 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001115 }
1116
1117 // 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 +00001118 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1119 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001120 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001121 BlockMap[R->getExit()] = ExitBBCopy;
1122
Michael Krused6fb6f12015-11-09 23:07:38 +00001123 if (ExitBB == R->getExit())
1124 repairDominance(ExitBB, ExitBBCopy);
1125 else
1126 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001127
1128 // As the block generator doesn't handle control flow we need to add the
1129 // region control flow by hand after all blocks have been copied.
1130 for (BasicBlock *BB : SeenBlocks) {
1131
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001132 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001133 TerminatorInst *TI = BB->getTerminator();
1134 if (isa<UnreachableInst>(TI)) {
1135 while (!BBCopy->empty())
1136 BBCopy->begin()->eraseFromParent();
1137 new UnreachableInst(BBCopy->getContext(), BBCopy);
1138 continue;
1139 }
1140
Johannes Doerfert275a1752015-02-24 16:16:32 +00001141 Instruction *BICopy = BBCopy->getTerminator();
1142
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001143 ValueMapT &RegionMap = RegionMaps[BBCopy];
1144 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1145
Tobias Grosser45e79442015-08-01 09:07:57 +00001146 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001147 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001148 BICopy->eraseFromParent();
1149 }
1150
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001151 // Add counting PHI nodes to all loops in the region that can be used as
1152 // replacement for SCEVs refering to the old loop.
1153 for (BasicBlock *BB : SeenBlocks) {
1154 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001155 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001156 continue;
1157
1158 BasicBlock *BBCopy = BlockMap[BB];
1159 Value *NullVal = Builder.getInt32(0);
1160 PHINode *LoopPHI =
1161 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1162 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1163 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001164 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001165 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1166
1167 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1168 if (!R->contains(PredBB))
1169 continue;
1170 if (L->contains(PredBB))
1171 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1172 else
1173 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1174 }
1175
1176 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1177 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1178 LoopPHI->addIncoming(NullVal, PredBBCopy);
1179
1180 LTS[L] = SE.getUnknown(LoopPHI);
1181 }
1182
Michael Kruse225f0d12015-10-17 21:36:00 +00001183 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001184 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001185
1186 // Write values visible to other statements.
1187 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001188 BlockMap.clear();
1189 RegionMaps.clear();
1190 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001191}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001192
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001193PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1194 ValueMapT &BBMap, Loop *L) {
1195 ScopStmt *Stmt = MA->getStatement();
1196 Region *SubR = Stmt->getRegion();
1197 auto Incoming = MA->getIncoming();
1198
1199 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1200 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1201 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1202
1203 // This can happen if the subregion is simplified after the ScopStmts
1204 // have been created; simplification happens as part of CodeGeneration.
1205 if (OrigPHI->getParent() != SubR->getExit()) {
1206 BasicBlock *FormerExit = SubR->getExitingBlock();
1207 if (FormerExit)
1208 NewSubregionExit = BlockMap.lookup(FormerExit);
1209 }
1210
1211 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1212 "polly." + OrigPHI->getName(),
1213 NewSubregionExit->getFirstNonPHI());
1214
1215 // Add the incoming values to the PHI.
1216 for (auto &Pair : Incoming) {
1217 BasicBlock *OrigIncomingBlock = Pair.first;
1218 BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1219 Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1220 assert(RegionMaps.count(NewIncomingBlock));
1221 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1222
1223 Value *OrigIncomingValue = Pair.second;
1224 Value *NewIncomingValue =
1225 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1226 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1227 }
1228
1229 return NewPHI;
1230}
1231
1232Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1233 ValueMapT &BBMap) {
1234 ScopStmt *Stmt = MA->getStatement();
1235
1236 // TODO: Add some test cases that ensure this is really the right choice.
1237 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1238
1239 if (MA->isAnyPHIKind()) {
1240 auto Incoming = MA->getIncoming();
1241 assert(!Incoming.empty() &&
1242 "PHI WRITEs must have originate from at least one incoming block");
1243
1244 // If there is only one incoming value, we do not need to create a PHI.
1245 if (Incoming.size() == 1) {
1246 Value *OldVal = Incoming[0].second;
1247 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1248 }
1249
1250 return buildExitPHI(MA, LTS, BBMap, L);
1251 }
1252
1253 // MK_Value accesses leaving the subregion must dominate the exit block; just
1254 // pass the copied value
1255 Value *OldVal = MA->getAccessValue();
1256 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1257}
1258
Michael Kruse225f0d12015-10-17 21:36:00 +00001259void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001260 ValueMapT &BBMap) {
Tobias Grosser75296902015-08-21 19:23:21 +00001261 assert(Stmt.getRegion() &&
1262 "Block statements need to use the generateScalarStores() "
1263 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001264
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001265 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001266 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001267 continue;
1268
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001269 Value *NewVal = getExitScalar(MA, LTS, BBMap);
1270 Value *Address = getOrCreateAlloca(*MA);
1271 Builder.CreateStore(NewVal, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001272 }
1273}
1274
1275void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1276 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001277 LoopToScevMapT &LTS) {
1278 Region *StmtR = Stmt.getRegion();
1279
1280 // If the incoming block was not yet copied mark this PHI as incomplete.
1281 // Once the block will be copied the incoming value will be added.
1282 BasicBlock *BBCopy = BlockMap[IncomingBB];
1283 if (!BBCopy) {
1284 assert(StmtR->contains(IncomingBB) &&
1285 "Bad incoming block for PHI in non-affine region");
1286 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1287 return;
1288 }
1289
1290 Value *OpCopy = nullptr;
1291 if (StmtR->contains(IncomingBB)) {
1292 assert(RegionMaps.count(BBCopy) &&
1293 "Incoming PHI block did not have a BBMap");
1294 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1295
1296 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001297
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001298 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001299 auto OldIP = Builder.GetInsertPoint();
1300 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001301 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001302 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001303 } else {
1304
1305 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1306 return;
1307
Tobias Grosserbc132602015-09-05 09:56:54 +00001308 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001309 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1310 BlockMap[IncomingBB]->getTerminator());
1311 }
1312
1313 assert(OpCopy && "Incoming PHI value was not copied properly");
1314 assert(BBCopy && "Incoming PHI block was not copied properly");
1315 PHICopy->addIncoming(OpCopy, BBCopy);
1316}
1317
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001318Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001319 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001320 LoopToScevMapT &LTS) {
1321 unsigned NumIncoming = PHI->getNumIncomingValues();
1322 PHINode *PHICopy =
1323 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1324 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1325 BBMap[PHI] = PHICopy;
1326
1327 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001328 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001329 return PHICopy;
1330}