13b11a16aSHongbin Zheng //===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
23b11a16aSHongbin Zheng //
33b11a16aSHongbin Zheng //                     The LLVM Compiler Infrastructure
43b11a16aSHongbin Zheng //
53b11a16aSHongbin Zheng // This file is distributed under the University of Illinois Open Source
63b11a16aSHongbin Zheng // License. See LICENSE.TXT for details.
73b11a16aSHongbin Zheng //
83b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
93b11a16aSHongbin Zheng //
103b11a16aSHongbin Zheng // This file implements the BlockGenerator and VectorBlockGenerator classes,
113b11a16aSHongbin Zheng // which generate sequential code and vectorized code for a polyhedral
123b11a16aSHongbin Zheng // statement, respectively.
133b11a16aSHongbin Zheng //
143b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
153b11a16aSHongbin Zheng 
168a846610SHongbin Zheng #include "polly/CodeGen/BlockGenerators.h"
1783628182STobias Grosser #include "polly/CodeGen/CodeGeneration.h"
18a63b2579SJohannes Doerfert #include "polly/CodeGen/IslExprBuilder.h"
1986bc93a9STobias Grosser #include "polly/CodeGen/RuntimeDebugBuilder.h"
20637bd631STobias Grosser #include "polly/Options.h"
215624d3c9STobias Grosser #include "polly/ScopInfo.h"
223b11a16aSHongbin Zheng #include "polly/Support/GICHelper.h"
2397cb813cSSebastian Pop #include "polly/Support/SCEVValidator.h"
24ecfe21b7STobias Grosser #include "polly/Support/ScopHelper.h"
25eedae763SMichael Kruse #include "polly/Support/VirtualInstruction.h"
26e71c6ab5STobias Grosser #include "llvm/Analysis/LoopInfo.h"
27f32d651dSJohannes Doerfert #include "llvm/Analysis/RegionInfo.h"
28e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolution.h"
29fd94eee3SDavid Blaikie #include "llvm/Analysis/Utils/Local.h"
30030237d0STobias Grosser #include "llvm/IR/IntrinsicInst.h"
31c9895067STobias Grosser #include "llvm/IR/Module.h"
323b11a16aSHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33f32d651dSJohannes Doerfert #include "isl/aff.h"
34f32d651dSJohannes Doerfert #include "isl/ast.h"
35f32d651dSJohannes Doerfert #include "isl/ast_build.h"
36ba0d0922STobias Grosser #include "isl/set.h"
37f32d651dSJohannes Doerfert #include <deque>
38f32d651dSJohannes Doerfert 
393b11a16aSHongbin Zheng using namespace llvm;
403b11a16aSHongbin Zheng using namespace polly;
413b11a16aSHongbin Zheng 
42878aba49STobias Grosser static cl::opt<bool> Aligned("enable-polly-aligned",
43878aba49STobias Grosser                              cl::desc("Assumed aligned memory accesses."),
44878aba49STobias Grosser                              cl::Hidden, cl::init(false), cl::ZeroOrMore,
45878aba49STobias Grosser                              cl::cat(PollyCategory));
463b11a16aSHongbin Zheng 
471be726a4STobias Grosser bool PollyDebugPrinting;
481be726a4STobias Grosser static cl::opt<bool, true> DebugPrintingX(
4986bc93a9STobias Grosser     "polly-codegen-add-debug-printing",
5086bc93a9STobias Grosser     cl::desc("Add printf calls that show the values loaded/stored."),
511be726a4STobias Grosser     cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false),
521be726a4STobias Grosser     cl::ZeroOrMore, cl::cat(PollyCategory));
5386bc93a9STobias Grosser 
54acf80064SEli Friedman BlockGenerator::BlockGenerator(
55acf80064SEli Friedman     PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
56587f1f57STobias Grosser     AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
57587f1f57STobias Grosser     ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
58ecff11dcSJohannes Doerfert     : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
59587f1f57STobias Grosser       EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
60587f1f57STobias Grosser       GlobalMap(GlobalMap), StartBlock(StartBlock) {}
61e71c6ab5STobias Grosser 
622f1acac6STobias Grosser Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
6333cb9f94STobias Grosser                                              ValueMapT &BBMap,
6433cb9f94STobias Grosser                                              LoopToScevMapT &LTS,
65bc132607STobias Grosser                                              Loop *L) const {
6642df8d1dSJohannes Doerfert   if (!SE.isSCEVable(Old->getType()))
6742df8d1dSJohannes Doerfert     return nullptr;
6842df8d1dSJohannes Doerfert 
6942df8d1dSJohannes Doerfert   const SCEV *Scev = SE.getSCEVAtScope(Old, L);
7042df8d1dSJohannes Doerfert   if (!Scev)
7142df8d1dSJohannes Doerfert     return nullptr;
7242df8d1dSJohannes Doerfert 
7342df8d1dSJohannes Doerfert   if (isa<SCEVCouldNotCompute>(Scev))
7442df8d1dSJohannes Doerfert     return nullptr;
7542df8d1dSJohannes Doerfert 
7603bcb910SSanjoy Das   const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
7709e3697fSJohannes Doerfert   ValueMapT VTV;
78637b23dcSSebastian Pop   VTV.insert(BBMap.begin(), BBMap.end());
79637b23dcSSebastian Pop   VTV.insert(GlobalMap.begin(), GlobalMap.end());
80e69e1141SJohannes Doerfert 
81e69e1141SJohannes Doerfert   Scop &S = *Stmt.getParent();
823f52e354SJohannes Doerfert   const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
83e69e1141SJohannes Doerfert   auto IP = Builder.GetInsertPoint();
84e69e1141SJohannes Doerfert 
85e69e1141SJohannes Doerfert   assert(IP != Builder.GetInsertBlock()->end() &&
8645e7944bSTobias Grosser          "Only instructions can be insert points for SCEVExpander");
8742df8d1dSJohannes Doerfert   Value *Expanded =
88acf80064SEli Friedman       expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
89acf80064SEli Friedman                     StartBlock->getSinglePredecessor());
90e71c6ab5STobias Grosser 
91e71c6ab5STobias Grosser   BBMap[Old] = Expanded;
92e71c6ab5STobias Grosser   return Expanded;
93e71c6ab5STobias Grosser }
9433cb9f94STobias Grosser 
952f1acac6STobias Grosser Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
962f1acac6STobias Grosser                                    LoopToScevMapT &LTS, Loop *L) const {
9733cb9f94STobias Grosser 
98eedae763SMichael Kruse   auto lookupGlobally = [this](Value *Old) -> Value * {
99eedae763SMichael Kruse     Value *New = GlobalMap.lookup(Old);
100eedae763SMichael Kruse     if (!New)
101eedae763SMichael Kruse       return nullptr;
10228f8ac1dSJohannes Doerfert 
103eedae763SMichael Kruse     // Required by:
104eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll
105eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll
106eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll
107eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll
108eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
109eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
110eedae763SMichael Kruse     // GlobalMap should be a mapping from (value in original SCoP) to (copied
111eedae763SMichael Kruse     // value in generated SCoP), without intermediate mappings, which might
112eedae763SMichael Kruse     // easily require transitiveness as well.
11333cb9f94STobias Grosser     if (Value *NewRemapped = GlobalMap.lookup(New))
11433cb9f94STobias Grosser       New = NewRemapped;
115eedae763SMichael Kruse 
116eedae763SMichael Kruse     // No test case for this code.
11733cb9f94STobias Grosser     if (Old->getType()->getScalarSizeInBits() <
11833cb9f94STobias Grosser         New->getType()->getScalarSizeInBits())
11933cb9f94STobias Grosser       New = Builder.CreateTruncOrBitCast(New, Old->getType());
12033cb9f94STobias Grosser 
12133cb9f94STobias Grosser     return New;
122eedae763SMichael Kruse   };
123eedae763SMichael Kruse 
124eedae763SMichael Kruse   Value *New = nullptr;
125eedae763SMichael Kruse   auto VUse = VirtualUse::create(&Stmt, L, Old, true);
126eedae763SMichael Kruse   switch (VUse.getKind()) {
127eedae763SMichael Kruse   case VirtualUse::Block:
128eedae763SMichael Kruse     // BasicBlock are constants, but the BlockGenerator copies them.
129eedae763SMichael Kruse     New = BBMap.lookup(Old);
130eedae763SMichael Kruse     break;
131eedae763SMichael Kruse 
132eedae763SMichael Kruse   case VirtualUse::Constant:
133eedae763SMichael Kruse     // Used by:
134eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll
135eedae763SMichael Kruse     // Constants should not be redefined. In this case, the GlobalMap just
136eedae763SMichael Kruse     // contains a mapping to the same constant, which is unnecessary, but
137eedae763SMichael Kruse     // harmless.
138eedae763SMichael Kruse     if ((New = lookupGlobally(Old)))
139eedae763SMichael Kruse       break;
140eedae763SMichael Kruse 
141eedae763SMichael Kruse     assert(!BBMap.count(Old));
142eedae763SMichael Kruse     New = Old;
143eedae763SMichael Kruse     break;
144eedae763SMichael Kruse 
145eedae763SMichael Kruse   case VirtualUse::ReadOnly:
146eedae763SMichael Kruse     assert(!GlobalMap.count(Old));
147eedae763SMichael Kruse 
148eedae763SMichael Kruse     // Required for:
149eedae763SMichael Kruse     // * Isl/CodeGen/MemAccess/create_arrays.ll
150eedae763SMichael Kruse     // * Isl/CodeGen/read-only-scalars.ll
151eedae763SMichael Kruse     // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
152eedae763SMichael Kruse     // For some reason these reload a read-only value. The reloaded value ends
153eedae763SMichael Kruse     // up in BBMap, buts its value should be identical.
154eedae763SMichael Kruse     //
155eedae763SMichael Kruse     // Required for:
156eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/single_loop_with_param.ll
157eedae763SMichael Kruse     // The parallel subfunctions need to reference the read-only value from the
158eedae763SMichael Kruse     // parent function, this is done by reloading them locally.
159eedae763SMichael Kruse     if ((New = BBMap.lookup(Old)))
160eedae763SMichael Kruse       break;
161eedae763SMichael Kruse 
162eedae763SMichael Kruse     New = Old;
163eedae763SMichael Kruse     break;
164eedae763SMichael Kruse 
165eedae763SMichael Kruse   case VirtualUse::Synthesizable:
166eedae763SMichael Kruse     // Used by:
167eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
168eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/recomputed-srem.ll
169eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/reference-other-bb.ll
170eedae763SMichael Kruse     // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll
171eedae763SMichael Kruse     // For some reason synthesizable values end up in GlobalMap. Their values
172eedae763SMichael Kruse     // are the same as trySynthesizeNewValue would return. The legacy
173eedae763SMichael Kruse     // implementation prioritized GlobalMap, so this is what we do here as well.
174eedae763SMichael Kruse     // Ideally, synthesizable values should not end up in GlobalMap.
175eedae763SMichael Kruse     if ((New = lookupGlobally(Old)))
176eedae763SMichael Kruse       break;
177eedae763SMichael Kruse 
178eedae763SMichael Kruse     // Required for:
179eedae763SMichael Kruse     // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll
180eedae763SMichael Kruse     // * Isl/CodeGen/getNumberOfIterations.ll
181eedae763SMichael Kruse     // * Isl/CodeGen/non_affine_float_compare.ll
182eedae763SMichael Kruse     // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
183eedae763SMichael Kruse     // Ideally, synthesizable values are synthesized by trySynthesizeNewValue,
184eedae763SMichael Kruse     // not precomputed (SCEVExpander has its own caching mechanism).
185eedae763SMichael Kruse     // These tests fail without this, but I think trySynthesizeNewValue would
186eedae763SMichael Kruse     // just re-synthesize the same instructions.
187eedae763SMichael Kruse     if ((New = BBMap.lookup(Old)))
188eedae763SMichael Kruse       break;
189eedae763SMichael Kruse 
190eedae763SMichael Kruse     New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L);
191eedae763SMichael Kruse     break;
192eedae763SMichael Kruse 
193eedae763SMichael Kruse   case VirtualUse::Hoisted:
194eedae763SMichael Kruse     // TODO: Hoisted invariant loads should be found in GlobalMap only, but not
195eedae763SMichael Kruse     // redefined locally (which will be ignored anyway). That is, the following
196eedae763SMichael Kruse     // assertion should apply: assert(!BBMap.count(Old))
197eedae763SMichael Kruse 
198eedae763SMichael Kruse     New = lookupGlobally(Old);
199eedae763SMichael Kruse     break;
200eedae763SMichael Kruse 
201eedae763SMichael Kruse   case VirtualUse::Intra:
202eedae763SMichael Kruse   case VirtualUse::Inter:
203eedae763SMichael Kruse     assert(!GlobalMap.count(Old) &&
204eedae763SMichael Kruse            "Intra and inter-stmt values are never global");
205eedae763SMichael Kruse     New = BBMap.lookup(Old);
206eedae763SMichael Kruse     break;
20733cb9f94STobias Grosser   }
208eedae763SMichael Kruse   assert(New && "Unexpected scalar dependence in region!");
20933cb9f94STobias Grosser   return New;
2103b11a16aSHongbin Zheng }
2113b11a16aSHongbin Zheng 
2122f1acac6STobias Grosser void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
213bc132607STobias Grosser                                     ValueMapT &BBMap, LoopToScevMapT &LTS) {
214030237d0STobias Grosser   // We do not generate debug intrinsics as we did not investigate how to
215030237d0STobias Grosser   // copy them correctly. At the current state, they just crash the code
216030237d0STobias Grosser   // generation as the meta-data operands are not correctly copied.
217030237d0STobias Grosser   if (isa<DbgInfoIntrinsic>(Inst))
218030237d0STobias Grosser     return;
219030237d0STobias Grosser 
2203b11a16aSHongbin Zheng   Instruction *NewInst = Inst->clone();
2213b11a16aSHongbin Zheng 
2223b11a16aSHongbin Zheng   // Replace old operands with the new ones.
22391f5b262STobias Grosser   for (Value *OldOperand : Inst->operands()) {
224bc132607STobias Grosser     Value *NewOperand =
2252c3ffc04SJohannes Doerfert         getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
2263b11a16aSHongbin Zheng 
2273b11a16aSHongbin Zheng     if (!NewOperand) {
228c14582f2STobias Grosser       assert(!isa<StoreInst>(NewInst) &&
229c14582f2STobias Grosser              "Store instructions are always needed!");
23096ab8726SReid Kleckner       NewInst->deleteValue();
2313b11a16aSHongbin Zheng       return;
2323b11a16aSHongbin Zheng     }
2333b11a16aSHongbin Zheng 
2343b11a16aSHongbin Zheng     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
2353b11a16aSHongbin Zheng   }
2363b11a16aSHongbin Zheng 
2373b11a16aSHongbin Zheng   Builder.Insert(NewInst);
2383b11a16aSHongbin Zheng   BBMap[Inst] = NewInst;
2393b11a16aSHongbin Zheng 
240188053afSSingapuram Sanjay Srivallabh   // When copying the instruction onto the Module meant for the GPU,
241188053afSSingapuram Sanjay Srivallabh   // debug metadata attached to an instruction causes all related
242188053afSSingapuram Sanjay Srivallabh   // metadata to be pulled into the Module. This includes the DICompileUnit,
243188053afSSingapuram Sanjay Srivallabh   // which will not be listed in llvm.dbg.cu of the Module since the Module
244188053afSSingapuram Sanjay Srivallabh   // doesn't contain one. This fails the verification of the Module and the
245188053afSSingapuram Sanjay Srivallabh   // subsequent generation of the ASM string.
246188053afSSingapuram Sanjay Srivallabh   if (NewInst->getModule() != Inst->getModule())
247188053afSSingapuram Sanjay Srivallabh     NewInst->setDebugLoc(llvm::DebugLoc());
248188053afSSingapuram Sanjay Srivallabh 
2493b11a16aSHongbin Zheng   if (!NewInst->getType()->isVoidTy())
2503b11a16aSHongbin Zheng     NewInst->setName("p_" + Inst->getName());
2513b11a16aSHongbin Zheng }
2523b11a16aSHongbin Zheng 
25370131d34SMichael Kruse Value *
25470131d34SMichael Kruse BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
25570131d34SMichael Kruse                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
25670131d34SMichael Kruse                                          isl_id_to_ast_expr *NewAccesses) {
25709214772STobias Grosser   const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
2582fa35194SMichael Kruse   return generateLocationAccessed(
2592fa35194SMichael Kruse       Stmt, getLoopForStmt(Stmt),
2602fa35194SMichael Kruse       Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
261fe46c3ffSTobias Grosser       NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
2622fa35194SMichael Kruse }
2633b11a16aSHongbin Zheng 
2642fa35194SMichael Kruse Value *BlockGenerator::generateLocationAccessed(
2652fa35194SMichael Kruse     ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
2662fa35194SMichael Kruse     LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
2672fa35194SMichael Kruse     Type *ExpectedType) {
2682fa35194SMichael Kruse   isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
2693b11a16aSHongbin Zheng 
2702d1ed0bfSTobias Grosser   if (AccessExpr) {
2712d1ed0bfSTobias Grosser     AccessExpr = isl_ast_expr_address_of(AccessExpr);
27298b3ee50STobias Grosser     auto Address = ExprBuilder->create(AccessExpr);
27398b3ee50STobias Grosser 
27498b3ee50STobias Grosser     // Cast the address of this memory access to a pointer type that has the
27598b3ee50STobias Grosser     // same element type as the original access, but uses the address space of
27698b3ee50STobias Grosser     // the newly generated pointer.
2772fa35194SMichael Kruse     auto OldPtrTy = ExpectedType->getPointerTo();
27898b3ee50STobias Grosser     auto NewPtrTy = Address->getType();
27998b3ee50STobias Grosser     OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
28098b3ee50STobias Grosser                                 NewPtrTy->getPointerAddressSpace());
28198b3ee50STobias Grosser 
282d840fc72STobias Grosser     if (OldPtrTy != NewPtrTy)
28398b3ee50STobias Grosser       Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
28498b3ee50STobias Grosser     return Address;
2852d1ed0bfSTobias Grosser   }
2862fa35194SMichael Kruse   assert(
2872fa35194SMichael Kruse       Pointer &&
2882fa35194SMichael Kruse       "If expression was not generated, must use the original pointer value");
2892fa35194SMichael Kruse   return getNewValue(Stmt, Pointer, BBMap, LTS, L);
2902fa35194SMichael Kruse }
2912d1ed0bfSTobias Grosser 
2922fa35194SMichael Kruse Value *
2932fa35194SMichael Kruse BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
2942fa35194SMichael Kruse                                    LoopToScevMapT &LTS, ValueMapT &BBMap,
2952fa35194SMichael Kruse                                    __isl_keep isl_id_to_ast_expr *NewAccesses) {
2962fa35194SMichael Kruse   if (Access.isLatestArrayKind())
2972fa35194SMichael Kruse     return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
298fe46c3ffSTobias Grosser                                     LTS, NewAccesses, Access.getId().release(),
2992fa35194SMichael Kruse                                     Access.getAccessValue()->getType());
3002fa35194SMichael Kruse 
301587f1f57STobias Grosser   return getOrCreateAlloca(Access);
3023b11a16aSHongbin Zheng }
3033b11a16aSHongbin Zheng 
3042c3ffc04SJohannes Doerfert Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
305375cb5feSMichael Kruse   auto *StmtBB = Stmt.getEntryBlock();
3062c3ffc04SJohannes Doerfert   return LI.getLoopFor(StmtBB);
307369430ffSTobias Grosser }
308369430ffSTobias Grosser 
309888ab551SMichael Kruse Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
310bc132607STobias Grosser                                          ValueMapT &BBMap, LoopToScevMapT &LTS,
3112d1ed0bfSTobias Grosser                                          isl_id_to_ast_expr *NewAccesses) {
312c1db67e2SJohannes Doerfert   if (Value *PreloadLoad = GlobalMap.lookup(Load))
313c1db67e2SJohannes Doerfert     return PreloadLoad;
314c1db67e2SJohannes Doerfert 
315bc132607STobias Grosser   Value *NewPointer =
31670131d34SMichael Kruse       generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
31787901453SJohannes Doerfert   Value *ScalarLoad = Builder.CreateAlignedLoad(
31887901453SJohannes Doerfert       NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
31986bc93a9STobias Grosser 
3201be726a4STobias Grosser   if (PollyDebugPrinting)
32186bc93a9STobias Grosser     RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
32286bc93a9STobias Grosser                                           ": ", ScalarLoad, "\n");
32386bc93a9STobias Grosser 
3243b11a16aSHongbin Zheng   return ScalarLoad;
3253b11a16aSHongbin Zheng }
3263b11a16aSHongbin Zheng 
327888ab551SMichael Kruse void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
328bc132607STobias Grosser                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
3292d1ed0bfSTobias Grosser                                         isl_id_to_ast_expr *NewAccesses) {
330706f79abSMichael Kruse   MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
3311515f6b9STobias Grosser   isl::set AccDom = MA.getAccessRelation().domain();
332fe46c3ffSTobias Grosser   std::string Subject = MA.getId().get_name();
333706f79abSMichael Kruse 
334fe46c3ffSTobias Grosser   generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
335bc132607STobias Grosser     Value *NewPointer =
33670131d34SMichael Kruse         generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
337706f79abSMichael Kruse     Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
338706f79abSMichael Kruse                                       LTS, getLoopForStmt(Stmt));
3393b11a16aSHongbin Zheng 
3401be726a4STobias Grosser     if (PollyDebugPrinting)
34186bc93a9STobias Grosser       RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
34286bc93a9STobias Grosser                                             ": ", ValueOperand, "\n");
34386bc93a9STobias Grosser 
344c186ac7aSTobias Grosser     Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
345706f79abSMichael Kruse   });
3463b11a16aSHongbin Zheng }
3473b11a16aSHongbin Zheng 
3485dced269SJohannes Doerfert bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
3492c3ffc04SJohannes Doerfert   Loop *L = getLoopForStmt(Stmt);
3505dced269SJohannes Doerfert   return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
35111c5e079SMichael Kruse          canSynthesize(Inst, *Stmt.getParent(), &SE, L);
3525dced269SJohannes Doerfert }
3535dced269SJohannes Doerfert 
3542f1acac6STobias Grosser void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
355bc132607STobias Grosser                                      ValueMapT &BBMap, LoopToScevMapT &LTS,
3562d1ed0bfSTobias Grosser                                      isl_id_to_ast_expr *NewAccesses) {
3573b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
3583b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
3593b11a16aSHongbin Zheng   if (Inst->isTerminator())
3603b11a16aSHongbin Zheng     return;
3613b11a16aSHongbin Zheng 
362aff56c8aSTobias Grosser   // Synthesizable statements will be generated on-demand.
3635dced269SJohannes Doerfert   if (canSyntheziseInStmt(Stmt, Inst))
364e71c6ab5STobias Grosser     return;
365e71c6ab5STobias Grosser 
3669646e3feSTobias Grosser   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
367888ab551SMichael Kruse     Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
3683d94fedfSSebastian Pop     // Compute NewLoad before its insertion in BBMap to make the insertion
3693d94fedfSSebastian Pop     // deterministic.
370753d43f9SSebastian Pop     BBMap[Load] = NewLoad;
3713b11a16aSHongbin Zheng     return;
3723b11a16aSHongbin Zheng   }
3733b11a16aSHongbin Zheng 
3749646e3feSTobias Grosser   if (auto *Store = dyn_cast<StoreInst>(Inst)) {
3750446d81eSMichael Kruse     // Identified as redundant by -polly-simplify.
3760446d81eSMichael Kruse     if (!Stmt.getArrayAccessOrNULLFor(Store))
3770446d81eSMichael Kruse       return;
3780446d81eSMichael Kruse 
379888ab551SMichael Kruse     generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
3803b11a16aSHongbin Zheng     return;
3813b11a16aSHongbin Zheng   }
3823b11a16aSHongbin Zheng 
3839646e3feSTobias Grosser   if (auto *PHI = dyn_cast<PHINode>(Inst)) {
384bc132607STobias Grosser     copyPHIInstruction(Stmt, PHI, BBMap, LTS);
385ecff11dcSJohannes Doerfert     return;
386ecff11dcSJohannes Doerfert   }
387ecff11dcSJohannes Doerfert 
3883f500fa2SJohannes Doerfert   // Skip some special intrinsics for which we do not adjust the semantics to
3893f500fa2SJohannes Doerfert   // the new schedule. All others are handled like every other instruction.
3909c0ffe3aSTobias Grosser   if (isIgnoredIntrinsic(Inst))
3913f500fa2SJohannes Doerfert     return;
3923f500fa2SJohannes Doerfert 
393bc132607STobias Grosser   copyInstScalar(Stmt, Inst, BBMap, LTS);
3943b11a16aSHongbin Zheng }
3953b11a16aSHongbin Zheng 
3969d12d8adSTobias Grosser void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
397c59b3ce0STobias Grosser   auto NewBB = Builder.GetInsertBlock();
398c59b3ce0STobias Grosser   for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
399c59b3ce0STobias Grosser     Instruction *NewInst = &*I;
4009d12d8adSTobias Grosser 
4019d12d8adSTobias Grosser     if (!isInstructionTriviallyDead(NewInst))
4029d12d8adSTobias Grosser       continue;
4039d12d8adSTobias Grosser 
404c59b3ce0STobias Grosser     for (auto Pair : BBMap)
405c59b3ce0STobias Grosser       if (Pair.second == NewInst) {
406c59b3ce0STobias Grosser         BBMap.erase(Pair.first);
407c59b3ce0STobias Grosser       }
408c59b3ce0STobias Grosser 
4099d12d8adSTobias Grosser     NewInst->eraseFromParent();
410c59b3ce0STobias Grosser     I = NewBB->rbegin();
4119d12d8adSTobias Grosser   }
4129d12d8adSTobias Grosser }
4139d12d8adSTobias Grosser 
414bc132607STobias Grosser void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
4152d1ed0bfSTobias Grosser                               isl_id_to_ast_expr *NewAccesses) {
416275a1756SJohannes Doerfert   assert(Stmt.isBlockStmt() &&
417275a1756SJohannes Doerfert          "Only block statements can be copied by the block generator");
418275a1756SJohannes Doerfert 
419275a1756SJohannes Doerfert   ValueMapT BBMap;
420275a1756SJohannes Doerfert 
421be9c9117SJohannes Doerfert   BasicBlock *BB = Stmt.getBasicBlock();
422bc132607STobias Grosser   copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
4239d12d8adSTobias Grosser   removeDeadInstructions(BB, BBMap);
424275a1756SJohannes Doerfert }
425275a1756SJohannes Doerfert 
426514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
427b8f58b53SDuncan P. N. Exon Smith   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
428b8f58b53SDuncan P. N. Exon Smith                                   &*Builder.GetInsertPoint(), &DT, &LI);
4293b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
430514f6efaSJohannes Doerfert   return CopyBB;
431514f6efaSJohannes Doerfert }
4323b11a16aSHongbin Zheng 
433514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
434bc132607STobias Grosser                                    ValueMapT &BBMap, LoopToScevMapT &LTS,
4352d1ed0bfSTobias Grosser                                    isl_id_to_ast_expr *NewAccesses) {
436514f6efaSJohannes Doerfert   BasicBlock *CopyBB = splitBB(BB);
437b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&CopyBB->front());
4382fa35194SMichael Kruse   generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
439225f0d1eSMichael Kruse 
440bc132607STobias Grosser   copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
441225f0d1eSMichael Kruse 
442225f0d1eSMichael Kruse   // After a basic block was copied store all scalars that escape this block in
443225f0d1eSMichael Kruse   // their alloca.
4442fa35194SMichael Kruse   generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
445514f6efaSJohannes Doerfert   return CopyBB;
446514f6efaSJohannes Doerfert }
447514f6efaSJohannes Doerfert 
448514f6efaSJohannes Doerfert void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
449bc132607STobias Grosser                             ValueMapT &BBMap, LoopToScevMapT &LTS,
4502d1ed0bfSTobias Grosser                             isl_id_to_ast_expr *NewAccesses) {
451ecff11dcSJohannes Doerfert   EntryBB = &CopyBB->getParent()->getEntryBlock();
452ecff11dcSJohannes Doerfert 
453c43d0360STobias Grosser   // Block statements and the entry blocks of region statement are code
454c43d0360STobias Grosser   // generated from instruction lists. This allow us to optimize the
455c43d0360STobias Grosser   // instructions that belong to a certain scop statement. As the code
456c43d0360STobias Grosser   // structure of region statements might be arbitrary complex, optimizing the
457c43d0360STobias Grosser   // instruction list is not yet supported.
458c43d0360STobias Grosser   if (Stmt.isBlockStmt() || (Stmt.isRegionStmt() && Stmt.getEntryBlock() == BB))
4593bb48299SMichael Kruse     for (Instruction *Inst : Stmt.getInstructions())
4603bb48299SMichael Kruse       copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
4613bb48299SMichael Kruse   else
46291f5b262STobias Grosser     for (Instruction &Inst : *BB)
463bc132607STobias Grosser       copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
464ecff11dcSJohannes Doerfert }
465ecff11dcSJohannes Doerfert 
466800e17a7SJohannes Doerfert Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
467587f1f57STobias Grosser   assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
4683216f854STobias Grosser 
469587f1f57STobias Grosser   return getOrCreateAlloca(Access.getLatestScopArrayInfo());
470a4f0988dSTobias Grosser }
471a4f0988dSTobias Grosser 
472a4f0988dSTobias Grosser Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
4733216f854STobias Grosser   assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
4743216f854STobias Grosser 
475587f1f57STobias Grosser   auto &Addr = ScalarMap[Array];
476587f1f57STobias Grosser 
477587f1f57STobias Grosser   if (Addr) {
478587f1f57STobias Grosser     // Allow allocas to be (temporarily) redirected once by adding a new
479a6d48f59SMichael Kruse     // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
480587f1f57STobias Grosser     // is used for example by the OpenMP code generation where a first use
481587f1f57STobias Grosser     // of a scalar while still in the host code allocates a normal alloca with
482587f1f57STobias Grosser     // getOrCreateAlloca. When the values of this scalar are accessed during
483587f1f57STobias Grosser     // the generation of the parallel subfunction, these values are copied over
484587f1f57STobias Grosser     // to the parallel subfunction and each request for a scalar alloca slot
485a6d48f59SMichael Kruse     // must be forwarded to the temporary in-subfunction slot. This mapping is
486587f1f57STobias Grosser     // removed when the subfunction has been generated and again normal host
487682c5114STobias Grosser     // code is generated. Due to the following reasons it is not possible to
488682c5114STobias Grosser     // perform the GlobalMap lookup right after creating the alloca below, but
489682c5114STobias Grosser     // instead we need to check GlobalMap at each call to getOrCreateAlloca:
490682c5114STobias Grosser     //
491682c5114STobias Grosser     //   1) GlobalMap may be changed multiple times (for each parallel loop),
492682c5114STobias Grosser     //   2) The temporary mapping is commonly only known after the initial
493682c5114STobias Grosser     //      alloca has already been generated, and
494682c5114STobias Grosser     //   3) The original alloca value must be restored after leaving the
495682c5114STobias Grosser     //      sub-function.
496587f1f57STobias Grosser     if (Value *NewAddr = GlobalMap.lookup(&*Addr))
497587f1f57STobias Grosser       return NewAddr;
498587f1f57STobias Grosser     return Addr;
499587f1f57STobias Grosser   }
500587f1f57STobias Grosser 
501587f1f57STobias Grosser   Type *Ty = Array->getElementType();
502587f1f57STobias Grosser   Value *ScalarBase = Array->getBasePtr();
503587f1f57STobias Grosser   std::string NameExt;
504a535dff4STobias Grosser   if (Array->isPHIKind())
505587f1f57STobias Grosser     NameExt = ".phiops";
506f8d55f7eSTobias Grosser   else
507587f1f57STobias Grosser     NameExt = ".s2a";
508587f1f57STobias Grosser 
5097b5a4dfdSTobias Grosser   const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
510b3e30c32SMatt Arsenault 
511b3e30c32SMatt Arsenault   Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(),
512b3e30c32SMatt Arsenault                         ScalarBase->getName() + NameExt);
513587f1f57STobias Grosser   EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
514587f1f57STobias Grosser   Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
515587f1f57STobias Grosser 
516587f1f57STobias Grosser   return Addr;
517f8d55f7eSTobias Grosser }
518f8d55f7eSTobias Grosser 
519587f1f57STobias Grosser void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
520587f1f57STobias Grosser   Instruction *Inst = cast<Instruction>(Array->getBasePtr());
521b79a67dfSTobias Grosser 
5222985400aSTobias Grosser   // If there are escape users we get the alloca for this instruction and put it
5232985400aSTobias Grosser   // in the EscapeMap for later finalization. Lastly, if the instruction was
5242985400aSTobias Grosser   // copied multiple times we already did this and can exit.
525acb6ade7SMichael Kruse   if (EscapeMap.count(Inst))
526acb6ade7SMichael Kruse     return;
527e69e1141SJohannes Doerfert 
528ecff11dcSJohannes Doerfert   EscapeUserVectorTy EscapeUsers;
529ecff11dcSJohannes Doerfert   for (User *U : Inst->users()) {
530ecff11dcSJohannes Doerfert 
531ecff11dcSJohannes Doerfert     // Non-instruction user will never escape.
532ecff11dcSJohannes Doerfert     Instruction *UI = dyn_cast<Instruction>(U);
533ecff11dcSJohannes Doerfert     if (!UI)
534ecff11dcSJohannes Doerfert       continue;
535ecff11dcSJohannes Doerfert 
536952b5304SJohannes Doerfert     if (S.contains(UI))
537ecff11dcSJohannes Doerfert       continue;
538ecff11dcSJohannes Doerfert 
539ecff11dcSJohannes Doerfert     EscapeUsers.push_back(UI);
540ecff11dcSJohannes Doerfert   }
541ecff11dcSJohannes Doerfert 
542ecff11dcSJohannes Doerfert   // Exit if no escape uses were found.
543ecff11dcSJohannes Doerfert   if (EscapeUsers.empty())
544ecff11dcSJohannes Doerfert     return;
545ecff11dcSJohannes Doerfert 
546ecff11dcSJohannes Doerfert   // Get or create an escape alloca for this instruction.
547587f1f57STobias Grosser   auto *ScalarAddr = getOrCreateAlloca(Array);
548ecff11dcSJohannes Doerfert 
549ecff11dcSJohannes Doerfert   // Remember that this instruction has escape uses and the escape alloca.
550ecff11dcSJohannes Doerfert   EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
551ecff11dcSJohannes Doerfert }
552ecff11dcSJohannes Doerfert 
5532fa35194SMichael Kruse void BlockGenerator::generateScalarLoads(
5542fa35194SMichael Kruse     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
5552fa35194SMichael Kruse     __isl_keep isl_id_to_ast_expr *NewAccesses) {
556225f0d1eSMichael Kruse   for (MemoryAccess *MA : Stmt) {
5572fa35194SMichael Kruse     if (MA->isOriginalArrayKind() || MA->isWrite())
558ecff11dcSJohannes Doerfert       continue;
559ecff11dcSJohannes Doerfert 
56077394f13SMichael Kruse #ifndef NDEBUG
561*4485ae08SMichael Kruse     auto StmtDom =
562*4485ae08SMichael Kruse         Stmt.getDomain().intersect_params(Stmt.getParent()->getContext());
563388730c9SMichael Kruse     auto AccDom = MA->getAccessRelation().domain();
564388730c9SMichael Kruse     assert(!StmtDom.is_subset(AccDom).is_false() &&
56577394f13SMichael Kruse            "Scalar must be loaded in all statement instances");
56677394f13SMichael Kruse #endif
56777394f13SMichael Kruse 
5682fa35194SMichael Kruse     auto *Address =
5692fa35194SMichael Kruse         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
570eac9726eSMichael Kruse     assert((!isa<Instruction>(Address) ||
571eac9726eSMichael Kruse             DT.dominates(cast<Instruction>(Address)->getParent(),
572eac9726eSMichael Kruse                          Builder.GetInsertBlock())) &&
573eac9726eSMichael Kruse            "Domination violation");
574583be06fSTobias Grosser     BBMap[MA->getAccessValue()] =
5752fc50df9STobias Grosser         Builder.CreateLoad(Address, Address->getName() + ".reload");
576ecff11dcSJohannes Doerfert   }
577ecff11dcSJohannes Doerfert }
578ecff11dcSJohannes Doerfert 
579706f79abSMichael Kruse Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
580706f79abSMichael Kruse                                               const isl::set &Subdomain) {
581132860afSTobias Grosser   isl::ast_build AstBuild = Stmt.getAstBuild();
582dcf8d696STobias Grosser   isl::set Domain = Stmt.getDomain();
583706f79abSMichael Kruse 
5846b6ac900STobias Grosser   isl::union_map USchedule = AstBuild.get_schedule();
5856b6ac900STobias Grosser   USchedule = USchedule.intersect_domain(Domain);
586706f79abSMichael Kruse 
5876b6ac900STobias Grosser   assert(!USchedule.is_empty());
5886b6ac900STobias Grosser   isl::map Schedule = isl::map::from_union_map(USchedule);
589706f79abSMichael Kruse 
5906b6ac900STobias Grosser   isl::set ScheduledDomain = Schedule.range();
5916b6ac900STobias Grosser   isl::set ScheduledSet = Subdomain.apply(Schedule);
592706f79abSMichael Kruse 
5936b6ac900STobias Grosser   isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
5946b6ac900STobias Grosser 
5956b6ac900STobias Grosser   isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
596706f79abSMichael Kruse   Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
597706f79abSMichael Kruse   IsInSetExpr = Builder.CreateICmpNE(
598706f79abSMichael Kruse       IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
599706f79abSMichael Kruse 
600706f79abSMichael Kruse   return IsInSetExpr;
601706f79abSMichael Kruse }
602706f79abSMichael Kruse 
603706f79abSMichael Kruse void BlockGenerator::generateConditionalExecution(
604706f79abSMichael Kruse     ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
605706f79abSMichael Kruse     const std::function<void()> &GenThenFunc) {
606dcf8d696STobias Grosser   isl::set StmtDom = Stmt.getDomain();
607706f79abSMichael Kruse 
608706f79abSMichael Kruse   // If the condition is a tautology, don't generate a condition around the
609706f79abSMichael Kruse   // code.
610f51decb5STobias Grosser   bool IsPartialWrite =
6118ea1fc19STobias Grosser       !StmtDom.intersect_params(Stmt.getParent()->getContext())
612f51decb5STobias Grosser            .is_subset(Subdomain);
613f51decb5STobias Grosser   if (!IsPartialWrite) {
614706f79abSMichael Kruse     GenThenFunc();
615706f79abSMichael Kruse     return;
616706f79abSMichael Kruse   }
617706f79abSMichael Kruse 
618706f79abSMichael Kruse   // Generate the condition.
619706f79abSMichael Kruse   Value *Cond = buildContainsCondition(Stmt, Subdomain);
620b795bfc0SMichael Kruse 
621b795bfc0SMichael Kruse   // Don't call GenThenFunc if it is never executed. An ast index expression
622b795bfc0SMichael Kruse   // might not be defined in this case.
623b795bfc0SMichael Kruse   if (auto *Const = dyn_cast<ConstantInt>(Cond))
624b795bfc0SMichael Kruse     if (Const->isZero())
625b795bfc0SMichael Kruse       return;
626b795bfc0SMichael Kruse 
627706f79abSMichael Kruse   BasicBlock *HeadBlock = Builder.GetInsertBlock();
628706f79abSMichael Kruse   StringRef BlockName = HeadBlock->getName();
629706f79abSMichael Kruse 
630706f79abSMichael Kruse   // Generate the conditional block.
631706f79abSMichael Kruse   SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
632706f79abSMichael Kruse                             &DT, &LI);
633706f79abSMichael Kruse   BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
634706f79abSMichael Kruse   BasicBlock *ThenBlock = Branch->getSuccessor(0);
635706f79abSMichael Kruse   BasicBlock *TailBlock = Branch->getSuccessor(1);
636706f79abSMichael Kruse 
637706f79abSMichael Kruse   // Assign descriptive names.
638706f79abSMichael Kruse   if (auto *CondInst = dyn_cast<Instruction>(Cond))
639706f79abSMichael Kruse     CondInst->setName("polly." + Subject + ".cond");
640706f79abSMichael Kruse   ThenBlock->setName(BlockName + "." + Subject + ".partial");
641706f79abSMichael Kruse   TailBlock->setName(BlockName + ".cont");
642706f79abSMichael Kruse 
643706f79abSMichael Kruse   // Put the client code into the conditional block and continue in the merge
644706f79abSMichael Kruse   // block afterwards.
645706f79abSMichael Kruse   Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
646706f79abSMichael Kruse   GenThenFunc();
647706f79abSMichael Kruse   Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
648706f79abSMichael Kruse }
649706f79abSMichael Kruse 
6502fa35194SMichael Kruse void BlockGenerator::generateScalarStores(
6512fa35194SMichael Kruse     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
6522fa35194SMichael Kruse     __isl_keep isl_id_to_ast_expr *NewAccesses) {
653f2cdd144STobias Grosser   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
654ecff11dcSJohannes Doerfert 
65521a059afSTobias Grosser   assert(Stmt.isBlockStmt() &&
65621a059afSTobias Grosser          "Region statements need to use the generateScalarStores() function in "
65721a059afSTobias Grosser          "the RegionGenerator");
658ecff11dcSJohannes Doerfert 
659ecff11dcSJohannes Doerfert   for (MemoryAccess *MA : Stmt) {
6602fa35194SMichael Kruse     if (MA->isOriginalArrayKind() || MA->isRead())
661ecff11dcSJohannes Doerfert       continue;
662ecff11dcSJohannes Doerfert 
6631515f6b9STobias Grosser     isl::set AccDom = MA->getAccessRelation().domain();
664fe46c3ffSTobias Grosser     std::string Subject = MA->getId().get_name();
66577394f13SMichael Kruse 
666fe46c3ffSTobias Grosser     generateConditionalExecution(
667fe46c3ffSTobias Grosser         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
668d86f2157SJohannes Doerfert           Value *Val = MA->getAccessValue();
669ee6a4fc6SMichael Kruse           if (MA->isAnyPHIKind()) {
670fe46c3ffSTobias Grosser             assert(MA->getIncoming().size() >= 1 &&
671fe46c3ffSTobias Grosser                    "Block statements have exactly one exiting block, or "
672fe46c3ffSTobias Grosser                    "multiple but "
673ee6a4fc6SMichael Kruse                    "with same incoming block and value");
674fe46c3ffSTobias Grosser             assert(std::all_of(MA->getIncoming().begin(),
675fe46c3ffSTobias Grosser                                MA->getIncoming().end(),
676ee6a4fc6SMichael Kruse                                [&](std::pair<BasicBlock *, Value *> p) -> bool {
677ee6a4fc6SMichael Kruse                                  return p.first == Stmt.getBasicBlock();
678ee6a4fc6SMichael Kruse                                }) &&
679ee6a4fc6SMichael Kruse                    "Incoming block must be statement's block");
680ee6a4fc6SMichael Kruse             Val = MA->getIncoming()[0].second;
681ee6a4fc6SMichael Kruse           }
682fe46c3ffSTobias Grosser           auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
683fe46c3ffSTobias Grosser                                             BBMap, NewAccesses);
684d86f2157SJohannes Doerfert 
685f2cdd144STobias Grosser           Val = getNewValue(Stmt, Val, BBMap, LTS, L);
686eac9726eSMichael Kruse           assert((!isa<Instruction>(Val) ||
687eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Val)->getParent(),
688eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
689eac9726eSMichael Kruse                  "Domination violation");
690eac9726eSMichael Kruse           assert((!isa<Instruction>(Address) ||
691eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Address)->getParent(),
692eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
693eac9726eSMichael Kruse                  "Domination violation");
6942f5cbc44SMichael Kruse 
6952f5cbc44SMichael Kruse           // The new Val might have a different type than the old Val due to
6962f5cbc44SMichael Kruse           // ScalarEvolution looking through bitcasts.
6972f5cbc44SMichael Kruse           if (Val->getType() != Address->getType()->getPointerElementType())
6982f5cbc44SMichael Kruse             Address = Builder.CreateBitOrPointerCast(
6992f5cbc44SMichael Kruse                 Address, Val->getType()->getPointerTo());
7002f5cbc44SMichael Kruse 
70192245228STobias Grosser           Builder.CreateStore(Val, Address);
702706f79abSMichael Kruse         });
703ecff11dcSJohannes Doerfert   }
704ecff11dcSJohannes Doerfert }
705ecff11dcSJohannes Doerfert 
706c0091a77STobias Grosser void BlockGenerator::createScalarInitialization(Scop &S) {
707ef74443cSJohannes Doerfert   BasicBlock *ExitBB = S.getExit();
708acf80064SEli Friedman   BasicBlock *PreEntryBB = S.getEnteringBlock();
709188542fdSJohannes Doerfert 
710acf80064SEli Friedman   Builder.SetInsertPoint(&*StartBlock->begin());
711ecff11dcSJohannes Doerfert 
712d7754a12SRoman Gareev   for (auto &Array : S.arrays()) {
713c0091a77STobias Grosser     if (Array->getNumberOfDimensions() != 0)
714c0091a77STobias Grosser       continue;
715a535dff4STobias Grosser     if (Array->isPHIKind()) {
716c0091a77STobias Grosser       // For PHI nodes, the only values we need to store are the ones that
717c0091a77STobias Grosser       // reach the PHI node from outside the region. In general there should
718c0091a77STobias Grosser       // only be one such incoming edge and this edge should enter through
719acf80064SEli Friedman       // 'PreEntryBB'.
720c0091a77STobias Grosser       auto PHI = cast<PHINode>(Array->getBasePtr());
721ecff11dcSJohannes Doerfert 
722c0091a77STobias Grosser       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
723acf80064SEli Friedman         if (!S.contains(*BI) && *BI != PreEntryBB)
724c0091a77STobias Grosser           llvm_unreachable("Incoming edges from outside the scop should always "
725acf80064SEli Friedman                            "come from PreEntryBB");
726c0091a77STobias Grosser 
727acf80064SEli Friedman       int Idx = PHI->getBasicBlockIndex(PreEntryBB);
728c0091a77STobias Grosser       if (Idx < 0)
729ecff11dcSJohannes Doerfert         continue;
730ecff11dcSJohannes Doerfert 
731c0091a77STobias Grosser       Value *ScalarValue = PHI->getIncomingValue(Idx);
732ecff11dcSJohannes Doerfert 
733587f1f57STobias Grosser       Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
734c0091a77STobias Grosser       continue;
735c0091a77STobias Grosser     }
736c0091a77STobias Grosser 
737c0091a77STobias Grosser     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
738c0091a77STobias Grosser 
739952b5304SJohannes Doerfert     if (Inst && S.contains(Inst))
740c0091a77STobias Grosser       continue;
741c0091a77STobias Grosser 
742188542fdSJohannes Doerfert     // PHI nodes that are not marked as such in their SAI object are either exit
743188542fdSJohannes Doerfert     // PHI nodes we model as common scalars but without initialization, or
744188542fdSJohannes Doerfert     // incoming phi nodes that need to be initialized. Check if the first is the
745188542fdSJohannes Doerfert     // case for Inst and do not create and initialize memory if so.
746188542fdSJohannes Doerfert     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
747188542fdSJohannes Doerfert       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
748717b8667SJohannes Doerfert         continue;
749717b8667SJohannes Doerfert 
750587f1f57STobias Grosser     Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
751ecff11dcSJohannes Doerfert   }
752ecff11dcSJohannes Doerfert }
753ecff11dcSJohannes Doerfert 
754ef74443cSJohannes Doerfert void BlockGenerator::createScalarFinalization(Scop &S) {
755ecff11dcSJohannes Doerfert   // The exit block of the __unoptimized__ region.
756ef74443cSJohannes Doerfert   BasicBlock *ExitBB = S.getExitingBlock();
757ecff11dcSJohannes Doerfert   // The merge block __just after__ the region and the optimized region.
758ef74443cSJohannes Doerfert   BasicBlock *MergeBB = S.getExit();
759ecff11dcSJohannes Doerfert 
760ecff11dcSJohannes Doerfert   // The exit block of the __optimized__ region.
761ecff11dcSJohannes Doerfert   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
762ecff11dcSJohannes Doerfert   if (OptExitBB == ExitBB)
763ecff11dcSJohannes Doerfert     OptExitBB = *(++pred_begin(MergeBB));
764ecff11dcSJohannes Doerfert 
765ecff11dcSJohannes Doerfert   Builder.SetInsertPoint(OptExitBB->getTerminator());
766ecff11dcSJohannes Doerfert   for (const auto &EscapeMapping : EscapeMap) {
767ecff11dcSJohannes Doerfert     // Extract the escaping instruction and the escaping users as well as the
768ecff11dcSJohannes Doerfert     // alloca the instruction was demoted to.
769fbde4355SMichael Kruse     Instruction *EscapeInst = EscapeMapping.first;
770fbde4355SMichael Kruse     const auto &EscapeMappingValue = EscapeMapping.second;
771ecff11dcSJohannes Doerfert     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
77264c0ff41STobias Grosser     Value *ScalarAddr = EscapeMappingValue.first;
773ecff11dcSJohannes Doerfert 
774ecff11dcSJohannes Doerfert     // Reload the demoted instruction in the optimized version of the SCoP.
775d8b6ad25SJohannes Doerfert     Value *EscapeInstReload =
776ecff11dcSJohannes Doerfert         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
777d8b6ad25SJohannes Doerfert     EscapeInstReload =
778d8b6ad25SJohannes Doerfert         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
779ecff11dcSJohannes Doerfert 
780ecff11dcSJohannes Doerfert     // Create the merge PHI that merges the optimized and unoptimized version.
781ecff11dcSJohannes Doerfert     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
782ecff11dcSJohannes Doerfert                                         EscapeInst->getName() + ".merge");
783b8f58b53SDuncan P. N. Exon Smith     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
784ecff11dcSJohannes Doerfert 
785ecff11dcSJohannes Doerfert     // Add the respective values to the merge PHI.
786ecff11dcSJohannes Doerfert     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
787ecff11dcSJohannes Doerfert     MergePHI->addIncoming(EscapeInst, ExitBB);
788ecff11dcSJohannes Doerfert 
789ecff11dcSJohannes Doerfert     // The information of scalar evolution about the escaping instruction needs
790ecff11dcSJohannes Doerfert     // to be revoked so the new merged instruction will be used.
791ecff11dcSJohannes Doerfert     if (SE.isSCEVable(EscapeInst->getType()))
792ecff11dcSJohannes Doerfert       SE.forgetValue(EscapeInst);
793ecff11dcSJohannes Doerfert 
794ecff11dcSJohannes Doerfert     // Replace all uses of the demoted instruction with the merge PHI.
795ecff11dcSJohannes Doerfert     for (Instruction *EUser : EscapeUsers)
796ecff11dcSJohannes Doerfert       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
797ecff11dcSJohannes Doerfert   }
798ecff11dcSJohannes Doerfert }
799ecff11dcSJohannes Doerfert 
800ffa2446fSTobias Grosser void BlockGenerator::findOutsideUsers(Scop &S) {
801d7754a12SRoman Gareev   for (auto &Array : S.arrays()) {
802ffa2446fSTobias Grosser 
803ffa2446fSTobias Grosser     if (Array->getNumberOfDimensions() != 0)
804ffa2446fSTobias Grosser       continue;
805ffa2446fSTobias Grosser 
806a535dff4STobias Grosser     if (Array->isPHIKind())
807ffa2446fSTobias Grosser       continue;
808ffa2446fSTobias Grosser 
809ffa2446fSTobias Grosser     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
810ffa2446fSTobias Grosser 
811ffa2446fSTobias Grosser     if (!Inst)
812ffa2446fSTobias Grosser       continue;
813ffa2446fSTobias Grosser 
814ffa2446fSTobias Grosser     // Scop invariant hoisting moves some of the base pointers out of the scop.
815ffa2446fSTobias Grosser     // We can ignore these, as the invariant load hoisting already registers the
816ffa2446fSTobias Grosser     // relevant outside users.
817952b5304SJohannes Doerfert     if (!S.contains(Inst))
818ffa2446fSTobias Grosser       continue;
819ffa2446fSTobias Grosser 
820587f1f57STobias Grosser     handleOutsideUsers(S, Array);
821ffa2446fSTobias Grosser   }
822ffa2446fSTobias Grosser }
823ffa2446fSTobias Grosser 
82427d742daSTobias Grosser void BlockGenerator::createExitPHINodeMerges(Scop &S) {
82527d742daSTobias Grosser   if (S.hasSingleExitEdge())
82627d742daSTobias Grosser     return;
82727d742daSTobias Grosser 
828ef74443cSJohannes Doerfert   auto *ExitBB = S.getExitingBlock();
829ef74443cSJohannes Doerfert   auto *MergeBB = S.getExit();
83027d742daSTobias Grosser   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
83127d742daSTobias Grosser   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
83227d742daSTobias Grosser   if (OptExitBB == ExitBB)
83327d742daSTobias Grosser     OptExitBB = *(++pred_begin(MergeBB));
83427d742daSTobias Grosser 
83527d742daSTobias Grosser   Builder.SetInsertPoint(OptExitBB->getTerminator());
83627d742daSTobias Grosser 
837d7754a12SRoman Gareev   for (auto &SAI : S.arrays()) {
83827d742daSTobias Grosser     auto *Val = SAI->getBasePtr();
83927d742daSTobias Grosser 
840faedfcbfSMichael Kruse     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
841faedfcbfSMichael Kruse     // the original PHI's value or the reloaded incoming values from the
842faedfcbfSMichael Kruse     // generated code. An llvm::Value is merged between the original code's
843faedfcbfSMichael Kruse     // value or the generated one.
844fa53c86dSMichael Kruse     if (!SAI->isExitPHIKind())
845faedfcbfSMichael Kruse       continue;
846faedfcbfSMichael Kruse 
84727d742daSTobias Grosser     PHINode *PHI = dyn_cast<PHINode>(Val);
84827d742daSTobias Grosser     if (!PHI)
84927d742daSTobias Grosser       continue;
85027d742daSTobias Grosser 
851a3f6edaeSTobias Grosser     if (PHI->getParent() != AfterMergeBB)
85227d742daSTobias Grosser       continue;
85327d742daSTobias Grosser 
85427d742daSTobias Grosser     std::string Name = PHI->getName();
855587f1f57STobias Grosser     Value *ScalarAddr = getOrCreateAlloca(SAI);
85627d742daSTobias Grosser     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
85727d742daSTobias Grosser     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
85827d742daSTobias Grosser     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
859faedfcbfSMichael Kruse     assert((!isa<Instruction>(OriginalValue) ||
860faedfcbfSMichael Kruse             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
861faedfcbfSMichael Kruse            "Original value must no be one we just generated.");
86227d742daSTobias Grosser     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
863b8f58b53SDuncan P. N. Exon Smith     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
86427d742daSTobias Grosser     MergePHI->addIncoming(Reload, OptExitBB);
86527d742daSTobias Grosser     MergePHI->addIncoming(OriginalValue, ExitBB);
86627d742daSTobias Grosser     int Idx = PHI->getBasicBlockIndex(MergeBB);
86727d742daSTobias Grosser     PHI->setIncomingValue(Idx, MergePHI);
86827d742daSTobias Grosser   }
86927d742daSTobias Grosser }
87027d742daSTobias Grosser 
8711c184409STobias Grosser void BlockGenerator::invalidateScalarEvolution(Scop &S) {
8721c184409STobias Grosser   for (auto &Stmt : S)
873b3224adfSRoman Gareev     if (Stmt.isCopyStmt())
874b3224adfSRoman Gareev       continue;
875b3224adfSRoman Gareev     else if (Stmt.isBlockStmt())
8761c184409STobias Grosser       for (auto &Inst : *Stmt.getBasicBlock())
8771c184409STobias Grosser         SE.forgetValue(&Inst);
8781c184409STobias Grosser     else if (Stmt.isRegionStmt())
8791c184409STobias Grosser       for (auto *BB : Stmt.getRegion()->blocks())
8801c184409STobias Grosser         for (auto &Inst : *BB)
8811c184409STobias Grosser           SE.forgetValue(&Inst);
8821c184409STobias Grosser     else
8831c184409STobias Grosser       llvm_unreachable("Unexpected statement type found");
8841aad76c1SMichael Kruse 
8851aad76c1SMichael Kruse   // Invalidate SCEV of loops surrounding the EscapeUsers.
8861aad76c1SMichael Kruse   for (const auto &EscapeMapping : EscapeMap) {
8871aad76c1SMichael Kruse     const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
8881aad76c1SMichael Kruse     for (Instruction *EUser : EscapeUsers) {
8891aad76c1SMichael Kruse       if (Loop *L = LI.getLoopFor(EUser->getParent()))
8901aad76c1SMichael Kruse         while (L) {
8911aad76c1SMichael Kruse           SE.forgetLoop(L);
8921aad76c1SMichael Kruse           L = L->getParentLoop();
8931aad76c1SMichael Kruse         }
8941aad76c1SMichael Kruse     }
8951aad76c1SMichael Kruse   }
8961c184409STobias Grosser }
8971c184409STobias Grosser 
898ffa2446fSTobias Grosser void BlockGenerator::finalizeSCoP(Scop &S) {
899ffa2446fSTobias Grosser   findOutsideUsers(S);
900c0091a77STobias Grosser   createScalarInitialization(S);
90127d742daSTobias Grosser   createExitPHINodeMerges(S);
902ef74443cSJohannes Doerfert   createScalarFinalization(S);
9031c184409STobias Grosser   invalidateScalarEvolution(S);
9043b11a16aSHongbin Zheng }
9053b11a16aSHongbin Zheng 
906be9c9117SJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
907be9c9117SJohannes Doerfert                                            std::vector<LoopToScevMapT> &VLTS,
908be9c9117SJohannes Doerfert                                            isl_map *Schedule)
909bc132607STobias Grosser     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
910a00a0291SSebastian Pop   assert(Schedule && "No statement domain provided");
9113b11a16aSHongbin Zheng }
9123b11a16aSHongbin Zheng 
9132f1acac6STobias Grosser Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
914e602a076STobias Grosser                                             ValueMapT &VectorMap,
915e602a076STobias Grosser                                             VectorValueMapT &ScalarMaps,
916e602a076STobias Grosser                                             Loop *L) {
917fe11e287SHongbin Zheng   if (Value *NewValue = VectorMap.lookup(Old))
918fe11e287SHongbin Zheng     return NewValue;
9193b11a16aSHongbin Zheng 
9203b11a16aSHongbin Zheng   int Width = getVectorWidth();
9213b11a16aSHongbin Zheng 
9223b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
9233b11a16aSHongbin Zheng 
9243b11a16aSHongbin Zheng   for (int Lane = 0; Lane < Width; Lane++)
925c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
926bc132607STobias Grosser         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
9277242ad92STobias Grosser         Builder.getInt32(Lane));
9283b11a16aSHongbin Zheng 
9293b11a16aSHongbin Zheng   VectorMap[Old] = Vector;
9303b11a16aSHongbin Zheng 
9313b11a16aSHongbin Zheng   return Vector;
9323b11a16aSHongbin Zheng }
9333b11a16aSHongbin Zheng 
9343b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
9353b11a16aSHongbin Zheng   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
9363b11a16aSHongbin Zheng   assert(PointerTy && "PointerType expected");
9373b11a16aSHongbin Zheng 
9383b11a16aSHongbin Zheng   Type *ScalarType = PointerTy->getElementType();
9393b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(ScalarType, Width);
9403b11a16aSHongbin Zheng 
9413b11a16aSHongbin Zheng   return PointerType::getUnqual(VectorType);
9423b11a16aSHongbin Zheng }
9433b11a16aSHongbin Zheng 
944be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateStrideOneLoad(
9452f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
9462d1ed0bfSTobias Grosser     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
9470dd463faSTobias Grosser   unsigned VectorWidth = getVectorWidth();
9489646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
9490dd463faSTobias Grosser   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
9500dd463faSTobias Grosser   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
9510dd463faSTobias Grosser 
9528f25b0cbSMichael Kruse   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
953bc132607STobias Grosser                                                VLTS[Offset], NewAccesses);
954c14582f2STobias Grosser   Value *VectorPtr =
955c14582f2STobias Grosser       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
956c14582f2STobias Grosser   LoadInst *VecLoad =
957c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
9583b11a16aSHongbin Zheng   if (!Aligned)
9593b11a16aSHongbin Zheng     VecLoad->setAlignment(8);
9603b11a16aSHongbin Zheng 
9610dd463faSTobias Grosser   if (NegativeStride) {
9620dd463faSTobias Grosser     SmallVector<Constant *, 16> Indices;
9630dd463faSTobias Grosser     for (int i = VectorWidth - 1; i >= 0; i--)
9640dd463faSTobias Grosser       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
9650dd463faSTobias Grosser     Constant *SV = llvm::ConstantVector::get(Indices);
9660dd463faSTobias Grosser     Value *RevVecLoad = Builder.CreateShuffleVector(
9670dd463faSTobias Grosser         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
9680dd463faSTobias Grosser     return RevVecLoad;
9690dd463faSTobias Grosser   }
9700dd463faSTobias Grosser 
9713b11a16aSHongbin Zheng   return VecLoad;
9723b11a16aSHongbin Zheng }
9733b11a16aSHongbin Zheng 
9742d1ed0bfSTobias Grosser Value *VectorBlockGenerator::generateStrideZeroLoad(
9752f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
9762d1ed0bfSTobias Grosser     __isl_keep isl_id_to_ast_expr *NewAccesses) {
9779646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
9783b11a16aSHongbin Zheng   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
97970131d34SMichael Kruse   Value *NewPointer =
98070131d34SMichael Kruse       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
9813b11a16aSHongbin Zheng   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
9823b11a16aSHongbin Zheng                                            Load->getName() + "_p_vec_p");
983c14582f2STobias Grosser   LoadInst *ScalarLoad =
984c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
9853b11a16aSHongbin Zheng 
9863b11a16aSHongbin Zheng   if (!Aligned)
9873b11a16aSHongbin Zheng     ScalarLoad->setAlignment(8);
9883b11a16aSHongbin Zheng 
989c14582f2STobias Grosser   Constant *SplatVector = Constant::getNullValue(
990c14582f2STobias Grosser       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
9913b11a16aSHongbin Zheng 
992c14582f2STobias Grosser   Value *VectorLoad = Builder.CreateShuffleVector(
993c14582f2STobias Grosser       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
9943b11a16aSHongbin Zheng   return VectorLoad;
9953b11a16aSHongbin Zheng }
9963b11a16aSHongbin Zheng 
997be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateUnknownStrideLoad(
9982f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
99909e3697fSJohannes Doerfert     __isl_keep isl_id_to_ast_expr *NewAccesses) {
10003b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
10019646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
10023b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(
10033b11a16aSHongbin Zheng       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
10043b11a16aSHongbin Zheng 
10053b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
10063b11a16aSHongbin Zheng 
10073b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++) {
100870131d34SMichael Kruse     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
100970131d34SMichael Kruse                                                  VLTS[i], NewAccesses);
1010c14582f2STobias Grosser     Value *ScalarLoad =
1011c14582f2STobias Grosser         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1012c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
1013c14582f2STobias Grosser         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
10143b11a16aSHongbin Zheng   }
10153b11a16aSHongbin Zheng 
10163b11a16aSHongbin Zheng   return Vector;
10173b11a16aSHongbin Zheng }
10183b11a16aSHongbin Zheng 
10192d1ed0bfSTobias Grosser void VectorBlockGenerator::generateLoad(
10202f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
10212d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1022c1db67e2SJohannes Doerfert   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1023c1db67e2SJohannes Doerfert     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1024c1db67e2SJohannes Doerfert                                                 Load->getName() + "_p");
1025c1db67e2SJohannes Doerfert     return;
1026c1db67e2SJohannes Doerfert   }
1027c1db67e2SJohannes Doerfert 
10282873645cSTobias Grosser   if (!VectorType::isValidElementType(Load->getType())) {
10293b11a16aSHongbin Zheng     for (int i = 0; i < getVectorWidth(); i++)
1030bc132607STobias Grosser       ScalarMaps[i][Load] =
1031888ab551SMichael Kruse           generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
10323b11a16aSHongbin Zheng     return;
10333b11a16aSHongbin Zheng   }
10343b11a16aSHongbin Zheng 
1035184a4926STobias Grosser   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
10363b11a16aSHongbin Zheng 
103795493984STobias Grosser   // Make sure we have scalar values available to access the pointer to
103895493984STobias Grosser   // the data location.
103995493984STobias Grosser   extractScalarValues(Load, VectorMap, ScalarMaps);
104095493984STobias Grosser 
10413b11a16aSHongbin Zheng   Value *NewLoad;
1042718d04c6STobias Grosser   if (Access.isStrideZero(isl::manage_copy(Schedule)))
10432d1ed0bfSTobias Grosser     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1044718d04c6STobias Grosser   else if (Access.isStrideOne(isl::manage_copy(Schedule)))
10452d1ed0bfSTobias Grosser     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1046718d04c6STobias Grosser   else if (Access.isStrideX(isl::manage_copy(Schedule), -1))
10472d1ed0bfSTobias Grosser     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
10483b11a16aSHongbin Zheng   else
10492d1ed0bfSTobias Grosser     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
10503b11a16aSHongbin Zheng 
10513b11a16aSHongbin Zheng   VectorMap[Load] = NewLoad;
10523b11a16aSHongbin Zheng }
10533b11a16aSHongbin Zheng 
10542f1acac6STobias Grosser void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
10553b11a16aSHongbin Zheng                                          ValueMapT &VectorMap,
10563b11a16aSHongbin Zheng                                          VectorValueMapT &ScalarMaps) {
10573b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
1058be9c9117SJohannes Doerfert   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
10592c3ffc04SJohannes Doerfert                                      ScalarMaps, getLoopForStmt(Stmt));
10603b11a16aSHongbin Zheng 
10613b11a16aSHongbin Zheng   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
10623b11a16aSHongbin Zheng 
10633b11a16aSHongbin Zheng   const CastInst *Cast = dyn_cast<CastInst>(Inst);
10643b11a16aSHongbin Zheng   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
10653b11a16aSHongbin Zheng   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
10663b11a16aSHongbin Zheng }
10673b11a16aSHongbin Zheng 
10682f1acac6STobias Grosser void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
10693b11a16aSHongbin Zheng                                           ValueMapT &VectorMap,
10703b11a16aSHongbin Zheng                                           VectorValueMapT &ScalarMaps) {
10712c3ffc04SJohannes Doerfert   Loop *L = getLoopForStmt(Stmt);
10723b11a16aSHongbin Zheng   Value *OpZero = Inst->getOperand(0);
10733b11a16aSHongbin Zheng   Value *OpOne = Inst->getOperand(1);
10743b11a16aSHongbin Zheng 
10753b11a16aSHongbin Zheng   Value *NewOpZero, *NewOpOne;
1076be9c9117SJohannes Doerfert   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1077be9c9117SJohannes Doerfert   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
10783b11a16aSHongbin Zheng 
10791bb59b0dSTobias Grosser   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
10803b11a16aSHongbin Zheng                                        Inst->getName() + "p_vec");
10813b11a16aSHongbin Zheng   VectorMap[Inst] = NewInst;
10823b11a16aSHongbin Zheng }
10833b11a16aSHongbin Zheng 
10842d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStore(
10852f1acac6STobias Grosser     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
10862d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1087184a4926STobias Grosser   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
10883b11a16aSHongbin Zheng 
10899646e3feSTobias Grosser   auto *Pointer = Store->getPointerOperand();
1090be9c9117SJohannes Doerfert   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
10912c3ffc04SJohannes Doerfert                                  ScalarMaps, getLoopForStmt(Stmt));
10923b11a16aSHongbin Zheng 
109350fd7010STobias Grosser   // Make sure we have scalar values available to access the pointer to
109450fd7010STobias Grosser   // the data location.
109550fd7010STobias Grosser   extractScalarValues(Store, VectorMap, ScalarMaps);
109650fd7010STobias Grosser 
1097718d04c6STobias Grosser   if (Access.isStrideOne(isl::manage_copy(Schedule))) {
10981947f863SJohannes Doerfert     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
109970131d34SMichael Kruse     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
110070131d34SMichael Kruse                                                  VLTS[0], NewAccesses);
11013b11a16aSHongbin Zheng 
1102c14582f2STobias Grosser     Value *VectorPtr =
1103c14582f2STobias Grosser         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
11043b11a16aSHongbin Zheng     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
11053b11a16aSHongbin Zheng 
11063b11a16aSHongbin Zheng     if (!Aligned)
11073b11a16aSHongbin Zheng       Store->setAlignment(8);
11083b11a16aSHongbin Zheng   } else {
11093b11a16aSHongbin Zheng     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
11101bb59b0dSTobias Grosser       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
111170131d34SMichael Kruse       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
111270131d34SMichael Kruse                                                    VLTS[i], NewAccesses);
11133b11a16aSHongbin Zheng       Builder.CreateStore(Scalar, NewPointer);
11143b11a16aSHongbin Zheng     }
11153b11a16aSHongbin Zheng   }
11163b11a16aSHongbin Zheng }
11173b11a16aSHongbin Zheng 
11183b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
11193b11a16aSHongbin Zheng                                              ValueMapT &VectorMap) {
112091f5b262STobias Grosser   for (Value *Operand : Inst->operands())
112191f5b262STobias Grosser     if (VectorMap.count(Operand))
11223b11a16aSHongbin Zheng       return true;
11233b11a16aSHongbin Zheng   return false;
11243b11a16aSHongbin Zheng }
11253b11a16aSHongbin Zheng 
11263b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
11273b11a16aSHongbin Zheng                                                ValueMapT &VectorMap,
11283b11a16aSHongbin Zheng                                                VectorValueMapT &ScalarMaps) {
11293b11a16aSHongbin Zheng   bool HasVectorOperand = false;
11303b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
11313b11a16aSHongbin Zheng 
113291f5b262STobias Grosser   for (Value *Operand : Inst->operands()) {
113391f5b262STobias Grosser     ValueMapT::iterator VecOp = VectorMap.find(Operand);
11343b11a16aSHongbin Zheng 
11353b11a16aSHongbin Zheng     if (VecOp == VectorMap.end())
11363b11a16aSHongbin Zheng       continue;
11373b11a16aSHongbin Zheng 
11383b11a16aSHongbin Zheng     HasVectorOperand = true;
11393b11a16aSHongbin Zheng     Value *NewVector = VecOp->second;
11403b11a16aSHongbin Zheng 
11413b11a16aSHongbin Zheng     for (int i = 0; i < VectorWidth; ++i) {
11423b11a16aSHongbin Zheng       ValueMapT &SM = ScalarMaps[i];
11433b11a16aSHongbin Zheng 
11443b11a16aSHongbin Zheng       // If there is one scalar extracted, all scalar elements should have
11453b11a16aSHongbin Zheng       // already been extracted by the code here. So no need to check for the
11462219d157STobias Grosser       // existence of all of them.
114791f5b262STobias Grosser       if (SM.count(Operand))
11483b11a16aSHongbin Zheng         break;
11493b11a16aSHongbin Zheng 
115091f5b262STobias Grosser       SM[Operand] =
115191f5b262STobias Grosser           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
11523b11a16aSHongbin Zheng     }
11533b11a16aSHongbin Zheng   }
11543b11a16aSHongbin Zheng 
11553b11a16aSHongbin Zheng   return HasVectorOperand;
11563b11a16aSHongbin Zheng }
11573b11a16aSHongbin Zheng 
11582d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstScalarized(
11592f1acac6STobias Grosser     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
11602d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
11613b11a16aSHongbin Zheng   bool HasVectorOperand;
11623b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
11633b11a16aSHongbin Zheng 
11643b11a16aSHongbin Zheng   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
11653b11a16aSHongbin Zheng 
11663b11a16aSHongbin Zheng   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
1167be9c9117SJohannes Doerfert     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1168bc132607STobias Grosser                                     VLTS[VectorLane], NewAccesses);
11693b11a16aSHongbin Zheng 
11703b11a16aSHongbin Zheng   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
11713b11a16aSHongbin Zheng     return;
11723b11a16aSHongbin Zheng 
11733b11a16aSHongbin Zheng   // Make the result available as vector value.
11743b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
11753b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
11763b11a16aSHongbin Zheng 
11773b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++)
11783b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
11793b11a16aSHongbin Zheng                                          Builder.getInt32(i));
11803b11a16aSHongbin Zheng 
11813b11a16aSHongbin Zheng   VectorMap[Inst] = Vector;
11823b11a16aSHongbin Zheng }
11833b11a16aSHongbin Zheng 
1184bc132607STobias Grosser int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
11853b11a16aSHongbin Zheng 
11862d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstruction(
11872f1acac6STobias Grosser     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
11882d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
11893b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
11903b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
11913b11a16aSHongbin Zheng   if (Inst->isTerminator())
11923b11a16aSHongbin Zheng     return;
11933b11a16aSHongbin Zheng 
11945dced269SJohannes Doerfert   if (canSyntheziseInStmt(Stmt, Inst))
1195e71c6ab5STobias Grosser     return;
1196e71c6ab5STobias Grosser 
11979646e3feSTobias Grosser   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
11982d1ed0bfSTobias Grosser     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
11993b11a16aSHongbin Zheng     return;
12003b11a16aSHongbin Zheng   }
12013b11a16aSHongbin Zheng 
12023b11a16aSHongbin Zheng   if (hasVectorOperands(Inst, VectorMap)) {
12039646e3feSTobias Grosser     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
12040446d81eSMichael Kruse       // Identified as redundant by -polly-simplify.
12050446d81eSMichael Kruse       if (!Stmt.getArrayAccessOrNULLFor(Store))
12060446d81eSMichael Kruse         return;
12070446d81eSMichael Kruse 
12082d1ed0bfSTobias Grosser       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
12093b11a16aSHongbin Zheng       return;
12103b11a16aSHongbin Zheng     }
12113b11a16aSHongbin Zheng 
12129646e3feSTobias Grosser     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1213be9c9117SJohannes Doerfert       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
12143b11a16aSHongbin Zheng       return;
12153b11a16aSHongbin Zheng     }
12163b11a16aSHongbin Zheng 
12179646e3feSTobias Grosser     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1218be9c9117SJohannes Doerfert       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
12193b11a16aSHongbin Zheng       return;
12203b11a16aSHongbin Zheng     }
12213b11a16aSHongbin Zheng 
1222a6d48f59SMichael Kruse     // Fallthrough: We generate scalar instructions, if we don't know how to
12233b11a16aSHongbin Zheng     // generate vector code.
12243b11a16aSHongbin Zheng   }
12253b11a16aSHongbin Zheng 
12262d1ed0bfSTobias Grosser   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
12273b11a16aSHongbin Zheng }
12283b11a16aSHongbin Zheng 
1229a69d4f0dSTobias Grosser void VectorBlockGenerator::generateScalarVectorLoads(
1230a69d4f0dSTobias Grosser     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1231a69d4f0dSTobias Grosser   for (MemoryAccess *MA : Stmt) {
1232a69d4f0dSTobias Grosser     if (MA->isArrayKind() || MA->isWrite())
1233a69d4f0dSTobias Grosser       continue;
1234a69d4f0dSTobias Grosser 
1235a69d4f0dSTobias Grosser     auto *Address = getOrCreateAlloca(*MA);
1236a69d4f0dSTobias Grosser     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1237a69d4f0dSTobias Grosser     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1238a69d4f0dSTobias Grosser                                              Address->getName() + "_p_vec_p");
1239a69d4f0dSTobias Grosser     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1240a69d4f0dSTobias Grosser     Constant *SplatVector = Constant::getNullValue(
1241a69d4f0dSTobias Grosser         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1242a69d4f0dSTobias Grosser 
1243a69d4f0dSTobias Grosser     Value *VectorVal = Builder.CreateShuffleVector(
1244a69d4f0dSTobias Grosser         Val, Val, SplatVector, Address->getName() + "_p_splat");
1245583be06fSTobias Grosser     VectorBlockMap[MA->getAccessValue()] = VectorVal;
1246a69d4f0dSTobias Grosser   }
1247a69d4f0dSTobias Grosser }
1248a69d4f0dSTobias Grosser 
1249a69d4f0dSTobias Grosser void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1250a69d4f0dSTobias Grosser   for (MemoryAccess *MA : Stmt) {
1251a69d4f0dSTobias Grosser     if (MA->isArrayKind() || MA->isRead())
1252a69d4f0dSTobias Grosser       continue;
1253a69d4f0dSTobias Grosser 
1254a69d4f0dSTobias Grosser     llvm_unreachable("Scalar stores not expected in vector loop");
1255a69d4f0dSTobias Grosser   }
1256a69d4f0dSTobias Grosser }
1257a69d4f0dSTobias Grosser 
12582d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStmt(
12592d1ed0bfSTobias Grosser     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
126021a059afSTobias Grosser   assert(Stmt.isBlockStmt() &&
126121a059afSTobias Grosser          "TODO: Only block statements can be copied by the vector block "
126221a059afSTobias Grosser          "generator");
1263275a1756SJohannes Doerfert 
1264be9c9117SJohannes Doerfert   BasicBlock *BB = Stmt.getBasicBlock();
1265b8f58b53SDuncan P. N. Exon Smith   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1266b8f58b53SDuncan P. N. Exon Smith                                   &*Builder.GetInsertPoint(), &DT, &LI);
12673b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
1268b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&CopyBB->front());
12693b11a16aSHongbin Zheng 
12703b11a16aSHongbin Zheng   // Create two maps that store the mapping from the original instructions of
12713b11a16aSHongbin Zheng   // the old basic block to their copies in the new basic block. Those maps
12723b11a16aSHongbin Zheng   // are basic block local.
12733b11a16aSHongbin Zheng   //
12743b11a16aSHongbin Zheng   // As vector code generation is supported there is one map for scalar values
12753b11a16aSHongbin Zheng   // and one for vector values.
12763b11a16aSHongbin Zheng   //
12773b11a16aSHongbin Zheng   // In case we just do scalar code generation, the vectorMap is not used and
12783b11a16aSHongbin Zheng   // the scalarMap has just one dimension, which contains the mapping.
12793b11a16aSHongbin Zheng   //
12803b11a16aSHongbin Zheng   // In case vector code generation is done, an instruction may either appear
12813b11a16aSHongbin Zheng   // in the vector map once (as it is calculating >vectorwidth< values at a
12823b11a16aSHongbin Zheng   // time. Or (if the values are calculated using scalar operations), it
12833b11a16aSHongbin Zheng   // appears once in every dimension of the scalarMap.
12843b11a16aSHongbin Zheng   VectorValueMapT ScalarBlockMap(getVectorWidth());
12853b11a16aSHongbin Zheng   ValueMapT VectorBlockMap;
12863b11a16aSHongbin Zheng 
1287a69d4f0dSTobias Grosser   generateScalarVectorLoads(Stmt, VectorBlockMap);
1288a69d4f0dSTobias Grosser 
128991f5b262STobias Grosser   for (Instruction &Inst : *BB)
12902d1ed0bfSTobias Grosser     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1291a69d4f0dSTobias Grosser 
1292a69d4f0dSTobias Grosser   verifyNoScalarStores(Stmt);
12933b11a16aSHongbin Zheng }
1294275a1756SJohannes Doerfert 
1295ecff11dcSJohannes Doerfert BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1296ecff11dcSJohannes Doerfert                                              BasicBlock *BBCopy) {
1297514f6efaSJohannes Doerfert 
1298514f6efaSJohannes Doerfert   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1299deefbcedSTobias Grosser   BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1300514f6efaSJohannes Doerfert 
1301514f6efaSJohannes Doerfert   if (BBCopyIDom)
1302514f6efaSJohannes Doerfert     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1303514f6efaSJohannes Doerfert 
1304deefbcedSTobias Grosser   return StartBlockMap.lookup(BBIDom);
1305514f6efaSJohannes Doerfert }
1306514f6efaSJohannes Doerfert 
1307f33c125dSMichael Kruse // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1308f33c125dSMichael Kruse // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1309f33c125dSMichael Kruse // does not work in cases where the exit block has edges from outside the
1310f33c125dSMichael Kruse // region. In that case the llvm::Value would never be usable in in the exit
1311f33c125dSMichael Kruse // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1312f33c125dSMichael Kruse // for the subregion's exiting edges only. We need to determine whether an
1313f33c125dSMichael Kruse // llvm::Value is usable in there. We do this by checking whether it dominates
1314f33c125dSMichael Kruse // all exiting blocks individually.
1315f33c125dSMichael Kruse static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1316f33c125dSMichael Kruse                                       BasicBlock *BB) {
1317f33c125dSMichael Kruse   for (auto ExitingBB : predecessors(R->getExit())) {
1318f33c125dSMichael Kruse     // Check for non-subregion incoming edges.
1319f33c125dSMichael Kruse     if (!R->contains(ExitingBB))
1320f33c125dSMichael Kruse       continue;
1321f33c125dSMichael Kruse 
1322f33c125dSMichael Kruse     if (!DT.dominates(BB, ExitingBB))
1323f33c125dSMichael Kruse       return false;
1324f33c125dSMichael Kruse   }
1325f33c125dSMichael Kruse 
1326f33c125dSMichael Kruse   return true;
1327f33c125dSMichael Kruse }
1328f33c125dSMichael Kruse 
1329f33c125dSMichael Kruse // Find the direct dominator of the subregion's exit block if the subregion was
1330f33c125dSMichael Kruse // simplified.
1331f33c125dSMichael Kruse static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1332f33c125dSMichael Kruse   BasicBlock *Common = nullptr;
1333f33c125dSMichael Kruse   for (auto ExitingBB : predecessors(R->getExit())) {
1334f33c125dSMichael Kruse     // Check for non-subregion incoming edges.
1335f33c125dSMichael Kruse     if (!R->contains(ExitingBB))
1336f33c125dSMichael Kruse       continue;
1337f33c125dSMichael Kruse 
1338f33c125dSMichael Kruse     // First exiting edge.
1339f33c125dSMichael Kruse     if (!Common) {
1340f33c125dSMichael Kruse       Common = ExitingBB;
1341f33c125dSMichael Kruse       continue;
1342f33c125dSMichael Kruse     }
1343f33c125dSMichael Kruse 
1344f33c125dSMichael Kruse     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1345f33c125dSMichael Kruse   }
1346f33c125dSMichael Kruse 
1347f33c125dSMichael Kruse   assert(Common && R->contains(Common));
1348f33c125dSMichael Kruse   return Common;
1349f33c125dSMichael Kruse }
1350f33c125dSMichael Kruse 
1351bc132607STobias Grosser void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
13522d1ed0bfSTobias Grosser                                isl_id_to_ast_expr *IdToAstExp) {
1353275a1756SJohannes Doerfert   assert(Stmt.isRegionStmt() &&
1354d3f21833STobias Grosser          "Only region statements can be copied by the region generator");
1355275a1756SJohannes Doerfert 
1356ecff11dcSJohannes Doerfert   // Forget all old mappings.
1357deefbcedSTobias Grosser   StartBlockMap.clear();
1358deefbcedSTobias Grosser   EndBlockMap.clear();
1359ecff11dcSJohannes Doerfert   RegionMaps.clear();
1360ecff11dcSJohannes Doerfert   IncompletePHINodeMap.clear();
1361ecff11dcSJohannes Doerfert 
1362225f0d1eSMichael Kruse   // Collection of all values related to this subregion.
1363225f0d1eSMichael Kruse   ValueMapT ValueMap;
1364225f0d1eSMichael Kruse 
1365275a1756SJohannes Doerfert   // The region represented by the statement.
1366275a1756SJohannes Doerfert   Region *R = Stmt.getRegion();
1367275a1756SJohannes Doerfert 
1368ecff11dcSJohannes Doerfert   // Create a dedicated entry for the region where we can reload all demoted
1369ecff11dcSJohannes Doerfert   // inputs.
1370ecff11dcSJohannes Doerfert   BasicBlock *EntryBB = R->getEntry();
1371b8f58b53SDuncan P. N. Exon Smith   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1372b8f58b53SDuncan P. N. Exon Smith                                        &*Builder.GetInsertPoint(), &DT, &LI);
1373ecff11dcSJohannes Doerfert   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1374b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&EntryBBCopy->front());
1375514f6efaSJohannes Doerfert 
1376c993739eSMichael Kruse   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
13772fa35194SMichael Kruse   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1378225f0d1eSMichael Kruse 
1379ecff11dcSJohannes Doerfert   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1380deefbcedSTobias Grosser     if (!R->contains(*PI)) {
1381deefbcedSTobias Grosser       StartBlockMap[*PI] = EntryBBCopy;
1382deefbcedSTobias Grosser       EndBlockMap[*PI] = EntryBBCopy;
1383deefbcedSTobias Grosser     }
1384275a1756SJohannes Doerfert 
1385275a1756SJohannes Doerfert   // Iterate over all blocks in the region in a breadth-first search.
1386275a1756SJohannes Doerfert   std::deque<BasicBlock *> Blocks;
13875b1abfc8SMandeep Singh Grang   SmallSetVector<BasicBlock *, 8> SeenBlocks;
1388ecff11dcSJohannes Doerfert   Blocks.push_back(EntryBB);
1389ecff11dcSJohannes Doerfert   SeenBlocks.insert(EntryBB);
1390275a1756SJohannes Doerfert 
1391275a1756SJohannes Doerfert   while (!Blocks.empty()) {
1392275a1756SJohannes Doerfert     BasicBlock *BB = Blocks.front();
1393275a1756SJohannes Doerfert     Blocks.pop_front();
1394275a1756SJohannes Doerfert 
1395514f6efaSJohannes Doerfert     // First split the block and update dominance information.
1396514f6efaSJohannes Doerfert     BasicBlock *BBCopy = splitBB(BB);
1397ecff11dcSJohannes Doerfert     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1398ecff11dcSJohannes Doerfert 
1399c993739eSMichael Kruse     // Get the mapping for this block and initialize it with either the scalar
1400c993739eSMichael Kruse     // loads from the generated entering block (which dominates all blocks of
1401c993739eSMichael Kruse     // this subregion) or the maps of the immediate dominator, if part of the
1402c993739eSMichael Kruse     // subregion. The latter necessarily includes the former.
1403c993739eSMichael Kruse     ValueMapT *InitBBMap;
1404c993739eSMichael Kruse     if (BBCopyIDom) {
1405c993739eSMichael Kruse       assert(RegionMaps.count(BBCopyIDom));
1406c993739eSMichael Kruse       InitBBMap = &RegionMaps[BBCopyIDom];
1407c993739eSMichael Kruse     } else
1408c993739eSMichael Kruse       InitBBMap = &EntryBBMap;
1409c993739eSMichael Kruse     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1410c993739eSMichael Kruse     ValueMapT &RegionMap = Inserted.first->second;
1411514f6efaSJohannes Doerfert 
1412275a1756SJohannes Doerfert     // Copy the block with the BlockGenerator.
1413b8f58b53SDuncan P. N. Exon Smith     Builder.SetInsertPoint(&BBCopy->front());
1414bc132607STobias Grosser     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1415275a1756SJohannes Doerfert 
1416ecff11dcSJohannes Doerfert     // In order to remap PHI nodes we store also basic block mappings.
1417deefbcedSTobias Grosser     StartBlockMap[BB] = BBCopy;
1418deefbcedSTobias Grosser     EndBlockMap[BB] = Builder.GetInsertBlock();
1419ecff11dcSJohannes Doerfert 
1420ecff11dcSJohannes Doerfert     // Add values to incomplete PHI nodes waiting for this block to be copied.
1421ecff11dcSJohannes Doerfert     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1422bc132607STobias Grosser       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1423ecff11dcSJohannes Doerfert     IncompletePHINodeMap[BB].clear();
1424ecff11dcSJohannes Doerfert 
1425275a1756SJohannes Doerfert     // And continue with new successors inside the region.
1426275a1756SJohannes Doerfert     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
14275b1abfc8SMandeep Singh Grang       if (R->contains(*SI) && SeenBlocks.insert(*SI))
1428275a1756SJohannes Doerfert         Blocks.push_back(*SI);
1429ebffcbeeSMichael Kruse 
1430ebffcbeeSMichael Kruse     // Remember value in case it is visible after this subregion.
1431f33c125dSMichael Kruse     if (isDominatingSubregionExit(DT, R, BB))
1432ebffcbeeSMichael Kruse       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1433275a1756SJohannes Doerfert   }
1434275a1756SJohannes Doerfert 
1435275a1756SJohannes Doerfert   // Now create a new dedicated region exit block and add it to the region map.
1436b8f58b53SDuncan P. N. Exon Smith   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1437b8f58b53SDuncan P. N. Exon Smith                                       &*Builder.GetInsertPoint(), &DT, &LI);
1438ecff11dcSJohannes Doerfert   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1439deefbcedSTobias Grosser   StartBlockMap[R->getExit()] = ExitBBCopy;
1440deefbcedSTobias Grosser   EndBlockMap[R->getExit()] = ExitBBCopy;
1441514f6efaSJohannes Doerfert 
1442deefbcedSTobias Grosser   BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
144321a059afSTobias Grosser   assert(ExitDomBBCopy &&
144421a059afSTobias Grosser          "Common exit dominator must be within region; at least the entry node "
144521a059afSTobias Grosser          "must match");
1446f33c125dSMichael Kruse   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1447275a1756SJohannes Doerfert 
1448275a1756SJohannes Doerfert   // As the block generator doesn't handle control flow we need to add the
1449275a1756SJohannes Doerfert   // region control flow by hand after all blocks have been copied.
1450275a1756SJohannes Doerfert   for (BasicBlock *BB : SeenBlocks) {
1451275a1756SJohannes Doerfert 
1452deefbcedSTobias Grosser     BasicBlock *BBCopyStart = StartBlockMap[BB];
1453deefbcedSTobias Grosser     BasicBlock *BBCopyEnd = EndBlockMap[BB];
1454e114dc02SJohannes Doerfert     TerminatorInst *TI = BB->getTerminator();
1455e114dc02SJohannes Doerfert     if (isa<UnreachableInst>(TI)) {
1456deefbcedSTobias Grosser       while (!BBCopyEnd->empty())
1457deefbcedSTobias Grosser         BBCopyEnd->begin()->eraseFromParent();
1458deefbcedSTobias Grosser       new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1459e114dc02SJohannes Doerfert       continue;
1460e114dc02SJohannes Doerfert     }
1461e114dc02SJohannes Doerfert 
1462deefbcedSTobias Grosser     Instruction *BICopy = BBCopyEnd->getTerminator();
1463275a1756SJohannes Doerfert 
1464deefbcedSTobias Grosser     ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1465deefbcedSTobias Grosser     RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1466514f6efaSJohannes Doerfert 
146745e7944bSTobias Grosser     Builder.SetInsertPoint(BICopy);
14689a132f36SJohannes Doerfert     copyInstScalar(Stmt, TI, RegionMap, LTS);
1469275a1756SJohannes Doerfert     BICopy->eraseFromParent();
1470275a1756SJohannes Doerfert   }
1471275a1756SJohannes Doerfert 
1472ecff11dcSJohannes Doerfert   // Add counting PHI nodes to all loops in the region that can be used as
1473a6d48f59SMichael Kruse   // replacement for SCEVs referring to the old loop.
1474ecff11dcSJohannes Doerfert   for (BasicBlock *BB : SeenBlocks) {
1475ecff11dcSJohannes Doerfert     Loop *L = LI.getLoopFor(BB);
1476bc29e0b2STobias Grosser     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1477ecff11dcSJohannes Doerfert       continue;
1478ecff11dcSJohannes Doerfert 
1479deefbcedSTobias Grosser     BasicBlock *BBCopy = StartBlockMap[BB];
1480ecff11dcSJohannes Doerfert     Value *NullVal = Builder.getInt32(0);
1481ecff11dcSJohannes Doerfert     PHINode *LoopPHI =
1482ecff11dcSJohannes Doerfert         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1483ecff11dcSJohannes Doerfert     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1484ecff11dcSJohannes Doerfert         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1485b8f58b53SDuncan P. N. Exon Smith     LoopPHI->insertBefore(&BBCopy->front());
1486ecff11dcSJohannes Doerfert     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1487ecff11dcSJohannes Doerfert 
1488ecff11dcSJohannes Doerfert     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1489ecff11dcSJohannes Doerfert       if (!R->contains(PredBB))
1490ecff11dcSJohannes Doerfert         continue;
1491ecff11dcSJohannes Doerfert       if (L->contains(PredBB))
1492deefbcedSTobias Grosser         LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1493ecff11dcSJohannes Doerfert       else
1494deefbcedSTobias Grosser         LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1495ecff11dcSJohannes Doerfert     }
1496ecff11dcSJohannes Doerfert 
1497ecff11dcSJohannes Doerfert     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1498ecff11dcSJohannes Doerfert       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1499ecff11dcSJohannes Doerfert         LoopPHI->addIncoming(NullVal, PredBBCopy);
1500ecff11dcSJohannes Doerfert 
1501ecff11dcSJohannes Doerfert     LTS[L] = SE.getUnknown(LoopPHI);
1502ecff11dcSJohannes Doerfert   }
1503ecff11dcSJohannes Doerfert 
1504225f0d1eSMichael Kruse   // Continue generating code in the exit block.
1505b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1506225f0d1eSMichael Kruse 
1507225f0d1eSMichael Kruse   // Write values visible to other statements.
15082fa35194SMichael Kruse   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1509deefbcedSTobias Grosser   StartBlockMap.clear();
1510deefbcedSTobias Grosser   EndBlockMap.clear();
15113e956020STobias Grosser   RegionMaps.clear();
15123e956020STobias Grosser   IncompletePHINodeMap.clear();
1513275a1756SJohannes Doerfert }
1514ecff11dcSJohannes Doerfert 
1515ee6a4fc6SMichael Kruse PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1516ee6a4fc6SMichael Kruse                                        ValueMapT &BBMap, Loop *L) {
1517ee6a4fc6SMichael Kruse   ScopStmt *Stmt = MA->getStatement();
1518ee6a4fc6SMichael Kruse   Region *SubR = Stmt->getRegion();
1519ee6a4fc6SMichael Kruse   auto Incoming = MA->getIncoming();
1520ee6a4fc6SMichael Kruse 
1521ee6a4fc6SMichael Kruse   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1522ee6a4fc6SMichael Kruse   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1523ee6a4fc6SMichael Kruse   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1524ee6a4fc6SMichael Kruse 
1525ee6a4fc6SMichael Kruse   // This can happen if the subregion is simplified after the ScopStmts
1526ee6a4fc6SMichael Kruse   // have been created; simplification happens as part of CodeGeneration.
1527ee6a4fc6SMichael Kruse   if (OrigPHI->getParent() != SubR->getExit()) {
1528ee6a4fc6SMichael Kruse     BasicBlock *FormerExit = SubR->getExitingBlock();
1529ee6a4fc6SMichael Kruse     if (FormerExit)
1530deefbcedSTobias Grosser       NewSubregionExit = StartBlockMap.lookup(FormerExit);
1531ee6a4fc6SMichael Kruse   }
1532ee6a4fc6SMichael Kruse 
1533ee6a4fc6SMichael Kruse   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1534ee6a4fc6SMichael Kruse                                     "polly." + OrigPHI->getName(),
1535ee6a4fc6SMichael Kruse                                     NewSubregionExit->getFirstNonPHI());
1536ee6a4fc6SMichael Kruse 
1537ee6a4fc6SMichael Kruse   // Add the incoming values to the PHI.
1538ee6a4fc6SMichael Kruse   for (auto &Pair : Incoming) {
1539ee6a4fc6SMichael Kruse     BasicBlock *OrigIncomingBlock = Pair.first;
1540deefbcedSTobias Grosser     BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1541deefbcedSTobias Grosser     BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1542deefbcedSTobias Grosser     Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1543deefbcedSTobias Grosser     assert(RegionMaps.count(NewIncomingBlockStart));
1544deefbcedSTobias Grosser     assert(RegionMaps.count(NewIncomingBlockEnd));
1545deefbcedSTobias Grosser     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1546ee6a4fc6SMichael Kruse 
1547ee6a4fc6SMichael Kruse     Value *OrigIncomingValue = Pair.second;
1548ee6a4fc6SMichael Kruse     Value *NewIncomingValue =
1549ee6a4fc6SMichael Kruse         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1550deefbcedSTobias Grosser     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1551ee6a4fc6SMichael Kruse   }
1552ee6a4fc6SMichael Kruse 
1553ee6a4fc6SMichael Kruse   return NewPHI;
1554ee6a4fc6SMichael Kruse }
1555ee6a4fc6SMichael Kruse 
1556ee6a4fc6SMichael Kruse Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1557ee6a4fc6SMichael Kruse                                       ValueMapT &BBMap) {
1558ee6a4fc6SMichael Kruse   ScopStmt *Stmt = MA->getStatement();
1559ee6a4fc6SMichael Kruse 
1560ee6a4fc6SMichael Kruse   // TODO: Add some test cases that ensure this is really the right choice.
1561ee6a4fc6SMichael Kruse   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1562ee6a4fc6SMichael Kruse 
1563ee6a4fc6SMichael Kruse   if (MA->isAnyPHIKind()) {
1564ee6a4fc6SMichael Kruse     auto Incoming = MA->getIncoming();
1565ee6a4fc6SMichael Kruse     assert(!Incoming.empty() &&
1566ee6a4fc6SMichael Kruse            "PHI WRITEs must have originate from at least one incoming block");
1567ee6a4fc6SMichael Kruse 
1568ee6a4fc6SMichael Kruse     // If there is only one incoming value, we do not need to create a PHI.
1569ee6a4fc6SMichael Kruse     if (Incoming.size() == 1) {
1570ee6a4fc6SMichael Kruse       Value *OldVal = Incoming[0].second;
1571ee6a4fc6SMichael Kruse       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1572ee6a4fc6SMichael Kruse     }
1573ee6a4fc6SMichael Kruse 
1574ee6a4fc6SMichael Kruse     return buildExitPHI(MA, LTS, BBMap, L);
1575ee6a4fc6SMichael Kruse   }
1576ee6a4fc6SMichael Kruse 
15774d5a9172STobias Grosser   // MemoryKind::Value accesses leaving the subregion must dominate the exit
15784d5a9172STobias Grosser   // block; just pass the copied value.
1579ee6a4fc6SMichael Kruse   Value *OldVal = MA->getAccessValue();
1580ee6a4fc6SMichael Kruse   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1581ee6a4fc6SMichael Kruse }
1582ee6a4fc6SMichael Kruse 
15832fa35194SMichael Kruse void RegionGenerator::generateScalarStores(
15842fa35194SMichael Kruse     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
15852fa35194SMichael Kruse     __isl_keep isl_id_to_ast_expr *NewAccesses) {
158675296901STobias Grosser   assert(Stmt.getRegion() &&
158775296901STobias Grosser          "Block statements need to use the generateScalarStores() "
1588ecff11dcSJohannes Doerfert          "function in the BlockGenerator");
1589ecff11dcSJohannes Doerfert 
1590ecff11dcSJohannes Doerfert   for (MemoryAccess *MA : Stmt) {
15912fa35194SMichael Kruse     if (MA->isOriginalArrayKind() || MA->isRead())
1592ecff11dcSJohannes Doerfert       continue;
1593ecff11dcSJohannes Doerfert 
15941515f6b9STobias Grosser     isl::set AccDom = MA->getAccessRelation().domain();
1595fe46c3ffSTobias Grosser     std::string Subject = MA->getId().get_name();
1596fe46c3ffSTobias Grosser     generateConditionalExecution(
1597fe46c3ffSTobias Grosser         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1598ee6a4fc6SMichael Kruse           Value *NewVal = getExitScalar(MA, LTS, BBMap);
1599fe46c3ffSTobias Grosser           Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1600fe46c3ffSTobias Grosser                                               BBMap, NewAccesses);
1601eac9726eSMichael Kruse           assert((!isa<Instruction>(NewVal) ||
1602eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(NewVal)->getParent(),
1603eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
1604eac9726eSMichael Kruse                  "Domination violation");
1605eac9726eSMichael Kruse           assert((!isa<Instruction>(Address) ||
1606eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Address)->getParent(),
1607eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
1608eac9726eSMichael Kruse                  "Domination violation");
1609ee6a4fc6SMichael Kruse           Builder.CreateStore(NewVal, Address);
1610706f79abSMichael Kruse         });
1611ecff11dcSJohannes Doerfert   }
1612ecff11dcSJohannes Doerfert }
1613ecff11dcSJohannes Doerfert 
1614943c369cSTobias Grosser void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1615ecff11dcSJohannes Doerfert                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1616ecff11dcSJohannes Doerfert                                       LoopToScevMapT &LTS) {
1617ecff11dcSJohannes Doerfert   // If the incoming block was not yet copied mark this PHI as incomplete.
1618ecff11dcSJohannes Doerfert   // Once the block will be copied the incoming value will be added.
1619deefbcedSTobias Grosser   BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1620deefbcedSTobias Grosser   BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1621deefbcedSTobias Grosser   if (!BBCopyStart) {
1622deefbcedSTobias Grosser     assert(!BBCopyEnd);
16238d89179eSMichael Kruse     assert(Stmt.represents(IncomingBB) &&
1624ecff11dcSJohannes Doerfert            "Bad incoming block for PHI in non-affine region");
1625ecff11dcSJohannes Doerfert     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1626ecff11dcSJohannes Doerfert     return;
1627ecff11dcSJohannes Doerfert   }
1628ecff11dcSJohannes Doerfert 
1629deefbcedSTobias Grosser   assert(RegionMaps.count(BBCopyStart) &&
1630deefbcedSTobias Grosser          "Incoming PHI block did not have a BBMap");
1631deefbcedSTobias Grosser   ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1632ecff11dcSJohannes Doerfert 
163375dfaa1dSTobias Grosser   Value *OpCopy = nullptr;
163475dfaa1dSTobias Grosser 
16358d89179eSMichael Kruse   if (Stmt.represents(IncomingBB)) {
1636ecff11dcSJohannes Doerfert     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1637dc122222SMichael Kruse 
16386ba92714SJohannes Doerfert     // If the current insert block is different from the PHIs incoming block
16396ba92714SJohannes Doerfert     // change it, otherwise do not.
16406ba92714SJohannes Doerfert     auto IP = Builder.GetInsertPoint();
1641deefbcedSTobias Grosser     if (IP->getParent() != BBCopyEnd)
1642deefbcedSTobias Grosser       Builder.SetInsertPoint(BBCopyEnd->getTerminator());
16432c3ffc04SJohannes Doerfert     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1644deefbcedSTobias Grosser     if (IP->getParent() != BBCopyEnd)
16456ba92714SJohannes Doerfert       Builder.SetInsertPoint(&*IP);
1646ecff11dcSJohannes Doerfert   } else {
164775dfaa1dSTobias Grosser     // All edges from outside the non-affine region become a single edge
164875dfaa1dSTobias Grosser     // in the new copy of the non-affine region. Make sure to only add the
164975dfaa1dSTobias Grosser     // corresponding edge the first time we encounter a basic block from
165075dfaa1dSTobias Grosser     // outside the non-affine region.
1651deefbcedSTobias Grosser     if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1652ecff11dcSJohannes Doerfert       return;
1653ecff11dcSJohannes Doerfert 
165475dfaa1dSTobias Grosser     // Get the reloaded value.
165575dfaa1dSTobias Grosser     OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1656ecff11dcSJohannes Doerfert   }
1657ecff11dcSJohannes Doerfert 
1658ecff11dcSJohannes Doerfert   assert(OpCopy && "Incoming PHI value was not copied properly");
1659deefbcedSTobias Grosser   PHICopy->addIncoming(OpCopy, BBCopyEnd);
1660ecff11dcSJohannes Doerfert }
1661ecff11dcSJohannes Doerfert 
16622b809d13STobias Grosser void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1663ecff11dcSJohannes Doerfert                                          ValueMapT &BBMap,
1664ecff11dcSJohannes Doerfert                                          LoopToScevMapT &LTS) {
1665ecff11dcSJohannes Doerfert   unsigned NumIncoming = PHI->getNumIncomingValues();
1666ecff11dcSJohannes Doerfert   PHINode *PHICopy =
1667ecff11dcSJohannes Doerfert       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1668ecff11dcSJohannes Doerfert   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1669ecff11dcSJohannes Doerfert   BBMap[PHI] = PHICopy;
1670ecff11dcSJohannes Doerfert 
167197b84909STobias Grosser   for (BasicBlock *IncomingBB : PHI->blocks())
167297b84909STobias Grosser     addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1673ecff11dcSJohannes Doerfert }
1674