blob: 9143307041830757ff2a16361c90c402ec428ff4 [file] [log] [blame]
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the BlockGenerator and VectorBlockGenerator classes,
11// which generate sequential code and vectorized code for a polyhedral
12// statement, respectively.
13//
14//===----------------------------------------------------------------------===//
15
16#include "polly/ScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000017#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000018#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000019#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser86bc93a2015-09-06 08:47:57 +000020#include "polly/CodeGen/RuntimeDebugBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000021#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000022#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000023#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000024#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000025#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000026#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000027#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser030237d2014-02-21 15:06:05 +000028#include "llvm/IR/IntrinsicInst.h"
Tobias Grosserc9895062015-03-10 15:24:33 +000029#include "llvm/IR/Module.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser1b9d25a2015-09-27 11:17:22 +000031#include "llvm/Transforms/Utils/Local.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000032#include "isl/aff.h"
33#include "isl/ast.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000034#include "isl/ast_build.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "isl/set.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000036#include <deque>
37
Hongbin Zheng3b11a162012-04-25 13:16:49 +000038using namespace llvm;
39using namespace polly;
40
Tobias Grosser878aba42014-10-22 23:22:41 +000041static cl::opt<bool> Aligned("enable-polly-aligned",
42 cl::desc("Assumed aligned memory accesses."),
43 cl::Hidden, cl::init(false), cl::ZeroOrMore,
44 cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000045
Tobias Grosser86bc93a2015-09-06 08:47:57 +000046static cl::opt<bool> DebugPrinting(
47 "polly-codegen-add-debug-printing",
48 cl::desc("Add printf calls that show the values loaded/stored."),
49 cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
50
Tobias Grosserdcc3b432015-08-04 13:54:20 +000051bool polly::canSynthesize(const Value *V, const llvm::LoopInfo *LI,
Tobias Grosserecfe21b2013-03-20 18:03:18 +000052 ScalarEvolution *SE, const Region *R) {
Tobias Grosserdcc3b432015-08-04 13:54:20 +000053 if (!V || !SE->isSCEVable(V->getType()))
Tobias Grosserecfe21b2013-03-20 18:03:18 +000054 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000055
Tobias Grosserdcc3b432015-08-04 13:54:20 +000056 if (const SCEV *Scev = SE->getSCEV(const_cast<Value *>(V)))
Tobias Grosser683b8e42014-11-30 14:33:31 +000057 if (!isa<SCEVCouldNotCompute>(Scev))
58 if (!hasScalarDepsInsideRegion(Scev, R))
59 return true;
60
61 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000062}
63
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000064bool polly::isIgnoredIntrinsic(const Value *V) {
65 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
66 switch (IT->getIntrinsicID()) {
67 // Lifetime markers are supported/ignored.
68 case llvm::Intrinsic::lifetime_start:
69 case llvm::Intrinsic::lifetime_end:
70 // Invariant markers are supported/ignored.
71 case llvm::Intrinsic::invariant_start:
72 case llvm::Intrinsic::invariant_end:
73 // Some misc annotations are supported/ignored.
74 case llvm::Intrinsic::var_annotation:
75 case llvm::Intrinsic::ptr_annotation:
76 case llvm::Intrinsic::annotation:
77 case llvm::Intrinsic::donothing:
78 case llvm::Intrinsic::assume:
79 case llvm::Intrinsic::expect:
Tobias Grossere83a3962015-08-30 16:57:20 +000080 // Some debug info intrisics are supported/ignored.
81 case llvm::Intrinsic::dbg_value:
82 case llvm::Intrinsic::dbg_declare:
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000083 return true;
84 default:
85 break;
86 }
87 }
88 return false;
89}
90
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000091BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
92 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000093 ScalarAllocaMapTy &ScalarMap,
94 ScalarAllocaMapTy &PHIOpMap,
95 EscapeUsersAllocaMapTy &EscapeMap,
Tobias Grosserf4bb7a62015-10-04 10:18:32 +000096 ValueMapT &GlobalMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000097 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000098 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
99 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
Tobias Grosserbc132602015-09-05 09:56:54 +0000100 EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000101
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000102Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000103 ValueMapT &BBMap,
104 LoopToScevMapT &LTS,
105 Loop *L) const {
Tobias Grosser683b8e42014-11-30 14:33:31 +0000106 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000107 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000108 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000109 const SCEV *NewScev = apply(Scev, LTS, SE);
Johannes Doerfert09e36972015-10-07 20:17:36 +0000110 ValueMapT VTV;
Sebastian Pop637b23d2013-02-15 20:56:01 +0000111 VTV.insert(BBMap.begin(), BBMap.end());
112 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Johannes Doerferte69e1142015-08-18 11:56:00 +0000113
114 Scop &S = *Stmt.getParent();
115 const DataLayout &DL =
116 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
117 auto IP = Builder.GetInsertPoint();
118
119 assert(IP != Builder.GetInsertBlock()->end() &&
Tobias Grosser45e79442015-08-01 09:07:57 +0000120 "Only instructions can be insert points for SCEVExpander");
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000121 Value *Expanded = expandCodeFor(S, SE, DL, "polly", NewScev,
122 Old->getType(), IP, &VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000123
124 BBMap[Old] = Expanded;
125 return Expanded;
126 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000127 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000128
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000129 return nullptr;
130}
131
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000132Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
133 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000134 // We assume constants never change.
135 // This avoids map lookups for many calls to this function.
136 if (isa<Constant>(Old))
137 return const_cast<Value *>(Old);
138
139 if (Value *New = GlobalMap.lookup(Old)) {
140 if (Value *NewRemapped = GlobalMap.lookup(New))
141 New = NewRemapped;
142 if (Old->getType()->getScalarSizeInBits() <
143 New->getType()->getScalarSizeInBits())
144 New = Builder.CreateTruncOrBitCast(New, Old->getType());
145
146 return New;
147 }
148
149 if (Value *New = BBMap.lookup(Old))
150 return New;
151
152 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
153 return New;
154
Tobias Grosser16371ac2014-11-05 20:48:56 +0000155 // A scop-constant value defined by a global or a function parameter.
156 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
157 return const_cast<Value *>(Old);
158
159 // A scop-constant value defined by an instruction executed outside the scop.
160 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000161 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000162 return const_cast<Value *>(Old);
163
164 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000165 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000166 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000167}
168
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000169void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000170 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000171 // We do not generate debug intrinsics as we did not investigate how to
172 // copy them correctly. At the current state, they just crash the code
173 // generation as the meta-data operands are not correctly copied.
174 if (isa<DbgInfoIntrinsic>(Inst))
175 return;
176
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000177 Instruction *NewInst = Inst->clone();
178
179 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000180 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000181 Value *NewOperand =
182 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000183
184 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000185 assert(!isa<StoreInst>(NewInst) &&
186 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000187 delete NewInst;
188 return;
189 }
190
191 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
192 }
193
194 Builder.Insert(NewInst);
195 BBMap[Inst] = NewInst;
196
197 if (!NewInst->getType()->isVoidTy())
198 NewInst->setName("p_" + Inst->getName());
199}
200
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000201Value *BlockGenerator::generateLocationAccessed(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000202 ScopStmt &Stmt, const Instruction *Inst, Value *Pointer, ValueMapT &BBMap,
203 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000204 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000205
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000206 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000207
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000208 if (AccessExpr) {
209 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000210 auto Address = ExprBuilder->create(AccessExpr);
211
212 // Cast the address of this memory access to a pointer type that has the
213 // same element type as the original access, but uses the address space of
214 // the newly generated pointer.
215 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
216 auto NewPtrTy = Address->getType();
217 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
218 NewPtrTy->getPointerAddressSpace());
219
220 if (OldPtrTy != NewPtrTy) {
221 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
222 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
223 "Pointer types to elements with different size found");
224 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
225 }
226 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000227 }
228
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000230}
231
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000232Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000233 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000234}
235
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000236Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000237 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000238 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000239 if (Value *PreloadLoad = GlobalMap.lookup(Load))
240 return PreloadLoad;
241
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000242 auto *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000243 Value *NewPointer =
244 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000245 Value *ScalarLoad = Builder.CreateAlignedLoad(
246 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000247
248 if (DebugPrinting)
249 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
250 ": ", ScalarLoad, "\n");
251
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000252 return ScalarLoad;
253}
254
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000255void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000256 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000257 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000258 auto *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000259 Value *NewPointer =
260 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
261 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
262 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000263
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000264 if (DebugPrinting)
265 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
266 ": ", ValueOperand, "\n");
267
Tobias Grosserc186ac72015-08-11 08:13:15 +0000268 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000269}
270
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000271void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000272 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000273 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000274
275 // First check for possible scalar dependences for this instruction.
Tobias Grosserbc132602015-09-05 09:56:54 +0000276 generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000277
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000278 // Terminator instructions control the control flow. They are explicitly
279 // expressed in the clast and do not need to be copied.
280 if (Inst->isTerminator())
281 return;
282
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000283 Loop *L = getLoopForInst(Inst);
284 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
285 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000286 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000287 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000288 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000289
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000290 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000291 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000292 // Compute NewLoad before its insertion in BBMap to make the insertion
293 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000294 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000295 return;
296 }
297
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000298 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000299 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000300 return;
301 }
302
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000303 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000304 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000305 return;
306 }
307
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000308 // Skip some special intrinsics for which we do not adjust the semantics to
309 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000310 if (isIgnoredIntrinsic(Inst))
311 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000312
Tobias Grosserbc132602015-09-05 09:56:54 +0000313 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000314}
315
Tobias Grosserbc132602015-09-05 09:56:54 +0000316void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000317 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000318 assert(Stmt.isBlockStmt() &&
319 "Only block statements can be copied by the block generator");
320
321 ValueMapT BBMap;
322
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000323 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000324 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000325}
326
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000327BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000328 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000329 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000330 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000331 return CopyBB;
332}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000333
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000334BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000335 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000336 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000337 BasicBlock *CopyBB = splitBB(BB);
Tobias Grosserbc132602015-09-05 09:56:54 +0000338 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000339 return CopyBB;
340}
341
342void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
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 Builder.SetInsertPoint(CopyBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000346 EntryBB = &CopyBB->getParent()->getEntryBlock();
347
Tobias Grosser91f5b262014-06-04 08:06:40 +0000348 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000349 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000350
351 // After a basic block was copied store all scalars that escape this block
352 // in their alloca. First the scalars that have dependences inside the SCoP,
353 // then the ones that might escape the SCoP.
Tobias Grosseraff56c82015-09-30 13:36:54 +0000354 generateScalarStores(Stmt, BB, LTS, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000355
356 const Region &R = Stmt.getParent()->getRegion();
357 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000358 handleOutsideUsers(R, &Inst, BBMap[&Inst]);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000359}
360
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000361Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
362 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000363 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000364 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000365 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000366 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000367 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000368 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000369 NewAddr->insertBefore(EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000370 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000371 }
372
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000373 auto Addr = Map[ScalarBase];
374
Tobias Grosserbc132602015-09-05 09:56:54 +0000375 if (GlobalMap.count(Addr))
376 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000377
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000378 return Addr;
379}
380
Tobias Grosserbc132602015-09-05 09:56:54 +0000381Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000382 if (Access.getScopArrayInfo()->isPHI())
Tobias Grosserbc132602015-09-05 09:56:54 +0000383 return getOrCreatePHIAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000384 else
Tobias Grosserbc132602015-09-05 09:56:54 +0000385 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000386}
387
Tobias Grosserbc132602015-09-05 09:56:54 +0000388Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
389 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000390}
391
Tobias Grosserbc132602015-09-05 09:56:54 +0000392Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
393 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000394}
395
Tobias Grosserbc132602015-09-05 09:56:54 +0000396void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosserb09455d2015-09-18 06:01:11 +0000397 Value *InstCopy, Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000398 // If there are escape users we get the alloca for this instruction and put it
399 // in the EscapeMap for later finalization. Lastly, if the instruction was
400 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000401 if (EscapeMap.count(Inst))
402 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000403
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000404 EscapeUserVectorTy EscapeUsers;
405 for (User *U : Inst->users()) {
406
407 // Non-instruction user will never escape.
408 Instruction *UI = dyn_cast<Instruction>(U);
409 if (!UI)
410 continue;
411
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000412 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000413 continue;
414
415 EscapeUsers.push_back(UI);
416 }
417
418 // Exit if no escape uses were found.
419 if (EscapeUsers.empty())
420 return;
421
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000422 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000423 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000424
425 // Remember that this instruction has escape uses and the escape alloca.
426 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000427}
428
429void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
430 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000431 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000432 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000433
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000434 if (!MAL)
435 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000436
Michael Krusee2bccbb2015-09-18 19:59:43 +0000437 for (MemoryAccess *MA : *MAL) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000438 if (MA->isExplicit() || !MA->isRead())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000439 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000440
Michael Krusee2bccbb2015-09-18 19:59:43 +0000441 auto *Address = getOrCreateAlloca(*MA);
442 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000443 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000444 }
445}
446
447Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000448 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000449 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000450 // If the value we want to store is an instruction we might have demoted it
451 // in order to make it accessible here. In such a case a reload is
452 // necessary. If it is no instruction it will always be a value that
453 // dominates the current point and we can just use it. In total there are 4
454 // options:
455 // (1) The value is no instruction ==> use the value.
456 // (2) The value is an instruction that was split out of the region prior to
457 // code generation ==> use the instruction as it dominates the region.
458 // (3) The value is an instruction:
459 // (a) The value was defined in the current block, thus a copy is in
460 // the BBMap ==> use the mapped value.
461 // (b) The value was defined in a previous block, thus we demoted it
462 // earlier ==> use the reloaded value.
463 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
464 if (!ScalarValueInst)
465 return ScalarValue;
466
467 if (!R.contains(ScalarValueInst)) {
468 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
469 return /* Case (3a) */ ScalarValueCopy;
470 else
471 return /* Case 2 */ ScalarValue;
472 }
473
474 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
475 return /* Case (3a) */ ScalarValueCopy;
476
Tobias Grosseraff56c82015-09-30 13:36:54 +0000477 if ((Stmt.isBlockStmt() &&
478 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
479 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
480 auto SynthesizedValue = trySynthesizeNewValue(
481 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
482
483 if (SynthesizedValue)
484 return SynthesizedValue;
485 }
486
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000487 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000488 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000489 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000490
491 return ScalarValue;
492}
493
494void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000495 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000496 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000497 const Region &R = Stmt.getParent()->getRegion();
498
499 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
500 "Region statements need to use the generateScalarStores() "
501 "function in the RegionGenerator");
502
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000503 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000504 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000505 continue;
506
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000507 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000508 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000509
Tobias Grosseraff56c82015-09-30 13:36:54 +0000510 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000511 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000512 }
513}
514
Tobias Grosserc0091a72015-08-30 19:19:34 +0000515void BlockGenerator::createScalarInitialization(Scop &S) {
516 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000517 // The split block __just before__ the region and optimized region.
518 BasicBlock *SplitBB = R.getEnteringBlock();
519 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
520 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
521
522 // Get the start block of the __optimized__ region.
523 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
524 if (StartBB == R.getEntry())
525 StartBB = SplitBBTerm->getSuccessor(1);
526
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000527 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000528
Tobias Grosserc0091a72015-08-30 19:19:34 +0000529 for (auto &Pair : S.arrays()) {
530 auto &Array = Pair.second;
531 if (Array->getNumberOfDimensions() != 0)
532 continue;
533 if (Array->isPHI()) {
534 // For PHI nodes, the only values we need to store are the ones that
535 // reach the PHI node from outside the region. In general there should
536 // only be one such incoming edge and this edge should enter through
537 // 'SplitBB'.
538 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000539
Tobias Grosserc0091a72015-08-30 19:19:34 +0000540 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
541 if (!R.contains(*BI) && *BI != SplitBB)
542 llvm_unreachable("Incoming edges from outside the scop should always "
543 "come from SplitBB");
544
545 int Idx = PHI->getBasicBlockIndex(SplitBB);
546 if (Idx < 0)
547 continue;
548
549 Value *ScalarValue = PHI->getIncomingValue(Idx);
550
Tobias Grosserbc132602015-09-05 09:56:54 +0000551 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000552 continue;
553 }
554
555 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
556
557 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000558 continue;
559
Johannes Doerfert717b8662015-09-08 21:44:27 +0000560 // PHI nodes that are not marked as such in their SAI object are exit PHI
561 // nodes we model as common scalars but do not need to initialize.
562 if (Inst && isa<PHINode>(Inst))
563 continue;
564
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000565 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000566 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000567 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000568 }
569}
570
571void BlockGenerator::createScalarFinalization(Region &R) {
572 // The exit block of the __unoptimized__ region.
573 BasicBlock *ExitBB = R.getExitingBlock();
574 // The merge block __just after__ the region and the optimized region.
575 BasicBlock *MergeBB = R.getExit();
576
577 // The exit block of the __optimized__ region.
578 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
579 if (OptExitBB == ExitBB)
580 OptExitBB = *(++pred_begin(MergeBB));
581
582 Builder.SetInsertPoint(OptExitBB->getTerminator());
583 for (const auto &EscapeMapping : EscapeMap) {
584 // Extract the escaping instruction and the escaping users as well as the
585 // alloca the instruction was demoted to.
586 Instruction *EscapeInst = EscapeMapping.getFirst();
587 const auto &EscapeMappingValue = EscapeMapping.getSecond();
588 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000589 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000590
591 // Reload the demoted instruction in the optimized version of the SCoP.
592 Instruction *EscapeInstReload =
593 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
594
595 // Create the merge PHI that merges the optimized and unoptimized version.
596 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
597 EscapeInst->getName() + ".merge");
598 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
599
600 // Add the respective values to the merge PHI.
601 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
602 MergePHI->addIncoming(EscapeInst, ExitBB);
603
604 // The information of scalar evolution about the escaping instruction needs
605 // to be revoked so the new merged instruction will be used.
606 if (SE.isSCEVable(EscapeInst->getType()))
607 SE.forgetValue(EscapeInst);
608
609 // Replace all uses of the demoted instruction with the merge PHI.
610 for (Instruction *EUser : EscapeUsers)
611 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
612 }
613}
614
Tobias Grosser655a4572015-08-30 17:32:39 +0000615void BlockGenerator::finalizeSCoP(Scop &S) {
Johannes Doerfert717b8662015-09-08 21:44:27 +0000616
617 // Handle PHI nodes that were in the original exit and are now
618 // moved into the region exiting block.
619 if (!S.hasSingleExitEdge()) {
620 for (Instruction &I : *S.getRegion().getExitingBlock()) {
621 PHINode *PHI = dyn_cast<PHINode>(&I);
622 if (!PHI)
623 break;
624
625 assert(PHI->getNumUses() == 1);
626 assert(ScalarMap.count(PHI->user_back()));
627
628 handleOutsideUsers(S.getRegion(), PHI, nullptr,
629 ScalarMap[PHI->user_back()]);
630 }
631 }
632
Tobias Grosserc0091a72015-08-30 19:19:34 +0000633 createScalarInitialization(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000634 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000635}
636
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000637VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000638 std::vector<LoopToScevMapT> &VLTS,
639 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000640 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000641 assert(Schedule && "No statement domain provided");
642}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000643
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000644Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000645 ValueMapT &VectorMap,
646 VectorValueMapT &ScalarMaps,
647 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000648 if (Value *NewValue = VectorMap.lookup(Old))
649 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000650
651 int Width = getVectorWidth();
652
653 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
654
655 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000656 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000657 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000658 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000659
660 VectorMap[Old] = Vector;
661
662 return Vector;
663}
664
665Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
666 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
667 assert(PointerTy && "PointerType expected");
668
669 Type *ScalarType = PointerTy->getElementType();
670 VectorType *VectorType = VectorType::get(ScalarType, Width);
671
672 return PointerType::getUnqual(VectorType);
673}
674
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000675Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000676 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000677 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000678 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000679 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000680 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
681 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
682
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000683 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000684 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
685 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000686 Value *VectorPtr =
687 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
688 LoadInst *VecLoad =
689 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000690 if (!Aligned)
691 VecLoad->setAlignment(8);
692
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000693 if (NegativeStride) {
694 SmallVector<Constant *, 16> Indices;
695 for (int i = VectorWidth - 1; i >= 0; i--)
696 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
697 Constant *SV = llvm::ConstantVector::get(Indices);
698 Value *RevVecLoad = Builder.CreateShuffleVector(
699 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
700 return RevVecLoad;
701 }
702
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000703 return VecLoad;
704}
705
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000706Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000707 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000708 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000709 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000710 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000711 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
712 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000713 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
714 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000715 LoadInst *ScalarLoad =
716 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000717
718 if (!Aligned)
719 ScalarLoad->setAlignment(8);
720
Tobias Grosserc14582f2013-02-05 18:01:29 +0000721 Constant *SplatVector = Constant::getNullValue(
722 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000723
Tobias Grosserc14582f2013-02-05 18:01:29 +0000724 Value *VectorLoad = Builder.CreateShuffleVector(
725 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000726 return VectorLoad;
727}
728
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000729Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000730 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000731 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000733 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000734 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000735 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000736
737 Value *Vector = UndefValue::get(VectorType);
738
739 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000740 Value *NewPointer = generateLocationAccessed(
741 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000742 Value *ScalarLoad =
743 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
744 Vector = Builder.CreateInsertElement(
745 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000746 }
747
748 return Vector;
749}
750
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000751void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000752 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000753 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000754 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
755 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
756 Load->getName() + "_p");
757 return;
758 }
759
Tobias Grosser28736452015-03-23 07:00:36 +0000760 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000761 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000762 ScalarMaps[i][Load] =
763 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000764 return;
765 }
766
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000767 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000768
Tobias Grosser95493982014-04-18 09:46:35 +0000769 // Make sure we have scalar values available to access the pointer to
770 // the data location.
771 extractScalarValues(Load, VectorMap, ScalarMaps);
772
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000773 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000774 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000775 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000776 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000777 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000778 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000779 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000780 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000781 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000782
783 VectorMap[Load] = NewLoad;
784}
785
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000786void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787 ValueMapT &VectorMap,
788 VectorValueMapT &ScalarMaps) {
789 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000790 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
791 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792
793 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
794
795 const CastInst *Cast = dyn_cast<CastInst>(Inst);
796 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
797 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
798}
799
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000800void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000801 ValueMapT &VectorMap,
802 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000803 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000804 Value *OpZero = Inst->getOperand(0);
805 Value *OpOne = Inst->getOperand(1);
806
807 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000808 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
809 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000810
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000811 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000812 Inst->getName() + "p_vec");
813 VectorMap[Inst] = NewInst;
814}
815
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000816void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000817 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000818 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000819 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000820
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000821 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000822 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000823 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000824
Tobias Grosser50fd7012014-04-17 23:13:49 +0000825 // Make sure we have scalar values available to access the pointer to
826 // the data location.
827 extractScalarValues(Store, VectorMap, ScalarMaps);
828
Sebastian Popa00a0292012-12-18 07:46:06 +0000829 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000830 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000831 Value *NewPointer = generateLocationAccessed(
832 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000833
Tobias Grosserc14582f2013-02-05 18:01:29 +0000834 Value *VectorPtr =
835 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000836 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
837
838 if (!Aligned)
839 Store->setAlignment(8);
840 } else {
841 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000842 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000843 Value *NewPointer = generateLocationAccessed(
844 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000845 Builder.CreateStore(Scalar, NewPointer);
846 }
847 }
848}
849
850bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
851 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000852 for (Value *Operand : Inst->operands())
853 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000854 return true;
855 return false;
856}
857
858bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
859 ValueMapT &VectorMap,
860 VectorValueMapT &ScalarMaps) {
861 bool HasVectorOperand = false;
862 int VectorWidth = getVectorWidth();
863
Tobias Grosser91f5b262014-06-04 08:06:40 +0000864 for (Value *Operand : Inst->operands()) {
865 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866
867 if (VecOp == VectorMap.end())
868 continue;
869
870 HasVectorOperand = true;
871 Value *NewVector = VecOp->second;
872
873 for (int i = 0; i < VectorWidth; ++i) {
874 ValueMapT &SM = ScalarMaps[i];
875
876 // If there is one scalar extracted, all scalar elements should have
877 // already been extracted by the code here. So no need to check for the
878 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000879 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000880 break;
881
Tobias Grosser91f5b262014-06-04 08:06:40 +0000882 SM[Operand] =
883 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000884 }
885 }
886
887 return HasVectorOperand;
888}
889
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000890void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000891 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000892 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000893 bool HasVectorOperand;
894 int VectorWidth = getVectorWidth();
895
896 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
897
898 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000899 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000900 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000901
902 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
903 return;
904
905 // Make the result available as vector value.
906 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
907 Value *Vector = UndefValue::get(VectorType);
908
909 for (int i = 0; i < VectorWidth; i++)
910 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
911 Builder.getInt32(i));
912
913 VectorMap[Inst] = Vector;
914}
915
Tobias Grosserbc132602015-09-05 09:56:54 +0000916int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000917
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000918void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000919 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000920 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000921 // Terminator instructions control the control flow. They are explicitly
922 // expressed in the clast and do not need to be copied.
923 if (Inst->isTerminator())
924 return;
925
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000926 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000927 return;
928
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000929 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000930 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000931 return;
932 }
933
934 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000935 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000936 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000937 return;
938 }
939
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000940 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000941 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000942 return;
943 }
944
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000945 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000946 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000947 return;
948 }
949
950 // Falltrough: We generate scalar instructions, if we don't know how to
951 // generate vector code.
952 }
953
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000954 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000955}
956
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000957void VectorBlockGenerator::copyStmt(
958 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000959 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
960 "the vector block generator");
961
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000962 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000963 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000964 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000965 CopyBB->setName("polly.stmt." + BB->getName());
966 Builder.SetInsertPoint(CopyBB->begin());
967
968 // Create two maps that store the mapping from the original instructions of
969 // the old basic block to their copies in the new basic block. Those maps
970 // are basic block local.
971 //
972 // As vector code generation is supported there is one map for scalar values
973 // and one for vector values.
974 //
975 // In case we just do scalar code generation, the vectorMap is not used and
976 // the scalarMap has just one dimension, which contains the mapping.
977 //
978 // In case vector code generation is done, an instruction may either appear
979 // in the vector map once (as it is calculating >vectorwidth< values at a
980 // time. Or (if the values are calculated using scalar operations), it
981 // appears once in every dimension of the scalarMap.
982 VectorValueMapT ScalarBlockMap(getVectorWidth());
983 ValueMapT VectorBlockMap;
984
Tobias Grosser91f5b262014-06-04 08:06:40 +0000985 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000986 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000987}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000988
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000989BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
990 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000991
992 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
993 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
994
995 if (BBCopyIDom)
996 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
997
998 return BBCopyIDom;
999}
1000
Tobias Grosserbc132602015-09-05 09:56:54 +00001001void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001002 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001003 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001004 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001005
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001006 // Forget all old mappings.
1007 BlockMap.clear();
1008 RegionMaps.clear();
1009 IncompletePHINodeMap.clear();
1010
Johannes Doerfert275a1752015-02-24 16:16:32 +00001011 // The region represented by the statement.
1012 Region *R = Stmt.getRegion();
1013
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001014 // Create a dedicated entry for the region where we can reload all demoted
1015 // inputs.
1016 BasicBlock *EntryBB = R->getEntry();
1017 BasicBlock *EntryBBCopy =
1018 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
1019 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1020 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001021
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001022 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1023 if (!R->contains(*PI))
1024 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001025
1026 // Iterate over all blocks in the region in a breadth-first search.
1027 std::deque<BasicBlock *> Blocks;
1028 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001029 Blocks.push_back(EntryBB);
1030 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001031
1032 while (!Blocks.empty()) {
1033 BasicBlock *BB = Blocks.front();
1034 Blocks.pop_front();
1035
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001036 // First split the block and update dominance information.
1037 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001038 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1039
1040 // In order to remap PHI nodes we store also basic block mappings.
1041 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001042
1043 // Get the mapping for this block and initialize it with the mapping
1044 // available at its immediate dominator (in the new region).
1045 ValueMapT &RegionMap = RegionMaps[BBCopy];
1046 RegionMap = RegionMaps[BBCopyIDom];
1047
Johannes Doerfert275a1752015-02-24 16:16:32 +00001048 // Copy the block with the BlockGenerator.
Tobias Grosserbc132602015-09-05 09:56:54 +00001049 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001050
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001051 // In order to remap PHI nodes we store also basic block mappings.
1052 BlockMap[BB] = BBCopy;
1053
1054 // Add values to incomplete PHI nodes waiting for this block to be copied.
1055 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001056 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001057 IncompletePHINodeMap[BB].clear();
1058
Johannes Doerfert275a1752015-02-24 16:16:32 +00001059 // And continue with new successors inside the region.
1060 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1061 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1062 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001063 }
1064
1065 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001066 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001067 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001068 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001069 BlockMap[R->getExit()] = ExitBBCopy;
1070
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001071 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001072
1073 // As the block generator doesn't handle control flow we need to add the
1074 // region control flow by hand after all blocks have been copied.
1075 for (BasicBlock *BB : SeenBlocks) {
1076
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001077 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001078 TerminatorInst *TI = BB->getTerminator();
1079 if (isa<UnreachableInst>(TI)) {
1080 while (!BBCopy->empty())
1081 BBCopy->begin()->eraseFromParent();
1082 new UnreachableInst(BBCopy->getContext(), BBCopy);
1083 continue;
1084 }
1085
Johannes Doerfert275a1752015-02-24 16:16:32 +00001086 Instruction *BICopy = BBCopy->getTerminator();
1087
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001088 ValueMapT &RegionMap = RegionMaps[BBCopy];
1089 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1090
Tobias Grosser45e79442015-08-01 09:07:57 +00001091 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001092 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001093 BICopy->eraseFromParent();
1094 }
1095
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001096 // Add counting PHI nodes to all loops in the region that can be used as
1097 // replacement for SCEVs refering to the old loop.
1098 for (BasicBlock *BB : SeenBlocks) {
1099 Loop *L = LI.getLoopFor(BB);
1100 if (L == nullptr || L->getHeader() != BB)
1101 continue;
1102
1103 BasicBlock *BBCopy = BlockMap[BB];
1104 Value *NullVal = Builder.getInt32(0);
1105 PHINode *LoopPHI =
1106 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1107 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1108 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1109 LoopPHI->insertBefore(BBCopy->begin());
1110 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1111
1112 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1113 if (!R->contains(PredBB))
1114 continue;
1115 if (L->contains(PredBB))
1116 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1117 else
1118 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1119 }
1120
1121 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1122 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1123 LoopPHI->addIncoming(NullVal, PredBBCopy);
1124
1125 LTS[L] = SE.getUnknown(LoopPHI);
1126 }
1127
Johannes Doerfert275a1752015-02-24 16:16:32 +00001128 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001129 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001130}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001131
1132void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1133 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +00001134 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001135
1136 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1137 // phi is copied it will reload all inputs from outside the region, hence
1138 // we do not need to generate code for the read access of the operands of a
1139 // PHI.
1140 if (isa<PHINode>(Inst))
1141 return;
1142
Tobias Grosserbc132602015-09-05 09:56:54 +00001143 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001144}
1145
1146void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +00001147 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001148 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001149 const Region &R = Stmt.getParent()->getRegion();
1150
Tobias Grosser75296902015-08-21 19:23:21 +00001151 assert(Stmt.getRegion() &&
1152 "Block statements need to use the generateScalarStores() "
1153 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001154
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001155 for (MemoryAccess *MA : Stmt) {
1156
Michael Kruse8d0b7342015-09-25 21:21:00 +00001157 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001158 continue;
1159
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001160 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001161
Tobias Grosser62139132015-08-02 16:17:41 +00001162 // Only generate accesses that belong to this basic block.
1163 if (ScalarInst->getParent() != BB)
1164 continue;
1165
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001166 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001167
Tobias Grosserbc132602015-09-05 09:56:54 +00001168 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001169
Tobias Grosseraff56c82015-09-30 13:36:54 +00001170 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001171 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001172 }
1173}
1174
1175void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1176 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001177 LoopToScevMapT &LTS) {
1178 Region *StmtR = Stmt.getRegion();
1179
1180 // If the incoming block was not yet copied mark this PHI as incomplete.
1181 // Once the block will be copied the incoming value will be added.
1182 BasicBlock *BBCopy = BlockMap[IncomingBB];
1183 if (!BBCopy) {
1184 assert(StmtR->contains(IncomingBB) &&
1185 "Bad incoming block for PHI in non-affine region");
1186 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1187 return;
1188 }
1189
1190 Value *OpCopy = nullptr;
1191 if (StmtR->contains(IncomingBB)) {
1192 assert(RegionMaps.count(BBCopy) &&
1193 "Incoming PHI block did not have a BBMap");
1194 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1195
1196 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Tobias Grosserbc132602015-09-05 09:56:54 +00001197 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001198 } else {
1199
1200 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1201 return;
1202
Tobias Grosserbc132602015-09-05 09:56:54 +00001203 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001204 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1205 BlockMap[IncomingBB]->getTerminator());
1206 }
1207
1208 assert(OpCopy && "Incoming PHI value was not copied properly");
1209 assert(BBCopy && "Incoming PHI block was not copied properly");
1210 PHICopy->addIncoming(OpCopy, BBCopy);
1211}
1212
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001213Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001214 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001215 LoopToScevMapT &LTS) {
1216 unsigned NumIncoming = PHI->getNumIncomingValues();
1217 PHINode *PHICopy =
1218 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1219 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1220 BBMap[PHI] = PHICopy;
1221
1222 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001223 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001224 return PHICopy;
1225}