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"
29030237d0STobias Grosser #include "llvm/IR/IntrinsicInst.h"
30c9895067STobias Grosser #include "llvm/IR/Module.h"
313b11a16aSHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
321b9d25a4STobias Grosser #include "llvm/Transforms/Utils/Local.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
561dcf8d696STobias Grosser     auto *StmtDom = Stmt.getDomain().release();
5621515f6b9STobias Grosser     auto *AccDom = isl_map_domain(MA->getAccessRelation().release());
56377394f13SMichael Kruse     assert(isl_set_is_subset(StmtDom, AccDom) &&
56477394f13SMichael Kruse            "Scalar must be loaded in all statement instances");
56577394f13SMichael Kruse     isl_set_free(StmtDom);
56677394f13SMichael Kruse     isl_set_free(AccDom);
56777394f13SMichael Kruse #endif
56877394f13SMichael Kruse 
5692fa35194SMichael Kruse     auto *Address =
5702fa35194SMichael Kruse         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
571eac9726eSMichael Kruse     assert((!isa<Instruction>(Address) ||
572eac9726eSMichael Kruse             DT.dominates(cast<Instruction>(Address)->getParent(),
573eac9726eSMichael Kruse                          Builder.GetInsertBlock())) &&
574eac9726eSMichael Kruse            "Domination violation");
575583be06fSTobias Grosser     BBMap[MA->getAccessValue()] =
5762fc50df9STobias Grosser         Builder.CreateLoad(Address, Address->getName() + ".reload");
577ecff11dcSJohannes Doerfert   }
578ecff11dcSJohannes Doerfert }
579ecff11dcSJohannes Doerfert 
580706f79abSMichael Kruse Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
581706f79abSMichael Kruse                                               const isl::set &Subdomain) {
582132860afSTobias Grosser   isl::ast_build AstBuild = Stmt.getAstBuild();
583dcf8d696STobias Grosser   isl::set Domain = Stmt.getDomain();
584706f79abSMichael Kruse 
5856b6ac900STobias Grosser   isl::union_map USchedule = AstBuild.get_schedule();
5866b6ac900STobias Grosser   USchedule = USchedule.intersect_domain(Domain);
587706f79abSMichael Kruse 
5886b6ac900STobias Grosser   assert(!USchedule.is_empty());
5896b6ac900STobias Grosser   isl::map Schedule = isl::map::from_union_map(USchedule);
590706f79abSMichael Kruse 
5916b6ac900STobias Grosser   isl::set ScheduledDomain = Schedule.range();
5926b6ac900STobias Grosser   isl::set ScheduledSet = Subdomain.apply(Schedule);
593706f79abSMichael Kruse 
5946b6ac900STobias Grosser   isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
5956b6ac900STobias Grosser 
5966b6ac900STobias Grosser   isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
597706f79abSMichael Kruse   Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
598706f79abSMichael Kruse   IsInSetExpr = Builder.CreateICmpNE(
599706f79abSMichael Kruse       IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
600706f79abSMichael Kruse 
601706f79abSMichael Kruse   return IsInSetExpr;
602706f79abSMichael Kruse }
603706f79abSMichael Kruse 
604706f79abSMichael Kruse void BlockGenerator::generateConditionalExecution(
605706f79abSMichael Kruse     ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
606706f79abSMichael Kruse     const std::function<void()> &GenThenFunc) {
607dcf8d696STobias Grosser   isl::set StmtDom = Stmt.getDomain();
608706f79abSMichael Kruse 
609706f79abSMichael Kruse   // If the condition is a tautology, don't generate a condition around the
610706f79abSMichael Kruse   // code.
611f51decb5STobias Grosser   bool IsPartialWrite =
6128ea1fc19STobias Grosser       !StmtDom.intersect_params(Stmt.getParent()->getContext())
613f51decb5STobias Grosser            .is_subset(Subdomain);
614f51decb5STobias Grosser   if (!IsPartialWrite) {
615706f79abSMichael Kruse     GenThenFunc();
616706f79abSMichael Kruse     return;
617706f79abSMichael Kruse   }
618706f79abSMichael Kruse 
619706f79abSMichael Kruse   // Generate the condition.
620706f79abSMichael Kruse   Value *Cond = buildContainsCondition(Stmt, Subdomain);
621b795bfc0SMichael Kruse 
622b795bfc0SMichael Kruse   // Don't call GenThenFunc if it is never executed. An ast index expression
623b795bfc0SMichael Kruse   // might not be defined in this case.
624b795bfc0SMichael Kruse   if (auto *Const = dyn_cast<ConstantInt>(Cond))
625b795bfc0SMichael Kruse     if (Const->isZero())
626b795bfc0SMichael Kruse       return;
627b795bfc0SMichael Kruse 
628706f79abSMichael Kruse   BasicBlock *HeadBlock = Builder.GetInsertBlock();
629706f79abSMichael Kruse   StringRef BlockName = HeadBlock->getName();
630706f79abSMichael Kruse 
631706f79abSMichael Kruse   // Generate the conditional block.
632706f79abSMichael Kruse   SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
633706f79abSMichael Kruse                             &DT, &LI);
634706f79abSMichael Kruse   BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
635706f79abSMichael Kruse   BasicBlock *ThenBlock = Branch->getSuccessor(0);
636706f79abSMichael Kruse   BasicBlock *TailBlock = Branch->getSuccessor(1);
637706f79abSMichael Kruse 
638706f79abSMichael Kruse   // Assign descriptive names.
639706f79abSMichael Kruse   if (auto *CondInst = dyn_cast<Instruction>(Cond))
640706f79abSMichael Kruse     CondInst->setName("polly." + Subject + ".cond");
641706f79abSMichael Kruse   ThenBlock->setName(BlockName + "." + Subject + ".partial");
642706f79abSMichael Kruse   TailBlock->setName(BlockName + ".cont");
643706f79abSMichael Kruse 
644706f79abSMichael Kruse   // Put the client code into the conditional block and continue in the merge
645706f79abSMichael Kruse   // block afterwards.
646706f79abSMichael Kruse   Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
647706f79abSMichael Kruse   GenThenFunc();
648706f79abSMichael Kruse   Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
649706f79abSMichael Kruse }
650706f79abSMichael Kruse 
6512fa35194SMichael Kruse void BlockGenerator::generateScalarStores(
6522fa35194SMichael Kruse     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
6532fa35194SMichael Kruse     __isl_keep isl_id_to_ast_expr *NewAccesses) {
654f2cdd144STobias Grosser   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
655ecff11dcSJohannes Doerfert 
65621a059afSTobias Grosser   assert(Stmt.isBlockStmt() &&
65721a059afSTobias Grosser          "Region statements need to use the generateScalarStores() function in "
65821a059afSTobias Grosser          "the RegionGenerator");
659ecff11dcSJohannes Doerfert 
660ecff11dcSJohannes Doerfert   for (MemoryAccess *MA : Stmt) {
6612fa35194SMichael Kruse     if (MA->isOriginalArrayKind() || MA->isRead())
662ecff11dcSJohannes Doerfert       continue;
663ecff11dcSJohannes Doerfert 
6641515f6b9STobias Grosser     isl::set AccDom = MA->getAccessRelation().domain();
665fe46c3ffSTobias Grosser     std::string Subject = MA->getId().get_name();
66677394f13SMichael Kruse 
667fe46c3ffSTobias Grosser     generateConditionalExecution(
668fe46c3ffSTobias Grosser         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
669d86f2157SJohannes Doerfert           Value *Val = MA->getAccessValue();
670ee6a4fc6SMichael Kruse           if (MA->isAnyPHIKind()) {
671fe46c3ffSTobias Grosser             assert(MA->getIncoming().size() >= 1 &&
672fe46c3ffSTobias Grosser                    "Block statements have exactly one exiting block, or "
673fe46c3ffSTobias Grosser                    "multiple but "
674ee6a4fc6SMichael Kruse                    "with same incoming block and value");
675fe46c3ffSTobias Grosser             assert(std::all_of(MA->getIncoming().begin(),
676fe46c3ffSTobias Grosser                                MA->getIncoming().end(),
677ee6a4fc6SMichael Kruse                                [&](std::pair<BasicBlock *, Value *> p) -> bool {
678ee6a4fc6SMichael Kruse                                  return p.first == Stmt.getBasicBlock();
679ee6a4fc6SMichael Kruse                                }) &&
680ee6a4fc6SMichael Kruse                    "Incoming block must be statement's block");
681ee6a4fc6SMichael Kruse             Val = MA->getIncoming()[0].second;
682ee6a4fc6SMichael Kruse           }
683fe46c3ffSTobias Grosser           auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
684fe46c3ffSTobias Grosser                                             BBMap, NewAccesses);
685d86f2157SJohannes Doerfert 
686f2cdd144STobias Grosser           Val = getNewValue(Stmt, Val, BBMap, LTS, L);
687eac9726eSMichael Kruse           assert((!isa<Instruction>(Val) ||
688eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Val)->getParent(),
689eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
690eac9726eSMichael Kruse                  "Domination violation");
691eac9726eSMichael Kruse           assert((!isa<Instruction>(Address) ||
692eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Address)->getParent(),
693eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
694eac9726eSMichael Kruse                  "Domination violation");
695*2f5cbc44SMichael Kruse 
696*2f5cbc44SMichael Kruse           // The new Val might have a different type than the old Val due to
697*2f5cbc44SMichael Kruse           // ScalarEvolution looking through bitcasts.
698*2f5cbc44SMichael Kruse           if (Val->getType() != Address->getType()->getPointerElementType())
699*2f5cbc44SMichael Kruse             Address = Builder.CreateBitOrPointerCast(
700*2f5cbc44SMichael Kruse                 Address, Val->getType()->getPointerTo());
701*2f5cbc44SMichael Kruse 
70292245228STobias Grosser           Builder.CreateStore(Val, Address);
703706f79abSMichael Kruse 
704706f79abSMichael Kruse         });
705ecff11dcSJohannes Doerfert   }
706ecff11dcSJohannes Doerfert }
707ecff11dcSJohannes Doerfert 
708c0091a77STobias Grosser void BlockGenerator::createScalarInitialization(Scop &S) {
709ef74443cSJohannes Doerfert   BasicBlock *ExitBB = S.getExit();
710acf80064SEli Friedman   BasicBlock *PreEntryBB = S.getEnteringBlock();
711188542fdSJohannes Doerfert 
712acf80064SEli Friedman   Builder.SetInsertPoint(&*StartBlock->begin());
713ecff11dcSJohannes Doerfert 
714d7754a12SRoman Gareev   for (auto &Array : S.arrays()) {
715c0091a77STobias Grosser     if (Array->getNumberOfDimensions() != 0)
716c0091a77STobias Grosser       continue;
717a535dff4STobias Grosser     if (Array->isPHIKind()) {
718c0091a77STobias Grosser       // For PHI nodes, the only values we need to store are the ones that
719c0091a77STobias Grosser       // reach the PHI node from outside the region. In general there should
720c0091a77STobias Grosser       // only be one such incoming edge and this edge should enter through
721acf80064SEli Friedman       // 'PreEntryBB'.
722c0091a77STobias Grosser       auto PHI = cast<PHINode>(Array->getBasePtr());
723ecff11dcSJohannes Doerfert 
724c0091a77STobias Grosser       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
725acf80064SEli Friedman         if (!S.contains(*BI) && *BI != PreEntryBB)
726c0091a77STobias Grosser           llvm_unreachable("Incoming edges from outside the scop should always "
727acf80064SEli Friedman                            "come from PreEntryBB");
728c0091a77STobias Grosser 
729acf80064SEli Friedman       int Idx = PHI->getBasicBlockIndex(PreEntryBB);
730c0091a77STobias Grosser       if (Idx < 0)
731ecff11dcSJohannes Doerfert         continue;
732ecff11dcSJohannes Doerfert 
733c0091a77STobias Grosser       Value *ScalarValue = PHI->getIncomingValue(Idx);
734ecff11dcSJohannes Doerfert 
735587f1f57STobias Grosser       Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
736c0091a77STobias Grosser       continue;
737c0091a77STobias Grosser     }
738c0091a77STobias Grosser 
739c0091a77STobias Grosser     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
740c0091a77STobias Grosser 
741952b5304SJohannes Doerfert     if (Inst && S.contains(Inst))
742c0091a77STobias Grosser       continue;
743c0091a77STobias Grosser 
744188542fdSJohannes Doerfert     // PHI nodes that are not marked as such in their SAI object are either exit
745188542fdSJohannes Doerfert     // PHI nodes we model as common scalars but without initialization, or
746188542fdSJohannes Doerfert     // incoming phi nodes that need to be initialized. Check if the first is the
747188542fdSJohannes Doerfert     // case for Inst and do not create and initialize memory if so.
748188542fdSJohannes Doerfert     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
749188542fdSJohannes Doerfert       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
750717b8667SJohannes Doerfert         continue;
751717b8667SJohannes Doerfert 
752587f1f57STobias Grosser     Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
753ecff11dcSJohannes Doerfert   }
754ecff11dcSJohannes Doerfert }
755ecff11dcSJohannes Doerfert 
756ef74443cSJohannes Doerfert void BlockGenerator::createScalarFinalization(Scop &S) {
757ecff11dcSJohannes Doerfert   // The exit block of the __unoptimized__ region.
758ef74443cSJohannes Doerfert   BasicBlock *ExitBB = S.getExitingBlock();
759ecff11dcSJohannes Doerfert   // The merge block __just after__ the region and the optimized region.
760ef74443cSJohannes Doerfert   BasicBlock *MergeBB = S.getExit();
761ecff11dcSJohannes Doerfert 
762ecff11dcSJohannes Doerfert   // The exit block of the __optimized__ region.
763ecff11dcSJohannes Doerfert   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
764ecff11dcSJohannes Doerfert   if (OptExitBB == ExitBB)
765ecff11dcSJohannes Doerfert     OptExitBB = *(++pred_begin(MergeBB));
766ecff11dcSJohannes Doerfert 
767ecff11dcSJohannes Doerfert   Builder.SetInsertPoint(OptExitBB->getTerminator());
768ecff11dcSJohannes Doerfert   for (const auto &EscapeMapping : EscapeMap) {
769ecff11dcSJohannes Doerfert     // Extract the escaping instruction and the escaping users as well as the
770ecff11dcSJohannes Doerfert     // alloca the instruction was demoted to.
771fbde4355SMichael Kruse     Instruction *EscapeInst = EscapeMapping.first;
772fbde4355SMichael Kruse     const auto &EscapeMappingValue = EscapeMapping.second;
773ecff11dcSJohannes Doerfert     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
77464c0ff41STobias Grosser     Value *ScalarAddr = EscapeMappingValue.first;
775ecff11dcSJohannes Doerfert 
776ecff11dcSJohannes Doerfert     // Reload the demoted instruction in the optimized version of the SCoP.
777d8b6ad25SJohannes Doerfert     Value *EscapeInstReload =
778ecff11dcSJohannes Doerfert         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
779d8b6ad25SJohannes Doerfert     EscapeInstReload =
780d8b6ad25SJohannes Doerfert         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
781ecff11dcSJohannes Doerfert 
782ecff11dcSJohannes Doerfert     // Create the merge PHI that merges the optimized and unoptimized version.
783ecff11dcSJohannes Doerfert     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
784ecff11dcSJohannes Doerfert                                         EscapeInst->getName() + ".merge");
785b8f58b53SDuncan P. N. Exon Smith     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
786ecff11dcSJohannes Doerfert 
787ecff11dcSJohannes Doerfert     // Add the respective values to the merge PHI.
788ecff11dcSJohannes Doerfert     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
789ecff11dcSJohannes Doerfert     MergePHI->addIncoming(EscapeInst, ExitBB);
790ecff11dcSJohannes Doerfert 
791ecff11dcSJohannes Doerfert     // The information of scalar evolution about the escaping instruction needs
792ecff11dcSJohannes Doerfert     // to be revoked so the new merged instruction will be used.
793ecff11dcSJohannes Doerfert     if (SE.isSCEVable(EscapeInst->getType()))
794ecff11dcSJohannes Doerfert       SE.forgetValue(EscapeInst);
795ecff11dcSJohannes Doerfert 
796ecff11dcSJohannes Doerfert     // Replace all uses of the demoted instruction with the merge PHI.
797ecff11dcSJohannes Doerfert     for (Instruction *EUser : EscapeUsers)
798ecff11dcSJohannes Doerfert       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
799ecff11dcSJohannes Doerfert   }
800ecff11dcSJohannes Doerfert }
801ecff11dcSJohannes Doerfert 
802ffa2446fSTobias Grosser void BlockGenerator::findOutsideUsers(Scop &S) {
803d7754a12SRoman Gareev   for (auto &Array : S.arrays()) {
804ffa2446fSTobias Grosser 
805ffa2446fSTobias Grosser     if (Array->getNumberOfDimensions() != 0)
806ffa2446fSTobias Grosser       continue;
807ffa2446fSTobias Grosser 
808a535dff4STobias Grosser     if (Array->isPHIKind())
809ffa2446fSTobias Grosser       continue;
810ffa2446fSTobias Grosser 
811ffa2446fSTobias Grosser     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
812ffa2446fSTobias Grosser 
813ffa2446fSTobias Grosser     if (!Inst)
814ffa2446fSTobias Grosser       continue;
815ffa2446fSTobias Grosser 
816ffa2446fSTobias Grosser     // Scop invariant hoisting moves some of the base pointers out of the scop.
817ffa2446fSTobias Grosser     // We can ignore these, as the invariant load hoisting already registers the
818ffa2446fSTobias Grosser     // relevant outside users.
819952b5304SJohannes Doerfert     if (!S.contains(Inst))
820ffa2446fSTobias Grosser       continue;
821ffa2446fSTobias Grosser 
822587f1f57STobias Grosser     handleOutsideUsers(S, Array);
823ffa2446fSTobias Grosser   }
824ffa2446fSTobias Grosser }
825ffa2446fSTobias Grosser 
82627d742daSTobias Grosser void BlockGenerator::createExitPHINodeMerges(Scop &S) {
82727d742daSTobias Grosser   if (S.hasSingleExitEdge())
82827d742daSTobias Grosser     return;
82927d742daSTobias Grosser 
830ef74443cSJohannes Doerfert   auto *ExitBB = S.getExitingBlock();
831ef74443cSJohannes Doerfert   auto *MergeBB = S.getExit();
83227d742daSTobias Grosser   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
83327d742daSTobias Grosser   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
83427d742daSTobias Grosser   if (OptExitBB == ExitBB)
83527d742daSTobias Grosser     OptExitBB = *(++pred_begin(MergeBB));
83627d742daSTobias Grosser 
83727d742daSTobias Grosser   Builder.SetInsertPoint(OptExitBB->getTerminator());
83827d742daSTobias Grosser 
839d7754a12SRoman Gareev   for (auto &SAI : S.arrays()) {
84027d742daSTobias Grosser     auto *Val = SAI->getBasePtr();
84127d742daSTobias Grosser 
842faedfcbfSMichael Kruse     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
843faedfcbfSMichael Kruse     // the original PHI's value or the reloaded incoming values from the
844faedfcbfSMichael Kruse     // generated code. An llvm::Value is merged between the original code's
845faedfcbfSMichael Kruse     // value or the generated one.
846fa53c86dSMichael Kruse     if (!SAI->isExitPHIKind())
847faedfcbfSMichael Kruse       continue;
848faedfcbfSMichael Kruse 
84927d742daSTobias Grosser     PHINode *PHI = dyn_cast<PHINode>(Val);
85027d742daSTobias Grosser     if (!PHI)
85127d742daSTobias Grosser       continue;
85227d742daSTobias Grosser 
853a3f6edaeSTobias Grosser     if (PHI->getParent() != AfterMergeBB)
85427d742daSTobias Grosser       continue;
85527d742daSTobias Grosser 
85627d742daSTobias Grosser     std::string Name = PHI->getName();
857587f1f57STobias Grosser     Value *ScalarAddr = getOrCreateAlloca(SAI);
85827d742daSTobias Grosser     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
85927d742daSTobias Grosser     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
86027d742daSTobias Grosser     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
861faedfcbfSMichael Kruse     assert((!isa<Instruction>(OriginalValue) ||
862faedfcbfSMichael Kruse             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
863faedfcbfSMichael Kruse            "Original value must no be one we just generated.");
86427d742daSTobias Grosser     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
865b8f58b53SDuncan P. N. Exon Smith     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
86627d742daSTobias Grosser     MergePHI->addIncoming(Reload, OptExitBB);
86727d742daSTobias Grosser     MergePHI->addIncoming(OriginalValue, ExitBB);
86827d742daSTobias Grosser     int Idx = PHI->getBasicBlockIndex(MergeBB);
86927d742daSTobias Grosser     PHI->setIncomingValue(Idx, MergePHI);
87027d742daSTobias Grosser   }
87127d742daSTobias Grosser }
87227d742daSTobias Grosser 
8731c184409STobias Grosser void BlockGenerator::invalidateScalarEvolution(Scop &S) {
8741c184409STobias Grosser   for (auto &Stmt : S)
875b3224adfSRoman Gareev     if (Stmt.isCopyStmt())
876b3224adfSRoman Gareev       continue;
877b3224adfSRoman Gareev     else if (Stmt.isBlockStmt())
8781c184409STobias Grosser       for (auto &Inst : *Stmt.getBasicBlock())
8791c184409STobias Grosser         SE.forgetValue(&Inst);
8801c184409STobias Grosser     else if (Stmt.isRegionStmt())
8811c184409STobias Grosser       for (auto *BB : Stmt.getRegion()->blocks())
8821c184409STobias Grosser         for (auto &Inst : *BB)
8831c184409STobias Grosser           SE.forgetValue(&Inst);
8841c184409STobias Grosser     else
8851c184409STobias Grosser       llvm_unreachable("Unexpected statement type found");
8861aad76c1SMichael Kruse 
8871aad76c1SMichael Kruse   // Invalidate SCEV of loops surrounding the EscapeUsers.
8881aad76c1SMichael Kruse   for (const auto &EscapeMapping : EscapeMap) {
8891aad76c1SMichael Kruse     const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
8901aad76c1SMichael Kruse     for (Instruction *EUser : EscapeUsers) {
8911aad76c1SMichael Kruse       if (Loop *L = LI.getLoopFor(EUser->getParent()))
8921aad76c1SMichael Kruse         while (L) {
8931aad76c1SMichael Kruse           SE.forgetLoop(L);
8941aad76c1SMichael Kruse           L = L->getParentLoop();
8951aad76c1SMichael Kruse         }
8961aad76c1SMichael Kruse     }
8971aad76c1SMichael Kruse   }
8981c184409STobias Grosser }
8991c184409STobias Grosser 
900ffa2446fSTobias Grosser void BlockGenerator::finalizeSCoP(Scop &S) {
901ffa2446fSTobias Grosser   findOutsideUsers(S);
902c0091a77STobias Grosser   createScalarInitialization(S);
90327d742daSTobias Grosser   createExitPHINodeMerges(S);
904ef74443cSJohannes Doerfert   createScalarFinalization(S);
9051c184409STobias Grosser   invalidateScalarEvolution(S);
9063b11a16aSHongbin Zheng }
9073b11a16aSHongbin Zheng 
908be9c9117SJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
909be9c9117SJohannes Doerfert                                            std::vector<LoopToScevMapT> &VLTS,
910be9c9117SJohannes Doerfert                                            isl_map *Schedule)
911bc132607STobias Grosser     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
912a00a0291SSebastian Pop   assert(Schedule && "No statement domain provided");
9133b11a16aSHongbin Zheng }
9143b11a16aSHongbin Zheng 
9152f1acac6STobias Grosser Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
916e602a076STobias Grosser                                             ValueMapT &VectorMap,
917e602a076STobias Grosser                                             VectorValueMapT &ScalarMaps,
918e602a076STobias Grosser                                             Loop *L) {
919fe11e287SHongbin Zheng   if (Value *NewValue = VectorMap.lookup(Old))
920fe11e287SHongbin Zheng     return NewValue;
9213b11a16aSHongbin Zheng 
9223b11a16aSHongbin Zheng   int Width = getVectorWidth();
9233b11a16aSHongbin Zheng 
9243b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
9253b11a16aSHongbin Zheng 
9263b11a16aSHongbin Zheng   for (int Lane = 0; Lane < Width; Lane++)
927c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
928bc132607STobias Grosser         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
9297242ad92STobias Grosser         Builder.getInt32(Lane));
9303b11a16aSHongbin Zheng 
9313b11a16aSHongbin Zheng   VectorMap[Old] = Vector;
9323b11a16aSHongbin Zheng 
9333b11a16aSHongbin Zheng   return Vector;
9343b11a16aSHongbin Zheng }
9353b11a16aSHongbin Zheng 
9363b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
9373b11a16aSHongbin Zheng   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
9383b11a16aSHongbin Zheng   assert(PointerTy && "PointerType expected");
9393b11a16aSHongbin Zheng 
9403b11a16aSHongbin Zheng   Type *ScalarType = PointerTy->getElementType();
9413b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(ScalarType, Width);
9423b11a16aSHongbin Zheng 
9433b11a16aSHongbin Zheng   return PointerType::getUnqual(VectorType);
9443b11a16aSHongbin Zheng }
9453b11a16aSHongbin Zheng 
946be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateStrideOneLoad(
9472f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
9482d1ed0bfSTobias Grosser     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
9490dd463faSTobias Grosser   unsigned VectorWidth = getVectorWidth();
9509646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
9510dd463faSTobias Grosser   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
9520dd463faSTobias Grosser   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
9530dd463faSTobias Grosser 
9548f25b0cbSMichael Kruse   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
955bc132607STobias Grosser                                                VLTS[Offset], NewAccesses);
956c14582f2STobias Grosser   Value *VectorPtr =
957c14582f2STobias Grosser       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
958c14582f2STobias Grosser   LoadInst *VecLoad =
959c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
9603b11a16aSHongbin Zheng   if (!Aligned)
9613b11a16aSHongbin Zheng     VecLoad->setAlignment(8);
9623b11a16aSHongbin Zheng 
9630dd463faSTobias Grosser   if (NegativeStride) {
9640dd463faSTobias Grosser     SmallVector<Constant *, 16> Indices;
9650dd463faSTobias Grosser     for (int i = VectorWidth - 1; i >= 0; i--)
9660dd463faSTobias Grosser       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
9670dd463faSTobias Grosser     Constant *SV = llvm::ConstantVector::get(Indices);
9680dd463faSTobias Grosser     Value *RevVecLoad = Builder.CreateShuffleVector(
9690dd463faSTobias Grosser         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
9700dd463faSTobias Grosser     return RevVecLoad;
9710dd463faSTobias Grosser   }
9720dd463faSTobias Grosser 
9733b11a16aSHongbin Zheng   return VecLoad;
9743b11a16aSHongbin Zheng }
9753b11a16aSHongbin Zheng 
9762d1ed0bfSTobias Grosser Value *VectorBlockGenerator::generateStrideZeroLoad(
9772f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
9782d1ed0bfSTobias Grosser     __isl_keep isl_id_to_ast_expr *NewAccesses) {
9799646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
9803b11a16aSHongbin Zheng   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
98170131d34SMichael Kruse   Value *NewPointer =
98270131d34SMichael Kruse       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
9833b11a16aSHongbin Zheng   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
9843b11a16aSHongbin Zheng                                            Load->getName() + "_p_vec_p");
985c14582f2STobias Grosser   LoadInst *ScalarLoad =
986c14582f2STobias Grosser       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
9873b11a16aSHongbin Zheng 
9883b11a16aSHongbin Zheng   if (!Aligned)
9893b11a16aSHongbin Zheng     ScalarLoad->setAlignment(8);
9903b11a16aSHongbin Zheng 
991c14582f2STobias Grosser   Constant *SplatVector = Constant::getNullValue(
992c14582f2STobias Grosser       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
9933b11a16aSHongbin Zheng 
994c14582f2STobias Grosser   Value *VectorLoad = Builder.CreateShuffleVector(
995c14582f2STobias Grosser       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
9963b11a16aSHongbin Zheng   return VectorLoad;
9973b11a16aSHongbin Zheng }
9983b11a16aSHongbin Zheng 
999be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateUnknownStrideLoad(
10002f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
100109e3697fSJohannes Doerfert     __isl_keep isl_id_to_ast_expr *NewAccesses) {
10023b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
10039646e3feSTobias Grosser   auto *Pointer = Load->getPointerOperand();
10043b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(
10053b11a16aSHongbin Zheng       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
10063b11a16aSHongbin Zheng 
10073b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
10083b11a16aSHongbin Zheng 
10093b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++) {
101070131d34SMichael Kruse     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
101170131d34SMichael Kruse                                                  VLTS[i], NewAccesses);
1012c14582f2STobias Grosser     Value *ScalarLoad =
1013c14582f2STobias Grosser         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1014c14582f2STobias Grosser     Vector = Builder.CreateInsertElement(
1015c14582f2STobias Grosser         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
10163b11a16aSHongbin Zheng   }
10173b11a16aSHongbin Zheng 
10183b11a16aSHongbin Zheng   return Vector;
10193b11a16aSHongbin Zheng }
10203b11a16aSHongbin Zheng 
10212d1ed0bfSTobias Grosser void VectorBlockGenerator::generateLoad(
10222f1acac6STobias Grosser     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
10232d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1024c1db67e2SJohannes Doerfert   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1025c1db67e2SJohannes Doerfert     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1026c1db67e2SJohannes Doerfert                                                 Load->getName() + "_p");
1027c1db67e2SJohannes Doerfert     return;
1028c1db67e2SJohannes Doerfert   }
1029c1db67e2SJohannes Doerfert 
10302873645cSTobias Grosser   if (!VectorType::isValidElementType(Load->getType())) {
10313b11a16aSHongbin Zheng     for (int i = 0; i < getVectorWidth(); i++)
1032bc132607STobias Grosser       ScalarMaps[i][Load] =
1033888ab551SMichael Kruse           generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
10343b11a16aSHongbin Zheng     return;
10353b11a16aSHongbin Zheng   }
10363b11a16aSHongbin Zheng 
1037184a4926STobias Grosser   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
10383b11a16aSHongbin Zheng 
103995493984STobias Grosser   // Make sure we have scalar values available to access the pointer to
104095493984STobias Grosser   // the data location.
104195493984STobias Grosser   extractScalarValues(Load, VectorMap, ScalarMaps);
104295493984STobias Grosser 
10433b11a16aSHongbin Zheng   Value *NewLoad;
1044d7065e5dSTobias Grosser   if (Access.isStrideZero(isl::manage(isl_map_copy(Schedule))))
10452d1ed0bfSTobias Grosser     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1046d7065e5dSTobias Grosser   else if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule))))
10472d1ed0bfSTobias Grosser     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1048d7065e5dSTobias Grosser   else if (Access.isStrideX(isl::manage(isl_map_copy(Schedule)), -1))
10492d1ed0bfSTobias Grosser     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
10503b11a16aSHongbin Zheng   else
10512d1ed0bfSTobias Grosser     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
10523b11a16aSHongbin Zheng 
10533b11a16aSHongbin Zheng   VectorMap[Load] = NewLoad;
10543b11a16aSHongbin Zheng }
10553b11a16aSHongbin Zheng 
10562f1acac6STobias Grosser void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
10573b11a16aSHongbin Zheng                                          ValueMapT &VectorMap,
10583b11a16aSHongbin Zheng                                          VectorValueMapT &ScalarMaps) {
10593b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
1060be9c9117SJohannes Doerfert   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
10612c3ffc04SJohannes Doerfert                                      ScalarMaps, getLoopForStmt(Stmt));
10623b11a16aSHongbin Zheng 
10633b11a16aSHongbin Zheng   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
10643b11a16aSHongbin Zheng 
10653b11a16aSHongbin Zheng   const CastInst *Cast = dyn_cast<CastInst>(Inst);
10663b11a16aSHongbin Zheng   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
10673b11a16aSHongbin Zheng   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
10683b11a16aSHongbin Zheng }
10693b11a16aSHongbin Zheng 
10702f1acac6STobias Grosser void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
10713b11a16aSHongbin Zheng                                           ValueMapT &VectorMap,
10723b11a16aSHongbin Zheng                                           VectorValueMapT &ScalarMaps) {
10732c3ffc04SJohannes Doerfert   Loop *L = getLoopForStmt(Stmt);
10743b11a16aSHongbin Zheng   Value *OpZero = Inst->getOperand(0);
10753b11a16aSHongbin Zheng   Value *OpOne = Inst->getOperand(1);
10763b11a16aSHongbin Zheng 
10773b11a16aSHongbin Zheng   Value *NewOpZero, *NewOpOne;
1078be9c9117SJohannes Doerfert   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1079be9c9117SJohannes Doerfert   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
10803b11a16aSHongbin Zheng 
10811bb59b0dSTobias Grosser   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
10823b11a16aSHongbin Zheng                                        Inst->getName() + "p_vec");
10833b11a16aSHongbin Zheng   VectorMap[Inst] = NewInst;
10843b11a16aSHongbin Zheng }
10853b11a16aSHongbin Zheng 
10862d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStore(
10872f1acac6STobias Grosser     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
10882d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1089184a4926STobias Grosser   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
10903b11a16aSHongbin Zheng 
10919646e3feSTobias Grosser   auto *Pointer = Store->getPointerOperand();
1092be9c9117SJohannes Doerfert   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
10932c3ffc04SJohannes Doerfert                                  ScalarMaps, getLoopForStmt(Stmt));
10943b11a16aSHongbin Zheng 
109550fd7010STobias Grosser   // Make sure we have scalar values available to access the pointer to
109650fd7010STobias Grosser   // the data location.
109750fd7010STobias Grosser   extractScalarValues(Store, VectorMap, ScalarMaps);
109850fd7010STobias Grosser 
1099d7065e5dSTobias Grosser   if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) {
11001947f863SJohannes Doerfert     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
110170131d34SMichael Kruse     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
110270131d34SMichael Kruse                                                  VLTS[0], NewAccesses);
11033b11a16aSHongbin Zheng 
1104c14582f2STobias Grosser     Value *VectorPtr =
1105c14582f2STobias Grosser         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
11063b11a16aSHongbin Zheng     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
11073b11a16aSHongbin Zheng 
11083b11a16aSHongbin Zheng     if (!Aligned)
11093b11a16aSHongbin Zheng       Store->setAlignment(8);
11103b11a16aSHongbin Zheng   } else {
11113b11a16aSHongbin Zheng     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
11121bb59b0dSTobias Grosser       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
111370131d34SMichael Kruse       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
111470131d34SMichael Kruse                                                    VLTS[i], NewAccesses);
11153b11a16aSHongbin Zheng       Builder.CreateStore(Scalar, NewPointer);
11163b11a16aSHongbin Zheng     }
11173b11a16aSHongbin Zheng   }
11183b11a16aSHongbin Zheng }
11193b11a16aSHongbin Zheng 
11203b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
11213b11a16aSHongbin Zheng                                              ValueMapT &VectorMap) {
112291f5b262STobias Grosser   for (Value *Operand : Inst->operands())
112391f5b262STobias Grosser     if (VectorMap.count(Operand))
11243b11a16aSHongbin Zheng       return true;
11253b11a16aSHongbin Zheng   return false;
11263b11a16aSHongbin Zheng }
11273b11a16aSHongbin Zheng 
11283b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
11293b11a16aSHongbin Zheng                                                ValueMapT &VectorMap,
11303b11a16aSHongbin Zheng                                                VectorValueMapT &ScalarMaps) {
11313b11a16aSHongbin Zheng   bool HasVectorOperand = false;
11323b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
11333b11a16aSHongbin Zheng 
113491f5b262STobias Grosser   for (Value *Operand : Inst->operands()) {
113591f5b262STobias Grosser     ValueMapT::iterator VecOp = VectorMap.find(Operand);
11363b11a16aSHongbin Zheng 
11373b11a16aSHongbin Zheng     if (VecOp == VectorMap.end())
11383b11a16aSHongbin Zheng       continue;
11393b11a16aSHongbin Zheng 
11403b11a16aSHongbin Zheng     HasVectorOperand = true;
11413b11a16aSHongbin Zheng     Value *NewVector = VecOp->second;
11423b11a16aSHongbin Zheng 
11433b11a16aSHongbin Zheng     for (int i = 0; i < VectorWidth; ++i) {
11443b11a16aSHongbin Zheng       ValueMapT &SM = ScalarMaps[i];
11453b11a16aSHongbin Zheng 
11463b11a16aSHongbin Zheng       // If there is one scalar extracted, all scalar elements should have
11473b11a16aSHongbin Zheng       // already been extracted by the code here. So no need to check for the
11482219d157STobias Grosser       // existence of all of them.
114991f5b262STobias Grosser       if (SM.count(Operand))
11503b11a16aSHongbin Zheng         break;
11513b11a16aSHongbin Zheng 
115291f5b262STobias Grosser       SM[Operand] =
115391f5b262STobias Grosser           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
11543b11a16aSHongbin Zheng     }
11553b11a16aSHongbin Zheng   }
11563b11a16aSHongbin Zheng 
11573b11a16aSHongbin Zheng   return HasVectorOperand;
11583b11a16aSHongbin Zheng }
11593b11a16aSHongbin Zheng 
11602d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstScalarized(
11612f1acac6STobias Grosser     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
11622d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
11633b11a16aSHongbin Zheng   bool HasVectorOperand;
11643b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
11653b11a16aSHongbin Zheng 
11663b11a16aSHongbin Zheng   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
11673b11a16aSHongbin Zheng 
11683b11a16aSHongbin Zheng   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
1169be9c9117SJohannes Doerfert     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1170bc132607STobias Grosser                                     VLTS[VectorLane], NewAccesses);
11713b11a16aSHongbin Zheng 
11723b11a16aSHongbin Zheng   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
11733b11a16aSHongbin Zheng     return;
11743b11a16aSHongbin Zheng 
11753b11a16aSHongbin Zheng   // Make the result available as vector value.
11763b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
11773b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
11783b11a16aSHongbin Zheng 
11793b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++)
11803b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
11813b11a16aSHongbin Zheng                                          Builder.getInt32(i));
11823b11a16aSHongbin Zheng 
11833b11a16aSHongbin Zheng   VectorMap[Inst] = Vector;
11843b11a16aSHongbin Zheng }
11853b11a16aSHongbin Zheng 
1186bc132607STobias Grosser int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
11873b11a16aSHongbin Zheng 
11882d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstruction(
11892f1acac6STobias Grosser     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
11902d1ed0bfSTobias Grosser     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
11913b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
11923b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
11933b11a16aSHongbin Zheng   if (Inst->isTerminator())
11943b11a16aSHongbin Zheng     return;
11953b11a16aSHongbin Zheng 
11965dced269SJohannes Doerfert   if (canSyntheziseInStmt(Stmt, Inst))
1197e71c6ab5STobias Grosser     return;
1198e71c6ab5STobias Grosser 
11999646e3feSTobias Grosser   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
12002d1ed0bfSTobias Grosser     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
12013b11a16aSHongbin Zheng     return;
12023b11a16aSHongbin Zheng   }
12033b11a16aSHongbin Zheng 
12043b11a16aSHongbin Zheng   if (hasVectorOperands(Inst, VectorMap)) {
12059646e3feSTobias Grosser     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
12060446d81eSMichael Kruse       // Identified as redundant by -polly-simplify.
12070446d81eSMichael Kruse       if (!Stmt.getArrayAccessOrNULLFor(Store))
12080446d81eSMichael Kruse         return;
12090446d81eSMichael Kruse 
12102d1ed0bfSTobias Grosser       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
12113b11a16aSHongbin Zheng       return;
12123b11a16aSHongbin Zheng     }
12133b11a16aSHongbin Zheng 
12149646e3feSTobias Grosser     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1215be9c9117SJohannes Doerfert       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
12163b11a16aSHongbin Zheng       return;
12173b11a16aSHongbin Zheng     }
12183b11a16aSHongbin Zheng 
12199646e3feSTobias Grosser     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1220be9c9117SJohannes Doerfert       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
12213b11a16aSHongbin Zheng       return;
12223b11a16aSHongbin Zheng     }
12233b11a16aSHongbin Zheng 
1224a6d48f59SMichael Kruse     // Fallthrough: We generate scalar instructions, if we don't know how to
12253b11a16aSHongbin Zheng     // generate vector code.
12263b11a16aSHongbin Zheng   }
12273b11a16aSHongbin Zheng 
12282d1ed0bfSTobias Grosser   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
12293b11a16aSHongbin Zheng }
12303b11a16aSHongbin Zheng 
1231a69d4f0dSTobias Grosser void VectorBlockGenerator::generateScalarVectorLoads(
1232a69d4f0dSTobias Grosser     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1233a69d4f0dSTobias Grosser   for (MemoryAccess *MA : Stmt) {
1234a69d4f0dSTobias Grosser     if (MA->isArrayKind() || MA->isWrite())
1235a69d4f0dSTobias Grosser       continue;
1236a69d4f0dSTobias Grosser 
1237a69d4f0dSTobias Grosser     auto *Address = getOrCreateAlloca(*MA);
1238a69d4f0dSTobias Grosser     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1239a69d4f0dSTobias Grosser     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1240a69d4f0dSTobias Grosser                                              Address->getName() + "_p_vec_p");
1241a69d4f0dSTobias Grosser     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1242a69d4f0dSTobias Grosser     Constant *SplatVector = Constant::getNullValue(
1243a69d4f0dSTobias Grosser         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1244a69d4f0dSTobias Grosser 
1245a69d4f0dSTobias Grosser     Value *VectorVal = Builder.CreateShuffleVector(
1246a69d4f0dSTobias Grosser         Val, Val, SplatVector, Address->getName() + "_p_splat");
1247583be06fSTobias Grosser     VectorBlockMap[MA->getAccessValue()] = VectorVal;
1248a69d4f0dSTobias Grosser   }
1249a69d4f0dSTobias Grosser }
1250a69d4f0dSTobias Grosser 
1251a69d4f0dSTobias Grosser void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1252a69d4f0dSTobias Grosser   for (MemoryAccess *MA : Stmt) {
1253a69d4f0dSTobias Grosser     if (MA->isArrayKind() || MA->isRead())
1254a69d4f0dSTobias Grosser       continue;
1255a69d4f0dSTobias Grosser 
1256a69d4f0dSTobias Grosser     llvm_unreachable("Scalar stores not expected in vector loop");
1257a69d4f0dSTobias Grosser   }
1258a69d4f0dSTobias Grosser }
1259a69d4f0dSTobias Grosser 
12602d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStmt(
12612d1ed0bfSTobias Grosser     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
126221a059afSTobias Grosser   assert(Stmt.isBlockStmt() &&
126321a059afSTobias Grosser          "TODO: Only block statements can be copied by the vector block "
126421a059afSTobias Grosser          "generator");
1265275a1756SJohannes Doerfert 
1266be9c9117SJohannes Doerfert   BasicBlock *BB = Stmt.getBasicBlock();
1267b8f58b53SDuncan P. N. Exon Smith   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1268b8f58b53SDuncan P. N. Exon Smith                                   &*Builder.GetInsertPoint(), &DT, &LI);
12693b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
1270b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&CopyBB->front());
12713b11a16aSHongbin Zheng 
12723b11a16aSHongbin Zheng   // Create two maps that store the mapping from the original instructions of
12733b11a16aSHongbin Zheng   // the old basic block to their copies in the new basic block. Those maps
12743b11a16aSHongbin Zheng   // are basic block local.
12753b11a16aSHongbin Zheng   //
12763b11a16aSHongbin Zheng   // As vector code generation is supported there is one map for scalar values
12773b11a16aSHongbin Zheng   // and one for vector values.
12783b11a16aSHongbin Zheng   //
12793b11a16aSHongbin Zheng   // In case we just do scalar code generation, the vectorMap is not used and
12803b11a16aSHongbin Zheng   // the scalarMap has just one dimension, which contains the mapping.
12813b11a16aSHongbin Zheng   //
12823b11a16aSHongbin Zheng   // In case vector code generation is done, an instruction may either appear
12833b11a16aSHongbin Zheng   // in the vector map once (as it is calculating >vectorwidth< values at a
12843b11a16aSHongbin Zheng   // time. Or (if the values are calculated using scalar operations), it
12853b11a16aSHongbin Zheng   // appears once in every dimension of the scalarMap.
12863b11a16aSHongbin Zheng   VectorValueMapT ScalarBlockMap(getVectorWidth());
12873b11a16aSHongbin Zheng   ValueMapT VectorBlockMap;
12883b11a16aSHongbin Zheng 
1289a69d4f0dSTobias Grosser   generateScalarVectorLoads(Stmt, VectorBlockMap);
1290a69d4f0dSTobias Grosser 
129191f5b262STobias Grosser   for (Instruction &Inst : *BB)
12922d1ed0bfSTobias Grosser     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1293a69d4f0dSTobias Grosser 
1294a69d4f0dSTobias Grosser   verifyNoScalarStores(Stmt);
12953b11a16aSHongbin Zheng }
1296275a1756SJohannes Doerfert 
1297ecff11dcSJohannes Doerfert BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1298ecff11dcSJohannes Doerfert                                              BasicBlock *BBCopy) {
1299514f6efaSJohannes Doerfert 
1300514f6efaSJohannes Doerfert   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1301deefbcedSTobias Grosser   BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1302514f6efaSJohannes Doerfert 
1303514f6efaSJohannes Doerfert   if (BBCopyIDom)
1304514f6efaSJohannes Doerfert     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1305514f6efaSJohannes Doerfert 
1306deefbcedSTobias Grosser   return StartBlockMap.lookup(BBIDom);
1307514f6efaSJohannes Doerfert }
1308514f6efaSJohannes Doerfert 
1309f33c125dSMichael Kruse // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1310f33c125dSMichael Kruse // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1311f33c125dSMichael Kruse // does not work in cases where the exit block has edges from outside the
1312f33c125dSMichael Kruse // region. In that case the llvm::Value would never be usable in in the exit
1313f33c125dSMichael Kruse // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1314f33c125dSMichael Kruse // for the subregion's exiting edges only. We need to determine whether an
1315f33c125dSMichael Kruse // llvm::Value is usable in there. We do this by checking whether it dominates
1316f33c125dSMichael Kruse // all exiting blocks individually.
1317f33c125dSMichael Kruse static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1318f33c125dSMichael Kruse                                       BasicBlock *BB) {
1319f33c125dSMichael Kruse   for (auto ExitingBB : predecessors(R->getExit())) {
1320f33c125dSMichael Kruse     // Check for non-subregion incoming edges.
1321f33c125dSMichael Kruse     if (!R->contains(ExitingBB))
1322f33c125dSMichael Kruse       continue;
1323f33c125dSMichael Kruse 
1324f33c125dSMichael Kruse     if (!DT.dominates(BB, ExitingBB))
1325f33c125dSMichael Kruse       return false;
1326f33c125dSMichael Kruse   }
1327f33c125dSMichael Kruse 
1328f33c125dSMichael Kruse   return true;
1329f33c125dSMichael Kruse }
1330f33c125dSMichael Kruse 
1331f33c125dSMichael Kruse // Find the direct dominator of the subregion's exit block if the subregion was
1332f33c125dSMichael Kruse // simplified.
1333f33c125dSMichael Kruse static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1334f33c125dSMichael Kruse   BasicBlock *Common = nullptr;
1335f33c125dSMichael Kruse   for (auto ExitingBB : predecessors(R->getExit())) {
1336f33c125dSMichael Kruse     // Check for non-subregion incoming edges.
1337f33c125dSMichael Kruse     if (!R->contains(ExitingBB))
1338f33c125dSMichael Kruse       continue;
1339f33c125dSMichael Kruse 
1340f33c125dSMichael Kruse     // First exiting edge.
1341f33c125dSMichael Kruse     if (!Common) {
1342f33c125dSMichael Kruse       Common = ExitingBB;
1343f33c125dSMichael Kruse       continue;
1344f33c125dSMichael Kruse     }
1345f33c125dSMichael Kruse 
1346f33c125dSMichael Kruse     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1347f33c125dSMichael Kruse   }
1348f33c125dSMichael Kruse 
1349f33c125dSMichael Kruse   assert(Common && R->contains(Common));
1350f33c125dSMichael Kruse   return Common;
1351f33c125dSMichael Kruse }
1352f33c125dSMichael Kruse 
1353bc132607STobias Grosser void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
13542d1ed0bfSTobias Grosser                                isl_id_to_ast_expr *IdToAstExp) {
1355275a1756SJohannes Doerfert   assert(Stmt.isRegionStmt() &&
1356d3f21833STobias Grosser          "Only region statements can be copied by the region generator");
1357275a1756SJohannes Doerfert 
1358ecff11dcSJohannes Doerfert   // Forget all old mappings.
1359deefbcedSTobias Grosser   StartBlockMap.clear();
1360deefbcedSTobias Grosser   EndBlockMap.clear();
1361ecff11dcSJohannes Doerfert   RegionMaps.clear();
1362ecff11dcSJohannes Doerfert   IncompletePHINodeMap.clear();
1363ecff11dcSJohannes Doerfert 
1364225f0d1eSMichael Kruse   // Collection of all values related to this subregion.
1365225f0d1eSMichael Kruse   ValueMapT ValueMap;
1366225f0d1eSMichael Kruse 
1367275a1756SJohannes Doerfert   // The region represented by the statement.
1368275a1756SJohannes Doerfert   Region *R = Stmt.getRegion();
1369275a1756SJohannes Doerfert 
1370ecff11dcSJohannes Doerfert   // Create a dedicated entry for the region where we can reload all demoted
1371ecff11dcSJohannes Doerfert   // inputs.
1372ecff11dcSJohannes Doerfert   BasicBlock *EntryBB = R->getEntry();
1373b8f58b53SDuncan P. N. Exon Smith   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1374b8f58b53SDuncan P. N. Exon Smith                                        &*Builder.GetInsertPoint(), &DT, &LI);
1375ecff11dcSJohannes Doerfert   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1376b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&EntryBBCopy->front());
1377514f6efaSJohannes Doerfert 
1378c993739eSMichael Kruse   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
13792fa35194SMichael Kruse   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1380225f0d1eSMichael Kruse 
1381ecff11dcSJohannes Doerfert   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1382deefbcedSTobias Grosser     if (!R->contains(*PI)) {
1383deefbcedSTobias Grosser       StartBlockMap[*PI] = EntryBBCopy;
1384deefbcedSTobias Grosser       EndBlockMap[*PI] = EntryBBCopy;
1385deefbcedSTobias Grosser     }
1386275a1756SJohannes Doerfert 
1387275a1756SJohannes Doerfert   // Iterate over all blocks in the region in a breadth-first search.
1388275a1756SJohannes Doerfert   std::deque<BasicBlock *> Blocks;
13895b1abfc8SMandeep Singh Grang   SmallSetVector<BasicBlock *, 8> SeenBlocks;
1390ecff11dcSJohannes Doerfert   Blocks.push_back(EntryBB);
1391ecff11dcSJohannes Doerfert   SeenBlocks.insert(EntryBB);
1392275a1756SJohannes Doerfert 
1393275a1756SJohannes Doerfert   while (!Blocks.empty()) {
1394275a1756SJohannes Doerfert     BasicBlock *BB = Blocks.front();
1395275a1756SJohannes Doerfert     Blocks.pop_front();
1396275a1756SJohannes Doerfert 
1397514f6efaSJohannes Doerfert     // First split the block and update dominance information.
1398514f6efaSJohannes Doerfert     BasicBlock *BBCopy = splitBB(BB);
1399ecff11dcSJohannes Doerfert     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1400ecff11dcSJohannes Doerfert 
1401c993739eSMichael Kruse     // Get the mapping for this block and initialize it with either the scalar
1402c993739eSMichael Kruse     // loads from the generated entering block (which dominates all blocks of
1403c993739eSMichael Kruse     // this subregion) or the maps of the immediate dominator, if part of the
1404c993739eSMichael Kruse     // subregion. The latter necessarily includes the former.
1405c993739eSMichael Kruse     ValueMapT *InitBBMap;
1406c993739eSMichael Kruse     if (BBCopyIDom) {
1407c993739eSMichael Kruse       assert(RegionMaps.count(BBCopyIDom));
1408c993739eSMichael Kruse       InitBBMap = &RegionMaps[BBCopyIDom];
1409c993739eSMichael Kruse     } else
1410c993739eSMichael Kruse       InitBBMap = &EntryBBMap;
1411c993739eSMichael Kruse     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1412c993739eSMichael Kruse     ValueMapT &RegionMap = Inserted.first->second;
1413514f6efaSJohannes Doerfert 
1414275a1756SJohannes Doerfert     // Copy the block with the BlockGenerator.
1415b8f58b53SDuncan P. N. Exon Smith     Builder.SetInsertPoint(&BBCopy->front());
1416bc132607STobias Grosser     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1417275a1756SJohannes Doerfert 
1418ecff11dcSJohannes Doerfert     // In order to remap PHI nodes we store also basic block mappings.
1419deefbcedSTobias Grosser     StartBlockMap[BB] = BBCopy;
1420deefbcedSTobias Grosser     EndBlockMap[BB] = Builder.GetInsertBlock();
1421ecff11dcSJohannes Doerfert 
1422ecff11dcSJohannes Doerfert     // Add values to incomplete PHI nodes waiting for this block to be copied.
1423ecff11dcSJohannes Doerfert     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1424bc132607STobias Grosser       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1425ecff11dcSJohannes Doerfert     IncompletePHINodeMap[BB].clear();
1426ecff11dcSJohannes Doerfert 
1427275a1756SJohannes Doerfert     // And continue with new successors inside the region.
1428275a1756SJohannes Doerfert     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
14295b1abfc8SMandeep Singh Grang       if (R->contains(*SI) && SeenBlocks.insert(*SI))
1430275a1756SJohannes Doerfert         Blocks.push_back(*SI);
1431ebffcbeeSMichael Kruse 
1432ebffcbeeSMichael Kruse     // Remember value in case it is visible after this subregion.
1433f33c125dSMichael Kruse     if (isDominatingSubregionExit(DT, R, BB))
1434ebffcbeeSMichael Kruse       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1435275a1756SJohannes Doerfert   }
1436275a1756SJohannes Doerfert 
1437275a1756SJohannes Doerfert   // Now create a new dedicated region exit block and add it to the region map.
1438b8f58b53SDuncan P. N. Exon Smith   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1439b8f58b53SDuncan P. N. Exon Smith                                       &*Builder.GetInsertPoint(), &DT, &LI);
1440ecff11dcSJohannes Doerfert   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1441deefbcedSTobias Grosser   StartBlockMap[R->getExit()] = ExitBBCopy;
1442deefbcedSTobias Grosser   EndBlockMap[R->getExit()] = ExitBBCopy;
1443514f6efaSJohannes Doerfert 
1444deefbcedSTobias Grosser   BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
144521a059afSTobias Grosser   assert(ExitDomBBCopy &&
144621a059afSTobias Grosser          "Common exit dominator must be within region; at least the entry node "
144721a059afSTobias Grosser          "must match");
1448f33c125dSMichael Kruse   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1449275a1756SJohannes Doerfert 
1450275a1756SJohannes Doerfert   // As the block generator doesn't handle control flow we need to add the
1451275a1756SJohannes Doerfert   // region control flow by hand after all blocks have been copied.
1452275a1756SJohannes Doerfert   for (BasicBlock *BB : SeenBlocks) {
1453275a1756SJohannes Doerfert 
1454deefbcedSTobias Grosser     BasicBlock *BBCopyStart = StartBlockMap[BB];
1455deefbcedSTobias Grosser     BasicBlock *BBCopyEnd = EndBlockMap[BB];
1456e114dc02SJohannes Doerfert     TerminatorInst *TI = BB->getTerminator();
1457e114dc02SJohannes Doerfert     if (isa<UnreachableInst>(TI)) {
1458deefbcedSTobias Grosser       while (!BBCopyEnd->empty())
1459deefbcedSTobias Grosser         BBCopyEnd->begin()->eraseFromParent();
1460deefbcedSTobias Grosser       new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1461e114dc02SJohannes Doerfert       continue;
1462e114dc02SJohannes Doerfert     }
1463e114dc02SJohannes Doerfert 
1464deefbcedSTobias Grosser     Instruction *BICopy = BBCopyEnd->getTerminator();
1465275a1756SJohannes Doerfert 
1466deefbcedSTobias Grosser     ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1467deefbcedSTobias Grosser     RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1468514f6efaSJohannes Doerfert 
146945e7944bSTobias Grosser     Builder.SetInsertPoint(BICopy);
14709a132f36SJohannes Doerfert     copyInstScalar(Stmt, TI, RegionMap, LTS);
1471275a1756SJohannes Doerfert     BICopy->eraseFromParent();
1472275a1756SJohannes Doerfert   }
1473275a1756SJohannes Doerfert 
1474ecff11dcSJohannes Doerfert   // Add counting PHI nodes to all loops in the region that can be used as
1475a6d48f59SMichael Kruse   // replacement for SCEVs referring to the old loop.
1476ecff11dcSJohannes Doerfert   for (BasicBlock *BB : SeenBlocks) {
1477ecff11dcSJohannes Doerfert     Loop *L = LI.getLoopFor(BB);
1478bc29e0b2STobias Grosser     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1479ecff11dcSJohannes Doerfert       continue;
1480ecff11dcSJohannes Doerfert 
1481deefbcedSTobias Grosser     BasicBlock *BBCopy = StartBlockMap[BB];
1482ecff11dcSJohannes Doerfert     Value *NullVal = Builder.getInt32(0);
1483ecff11dcSJohannes Doerfert     PHINode *LoopPHI =
1484ecff11dcSJohannes Doerfert         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1485ecff11dcSJohannes Doerfert     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1486ecff11dcSJohannes Doerfert         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1487b8f58b53SDuncan P. N. Exon Smith     LoopPHI->insertBefore(&BBCopy->front());
1488ecff11dcSJohannes Doerfert     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1489ecff11dcSJohannes Doerfert 
1490ecff11dcSJohannes Doerfert     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1491ecff11dcSJohannes Doerfert       if (!R->contains(PredBB))
1492ecff11dcSJohannes Doerfert         continue;
1493ecff11dcSJohannes Doerfert       if (L->contains(PredBB))
1494deefbcedSTobias Grosser         LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1495ecff11dcSJohannes Doerfert       else
1496deefbcedSTobias Grosser         LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1497ecff11dcSJohannes Doerfert     }
1498ecff11dcSJohannes Doerfert 
1499ecff11dcSJohannes Doerfert     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1500ecff11dcSJohannes Doerfert       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1501ecff11dcSJohannes Doerfert         LoopPHI->addIncoming(NullVal, PredBBCopy);
1502ecff11dcSJohannes Doerfert 
1503ecff11dcSJohannes Doerfert     LTS[L] = SE.getUnknown(LoopPHI);
1504ecff11dcSJohannes Doerfert   }
1505ecff11dcSJohannes Doerfert 
1506225f0d1eSMichael Kruse   // Continue generating code in the exit block.
1507b8f58b53SDuncan P. N. Exon Smith   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1508225f0d1eSMichael Kruse 
1509225f0d1eSMichael Kruse   // Write values visible to other statements.
15102fa35194SMichael Kruse   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1511deefbcedSTobias Grosser   StartBlockMap.clear();
1512deefbcedSTobias Grosser   EndBlockMap.clear();
15133e956020STobias Grosser   RegionMaps.clear();
15143e956020STobias Grosser   IncompletePHINodeMap.clear();
1515275a1756SJohannes Doerfert }
1516ecff11dcSJohannes Doerfert 
1517ee6a4fc6SMichael Kruse PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1518ee6a4fc6SMichael Kruse                                        ValueMapT &BBMap, Loop *L) {
1519ee6a4fc6SMichael Kruse   ScopStmt *Stmt = MA->getStatement();
1520ee6a4fc6SMichael Kruse   Region *SubR = Stmt->getRegion();
1521ee6a4fc6SMichael Kruse   auto Incoming = MA->getIncoming();
1522ee6a4fc6SMichael Kruse 
1523ee6a4fc6SMichael Kruse   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1524ee6a4fc6SMichael Kruse   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1525ee6a4fc6SMichael Kruse   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1526ee6a4fc6SMichael Kruse 
1527ee6a4fc6SMichael Kruse   // This can happen if the subregion is simplified after the ScopStmts
1528ee6a4fc6SMichael Kruse   // have been created; simplification happens as part of CodeGeneration.
1529ee6a4fc6SMichael Kruse   if (OrigPHI->getParent() != SubR->getExit()) {
1530ee6a4fc6SMichael Kruse     BasicBlock *FormerExit = SubR->getExitingBlock();
1531ee6a4fc6SMichael Kruse     if (FormerExit)
1532deefbcedSTobias Grosser       NewSubregionExit = StartBlockMap.lookup(FormerExit);
1533ee6a4fc6SMichael Kruse   }
1534ee6a4fc6SMichael Kruse 
1535ee6a4fc6SMichael Kruse   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1536ee6a4fc6SMichael Kruse                                     "polly." + OrigPHI->getName(),
1537ee6a4fc6SMichael Kruse                                     NewSubregionExit->getFirstNonPHI());
1538ee6a4fc6SMichael Kruse 
1539ee6a4fc6SMichael Kruse   // Add the incoming values to the PHI.
1540ee6a4fc6SMichael Kruse   for (auto &Pair : Incoming) {
1541ee6a4fc6SMichael Kruse     BasicBlock *OrigIncomingBlock = Pair.first;
1542deefbcedSTobias Grosser     BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1543deefbcedSTobias Grosser     BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1544deefbcedSTobias Grosser     Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1545deefbcedSTobias Grosser     assert(RegionMaps.count(NewIncomingBlockStart));
1546deefbcedSTobias Grosser     assert(RegionMaps.count(NewIncomingBlockEnd));
1547deefbcedSTobias Grosser     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1548ee6a4fc6SMichael Kruse 
1549ee6a4fc6SMichael Kruse     Value *OrigIncomingValue = Pair.second;
1550ee6a4fc6SMichael Kruse     Value *NewIncomingValue =
1551ee6a4fc6SMichael Kruse         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1552deefbcedSTobias Grosser     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1553ee6a4fc6SMichael Kruse   }
1554ee6a4fc6SMichael Kruse 
1555ee6a4fc6SMichael Kruse   return NewPHI;
1556ee6a4fc6SMichael Kruse }
1557ee6a4fc6SMichael Kruse 
1558ee6a4fc6SMichael Kruse Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1559ee6a4fc6SMichael Kruse                                       ValueMapT &BBMap) {
1560ee6a4fc6SMichael Kruse   ScopStmt *Stmt = MA->getStatement();
1561ee6a4fc6SMichael Kruse 
1562ee6a4fc6SMichael Kruse   // TODO: Add some test cases that ensure this is really the right choice.
1563ee6a4fc6SMichael Kruse   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1564ee6a4fc6SMichael Kruse 
1565ee6a4fc6SMichael Kruse   if (MA->isAnyPHIKind()) {
1566ee6a4fc6SMichael Kruse     auto Incoming = MA->getIncoming();
1567ee6a4fc6SMichael Kruse     assert(!Incoming.empty() &&
1568ee6a4fc6SMichael Kruse            "PHI WRITEs must have originate from at least one incoming block");
1569ee6a4fc6SMichael Kruse 
1570ee6a4fc6SMichael Kruse     // If there is only one incoming value, we do not need to create a PHI.
1571ee6a4fc6SMichael Kruse     if (Incoming.size() == 1) {
1572ee6a4fc6SMichael Kruse       Value *OldVal = Incoming[0].second;
1573ee6a4fc6SMichael Kruse       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1574ee6a4fc6SMichael Kruse     }
1575ee6a4fc6SMichael Kruse 
1576ee6a4fc6SMichael Kruse     return buildExitPHI(MA, LTS, BBMap, L);
1577ee6a4fc6SMichael Kruse   }
1578ee6a4fc6SMichael Kruse 
15794d5a9172STobias Grosser   // MemoryKind::Value accesses leaving the subregion must dominate the exit
15804d5a9172STobias Grosser   // block; just pass the copied value.
1581ee6a4fc6SMichael Kruse   Value *OldVal = MA->getAccessValue();
1582ee6a4fc6SMichael Kruse   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1583ee6a4fc6SMichael Kruse }
1584ee6a4fc6SMichael Kruse 
15852fa35194SMichael Kruse void RegionGenerator::generateScalarStores(
15862fa35194SMichael Kruse     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
15872fa35194SMichael Kruse     __isl_keep isl_id_to_ast_expr *NewAccesses) {
158875296901STobias Grosser   assert(Stmt.getRegion() &&
158975296901STobias Grosser          "Block statements need to use the generateScalarStores() "
1590ecff11dcSJohannes Doerfert          "function in the BlockGenerator");
1591ecff11dcSJohannes Doerfert 
1592ecff11dcSJohannes Doerfert   for (MemoryAccess *MA : Stmt) {
15932fa35194SMichael Kruse     if (MA->isOriginalArrayKind() || MA->isRead())
1594ecff11dcSJohannes Doerfert       continue;
1595ecff11dcSJohannes Doerfert 
15961515f6b9STobias Grosser     isl::set AccDom = MA->getAccessRelation().domain();
1597fe46c3ffSTobias Grosser     std::string Subject = MA->getId().get_name();
1598fe46c3ffSTobias Grosser     generateConditionalExecution(
1599fe46c3ffSTobias Grosser         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1600706f79abSMichael Kruse 
1601ee6a4fc6SMichael Kruse           Value *NewVal = getExitScalar(MA, LTS, BBMap);
1602fe46c3ffSTobias Grosser           Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1603fe46c3ffSTobias Grosser                                               BBMap, NewAccesses);
1604eac9726eSMichael Kruse           assert((!isa<Instruction>(NewVal) ||
1605eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(NewVal)->getParent(),
1606eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
1607eac9726eSMichael Kruse                  "Domination violation");
1608eac9726eSMichael Kruse           assert((!isa<Instruction>(Address) ||
1609eac9726eSMichael Kruse                   DT.dominates(cast<Instruction>(Address)->getParent(),
1610eac9726eSMichael Kruse                                Builder.GetInsertBlock())) &&
1611eac9726eSMichael Kruse                  "Domination violation");
1612ee6a4fc6SMichael Kruse           Builder.CreateStore(NewVal, Address);
1613706f79abSMichael Kruse         });
1614ecff11dcSJohannes Doerfert   }
1615ecff11dcSJohannes Doerfert }
1616ecff11dcSJohannes Doerfert 
1617943c369cSTobias Grosser void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1618ecff11dcSJohannes Doerfert                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1619ecff11dcSJohannes Doerfert                                       LoopToScevMapT &LTS) {
1620ecff11dcSJohannes Doerfert   // If the incoming block was not yet copied mark this PHI as incomplete.
1621ecff11dcSJohannes Doerfert   // Once the block will be copied the incoming value will be added.
1622deefbcedSTobias Grosser   BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1623deefbcedSTobias Grosser   BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1624deefbcedSTobias Grosser   if (!BBCopyStart) {
1625deefbcedSTobias Grosser     assert(!BBCopyEnd);
16268d89179eSMichael Kruse     assert(Stmt.represents(IncomingBB) &&
1627ecff11dcSJohannes Doerfert            "Bad incoming block for PHI in non-affine region");
1628ecff11dcSJohannes Doerfert     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1629ecff11dcSJohannes Doerfert     return;
1630ecff11dcSJohannes Doerfert   }
1631ecff11dcSJohannes Doerfert 
1632deefbcedSTobias Grosser   assert(RegionMaps.count(BBCopyStart) &&
1633deefbcedSTobias Grosser          "Incoming PHI block did not have a BBMap");
1634deefbcedSTobias Grosser   ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1635ecff11dcSJohannes Doerfert 
163675dfaa1dSTobias Grosser   Value *OpCopy = nullptr;
163775dfaa1dSTobias Grosser 
16388d89179eSMichael Kruse   if (Stmt.represents(IncomingBB)) {
1639ecff11dcSJohannes Doerfert     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1640dc122222SMichael Kruse 
16416ba92714SJohannes Doerfert     // If the current insert block is different from the PHIs incoming block
16426ba92714SJohannes Doerfert     // change it, otherwise do not.
16436ba92714SJohannes Doerfert     auto IP = Builder.GetInsertPoint();
1644deefbcedSTobias Grosser     if (IP->getParent() != BBCopyEnd)
1645deefbcedSTobias Grosser       Builder.SetInsertPoint(BBCopyEnd->getTerminator());
16462c3ffc04SJohannes Doerfert     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1647deefbcedSTobias Grosser     if (IP->getParent() != BBCopyEnd)
16486ba92714SJohannes Doerfert       Builder.SetInsertPoint(&*IP);
1649ecff11dcSJohannes Doerfert   } else {
165075dfaa1dSTobias Grosser     // All edges from outside the non-affine region become a single edge
165175dfaa1dSTobias Grosser     // in the new copy of the non-affine region. Make sure to only add the
165275dfaa1dSTobias Grosser     // corresponding edge the first time we encounter a basic block from
165375dfaa1dSTobias Grosser     // outside the non-affine region.
1654deefbcedSTobias Grosser     if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1655ecff11dcSJohannes Doerfert       return;
1656ecff11dcSJohannes Doerfert 
165775dfaa1dSTobias Grosser     // Get the reloaded value.
165875dfaa1dSTobias Grosser     OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1659ecff11dcSJohannes Doerfert   }
1660ecff11dcSJohannes Doerfert 
1661ecff11dcSJohannes Doerfert   assert(OpCopy && "Incoming PHI value was not copied properly");
1662deefbcedSTobias Grosser   PHICopy->addIncoming(OpCopy, BBCopyEnd);
1663ecff11dcSJohannes Doerfert }
1664ecff11dcSJohannes Doerfert 
16652b809d13STobias Grosser void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1666ecff11dcSJohannes Doerfert                                          ValueMapT &BBMap,
1667ecff11dcSJohannes Doerfert                                          LoopToScevMapT &LTS) {
1668ecff11dcSJohannes Doerfert   unsigned NumIncoming = PHI->getNumIncomingValues();
1669ecff11dcSJohannes Doerfert   PHINode *PHICopy =
1670ecff11dcSJohannes Doerfert       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1671ecff11dcSJohannes Doerfert   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1672ecff11dcSJohannes Doerfert   BBMap[PHI] = PHICopy;
1673ecff11dcSJohannes Doerfert 
167497b84909STobias Grosser   for (BasicBlock *IncomingBB : PHI->blocks())
167597b84909STobias Grosser     addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1676ecff11dcSJohannes Doerfert }
1677