blob: 758aab43d06be5c0cb7632a6d497ec4fa676cb70 [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
Eli Friedmanacf80062016-11-02 22:32:23 +000051BlockGenerator::BlockGenerator(
52 PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
Tobias Grosser587f1f52017-01-28 07:42:10 +000053 AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
54 ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000055 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
Tobias Grosser587f1f52017-01-28 07:42:10 +000056 EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
57 GlobalMap(GlobalMap), StartBlock(StartBlock) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +000058
Tobias Grosser2f1acac2015-10-04 10:18:45 +000059Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
Tobias Grosser33cb9f92015-09-30 11:56:19 +000060 ValueMapT &BBMap,
61 LoopToScevMapT &LTS,
62 Loop *L) const {
Johannes Doerfert42df8d12015-12-22 19:08:01 +000063 if (!SE.isSCEVable(Old->getType()))
64 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000065
Johannes Doerfert42df8d12015-12-22 19:08:01 +000066 const SCEV *Scev = SE.getSCEVAtScope(Old, L);
67 if (!Scev)
68 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000069
Johannes Doerfert42df8d12015-12-22 19:08:01 +000070 if (isa<SCEVCouldNotCompute>(Scev))
71 return nullptr;
Tobias Grossere71c6ab2012-04-27 16:36:14 +000072
Sanjoy Das03bcb912016-05-29 07:33:16 +000073 const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
Johannes Doerfert42df8d12015-12-22 19:08:01 +000074 ValueMapT VTV;
75 VTV.insert(BBMap.begin(), BBMap.end());
76 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Tobias Grossere71c6ab2012-04-27 16:36:14 +000077
Johannes Doerfert42df8d12015-12-22 19:08:01 +000078 Scop &S = *Stmt.getParent();
Johannes Doerfert3f52e352016-05-23 12:38:05 +000079 const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
Johannes Doerfert42df8d12015-12-22 19:08:01 +000080 auto IP = Builder.GetInsertPoint();
81
82 assert(IP != Builder.GetInsertBlock()->end() &&
83 "Only instructions can be insert points for SCEVExpander");
84 Value *Expanded =
Eli Friedmanacf80062016-11-02 22:32:23 +000085 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
86 StartBlock->getSinglePredecessor());
Johannes Doerfert42df8d12015-12-22 19:08:01 +000087
88 BBMap[Old] = Expanded;
89 return Expanded;
Tobias Grosser33cb9f92015-09-30 11:56:19 +000090}
91
Tobias Grosser2f1acac2015-10-04 10:18:45 +000092Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
93 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000094 // Constants that do not reference any named value can always remain
Michael Kruse5bbc0e12015-12-14 23:41:32 +000095 // unchanged. Handle them early to avoid expensive map lookups. We do not take
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000096 // the fast-path for external constants which are referenced through globals
97 // as these may need to be rewritten when distributing code accross different
98 // LLVM modules.
99 if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000100 return Old;
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000101
Johannes Doerfert28f8ac12015-12-22 19:08:24 +0000102 // Inline asm is like a constant to us.
103 if (isa<InlineAsm>(Old))
104 return Old;
105
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000106 if (Value *New = GlobalMap.lookup(Old)) {
107 if (Value *NewRemapped = GlobalMap.lookup(New))
108 New = NewRemapped;
109 if (Old->getType()->getScalarSizeInBits() <
110 New->getType()->getScalarSizeInBits())
111 New = Builder.CreateTruncOrBitCast(New, Old->getType());
112
113 return New;
114 }
115
116 if (Value *New = BBMap.lookup(Old))
117 return New;
118
119 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
120 return New;
121
Tobias Grosser16371ac2014-11-05 20:48:56 +0000122 // A scop-constant value defined by a global or a function parameter.
123 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000124 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000125
126 // A scop-constant value defined by an instruction executed outside the scop.
127 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfert952b5302016-05-23 12:40:48 +0000128 if (!Stmt.getParent()->contains(Inst->getParent()))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000129 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000130
131 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000132 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000133 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000134}
135
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000136void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000137 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000138 // We do not generate debug intrinsics as we did not investigate how to
139 // copy them correctly. At the current state, they just crash the code
140 // generation as the meta-data operands are not correctly copied.
141 if (isa<DbgInfoIntrinsic>(Inst))
142 return;
143
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000144 Instruction *NewInst = Inst->clone();
145
146 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000147 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000148 Value *NewOperand =
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000149 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000150
151 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000152 assert(!isa<StoreInst>(NewInst) &&
153 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000154 delete NewInst;
155 return;
156 }
157
158 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
159 }
160
161 Builder.Insert(NewInst);
162 BBMap[Inst] = NewInst;
163
164 if (!NewInst->getType()->isVoidTy())
165 NewInst->setName("p_" + Inst->getName());
166}
167
Michael Kruse70131d32016-01-27 17:09:17 +0000168Value *
169BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
170 ValueMapT &BBMap, LoopToScevMapT &LTS,
171 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000172 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Michael Kruse2fa35192016-09-01 19:53:31 +0000173 return generateLocationAccessed(
174 Stmt, getLoopForStmt(Stmt),
175 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
176 NewAccesses, MA.getId(), MA.getAccessValue()->getType());
177}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000178
Michael Kruse2fa35192016-09-01 19:53:31 +0000179Value *BlockGenerator::generateLocationAccessed(
180 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
181 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
182 Type *ExpectedType) {
183 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000184
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000185 if (AccessExpr) {
186 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000187 auto Address = ExprBuilder->create(AccessExpr);
188
189 // Cast the address of this memory access to a pointer type that has the
190 // same element type as the original access, but uses the address space of
191 // the newly generated pointer.
Michael Kruse2fa35192016-09-01 19:53:31 +0000192 auto OldPtrTy = ExpectedType->getPointerTo();
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000193 auto NewPtrTy = Address->getType();
194 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
195 NewPtrTy->getPointerAddressSpace());
196
Tobias Grosserd840fc72016-02-04 13:18:42 +0000197 if (OldPtrTy != NewPtrTy)
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000198 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000199 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000200 }
Michael Kruse2fa35192016-09-01 19:53:31 +0000201 assert(
202 Pointer &&
203 "If expression was not generated, must use the original pointer value");
204 return getNewValue(Stmt, Pointer, BBMap, LTS, L);
205}
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000206
Michael Kruse2fa35192016-09-01 19:53:31 +0000207Value *
208BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
209 LoopToScevMapT &LTS, ValueMapT &BBMap,
210 __isl_keep isl_id_to_ast_expr *NewAccesses) {
211 if (Access.isLatestArrayKind())
212 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
213 LTS, NewAccesses, Access.getId(),
214 Access.getAccessValue()->getType());
215
Tobias Grosser587f1f52017-01-28 07:42:10 +0000216 return getOrCreateAlloca(Access);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000217}
218
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000219Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000220 auto *StmtBB = Stmt.getEntryBlock();
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000221 return LI.getLoopFor(StmtBB);
Tobias Grosser369430f2013-03-22 23:42:53 +0000222}
223
Michael Kruse888ab552016-09-30 14:34:05 +0000224Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
225 ValueMapT &BBMap, LoopToScevMapT &LTS,
226 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000227 if (Value *PreloadLoad = GlobalMap.lookup(Load))
228 return PreloadLoad;
229
Tobias Grosserbc132602015-09-05 09:56:54 +0000230 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000231 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000232 Value *ScalarLoad = Builder.CreateAlignedLoad(
233 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000234
235 if (DebugPrinting)
236 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
237 ": ", ScalarLoad, "\n");
238
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000239 return ScalarLoad;
240}
241
Michael Kruse888ab552016-09-30 14:34:05 +0000242void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
243 ValueMapT &BBMap, LoopToScevMapT &LTS,
244 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000245 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000246 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
Tobias Grosserbc132602015-09-05 09:56:54 +0000247 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000248 getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000249
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000250 if (DebugPrinting)
251 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
252 ": ", ValueOperand, "\n");
253
Tobias Grosserc186ac72015-08-11 08:13:15 +0000254 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000255}
256
Johannes Doerfert5dced262015-12-22 19:08:49 +0000257bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000258 Loop *L = getLoopForStmt(Stmt);
Johannes Doerfert5dced262015-12-22 19:08:49 +0000259 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
Michael Kruse11c5e0792016-11-29 15:11:04 +0000260 canSynthesize(Inst, *Stmt.getParent(), &SE, L);
Johannes Doerfert5dced262015-12-22 19:08:49 +0000261}
262
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000263void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000264 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000265 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000266 // Terminator instructions control the control flow. They are explicitly
267 // expressed in the clast and do not need to be copied.
268 if (Inst->isTerminator())
269 return;
270
Johannes Doerfert5dced262015-12-22 19:08:49 +0000271 // Synthesizable statements will be generated on-demand.
272 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000273 return;
274
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000275 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Michael Kruse888ab552016-09-30 14:34:05 +0000276 Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000277 // Compute NewLoad before its insertion in BBMap to make the insertion
278 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000279 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000280 return;
281 }
282
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000283 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Michael Kruse0446d812017-03-10 16:05:24 +0000284 // Identified as redundant by -polly-simplify.
285 if (!Stmt.getArrayAccessOrNULLFor(Store))
286 return;
287
Michael Kruse888ab552016-09-30 14:34:05 +0000288 generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000289 return;
290 }
291
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000292 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000293 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000294 return;
295 }
296
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000297 // Skip some special intrinsics for which we do not adjust the semantics to
298 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000299 if (isIgnoredIntrinsic(Inst))
300 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000301
Tobias Grosserbc132602015-09-05 09:56:54 +0000302 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000303}
304
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000305void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000306 auto NewBB = Builder.GetInsertBlock();
307 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
308 Instruction *NewInst = &*I;
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000309
310 if (!isInstructionTriviallyDead(NewInst))
311 continue;
312
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000313 for (auto Pair : BBMap)
314 if (Pair.second == NewInst) {
315 BBMap.erase(Pair.first);
316 }
317
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000318 NewInst->eraseFromParent();
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000319 I = NewBB->rbegin();
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000320 }
321}
322
Tobias Grosserbc132602015-09-05 09:56:54 +0000323void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000324 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000325 assert(Stmt.isBlockStmt() &&
326 "Only block statements can be copied by the block generator");
327
328 ValueMapT BBMap;
329
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000330 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000331 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000332 removeDeadInstructions(BB, BBMap);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000333}
334
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000335BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000336 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
337 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000338 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000339 return CopyBB;
340}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000341
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000342BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000343 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000344 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000345 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000346 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse2fa35192016-09-01 19:53:31 +0000347 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000348
Tobias Grosserbc132602015-09-05 09:56:54 +0000349 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000350
351 // After a basic block was copied store all scalars that escape this block in
352 // their alloca.
Michael Kruse2fa35192016-09-01 19:53:31 +0000353 generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000354 return CopyBB;
355}
356
357void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000358 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000359 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000360 EntryBB = &CopyBB->getParent()->getEntryBlock();
361
Tobias Grosser91f5b262014-06-04 08:06:40 +0000362 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000363 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000364}
365
Johannes Doerfert800e17a2016-02-02 14:16:01 +0000366Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
Tobias Grosser587f1f52017-01-28 07:42:10 +0000367 assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
Tobias Grosser3216f852016-08-04 06:55:53 +0000368
Tobias Grosser587f1f52017-01-28 07:42:10 +0000369 return getOrCreateAlloca(Access.getLatestScopArrayInfo());
Tobias Grossera4f09882015-10-17 22:16:00 +0000370}
371
372Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grosser3216f852016-08-04 06:55:53 +0000373 assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
374
Tobias Grosser587f1f52017-01-28 07:42:10 +0000375 auto &Addr = ScalarMap[Array];
376
377 if (Addr) {
378 // Allow allocas to be (temporarily) redirected once by adding a new
379 // old-alloca-addr to new-addr mapping to GlobalMap. This funcitionality
380 // is used for example by the OpenMP code generation where a first use
381 // of a scalar while still in the host code allocates a normal alloca with
382 // getOrCreateAlloca. When the values of this scalar are accessed during
383 // the generation of the parallel subfunction, these values are copied over
384 // to the parallel subfunction and each request for a scalar alloca slot
385 // must be forwared to the temporary in-subfunction slot. This mapping is
386 // removed when the subfunction has been generated and again normal host
Tobias Grosser682c5112017-01-28 11:39:02 +0000387 // code is generated. Due to the following reasons it is not possible to
388 // perform the GlobalMap lookup right after creating the alloca below, but
389 // instead we need to check GlobalMap at each call to getOrCreateAlloca:
390 //
391 // 1) GlobalMap may be changed multiple times (for each parallel loop),
392 // 2) The temporary mapping is commonly only known after the initial
393 // alloca has already been generated, and
394 // 3) The original alloca value must be restored after leaving the
395 // sub-function.
Tobias Grosser587f1f52017-01-28 07:42:10 +0000396 if (Value *NewAddr = GlobalMap.lookup(&*Addr))
397 return NewAddr;
398 return Addr;
399 }
400
401 Type *Ty = Array->getElementType();
402 Value *ScalarBase = Array->getBasePtr();
403 std::string NameExt;
Tobias Grossera535dff2015-12-13 19:59:01 +0000404 if (Array->isPHIKind())
Tobias Grosser587f1f52017-01-28 07:42:10 +0000405 NameExt = ".phiops";
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000406 else
Tobias Grosser587f1f52017-01-28 07:42:10 +0000407 NameExt = ".s2a";
408
409 Addr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
410 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
411 Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
412
413 return Addr;
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000414}
415
Tobias Grosser587f1f52017-01-28 07:42:10 +0000416void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
417 Instruction *Inst = cast<Instruction>(Array->getBasePtr());
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000418
Tobias Grosser29854002015-08-30 15:03:59 +0000419 // If there are escape users we get the alloca for this instruction and put it
420 // in the EscapeMap for later finalization. Lastly, if the instruction was
421 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000422 if (EscapeMap.count(Inst))
423 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000424
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000425 EscapeUserVectorTy EscapeUsers;
426 for (User *U : Inst->users()) {
427
428 // Non-instruction user will never escape.
429 Instruction *UI = dyn_cast<Instruction>(U);
430 if (!UI)
431 continue;
432
Johannes Doerfert952b5302016-05-23 12:40:48 +0000433 if (S.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000434 continue;
435
436 EscapeUsers.push_back(UI);
437 }
438
439 // Exit if no escape uses were found.
440 if (EscapeUsers.empty())
441 return;
442
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000443 // Get or create an escape alloca for this instruction.
Tobias Grosser587f1f52017-01-28 07:42:10 +0000444 auto *ScalarAddr = getOrCreateAlloca(Array);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000445
446 // Remember that this instruction has escape uses and the escape alloca.
447 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000448}
449
Michael Kruse2fa35192016-09-01 19:53:31 +0000450void BlockGenerator::generateScalarLoads(
451 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
452 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Michael Kruse225f0d12015-10-17 21:36:00 +0000453 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +0000454 if (MA->isOriginalArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000455 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000456
Michael Kruse77394f12016-09-30 14:01:46 +0000457#ifndef NDEBUG
458 auto *StmtDom = Stmt.getDomain();
459 auto *AccDom = isl_map_domain(MA->getAccessRelation());
460 assert(isl_set_is_subset(StmtDom, AccDom) &&
461 "Scalar must be loaded in all statement instances");
462 isl_set_free(StmtDom);
463 isl_set_free(AccDom);
464#endif
465
Michael Kruse2fa35192016-09-01 19:53:31 +0000466 auto *Address =
467 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Michael Kruseeac97262016-02-24 22:08:14 +0000468 assert((!isa<Instruction>(Address) ||
469 DT.dominates(cast<Instruction>(Address)->getParent(),
470 Builder.GetInsertBlock())) &&
471 "Domination violation");
Tobias Grosser583be062017-02-09 23:54:23 +0000472 BBMap[MA->getAccessValue()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000473 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000474 }
475}
476
Michael Kruse2fa35192016-09-01 19:53:31 +0000477void BlockGenerator::generateScalarStores(
478 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
479 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000480 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000481
Tobias Grosser21a059a2017-01-16 14:08:10 +0000482 assert(Stmt.isBlockStmt() &&
483 "Region statements need to use the generateScalarStores() function in "
484 "the RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000485
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000486 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +0000487 if (MA->isOriginalArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000488 continue;
489
Michael Kruse77394f12016-09-30 14:01:46 +0000490#ifndef NDEBUG
491 auto *StmtDom = Stmt.getDomain();
492 auto *AccDom = isl_map_domain(MA->getAccessRelation());
493 assert(isl_set_is_subset(StmtDom, AccDom) &&
494 "Scalar must be stored in all statement instances");
495 isl_set_free(StmtDom);
496 isl_set_free(AccDom);
497#endif
498
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000499 Value *Val = MA->getAccessValue();
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000500 if (MA->isAnyPHIKind()) {
501 assert(MA->getIncoming().size() >= 1 &&
502 "Block statements have exactly one exiting block, or multiple but "
503 "with same incoming block and value");
504 assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
505 [&](std::pair<BasicBlock *, Value *> p) -> bool {
506 return p.first == Stmt.getBasicBlock();
507 }) &&
508 "Incoming block must be statement's block");
509 Val = MA->getIncoming()[0].second;
510 }
Michael Kruse2fa35192016-09-01 19:53:31 +0000511 auto Address =
512 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000513
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000514 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
Michael Kruseeac97262016-02-24 22:08:14 +0000515 assert((!isa<Instruction>(Val) ||
516 DT.dominates(cast<Instruction>(Val)->getParent(),
517 Builder.GetInsertBlock())) &&
518 "Domination violation");
519 assert((!isa<Instruction>(Address) ||
520 DT.dominates(cast<Instruction>(Address)->getParent(),
521 Builder.GetInsertBlock())) &&
522 "Domination violation");
Tobias Grosser92245222015-07-28 14:53:44 +0000523 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000524 }
525}
526
Tobias Grosserc0091a72015-08-30 19:19:34 +0000527void BlockGenerator::createScalarInitialization(Scop &S) {
Johannes Doerfertef744432016-05-23 12:42:38 +0000528 BasicBlock *ExitBB = S.getExit();
Eli Friedmanacf80062016-11-02 22:32:23 +0000529 BasicBlock *PreEntryBB = S.getEnteringBlock();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000530
Eli Friedmanacf80062016-11-02 22:32:23 +0000531 Builder.SetInsertPoint(&*StartBlock->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000532
Roman Gareevd7754a12016-07-30 09:25:51 +0000533 for (auto &Array : S.arrays()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000534 if (Array->getNumberOfDimensions() != 0)
535 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000536 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000537 // For PHI nodes, the only values we need to store are the ones that
538 // reach the PHI node from outside the region. In general there should
539 // only be one such incoming edge and this edge should enter through
Eli Friedmanacf80062016-11-02 22:32:23 +0000540 // 'PreEntryBB'.
Tobias Grosserc0091a72015-08-30 19:19:34 +0000541 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000542
Tobias Grosserc0091a72015-08-30 19:19:34 +0000543 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
Eli Friedmanacf80062016-11-02 22:32:23 +0000544 if (!S.contains(*BI) && *BI != PreEntryBB)
Tobias Grosserc0091a72015-08-30 19:19:34 +0000545 llvm_unreachable("Incoming edges from outside the scop should always "
Eli Friedmanacf80062016-11-02 22:32:23 +0000546 "come from PreEntryBB");
Tobias Grosserc0091a72015-08-30 19:19:34 +0000547
Eli Friedmanacf80062016-11-02 22:32:23 +0000548 int Idx = PHI->getBasicBlockIndex(PreEntryBB);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000549 if (Idx < 0)
550 continue;
551
552 Value *ScalarValue = PHI->getIncomingValue(Idx);
553
Tobias Grosser587f1f52017-01-28 07:42:10 +0000554 Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000555 continue;
556 }
557
558 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
559
Johannes Doerfert952b5302016-05-23 12:40:48 +0000560 if (Inst && S.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000561 continue;
562
Johannes Doerfert188542f2015-11-09 00:21:21 +0000563 // PHI nodes that are not marked as such in their SAI object are either exit
564 // PHI nodes we model as common scalars but without initialization, or
565 // incoming phi nodes that need to be initialized. Check if the first is the
566 // case for Inst and do not create and initialize memory if so.
567 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
568 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
569 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000570
Tobias Grosser587f1f52017-01-28 07:42:10 +0000571 Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000572 }
573}
574
Johannes Doerfertef744432016-05-23 12:42:38 +0000575void BlockGenerator::createScalarFinalization(Scop &S) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000576 // The exit block of the __unoptimized__ region.
Johannes Doerfertef744432016-05-23 12:42:38 +0000577 BasicBlock *ExitBB = S.getExitingBlock();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000578 // The merge block __just after__ the region and the optimized region.
Johannes Doerfertef744432016-05-23 12:42:38 +0000579 BasicBlock *MergeBB = S.getExit();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000580
581 // The exit block of the __optimized__ region.
582 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
583 if (OptExitBB == ExitBB)
584 OptExitBB = *(++pred_begin(MergeBB));
585
586 Builder.SetInsertPoint(OptExitBB->getTerminator());
587 for (const auto &EscapeMapping : EscapeMap) {
588 // Extract the escaping instruction and the escaping users as well as the
589 // alloca the instruction was demoted to.
Michael Krusefbde4352016-08-05 16:45:51 +0000590 Instruction *EscapeInst = EscapeMapping.first;
591 const auto &EscapeMappingValue = EscapeMapping.second;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000592 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000593 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000594
595 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000596 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000597 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000598 EscapeInstReload =
599 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000600
601 // Create the merge PHI that merges the optimized and unoptimized version.
602 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
603 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000604 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000605
606 // Add the respective values to the merge PHI.
607 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
608 MergePHI->addIncoming(EscapeInst, ExitBB);
609
610 // The information of scalar evolution about the escaping instruction needs
611 // to be revoked so the new merged instruction will be used.
612 if (SE.isSCEVable(EscapeInst->getType()))
613 SE.forgetValue(EscapeInst);
614
615 // Replace all uses of the demoted instruction with the merge PHI.
616 for (Instruction *EUser : EscapeUsers)
617 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
618 }
619}
620
Tobias Grosserffa24462015-10-17 08:54:13 +0000621void BlockGenerator::findOutsideUsers(Scop &S) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000622 for (auto &Array : S.arrays()) {
Tobias Grosserffa24462015-10-17 08:54:13 +0000623
624 if (Array->getNumberOfDimensions() != 0)
625 continue;
626
Tobias Grossera535dff2015-12-13 19:59:01 +0000627 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000628 continue;
629
630 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
631
632 if (!Inst)
633 continue;
634
635 // Scop invariant hoisting moves some of the base pointers out of the scop.
636 // We can ignore these, as the invariant load hoisting already registers the
637 // relevant outside users.
Johannes Doerfert952b5302016-05-23 12:40:48 +0000638 if (!S.contains(Inst))
Tobias Grosserffa24462015-10-17 08:54:13 +0000639 continue;
640
Tobias Grosser587f1f52017-01-28 07:42:10 +0000641 handleOutsideUsers(S, Array);
Tobias Grosserffa24462015-10-17 08:54:13 +0000642 }
643}
644
Tobias Grosser27d742d2015-10-24 17:41:29 +0000645void BlockGenerator::createExitPHINodeMerges(Scop &S) {
646 if (S.hasSingleExitEdge())
647 return;
648
Johannes Doerfertef744432016-05-23 12:42:38 +0000649 auto *ExitBB = S.getExitingBlock();
650 auto *MergeBB = S.getExit();
Tobias Grosser27d742d2015-10-24 17:41:29 +0000651 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
652 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
653 if (OptExitBB == ExitBB)
654 OptExitBB = *(++pred_begin(MergeBB));
655
656 Builder.SetInsertPoint(OptExitBB->getTerminator());
657
Roman Gareevd7754a12016-07-30 09:25:51 +0000658 for (auto &SAI : S.arrays()) {
Tobias Grosser27d742d2015-10-24 17:41:29 +0000659 auto *Val = SAI->getBasePtr();
660
Michael Krusefaedfcb2016-03-03 17:20:43 +0000661 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
662 // the original PHI's value or the reloaded incoming values from the
663 // generated code. An llvm::Value is merged between the original code's
664 // value or the generated one.
Michael Krusefa53c862016-10-12 16:31:09 +0000665 if (!SAI->isExitPHIKind())
Michael Krusefaedfcb2016-03-03 17:20:43 +0000666 continue;
667
Tobias Grosser27d742d2015-10-24 17:41:29 +0000668 PHINode *PHI = dyn_cast<PHINode>(Val);
669 if (!PHI)
670 continue;
671
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000672 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000673 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000674
675 std::string Name = PHI->getName();
Tobias Grosser587f1f52017-01-28 07:42:10 +0000676 Value *ScalarAddr = getOrCreateAlloca(SAI);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000677 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
678 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
679 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
Michael Krusefaedfcb2016-03-03 17:20:43 +0000680 assert((!isa<Instruction>(OriginalValue) ||
681 cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
682 "Original value must no be one we just generated.");
Tobias Grosser27d742d2015-10-24 17:41:29 +0000683 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000684 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000685 MergePHI->addIncoming(Reload, OptExitBB);
686 MergePHI->addIncoming(OriginalValue, ExitBB);
687 int Idx = PHI->getBasicBlockIndex(MergeBB);
688 PHI->setIncomingValue(Idx, MergePHI);
689 }
690}
691
Tobias Grosser1c184402016-08-18 10:45:57 +0000692void BlockGenerator::invalidateScalarEvolution(Scop &S) {
693 for (auto &Stmt : S)
Roman Gareevb3224ad2016-09-14 06:26:09 +0000694 if (Stmt.isCopyStmt())
695 continue;
696 else if (Stmt.isBlockStmt())
Tobias Grosser1c184402016-08-18 10:45:57 +0000697 for (auto &Inst : *Stmt.getBasicBlock())
698 SE.forgetValue(&Inst);
699 else if (Stmt.isRegionStmt())
700 for (auto *BB : Stmt.getRegion()->blocks())
701 for (auto &Inst : *BB)
702 SE.forgetValue(&Inst);
703 else
704 llvm_unreachable("Unexpected statement type found");
705}
706
Tobias Grosserffa24462015-10-17 08:54:13 +0000707void BlockGenerator::finalizeSCoP(Scop &S) {
708 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000709 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000710 createExitPHINodeMerges(S);
Johannes Doerfertef744432016-05-23 12:42:38 +0000711 createScalarFinalization(S);
Tobias Grosser1c184402016-08-18 10:45:57 +0000712 invalidateScalarEvolution(S);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000713}
714
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000715VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000716 std::vector<LoopToScevMapT> &VLTS,
717 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000718 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000719 assert(Schedule && "No statement domain provided");
720}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000721
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000722Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000723 ValueMapT &VectorMap,
724 VectorValueMapT &ScalarMaps,
725 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000726 if (Value *NewValue = VectorMap.lookup(Old))
727 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000728
729 int Width = getVectorWidth();
730
731 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
732
733 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000734 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000735 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000736 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000737
738 VectorMap[Old] = Vector;
739
740 return Vector;
741}
742
743Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
744 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
745 assert(PointerTy && "PointerType expected");
746
747 Type *ScalarType = PointerTy->getElementType();
748 VectorType *VectorType = VectorType::get(ScalarType, Width);
749
750 return PointerType::getUnqual(VectorType);
751}
752
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000753Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000754 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000755 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000756 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000757 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000758 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
759 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
760
Michael Kruse8f25b0c2016-02-25 15:52:43 +0000761 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
762 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000763 Value *VectorPtr =
764 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
765 LoadInst *VecLoad =
766 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000767 if (!Aligned)
768 VecLoad->setAlignment(8);
769
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000770 if (NegativeStride) {
771 SmallVector<Constant *, 16> Indices;
772 for (int i = VectorWidth - 1; i >= 0; i--)
773 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
774 Constant *SV = llvm::ConstantVector::get(Indices);
775 Value *RevVecLoad = Builder.CreateShuffleVector(
776 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
777 return RevVecLoad;
778 }
779
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000780 return VecLoad;
781}
782
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000783Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000784 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000785 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000786 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Michael Kruse70131d32016-01-27 17:09:17 +0000788 Value *NewPointer =
789 generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000790 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
791 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000792 LoadInst *ScalarLoad =
793 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000794
795 if (!Aligned)
796 ScalarLoad->setAlignment(8);
797
Tobias Grosserc14582f2013-02-05 18:01:29 +0000798 Constant *SplatVector = Constant::getNullValue(
799 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000800
Tobias Grosserc14582f2013-02-05 18:01:29 +0000801 Value *VectorLoad = Builder.CreateShuffleVector(
802 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000803 return VectorLoad;
804}
805
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000806Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000807 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000808 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000809 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000810 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000811 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000812 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000813
814 Value *Vector = UndefValue::get(VectorType);
815
816 for (int i = 0; i < VectorWidth; i++) {
Michael Kruse70131d32016-01-27 17:09:17 +0000817 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
818 VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000819 Value *ScalarLoad =
820 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
821 Vector = Builder.CreateInsertElement(
822 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000823 }
824
825 return Vector;
826}
827
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000828void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000829 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000830 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000831 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
832 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
833 Load->getName() + "_p");
834 return;
835 }
836
Tobias Grosser28736452015-03-23 07:00:36 +0000837 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000838 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000839 ScalarMaps[i][Load] =
Michael Kruse888ab552016-09-30 14:34:05 +0000840 generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000841 return;
842 }
843
Tobias Grosser184a4922015-12-15 23:50:01 +0000844 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000845
Tobias Grosser95493982014-04-18 09:46:35 +0000846 // Make sure we have scalar values available to access the pointer to
847 // the data location.
848 extractScalarValues(Load, VectorMap, ScalarMaps);
849
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000850 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000851 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000852 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000853 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000854 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000855 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000856 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000857 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000858 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000859
860 VectorMap[Load] = NewLoad;
861}
862
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000863void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000864 ValueMapT &VectorMap,
865 VectorValueMapT &ScalarMaps) {
866 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000867 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000868 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000869
870 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
871
872 const CastInst *Cast = dyn_cast<CastInst>(Inst);
873 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
874 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
875}
876
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000877void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000878 ValueMapT &VectorMap,
879 VectorValueMapT &ScalarMaps) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000880 Loop *L = getLoopForStmt(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000881 Value *OpZero = Inst->getOperand(0);
882 Value *OpOne = Inst->getOperand(1);
883
884 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000885 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
886 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000887
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000888 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889 Inst->getName() + "p_vec");
890 VectorMap[Inst] = NewInst;
891}
892
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000893void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000894 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000895 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000896 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000897
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000898 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000899 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000900 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000901
Tobias Grosser50fd7012014-04-17 23:13:49 +0000902 // Make sure we have scalar values available to access the pointer to
903 // the data location.
904 extractScalarValues(Store, VectorMap, ScalarMaps);
905
Sebastian Popa00a0292012-12-18 07:46:06 +0000906 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000907 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Michael Kruse70131d32016-01-27 17:09:17 +0000908 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
909 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000910
Tobias Grosserc14582f2013-02-05 18:01:29 +0000911 Value *VectorPtr =
912 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
914
915 if (!Aligned)
916 Store->setAlignment(8);
917 } else {
918 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000919 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Michael Kruse70131d32016-01-27 17:09:17 +0000920 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
921 VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000922 Builder.CreateStore(Scalar, NewPointer);
923 }
924 }
925}
926
927bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
928 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000929 for (Value *Operand : Inst->operands())
930 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000931 return true;
932 return false;
933}
934
935bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
936 ValueMapT &VectorMap,
937 VectorValueMapT &ScalarMaps) {
938 bool HasVectorOperand = false;
939 int VectorWidth = getVectorWidth();
940
Tobias Grosser91f5b262014-06-04 08:06:40 +0000941 for (Value *Operand : Inst->operands()) {
942 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000943
944 if (VecOp == VectorMap.end())
945 continue;
946
947 HasVectorOperand = true;
948 Value *NewVector = VecOp->second;
949
950 for (int i = 0; i < VectorWidth; ++i) {
951 ValueMapT &SM = ScalarMaps[i];
952
953 // If there is one scalar extracted, all scalar elements should have
954 // already been extracted by the code here. So no need to check for the
Tobias Grosser2219d152016-08-03 05:28:09 +0000955 // existence of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000956 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000957 break;
958
Tobias Grosser91f5b262014-06-04 08:06:40 +0000959 SM[Operand] =
960 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000961 }
962 }
963
964 return HasVectorOperand;
965}
966
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000967void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000968 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000969 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000970 bool HasVectorOperand;
971 int VectorWidth = getVectorWidth();
972
973 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
974
975 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000976 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000977 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000978
979 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
980 return;
981
982 // Make the result available as vector value.
983 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
984 Value *Vector = UndefValue::get(VectorType);
985
986 for (int i = 0; i < VectorWidth; i++)
987 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
988 Builder.getInt32(i));
989
990 VectorMap[Inst] = Vector;
991}
992
Tobias Grosserbc132602015-09-05 09:56:54 +0000993int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000994
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000995void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000996 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000997 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000998 // Terminator instructions control the control flow. They are explicitly
999 // expressed in the clast and do not need to be copied.
1000 if (Inst->isTerminator())
1001 return;
1002
Johannes Doerfert5dced262015-12-22 19:08:49 +00001003 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +00001004 return;
1005
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001006 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001007 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001008 return;
1009 }
1010
1011 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001012 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Michael Kruse0446d812017-03-10 16:05:24 +00001013 // Identified as redundant by -polly-simplify.
1014 if (!Stmt.getArrayAccessOrNULLFor(Store))
1015 return;
1016
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001017 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001018 return;
1019 }
1020
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001021 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001022 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001023 return;
1024 }
1025
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001026 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001027 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001028 return;
1029 }
1030
1031 // Falltrough: We generate scalar instructions, if we don't know how to
1032 // generate vector code.
1033 }
1034
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001035 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001036}
1037
Tobias Grossera69d4f02015-12-15 23:49:58 +00001038void VectorBlockGenerator::generateScalarVectorLoads(
1039 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1040 for (MemoryAccess *MA : Stmt) {
1041 if (MA->isArrayKind() || MA->isWrite())
1042 continue;
1043
1044 auto *Address = getOrCreateAlloca(*MA);
1045 Type *VectorPtrType = getVectorPtrTy(Address, 1);
1046 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1047 Address->getName() + "_p_vec_p");
1048 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1049 Constant *SplatVector = Constant::getNullValue(
1050 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1051
1052 Value *VectorVal = Builder.CreateShuffleVector(
1053 Val, Val, SplatVector, Address->getName() + "_p_splat");
Tobias Grosser583be062017-02-09 23:54:23 +00001054 VectorBlockMap[MA->getAccessValue()] = VectorVal;
Tobias Grossera69d4f02015-12-15 23:49:58 +00001055 }
1056}
1057
1058void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1059 for (MemoryAccess *MA : Stmt) {
1060 if (MA->isArrayKind() || MA->isRead())
1061 continue;
1062
1063 llvm_unreachable("Scalar stores not expected in vector loop");
1064 }
1065}
1066
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001067void VectorBlockGenerator::copyStmt(
1068 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser21a059a2017-01-16 14:08:10 +00001069 assert(Stmt.isBlockStmt() &&
1070 "TODO: Only block statements can be copied by the vector block "
1071 "generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001072
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001073 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001074 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1075 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001076 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001077 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001078
1079 // Create two maps that store the mapping from the original instructions of
1080 // the old basic block to their copies in the new basic block. Those maps
1081 // are basic block local.
1082 //
1083 // As vector code generation is supported there is one map for scalar values
1084 // and one for vector values.
1085 //
1086 // In case we just do scalar code generation, the vectorMap is not used and
1087 // the scalarMap has just one dimension, which contains the mapping.
1088 //
1089 // In case vector code generation is done, an instruction may either appear
1090 // in the vector map once (as it is calculating >vectorwidth< values at a
1091 // time. Or (if the values are calculated using scalar operations), it
1092 // appears once in every dimension of the scalarMap.
1093 VectorValueMapT ScalarBlockMap(getVectorWidth());
1094 ValueMapT VectorBlockMap;
1095
Tobias Grossera69d4f02015-12-15 23:49:58 +00001096 generateScalarVectorLoads(Stmt, VectorBlockMap);
1097
Tobias Grosser91f5b262014-06-04 08:06:40 +00001098 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001099 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001100
1101 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001102}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001103
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001104BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1105 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001106
1107 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1108 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1109
1110 if (BBCopyIDom)
1111 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1112
1113 return BBCopyIDom;
1114}
1115
Michael Krusef33c1252016-02-25 14:08:48 +00001116// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1117// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1118// does not work in cases where the exit block has edges from outside the
1119// region. In that case the llvm::Value would never be usable in in the exit
1120// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1121// for the subregion's exiting edges only. We need to determine whether an
1122// llvm::Value is usable in there. We do this by checking whether it dominates
1123// all exiting blocks individually.
1124static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1125 BasicBlock *BB) {
1126 for (auto ExitingBB : predecessors(R->getExit())) {
1127 // Check for non-subregion incoming edges.
1128 if (!R->contains(ExitingBB))
1129 continue;
1130
1131 if (!DT.dominates(BB, ExitingBB))
1132 return false;
1133 }
1134
1135 return true;
1136}
1137
1138// Find the direct dominator of the subregion's exit block if the subregion was
1139// simplified.
1140static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1141 BasicBlock *Common = nullptr;
1142 for (auto ExitingBB : predecessors(R->getExit())) {
1143 // Check for non-subregion incoming edges.
1144 if (!R->contains(ExitingBB))
1145 continue;
1146
1147 // First exiting edge.
1148 if (!Common) {
1149 Common = ExitingBB;
1150 continue;
1151 }
1152
1153 Common = DT.findNearestCommonDominator(Common, ExitingBB);
1154 }
1155
1156 assert(Common && R->contains(Common));
1157 return Common;
1158}
1159
Tobias Grosserbc132602015-09-05 09:56:54 +00001160void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001161 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001162 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001163 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001164
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001165 // Forget all old mappings.
1166 BlockMap.clear();
1167 RegionMaps.clear();
1168 IncompletePHINodeMap.clear();
1169
Michael Kruse225f0d12015-10-17 21:36:00 +00001170 // Collection of all values related to this subregion.
1171 ValueMapT ValueMap;
1172
Johannes Doerfert275a1752015-02-24 16:16:32 +00001173 // The region represented by the statement.
1174 Region *R = Stmt.getRegion();
1175
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001176 // Create a dedicated entry for the region where we can reload all demoted
1177 // inputs.
1178 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001179 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1180 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001181 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001182 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001183
Michael Krusec9937392015-11-09 23:33:40 +00001184 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
Michael Kruse2fa35192016-09-01 19:53:31 +00001185 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
Michael Kruse225f0d12015-10-17 21:36:00 +00001186
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001187 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1188 if (!R->contains(*PI))
1189 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001190
1191 // Iterate over all blocks in the region in a breadth-first search.
1192 std::deque<BasicBlock *> Blocks;
Mandeep Singh Grang5b1abfc2016-10-19 17:56:49 +00001193 SmallSetVector<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001194 Blocks.push_back(EntryBB);
1195 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001196
1197 while (!Blocks.empty()) {
1198 BasicBlock *BB = Blocks.front();
1199 Blocks.pop_front();
1200
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001201 // First split the block and update dominance information.
1202 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001203 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1204
Michael Krusec9937392015-11-09 23:33:40 +00001205 // Get the mapping for this block and initialize it with either the scalar
1206 // loads from the generated entering block (which dominates all blocks of
1207 // this subregion) or the maps of the immediate dominator, if part of the
1208 // subregion. The latter necessarily includes the former.
1209 ValueMapT *InitBBMap;
1210 if (BBCopyIDom) {
1211 assert(RegionMaps.count(BBCopyIDom));
1212 InitBBMap = &RegionMaps[BBCopyIDom];
1213 } else
1214 InitBBMap = &EntryBBMap;
1215 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1216 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001217
Johannes Doerfert275a1752015-02-24 16:16:32 +00001218 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001219 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001220 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001221
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001222 // In order to remap PHI nodes we store also basic block mappings.
1223 BlockMap[BB] = BBCopy;
1224
1225 // Add values to incomplete PHI nodes waiting for this block to be copied.
1226 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001227 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001228 IncompletePHINodeMap[BB].clear();
1229
Johannes Doerfert275a1752015-02-24 16:16:32 +00001230 // And continue with new successors inside the region.
1231 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
Mandeep Singh Grang5b1abfc2016-10-19 17:56:49 +00001232 if (R->contains(*SI) && SeenBlocks.insert(*SI))
Johannes Doerfert275a1752015-02-24 16:16:32 +00001233 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001234
1235 // Remember value in case it is visible after this subregion.
Michael Krusef33c1252016-02-25 14:08:48 +00001236 if (isDominatingSubregionExit(DT, R, BB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001237 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001238 }
1239
1240 // 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 +00001241 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1242 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001243 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001244 BlockMap[R->getExit()] = ExitBBCopy;
1245
Michael Krusef33c1252016-02-25 14:08:48 +00001246 BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
Tobias Grosser21a059a2017-01-16 14:08:10 +00001247 assert(ExitDomBBCopy &&
1248 "Common exit dominator must be within region; at least the entry node "
1249 "must match");
Michael Krusef33c1252016-02-25 14:08:48 +00001250 DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001251
1252 // As the block generator doesn't handle control flow we need to add the
1253 // region control flow by hand after all blocks have been copied.
1254 for (BasicBlock *BB : SeenBlocks) {
1255
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001256 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001257 TerminatorInst *TI = BB->getTerminator();
1258 if (isa<UnreachableInst>(TI)) {
1259 while (!BBCopy->empty())
1260 BBCopy->begin()->eraseFromParent();
1261 new UnreachableInst(BBCopy->getContext(), BBCopy);
1262 continue;
1263 }
1264
Johannes Doerfert275a1752015-02-24 16:16:32 +00001265 Instruction *BICopy = BBCopy->getTerminator();
1266
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001267 ValueMapT &RegionMap = RegionMaps[BBCopy];
1268 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1269
Tobias Grosser45e79442015-08-01 09:07:57 +00001270 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001271 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001272 BICopy->eraseFromParent();
1273 }
1274
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001275 // Add counting PHI nodes to all loops in the region that can be used as
1276 // replacement for SCEVs refering to the old loop.
1277 for (BasicBlock *BB : SeenBlocks) {
1278 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001279 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001280 continue;
1281
1282 BasicBlock *BBCopy = BlockMap[BB];
1283 Value *NullVal = Builder.getInt32(0);
1284 PHINode *LoopPHI =
1285 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1286 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1287 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001288 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001289 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1290
1291 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1292 if (!R->contains(PredBB))
1293 continue;
1294 if (L->contains(PredBB))
1295 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1296 else
1297 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1298 }
1299
1300 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1301 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1302 LoopPHI->addIncoming(NullVal, PredBBCopy);
1303
1304 LTS[L] = SE.getUnknown(LoopPHI);
1305 }
1306
Michael Kruse225f0d12015-10-17 21:36:00 +00001307 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001308 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001309
1310 // Write values visible to other statements.
Michael Kruse2fa35192016-09-01 19:53:31 +00001311 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
Tobias Grosser3e956022015-10-26 20:41:53 +00001312 BlockMap.clear();
1313 RegionMaps.clear();
1314 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001315}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001316
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001317PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1318 ValueMapT &BBMap, Loop *L) {
1319 ScopStmt *Stmt = MA->getStatement();
1320 Region *SubR = Stmt->getRegion();
1321 auto Incoming = MA->getIncoming();
1322
1323 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1324 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1325 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1326
1327 // This can happen if the subregion is simplified after the ScopStmts
1328 // have been created; simplification happens as part of CodeGeneration.
1329 if (OrigPHI->getParent() != SubR->getExit()) {
1330 BasicBlock *FormerExit = SubR->getExitingBlock();
1331 if (FormerExit)
1332 NewSubregionExit = BlockMap.lookup(FormerExit);
1333 }
1334
1335 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1336 "polly." + OrigPHI->getName(),
1337 NewSubregionExit->getFirstNonPHI());
1338
1339 // Add the incoming values to the PHI.
1340 for (auto &Pair : Incoming) {
1341 BasicBlock *OrigIncomingBlock = Pair.first;
1342 BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1343 Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1344 assert(RegionMaps.count(NewIncomingBlock));
1345 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1346
1347 Value *OrigIncomingValue = Pair.second;
1348 Value *NewIncomingValue =
1349 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1350 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1351 }
1352
1353 return NewPHI;
1354}
1355
1356Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1357 ValueMapT &BBMap) {
1358 ScopStmt *Stmt = MA->getStatement();
1359
1360 // TODO: Add some test cases that ensure this is really the right choice.
1361 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1362
1363 if (MA->isAnyPHIKind()) {
1364 auto Incoming = MA->getIncoming();
1365 assert(!Incoming.empty() &&
1366 "PHI WRITEs must have originate from at least one incoming block");
1367
1368 // If there is only one incoming value, we do not need to create a PHI.
1369 if (Incoming.size() == 1) {
1370 Value *OldVal = Incoming[0].second;
1371 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1372 }
1373
1374 return buildExitPHI(MA, LTS, BBMap, L);
1375 }
1376
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001377 // MemoryKind::Value accesses leaving the subregion must dominate the exit
1378 // block; just pass the copied value.
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001379 Value *OldVal = MA->getAccessValue();
1380 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1381}
1382
Michael Kruse2fa35192016-09-01 19:53:31 +00001383void RegionGenerator::generateScalarStores(
1384 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1385 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser75296902015-08-21 19:23:21 +00001386 assert(Stmt.getRegion() &&
1387 "Block statements need to use the generateScalarStores() "
1388 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001389
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001390 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +00001391 if (MA->isOriginalArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001392 continue;
1393
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001394 Value *NewVal = getExitScalar(MA, LTS, BBMap);
Michael Kruse2fa35192016-09-01 19:53:31 +00001395 Value *Address =
1396 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Michael Kruseeac97262016-02-24 22:08:14 +00001397 assert((!isa<Instruction>(NewVal) ||
1398 DT.dominates(cast<Instruction>(NewVal)->getParent(),
1399 Builder.GetInsertBlock())) &&
1400 "Domination violation");
1401 assert((!isa<Instruction>(Address) ||
1402 DT.dominates(cast<Instruction>(Address)->getParent(),
1403 Builder.GetInsertBlock())) &&
1404 "Domination violation");
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001405 Builder.CreateStore(NewVal, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001406 }
1407}
1408
Tobias Grosser943c3692017-01-19 13:25:52 +00001409void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001410 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001411 LoopToScevMapT &LTS) {
1412 Region *StmtR = Stmt.getRegion();
1413
1414 // If the incoming block was not yet copied mark this PHI as incomplete.
1415 // Once the block will be copied the incoming value will be added.
1416 BasicBlock *BBCopy = BlockMap[IncomingBB];
1417 if (!BBCopy) {
1418 assert(StmtR->contains(IncomingBB) &&
1419 "Bad incoming block for PHI in non-affine region");
1420 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1421 return;
1422 }
1423
Tobias Grosser75dfaa12017-01-19 14:12:45 +00001424 assert(RegionMaps.count(BBCopy) && "Incoming PHI block did not have a BBMap");
1425 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001426
Tobias Grosser75dfaa12017-01-19 14:12:45 +00001427 Value *OpCopy = nullptr;
1428
1429 if (StmtR->contains(IncomingBB)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001430 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001431
Johannes Doerfert6ba92712016-04-01 11:25:47 +00001432 // If the current insert block is different from the PHIs incoming block
1433 // change it, otherwise do not.
1434 auto IP = Builder.GetInsertPoint();
1435 if (IP->getParent() != BBCopy)
1436 Builder.SetInsertPoint(BBCopy->getTerminator());
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +00001437 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
Johannes Doerfert6ba92712016-04-01 11:25:47 +00001438 if (IP->getParent() != BBCopy)
1439 Builder.SetInsertPoint(&*IP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001440 } else {
Tobias Grosser75dfaa12017-01-19 14:12:45 +00001441 // All edges from outside the non-affine region become a single edge
1442 // in the new copy of the non-affine region. Make sure to only add the
1443 // corresponding edge the first time we encounter a basic block from
1444 // outside the non-affine region.
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001445 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1446 return;
1447
Tobias Grosser75dfaa12017-01-19 14:12:45 +00001448 // Get the reloaded value.
1449 OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001450 }
1451
1452 assert(OpCopy && "Incoming PHI value was not copied properly");
1453 assert(BBCopy && "Incoming PHI block was not copied properly");
1454 PHICopy->addIncoming(OpCopy, BBCopy);
1455}
1456
Tobias Grosser2b809d12016-02-21 15:44:34 +00001457void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1458 ValueMapT &BBMap,
1459 LoopToScevMapT &LTS) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001460 unsigned NumIncoming = PHI->getNumIncomingValues();
1461 PHINode *PHICopy =
1462 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1463 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1464 BBMap[PHI] = PHICopy;
1465
Tobias Grosser97b84902017-01-19 05:09:23 +00001466 for (BasicBlock *IncomingBB : PHI->blocks())
1467 addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001468}