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 <S, 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 <S, 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 <S) { 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 2403b11a16aSHongbin Zheng if (!NewInst->getType()->isVoidTy()) 2413b11a16aSHongbin Zheng NewInst->setName("p_" + Inst->getName()); 2423b11a16aSHongbin Zheng } 2433b11a16aSHongbin Zheng 24470131d34SMichael Kruse Value * 24570131d34SMichael Kruse BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, 24670131d34SMichael Kruse ValueMapT &BBMap, LoopToScevMapT <S, 24770131d34SMichael Kruse isl_id_to_ast_expr *NewAccesses) { 24809214772STobias Grosser const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst); 2492fa35194SMichael Kruse return generateLocationAccessed( 2502fa35194SMichael Kruse Stmt, getLoopForStmt(Stmt), 2512fa35194SMichael Kruse Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS, 252fe46c3ffSTobias Grosser NewAccesses, MA.getId().release(), MA.getAccessValue()->getType()); 2532fa35194SMichael Kruse } 2543b11a16aSHongbin Zheng 2552fa35194SMichael Kruse Value *BlockGenerator::generateLocationAccessed( 2562fa35194SMichael Kruse ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap, 2572fa35194SMichael Kruse LoopToScevMapT <S, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id, 2582fa35194SMichael Kruse Type *ExpectedType) { 2592fa35194SMichael Kruse isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id); 2603b11a16aSHongbin Zheng 2612d1ed0bfSTobias Grosser if (AccessExpr) { 2622d1ed0bfSTobias Grosser AccessExpr = isl_ast_expr_address_of(AccessExpr); 26398b3ee50STobias Grosser auto Address = ExprBuilder->create(AccessExpr); 26498b3ee50STobias Grosser 26598b3ee50STobias Grosser // Cast the address of this memory access to a pointer type that has the 26698b3ee50STobias Grosser // same element type as the original access, but uses the address space of 26798b3ee50STobias Grosser // the newly generated pointer. 2682fa35194SMichael Kruse auto OldPtrTy = ExpectedType->getPointerTo(); 26998b3ee50STobias Grosser auto NewPtrTy = Address->getType(); 27098b3ee50STobias Grosser OldPtrTy = PointerType::get(OldPtrTy->getElementType(), 27198b3ee50STobias Grosser NewPtrTy->getPointerAddressSpace()); 27298b3ee50STobias Grosser 273d840fc72STobias Grosser if (OldPtrTy != NewPtrTy) 27498b3ee50STobias Grosser Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy); 27598b3ee50STobias Grosser return Address; 2762d1ed0bfSTobias Grosser } 2772fa35194SMichael Kruse assert( 2782fa35194SMichael Kruse Pointer && 2792fa35194SMichael Kruse "If expression was not generated, must use the original pointer value"); 2802fa35194SMichael Kruse return getNewValue(Stmt, Pointer, BBMap, LTS, L); 2812fa35194SMichael Kruse } 2822d1ed0bfSTobias Grosser 2832fa35194SMichael Kruse Value * 2842fa35194SMichael Kruse BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L, 2852fa35194SMichael Kruse LoopToScevMapT <S, ValueMapT &BBMap, 2862fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 2872fa35194SMichael Kruse if (Access.isLatestArrayKind()) 2882fa35194SMichael Kruse return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap, 289fe46c3ffSTobias Grosser LTS, NewAccesses, Access.getId().release(), 2902fa35194SMichael Kruse Access.getAccessValue()->getType()); 2912fa35194SMichael Kruse 292587f1f57STobias Grosser return getOrCreateAlloca(Access); 2933b11a16aSHongbin Zheng } 2943b11a16aSHongbin Zheng 2952c3ffc04SJohannes Doerfert Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const { 296375cb5feSMichael Kruse auto *StmtBB = Stmt.getEntryBlock(); 2972c3ffc04SJohannes Doerfert return LI.getLoopFor(StmtBB); 298369430ffSTobias Grosser } 299369430ffSTobias Grosser 300888ab551SMichael Kruse Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load, 301bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3022d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 303c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) 304c1db67e2SJohannes Doerfert return PreloadLoad; 305c1db67e2SJohannes Doerfert 306bc132607STobias Grosser Value *NewPointer = 30770131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses); 30887901453SJohannes Doerfert Value *ScalarLoad = Builder.CreateAlignedLoad( 30987901453SJohannes Doerfert NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_"); 31086bc93a9STobias Grosser 3111be726a4STobias Grosser if (PollyDebugPrinting) 31286bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer, 31386bc93a9STobias Grosser ": ", ScalarLoad, "\n"); 31486bc93a9STobias Grosser 3153b11a16aSHongbin Zheng return ScalarLoad; 3163b11a16aSHongbin Zheng } 3173b11a16aSHongbin Zheng 318888ab551SMichael Kruse void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store, 319bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3202d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 321706f79abSMichael Kruse MemoryAccess &MA = Stmt.getArrayAccessFor(Store); 3221515f6b9STobias Grosser isl::set AccDom = MA.getAccessRelation().domain(); 323fe46c3ffSTobias Grosser std::string Subject = MA.getId().get_name(); 324706f79abSMichael Kruse 325fe46c3ffSTobias Grosser generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() { 326bc132607STobias Grosser Value *NewPointer = 32770131d34SMichael Kruse generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses); 328706f79abSMichael Kruse Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, 329706f79abSMichael Kruse LTS, getLoopForStmt(Stmt)); 3303b11a16aSHongbin Zheng 3311be726a4STobias Grosser if (PollyDebugPrinting) 33286bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer, 33386bc93a9STobias Grosser ": ", ValueOperand, "\n"); 33486bc93a9STobias Grosser 335c186ac7aSTobias Grosser Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment()); 336706f79abSMichael Kruse }); 3373b11a16aSHongbin Zheng } 3383b11a16aSHongbin Zheng 3395dced269SJohannes Doerfert bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) { 3402c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 3415dced269SJohannes Doerfert return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) && 34211c5e079SMichael Kruse canSynthesize(Inst, *Stmt.getParent(), &SE, L); 3435dced269SJohannes Doerfert } 3445dced269SJohannes Doerfert 3452f1acac6STobias Grosser void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst, 346bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3472d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 3483b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 3493b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 3503b11a16aSHongbin Zheng if (Inst->isTerminator()) 3513b11a16aSHongbin Zheng return; 3523b11a16aSHongbin Zheng 353aff56c8aSTobias Grosser // Synthesizable statements will be generated on-demand. 3545dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 355e71c6ab5STobias Grosser return; 356e71c6ab5STobias Grosser 3579646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 358888ab551SMichael Kruse Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses); 3593d94fedfSSebastian Pop // Compute NewLoad before its insertion in BBMap to make the insertion 3603d94fedfSSebastian Pop // deterministic. 361753d43f9SSebastian Pop BBMap[Load] = NewLoad; 3623b11a16aSHongbin Zheng return; 3633b11a16aSHongbin Zheng } 3643b11a16aSHongbin Zheng 3659646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 3660446d81eSMichael Kruse // Identified as redundant by -polly-simplify. 3670446d81eSMichael Kruse if (!Stmt.getArrayAccessOrNULLFor(Store)) 3680446d81eSMichael Kruse return; 3690446d81eSMichael Kruse 370888ab551SMichael Kruse generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses); 3713b11a16aSHongbin Zheng return; 3723b11a16aSHongbin Zheng } 3733b11a16aSHongbin Zheng 3749646e3feSTobias Grosser if (auto *PHI = dyn_cast<PHINode>(Inst)) { 375bc132607STobias Grosser copyPHIInstruction(Stmt, PHI, BBMap, LTS); 376ecff11dcSJohannes Doerfert return; 377ecff11dcSJohannes Doerfert } 378ecff11dcSJohannes Doerfert 3793f500fa2SJohannes Doerfert // Skip some special intrinsics for which we do not adjust the semantics to 3803f500fa2SJohannes Doerfert // the new schedule. All others are handled like every other instruction. 3819c0ffe3aSTobias Grosser if (isIgnoredIntrinsic(Inst)) 3823f500fa2SJohannes Doerfert return; 3833f500fa2SJohannes Doerfert 384bc132607STobias Grosser copyInstScalar(Stmt, Inst, BBMap, LTS); 3853b11a16aSHongbin Zheng } 3863b11a16aSHongbin Zheng 3879d12d8adSTobias Grosser void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) { 388c59b3ce0STobias Grosser auto NewBB = Builder.GetInsertBlock(); 389c59b3ce0STobias Grosser for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) { 390c59b3ce0STobias Grosser Instruction *NewInst = &*I; 3919d12d8adSTobias Grosser 3929d12d8adSTobias Grosser if (!isInstructionTriviallyDead(NewInst)) 3939d12d8adSTobias Grosser continue; 3949d12d8adSTobias Grosser 395c59b3ce0STobias Grosser for (auto Pair : BBMap) 396c59b3ce0STobias Grosser if (Pair.second == NewInst) { 397c59b3ce0STobias Grosser BBMap.erase(Pair.first); 398c59b3ce0STobias Grosser } 399c59b3ce0STobias Grosser 4009d12d8adSTobias Grosser NewInst->eraseFromParent(); 401c59b3ce0STobias Grosser I = NewBB->rbegin(); 4029d12d8adSTobias Grosser } 4039d12d8adSTobias Grosser } 4049d12d8adSTobias Grosser 405bc132607STobias Grosser void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 4062d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 407275a1756SJohannes Doerfert assert(Stmt.isBlockStmt() && 408275a1756SJohannes Doerfert "Only block statements can be copied by the block generator"); 409275a1756SJohannes Doerfert 410275a1756SJohannes Doerfert ValueMapT BBMap; 411275a1756SJohannes Doerfert 412be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 413bc132607STobias Grosser copyBB(Stmt, BB, BBMap, LTS, NewAccesses); 4149d12d8adSTobias Grosser removeDeadInstructions(BB, BBMap); 415275a1756SJohannes Doerfert } 416275a1756SJohannes Doerfert 417514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) { 418b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 419b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 4203b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 421514f6efaSJohannes Doerfert return CopyBB; 422514f6efaSJohannes Doerfert } 4233b11a16aSHongbin Zheng 424514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, 425bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 4262d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 427514f6efaSJohannes Doerfert BasicBlock *CopyBB = splitBB(BB); 428b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 4292fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, BBMap, NewAccesses); 430225f0d1eSMichael Kruse 431bc132607STobias Grosser copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses); 432225f0d1eSMichael Kruse 433225f0d1eSMichael Kruse // After a basic block was copied store all scalars that escape this block in 434225f0d1eSMichael Kruse // their alloca. 4352fa35194SMichael Kruse generateScalarStores(Stmt, LTS, BBMap, NewAccesses); 436514f6efaSJohannes Doerfert return CopyBB; 437514f6efaSJohannes Doerfert } 438514f6efaSJohannes Doerfert 439514f6efaSJohannes Doerfert void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB, 440bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 4412d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 442ecff11dcSJohannes Doerfert EntryBB = &CopyBB->getParent()->getEntryBlock(); 443ecff11dcSJohannes Doerfert 4443bb48299SMichael Kruse if (Stmt.isBlockStmt()) 4453bb48299SMichael Kruse for (Instruction *Inst : Stmt.getInstructions()) 4463bb48299SMichael Kruse copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses); 4473bb48299SMichael Kruse else 44891f5b262STobias Grosser for (Instruction &Inst : *BB) 449bc132607STobias Grosser copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses); 450ecff11dcSJohannes Doerfert } 451ecff11dcSJohannes Doerfert 452800e17a7SJohannes Doerfert Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) { 453587f1f57STobias Grosser assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind"); 4543216f854STobias Grosser 455587f1f57STobias Grosser return getOrCreateAlloca(Access.getLatestScopArrayInfo()); 456a4f0988dSTobias Grosser } 457a4f0988dSTobias Grosser 458a4f0988dSTobias Grosser Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) { 4593216f854STobias Grosser assert(!Array->isArrayKind() && "Trying to get alloca for array kind"); 4603216f854STobias Grosser 461587f1f57STobias Grosser auto &Addr = ScalarMap[Array]; 462587f1f57STobias Grosser 463587f1f57STobias Grosser if (Addr) { 464587f1f57STobias Grosser // Allow allocas to be (temporarily) redirected once by adding a new 465a6d48f59SMichael Kruse // old-alloca-addr to new-addr mapping to GlobalMap. This functionality 466587f1f57STobias Grosser // is used for example by the OpenMP code generation where a first use 467587f1f57STobias Grosser // of a scalar while still in the host code allocates a normal alloca with 468587f1f57STobias Grosser // getOrCreateAlloca. When the values of this scalar are accessed during 469587f1f57STobias Grosser // the generation of the parallel subfunction, these values are copied over 470587f1f57STobias Grosser // to the parallel subfunction and each request for a scalar alloca slot 471a6d48f59SMichael Kruse // must be forwarded to the temporary in-subfunction slot. This mapping is 472587f1f57STobias Grosser // removed when the subfunction has been generated and again normal host 473682c5114STobias Grosser // code is generated. Due to the following reasons it is not possible to 474682c5114STobias Grosser // perform the GlobalMap lookup right after creating the alloca below, but 475682c5114STobias Grosser // instead we need to check GlobalMap at each call to getOrCreateAlloca: 476682c5114STobias Grosser // 477682c5114STobias Grosser // 1) GlobalMap may be changed multiple times (for each parallel loop), 478682c5114STobias Grosser // 2) The temporary mapping is commonly only known after the initial 479682c5114STobias Grosser // alloca has already been generated, and 480682c5114STobias Grosser // 3) The original alloca value must be restored after leaving the 481682c5114STobias Grosser // sub-function. 482587f1f57STobias Grosser if (Value *NewAddr = GlobalMap.lookup(&*Addr)) 483587f1f57STobias Grosser return NewAddr; 484587f1f57STobias Grosser return Addr; 485587f1f57STobias Grosser } 486587f1f57STobias Grosser 487587f1f57STobias Grosser Type *Ty = Array->getElementType(); 488587f1f57STobias Grosser Value *ScalarBase = Array->getBasePtr(); 489587f1f57STobias Grosser std::string NameExt; 490a535dff4STobias Grosser if (Array->isPHIKind()) 491587f1f57STobias Grosser NameExt = ".phiops"; 492f8d55f7eSTobias Grosser else 493587f1f57STobias Grosser NameExt = ".s2a"; 494587f1f57STobias Grosser 4957b5a4dfdSTobias Grosser const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout(); 496b3e30c32SMatt Arsenault 497b3e30c32SMatt Arsenault Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(), 498b3e30c32SMatt Arsenault ScalarBase->getName() + NameExt); 499587f1f57STobias Grosser EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 500587f1f57STobias Grosser Addr->insertBefore(&*EntryBB->getFirstInsertionPt()); 501587f1f57STobias Grosser 502587f1f57STobias Grosser return Addr; 503f8d55f7eSTobias Grosser } 504f8d55f7eSTobias Grosser 505587f1f57STobias Grosser void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) { 506587f1f57STobias Grosser Instruction *Inst = cast<Instruction>(Array->getBasePtr()); 507b79a67dfSTobias Grosser 5082985400aSTobias Grosser // If there are escape users we get the alloca for this instruction and put it 5092985400aSTobias Grosser // in the EscapeMap for later finalization. Lastly, if the instruction was 5102985400aSTobias Grosser // copied multiple times we already did this and can exit. 511acb6ade7SMichael Kruse if (EscapeMap.count(Inst)) 512acb6ade7SMichael Kruse return; 513e69e1141SJohannes Doerfert 514ecff11dcSJohannes Doerfert EscapeUserVectorTy EscapeUsers; 515ecff11dcSJohannes Doerfert for (User *U : Inst->users()) { 516ecff11dcSJohannes Doerfert 517ecff11dcSJohannes Doerfert // Non-instruction user will never escape. 518ecff11dcSJohannes Doerfert Instruction *UI = dyn_cast<Instruction>(U); 519ecff11dcSJohannes Doerfert if (!UI) 520ecff11dcSJohannes Doerfert continue; 521ecff11dcSJohannes Doerfert 522952b5304SJohannes Doerfert if (S.contains(UI)) 523ecff11dcSJohannes Doerfert continue; 524ecff11dcSJohannes Doerfert 525ecff11dcSJohannes Doerfert EscapeUsers.push_back(UI); 526ecff11dcSJohannes Doerfert } 527ecff11dcSJohannes Doerfert 528ecff11dcSJohannes Doerfert // Exit if no escape uses were found. 529ecff11dcSJohannes Doerfert if (EscapeUsers.empty()) 530ecff11dcSJohannes Doerfert return; 531ecff11dcSJohannes Doerfert 532ecff11dcSJohannes Doerfert // Get or create an escape alloca for this instruction. 533587f1f57STobias Grosser auto *ScalarAddr = getOrCreateAlloca(Array); 534ecff11dcSJohannes Doerfert 535ecff11dcSJohannes Doerfert // Remember that this instruction has escape uses and the escape alloca. 536ecff11dcSJohannes Doerfert EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers)); 537ecff11dcSJohannes Doerfert } 538ecff11dcSJohannes Doerfert 5392fa35194SMichael Kruse void BlockGenerator::generateScalarLoads( 5402fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 5412fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 542225f0d1eSMichael Kruse for (MemoryAccess *MA : Stmt) { 5432fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isWrite()) 544ecff11dcSJohannes Doerfert continue; 545ecff11dcSJohannes Doerfert 54677394f13SMichael Kruse #ifndef NDEBUG 54777394f13SMichael Kruse auto *StmtDom = Stmt.getDomain(); 5481515f6b9STobias Grosser auto *AccDom = isl_map_domain(MA->getAccessRelation().release()); 54977394f13SMichael Kruse assert(isl_set_is_subset(StmtDom, AccDom) && 55077394f13SMichael Kruse "Scalar must be loaded in all statement instances"); 55177394f13SMichael Kruse isl_set_free(StmtDom); 55277394f13SMichael Kruse isl_set_free(AccDom); 55377394f13SMichael Kruse #endif 55477394f13SMichael Kruse 5552fa35194SMichael Kruse auto *Address = 5562fa35194SMichael Kruse getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 557eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 558eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 559eac9726eSMichael Kruse Builder.GetInsertBlock())) && 560eac9726eSMichael Kruse "Domination violation"); 561583be06fSTobias Grosser BBMap[MA->getAccessValue()] = 5622fc50df9STobias Grosser Builder.CreateLoad(Address, Address->getName() + ".reload"); 563ecff11dcSJohannes Doerfert } 564ecff11dcSJohannes Doerfert } 565ecff11dcSJohannes Doerfert 566706f79abSMichael Kruse Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt, 567706f79abSMichael Kruse const isl::set &Subdomain) { 568706f79abSMichael Kruse isl::ast_build AstBuild = give(isl_ast_build_copy(Stmt.getAstBuild())); 569706f79abSMichael Kruse isl::set Domain = give(Stmt.getDomain()); 570706f79abSMichael Kruse 5716b6ac900STobias Grosser isl::union_map USchedule = AstBuild.get_schedule(); 5726b6ac900STobias Grosser USchedule = USchedule.intersect_domain(Domain); 573706f79abSMichael Kruse 5746b6ac900STobias Grosser assert(!USchedule.is_empty()); 5756b6ac900STobias Grosser isl::map Schedule = isl::map::from_union_map(USchedule); 576706f79abSMichael Kruse 5776b6ac900STobias Grosser isl::set ScheduledDomain = Schedule.range(); 5786b6ac900STobias Grosser isl::set ScheduledSet = Subdomain.apply(Schedule); 579706f79abSMichael Kruse 5806b6ac900STobias Grosser isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain); 5816b6ac900STobias Grosser 5826b6ac900STobias Grosser isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet); 583706f79abSMichael Kruse Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy()); 584706f79abSMichael Kruse IsInSetExpr = Builder.CreateICmpNE( 585706f79abSMichael Kruse IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0)); 586706f79abSMichael Kruse 587706f79abSMichael Kruse return IsInSetExpr; 588706f79abSMichael Kruse } 589706f79abSMichael Kruse 590706f79abSMichael Kruse void BlockGenerator::generateConditionalExecution( 591706f79abSMichael Kruse ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject, 592706f79abSMichael Kruse const std::function<void()> &GenThenFunc) { 593706f79abSMichael Kruse isl::set StmtDom = give(Stmt.getDomain()); 594706f79abSMichael Kruse 595706f79abSMichael Kruse // Don't call GenThenFunc if it is never executed. An ast index expression 596706f79abSMichael Kruse // might not be defined in this case. 5976b6ac900STobias Grosser if (Subdomain.is_empty()) 598706f79abSMichael Kruse return; 599706f79abSMichael Kruse 600706f79abSMichael Kruse // If the condition is a tautology, don't generate a condition around the 601706f79abSMichael Kruse // code. 602f51decb5STobias Grosser bool IsPartialWrite = 603f51decb5STobias Grosser !StmtDom.intersect_params(give(Stmt.getParent()->getContext())) 604f51decb5STobias Grosser .is_subset(Subdomain); 605f51decb5STobias Grosser if (!IsPartialWrite) { 606706f79abSMichael Kruse GenThenFunc(); 607706f79abSMichael Kruse return; 608706f79abSMichael Kruse } 609706f79abSMichael Kruse 610706f79abSMichael Kruse // Generate the condition. 611706f79abSMichael Kruse Value *Cond = buildContainsCondition(Stmt, Subdomain); 612706f79abSMichael Kruse BasicBlock *HeadBlock = Builder.GetInsertBlock(); 613706f79abSMichael Kruse StringRef BlockName = HeadBlock->getName(); 614706f79abSMichael Kruse 615706f79abSMichael Kruse // Generate the conditional block. 616706f79abSMichael Kruse SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr, 617706f79abSMichael Kruse &DT, &LI); 618706f79abSMichael Kruse BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator()); 619706f79abSMichael Kruse BasicBlock *ThenBlock = Branch->getSuccessor(0); 620706f79abSMichael Kruse BasicBlock *TailBlock = Branch->getSuccessor(1); 621706f79abSMichael Kruse 622706f79abSMichael Kruse // Assign descriptive names. 623706f79abSMichael Kruse if (auto *CondInst = dyn_cast<Instruction>(Cond)) 624706f79abSMichael Kruse CondInst->setName("polly." + Subject + ".cond"); 625706f79abSMichael Kruse ThenBlock->setName(BlockName + "." + Subject + ".partial"); 626706f79abSMichael Kruse TailBlock->setName(BlockName + ".cont"); 627706f79abSMichael Kruse 628706f79abSMichael Kruse // Put the client code into the conditional block and continue in the merge 629706f79abSMichael Kruse // block afterwards. 630706f79abSMichael Kruse Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt()); 631706f79abSMichael Kruse GenThenFunc(); 632706f79abSMichael Kruse Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt()); 633706f79abSMichael Kruse } 634706f79abSMichael Kruse 6352fa35194SMichael Kruse void BlockGenerator::generateScalarStores( 6362fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 6372fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 638f2cdd144STobias Grosser Loop *L = LI.getLoopFor(Stmt.getBasicBlock()); 639ecff11dcSJohannes Doerfert 64021a059afSTobias Grosser assert(Stmt.isBlockStmt() && 64121a059afSTobias Grosser "Region statements need to use the generateScalarStores() function in " 64221a059afSTobias Grosser "the RegionGenerator"); 643ecff11dcSJohannes Doerfert 644ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 6452fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 646ecff11dcSJohannes Doerfert continue; 647ecff11dcSJohannes Doerfert 6481515f6b9STobias Grosser isl::set AccDom = MA->getAccessRelation().domain(); 649fe46c3ffSTobias Grosser std::string Subject = MA->getId().get_name(); 65077394f13SMichael Kruse 651fe46c3ffSTobias Grosser generateConditionalExecution( 652fe46c3ffSTobias Grosser Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 653d86f2157SJohannes Doerfert Value *Val = MA->getAccessValue(); 654ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 655fe46c3ffSTobias Grosser assert(MA->getIncoming().size() >= 1 && 656fe46c3ffSTobias Grosser "Block statements have exactly one exiting block, or " 657fe46c3ffSTobias Grosser "multiple but " 658ee6a4fc6SMichael Kruse "with same incoming block and value"); 659fe46c3ffSTobias Grosser assert(std::all_of(MA->getIncoming().begin(), 660fe46c3ffSTobias Grosser MA->getIncoming().end(), 661ee6a4fc6SMichael Kruse [&](std::pair<BasicBlock *, Value *> p) -> bool { 662ee6a4fc6SMichael Kruse return p.first == Stmt.getBasicBlock(); 663ee6a4fc6SMichael Kruse }) && 664ee6a4fc6SMichael Kruse "Incoming block must be statement's block"); 665ee6a4fc6SMichael Kruse Val = MA->getIncoming()[0].second; 666ee6a4fc6SMichael Kruse } 667fe46c3ffSTobias Grosser auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 668fe46c3ffSTobias Grosser BBMap, NewAccesses); 669d86f2157SJohannes Doerfert 670f2cdd144STobias Grosser Val = getNewValue(Stmt, Val, BBMap, LTS, L); 671eac9726eSMichael Kruse assert((!isa<Instruction>(Val) || 672eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Val)->getParent(), 673eac9726eSMichael Kruse Builder.GetInsertBlock())) && 674eac9726eSMichael Kruse "Domination violation"); 675eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 676eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 677eac9726eSMichael Kruse Builder.GetInsertBlock())) && 678eac9726eSMichael Kruse "Domination violation"); 67992245228STobias Grosser Builder.CreateStore(Val, Address); 680706f79abSMichael Kruse 681706f79abSMichael Kruse }); 682ecff11dcSJohannes Doerfert } 683ecff11dcSJohannes Doerfert } 684ecff11dcSJohannes Doerfert 685c0091a77STobias Grosser void BlockGenerator::createScalarInitialization(Scop &S) { 686ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExit(); 687acf80064SEli Friedman BasicBlock *PreEntryBB = S.getEnteringBlock(); 688188542fdSJohannes Doerfert 689acf80064SEli Friedman Builder.SetInsertPoint(&*StartBlock->begin()); 690ecff11dcSJohannes Doerfert 691d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 692c0091a77STobias Grosser if (Array->getNumberOfDimensions() != 0) 693c0091a77STobias Grosser continue; 694a535dff4STobias Grosser if (Array->isPHIKind()) { 695c0091a77STobias Grosser // For PHI nodes, the only values we need to store are the ones that 696c0091a77STobias Grosser // reach the PHI node from outside the region. In general there should 697c0091a77STobias Grosser // only be one such incoming edge and this edge should enter through 698acf80064SEli Friedman // 'PreEntryBB'. 699c0091a77STobias Grosser auto PHI = cast<PHINode>(Array->getBasePtr()); 700ecff11dcSJohannes Doerfert 701c0091a77STobias Grosser for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++) 702acf80064SEli Friedman if (!S.contains(*BI) && *BI != PreEntryBB) 703c0091a77STobias Grosser llvm_unreachable("Incoming edges from outside the scop should always " 704acf80064SEli Friedman "come from PreEntryBB"); 705c0091a77STobias Grosser 706acf80064SEli Friedman int Idx = PHI->getBasicBlockIndex(PreEntryBB); 707c0091a77STobias Grosser if (Idx < 0) 708ecff11dcSJohannes Doerfert continue; 709ecff11dcSJohannes Doerfert 710c0091a77STobias Grosser Value *ScalarValue = PHI->getIncomingValue(Idx); 711ecff11dcSJohannes Doerfert 712587f1f57STobias Grosser Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array)); 713c0091a77STobias Grosser continue; 714c0091a77STobias Grosser } 715c0091a77STobias Grosser 716c0091a77STobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 717c0091a77STobias Grosser 718952b5304SJohannes Doerfert if (Inst && S.contains(Inst)) 719c0091a77STobias Grosser continue; 720c0091a77STobias Grosser 721188542fdSJohannes Doerfert // PHI nodes that are not marked as such in their SAI object are either exit 722188542fdSJohannes Doerfert // PHI nodes we model as common scalars but without initialization, or 723188542fdSJohannes Doerfert // incoming phi nodes that need to be initialized. Check if the first is the 724188542fdSJohannes Doerfert // case for Inst and do not create and initialize memory if so. 725188542fdSJohannes Doerfert if (auto *PHI = dyn_cast_or_null<PHINode>(Inst)) 726188542fdSJohannes Doerfert if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0) 727717b8667SJohannes Doerfert continue; 728717b8667SJohannes Doerfert 729587f1f57STobias Grosser Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array)); 730ecff11dcSJohannes Doerfert } 731ecff11dcSJohannes Doerfert } 732ecff11dcSJohannes Doerfert 733ef74443cSJohannes Doerfert void BlockGenerator::createScalarFinalization(Scop &S) { 734ecff11dcSJohannes Doerfert // The exit block of the __unoptimized__ region. 735ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExitingBlock(); 736ecff11dcSJohannes Doerfert // The merge block __just after__ the region and the optimized region. 737ef74443cSJohannes Doerfert BasicBlock *MergeBB = S.getExit(); 738ecff11dcSJohannes Doerfert 739ecff11dcSJohannes Doerfert // The exit block of the __optimized__ region. 740ecff11dcSJohannes Doerfert BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 741ecff11dcSJohannes Doerfert if (OptExitBB == ExitBB) 742ecff11dcSJohannes Doerfert OptExitBB = *(++pred_begin(MergeBB)); 743ecff11dcSJohannes Doerfert 744ecff11dcSJohannes Doerfert Builder.SetInsertPoint(OptExitBB->getTerminator()); 745ecff11dcSJohannes Doerfert for (const auto &EscapeMapping : EscapeMap) { 746ecff11dcSJohannes Doerfert // Extract the escaping instruction and the escaping users as well as the 747ecff11dcSJohannes Doerfert // alloca the instruction was demoted to. 748fbde4355SMichael Kruse Instruction *EscapeInst = EscapeMapping.first; 749fbde4355SMichael Kruse const auto &EscapeMappingValue = EscapeMapping.second; 750ecff11dcSJohannes Doerfert const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second; 75164c0ff41STobias Grosser Value *ScalarAddr = EscapeMappingValue.first; 752ecff11dcSJohannes Doerfert 753ecff11dcSJohannes Doerfert // Reload the demoted instruction in the optimized version of the SCoP. 754d8b6ad25SJohannes Doerfert Value *EscapeInstReload = 755ecff11dcSJohannes Doerfert Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload"); 756d8b6ad25SJohannes Doerfert EscapeInstReload = 757d8b6ad25SJohannes Doerfert Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType()); 758ecff11dcSJohannes Doerfert 759ecff11dcSJohannes Doerfert // Create the merge PHI that merges the optimized and unoptimized version. 760ecff11dcSJohannes Doerfert PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2, 761ecff11dcSJohannes Doerfert EscapeInst->getName() + ".merge"); 762b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 763ecff11dcSJohannes Doerfert 764ecff11dcSJohannes Doerfert // Add the respective values to the merge PHI. 765ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInstReload, OptExitBB); 766ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInst, ExitBB); 767ecff11dcSJohannes Doerfert 768ecff11dcSJohannes Doerfert // The information of scalar evolution about the escaping instruction needs 769ecff11dcSJohannes Doerfert // to be revoked so the new merged instruction will be used. 770ecff11dcSJohannes Doerfert if (SE.isSCEVable(EscapeInst->getType())) 771ecff11dcSJohannes Doerfert SE.forgetValue(EscapeInst); 772ecff11dcSJohannes Doerfert 773ecff11dcSJohannes Doerfert // Replace all uses of the demoted instruction with the merge PHI. 774ecff11dcSJohannes Doerfert for (Instruction *EUser : EscapeUsers) 775ecff11dcSJohannes Doerfert EUser->replaceUsesOfWith(EscapeInst, MergePHI); 776ecff11dcSJohannes Doerfert } 777ecff11dcSJohannes Doerfert } 778ecff11dcSJohannes Doerfert 779ffa2446fSTobias Grosser void BlockGenerator::findOutsideUsers(Scop &S) { 780d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 781ffa2446fSTobias Grosser 782ffa2446fSTobias Grosser if (Array->getNumberOfDimensions() != 0) 783ffa2446fSTobias Grosser continue; 784ffa2446fSTobias Grosser 785a535dff4STobias Grosser if (Array->isPHIKind()) 786ffa2446fSTobias Grosser continue; 787ffa2446fSTobias Grosser 788ffa2446fSTobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 789ffa2446fSTobias Grosser 790ffa2446fSTobias Grosser if (!Inst) 791ffa2446fSTobias Grosser continue; 792ffa2446fSTobias Grosser 793ffa2446fSTobias Grosser // Scop invariant hoisting moves some of the base pointers out of the scop. 794ffa2446fSTobias Grosser // We can ignore these, as the invariant load hoisting already registers the 795ffa2446fSTobias Grosser // relevant outside users. 796952b5304SJohannes Doerfert if (!S.contains(Inst)) 797ffa2446fSTobias Grosser continue; 798ffa2446fSTobias Grosser 799587f1f57STobias Grosser handleOutsideUsers(S, Array); 800ffa2446fSTobias Grosser } 801ffa2446fSTobias Grosser } 802ffa2446fSTobias Grosser 80327d742daSTobias Grosser void BlockGenerator::createExitPHINodeMerges(Scop &S) { 80427d742daSTobias Grosser if (S.hasSingleExitEdge()) 80527d742daSTobias Grosser return; 80627d742daSTobias Grosser 807ef74443cSJohannes Doerfert auto *ExitBB = S.getExitingBlock(); 808ef74443cSJohannes Doerfert auto *MergeBB = S.getExit(); 80927d742daSTobias Grosser auto *AfterMergeBB = MergeBB->getSingleSuccessor(); 81027d742daSTobias Grosser BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 81127d742daSTobias Grosser if (OptExitBB == ExitBB) 81227d742daSTobias Grosser OptExitBB = *(++pred_begin(MergeBB)); 81327d742daSTobias Grosser 81427d742daSTobias Grosser Builder.SetInsertPoint(OptExitBB->getTerminator()); 81527d742daSTobias Grosser 816d7754a12SRoman Gareev for (auto &SAI : S.arrays()) { 81727d742daSTobias Grosser auto *Val = SAI->getBasePtr(); 81827d742daSTobias Grosser 819faedfcbfSMichael Kruse // Only Value-like scalars need a merge PHI. Exit block PHIs receive either 820faedfcbfSMichael Kruse // the original PHI's value or the reloaded incoming values from the 821faedfcbfSMichael Kruse // generated code. An llvm::Value is merged between the original code's 822faedfcbfSMichael Kruse // value or the generated one. 823fa53c86dSMichael Kruse if (!SAI->isExitPHIKind()) 824faedfcbfSMichael Kruse continue; 825faedfcbfSMichael Kruse 82627d742daSTobias Grosser PHINode *PHI = dyn_cast<PHINode>(Val); 82727d742daSTobias Grosser if (!PHI) 82827d742daSTobias Grosser continue; 82927d742daSTobias Grosser 830a3f6edaeSTobias Grosser if (PHI->getParent() != AfterMergeBB) 83127d742daSTobias Grosser continue; 83227d742daSTobias Grosser 83327d742daSTobias Grosser std::string Name = PHI->getName(); 834587f1f57STobias Grosser Value *ScalarAddr = getOrCreateAlloca(SAI); 83527d742daSTobias Grosser Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload"); 83627d742daSTobias Grosser Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType()); 83727d742daSTobias Grosser Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB); 838faedfcbfSMichael Kruse assert((!isa<Instruction>(OriginalValue) || 839faedfcbfSMichael Kruse cast<Instruction>(OriginalValue)->getParent() != MergeBB) && 840faedfcbfSMichael Kruse "Original value must no be one we just generated."); 84127d742daSTobias Grosser auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge"); 842b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 84327d742daSTobias Grosser MergePHI->addIncoming(Reload, OptExitBB); 84427d742daSTobias Grosser MergePHI->addIncoming(OriginalValue, ExitBB); 84527d742daSTobias Grosser int Idx = PHI->getBasicBlockIndex(MergeBB); 84627d742daSTobias Grosser PHI->setIncomingValue(Idx, MergePHI); 84727d742daSTobias Grosser } 84827d742daSTobias Grosser } 84927d742daSTobias Grosser 8501c184409STobias Grosser void BlockGenerator::invalidateScalarEvolution(Scop &S) { 8511c184409STobias Grosser for (auto &Stmt : S) 852b3224adfSRoman Gareev if (Stmt.isCopyStmt()) 853b3224adfSRoman Gareev continue; 854b3224adfSRoman Gareev else if (Stmt.isBlockStmt()) 8551c184409STobias Grosser for (auto &Inst : *Stmt.getBasicBlock()) 8561c184409STobias Grosser SE.forgetValue(&Inst); 8571c184409STobias Grosser else if (Stmt.isRegionStmt()) 8581c184409STobias Grosser for (auto *BB : Stmt.getRegion()->blocks()) 8591c184409STobias Grosser for (auto &Inst : *BB) 8601c184409STobias Grosser SE.forgetValue(&Inst); 8611c184409STobias Grosser else 8621c184409STobias Grosser llvm_unreachable("Unexpected statement type found"); 8631aad76c1SMichael Kruse 8641aad76c1SMichael Kruse // Invalidate SCEV of loops surrounding the EscapeUsers. 8651aad76c1SMichael Kruse for (const auto &EscapeMapping : EscapeMap) { 8661aad76c1SMichael Kruse const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second; 8671aad76c1SMichael Kruse for (Instruction *EUser : EscapeUsers) { 8681aad76c1SMichael Kruse if (Loop *L = LI.getLoopFor(EUser->getParent())) 8691aad76c1SMichael Kruse while (L) { 8701aad76c1SMichael Kruse SE.forgetLoop(L); 8711aad76c1SMichael Kruse L = L->getParentLoop(); 8721aad76c1SMichael Kruse } 8731aad76c1SMichael Kruse } 8741aad76c1SMichael Kruse } 8751c184409STobias Grosser } 8761c184409STobias Grosser 877ffa2446fSTobias Grosser void BlockGenerator::finalizeSCoP(Scop &S) { 878ffa2446fSTobias Grosser findOutsideUsers(S); 879c0091a77STobias Grosser createScalarInitialization(S); 88027d742daSTobias Grosser createExitPHINodeMerges(S); 881ef74443cSJohannes Doerfert createScalarFinalization(S); 8821c184409STobias Grosser invalidateScalarEvolution(S); 8833b11a16aSHongbin Zheng } 8843b11a16aSHongbin Zheng 885be9c9117SJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen, 886be9c9117SJohannes Doerfert std::vector<LoopToScevMapT> &VLTS, 887be9c9117SJohannes Doerfert isl_map *Schedule) 888bc132607STobias Grosser : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) { 889a00a0291SSebastian Pop assert(Schedule && "No statement domain provided"); 8903b11a16aSHongbin Zheng } 8913b11a16aSHongbin Zheng 8922f1acac6STobias Grosser Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old, 893e602a076STobias Grosser ValueMapT &VectorMap, 894e602a076STobias Grosser VectorValueMapT &ScalarMaps, 895e602a076STobias Grosser Loop *L) { 896fe11e287SHongbin Zheng if (Value *NewValue = VectorMap.lookup(Old)) 897fe11e287SHongbin Zheng return NewValue; 8983b11a16aSHongbin Zheng 8993b11a16aSHongbin Zheng int Width = getVectorWidth(); 9003b11a16aSHongbin Zheng 9013b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width)); 9023b11a16aSHongbin Zheng 9033b11a16aSHongbin Zheng for (int Lane = 0; Lane < Width; Lane++) 904c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 905bc132607STobias Grosser Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L), 9067242ad92STobias Grosser Builder.getInt32(Lane)); 9073b11a16aSHongbin Zheng 9083b11a16aSHongbin Zheng VectorMap[Old] = Vector; 9093b11a16aSHongbin Zheng 9103b11a16aSHongbin Zheng return Vector; 9113b11a16aSHongbin Zheng } 9123b11a16aSHongbin Zheng 9133b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) { 9143b11a16aSHongbin Zheng PointerType *PointerTy = dyn_cast<PointerType>(Val->getType()); 9153b11a16aSHongbin Zheng assert(PointerTy && "PointerType expected"); 9163b11a16aSHongbin Zheng 9173b11a16aSHongbin Zheng Type *ScalarType = PointerTy->getElementType(); 9183b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(ScalarType, Width); 9193b11a16aSHongbin Zheng 9203b11a16aSHongbin Zheng return PointerType::getUnqual(VectorType); 9213b11a16aSHongbin Zheng } 9223b11a16aSHongbin Zheng 923be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateStrideOneLoad( 9242f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 9252d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) { 9260dd463faSTobias Grosser unsigned VectorWidth = getVectorWidth(); 9279646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9280dd463faSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth); 9290dd463faSTobias Grosser unsigned Offset = NegativeStride ? VectorWidth - 1 : 0; 9300dd463faSTobias Grosser 9318f25b0cbSMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset], 932bc132607STobias Grosser VLTS[Offset], NewAccesses); 933c14582f2STobias Grosser Value *VectorPtr = 934c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 935c14582f2STobias Grosser LoadInst *VecLoad = 936c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full"); 9373b11a16aSHongbin Zheng if (!Aligned) 9383b11a16aSHongbin Zheng VecLoad->setAlignment(8); 9393b11a16aSHongbin Zheng 9400dd463faSTobias Grosser if (NegativeStride) { 9410dd463faSTobias Grosser SmallVector<Constant *, 16> Indices; 9420dd463faSTobias Grosser for (int i = VectorWidth - 1; i >= 0; i--) 9430dd463faSTobias Grosser Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i)); 9440dd463faSTobias Grosser Constant *SV = llvm::ConstantVector::get(Indices); 9450dd463faSTobias Grosser Value *RevVecLoad = Builder.CreateShuffleVector( 9460dd463faSTobias Grosser VecLoad, VecLoad, SV, Load->getName() + "_reverse"); 9470dd463faSTobias Grosser return RevVecLoad; 9480dd463faSTobias Grosser } 9490dd463faSTobias Grosser 9503b11a16aSHongbin Zheng return VecLoad; 9513b11a16aSHongbin Zheng } 9523b11a16aSHongbin Zheng 9532d1ed0bfSTobias Grosser Value *VectorBlockGenerator::generateStrideZeroLoad( 9542f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap, 9552d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses) { 9569646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9573b11a16aSHongbin Zheng Type *VectorPtrType = getVectorPtrTy(Pointer, 1); 95870131d34SMichael Kruse Value *NewPointer = 95970131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses); 9603b11a16aSHongbin Zheng Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType, 9613b11a16aSHongbin Zheng Load->getName() + "_p_vec_p"); 962c14582f2STobias Grosser LoadInst *ScalarLoad = 963c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one"); 9643b11a16aSHongbin Zheng 9653b11a16aSHongbin Zheng if (!Aligned) 9663b11a16aSHongbin Zheng ScalarLoad->setAlignment(8); 9673b11a16aSHongbin Zheng 968c14582f2STobias Grosser Constant *SplatVector = Constant::getNullValue( 969c14582f2STobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 9703b11a16aSHongbin Zheng 971c14582f2STobias Grosser Value *VectorLoad = Builder.CreateShuffleVector( 972c14582f2STobias Grosser ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat"); 9733b11a16aSHongbin Zheng return VectorLoad; 9743b11a16aSHongbin Zheng } 9753b11a16aSHongbin Zheng 976be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateUnknownStrideLoad( 9772f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 97809e3697fSJohannes Doerfert __isl_keep isl_id_to_ast_expr *NewAccesses) { 9793b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 9809646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9813b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get( 9823b11a16aSHongbin Zheng dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth); 9833b11a16aSHongbin Zheng 9843b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 9853b11a16aSHongbin Zheng 9863b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) { 98770131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i], 98870131d34SMichael Kruse VLTS[i], NewAccesses); 989c14582f2STobias Grosser Value *ScalarLoad = 990c14582f2STobias Grosser Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_"); 991c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 992c14582f2STobias Grosser Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_"); 9933b11a16aSHongbin Zheng } 9943b11a16aSHongbin Zheng 9953b11a16aSHongbin Zheng return Vector; 9963b11a16aSHongbin Zheng } 9973b11a16aSHongbin Zheng 9982d1ed0bfSTobias Grosser void VectorBlockGenerator::generateLoad( 9992f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap, 10002d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1001c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) { 1002c1db67e2SJohannes Doerfert VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad, 1003c1db67e2SJohannes Doerfert Load->getName() + "_p"); 1004c1db67e2SJohannes Doerfert return; 1005c1db67e2SJohannes Doerfert } 1006c1db67e2SJohannes Doerfert 10072873645cSTobias Grosser if (!VectorType::isValidElementType(Load->getType())) { 10083b11a16aSHongbin Zheng for (int i = 0; i < getVectorWidth(); i++) 1009bc132607STobias Grosser ScalarMaps[i][Load] = 1010888ab551SMichael Kruse generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses); 10113b11a16aSHongbin Zheng return; 10123b11a16aSHongbin Zheng } 10133b11a16aSHongbin Zheng 1014184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Load); 10153b11a16aSHongbin Zheng 101695493984STobias Grosser // Make sure we have scalar values available to access the pointer to 101795493984STobias Grosser // the data location. 101895493984STobias Grosser extractScalarValues(Load, VectorMap, ScalarMaps); 101995493984STobias Grosser 10203b11a16aSHongbin Zheng Value *NewLoad; 1021d7065e5dSTobias Grosser if (Access.isStrideZero(isl::manage(isl_map_copy(Schedule)))) 10222d1ed0bfSTobias Grosser NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses); 1023d7065e5dSTobias Grosser else if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) 10242d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses); 1025d7065e5dSTobias Grosser else if (Access.isStrideX(isl::manage(isl_map_copy(Schedule)), -1)) 10262d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true); 10273b11a16aSHongbin Zheng else 10282d1ed0bfSTobias Grosser NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses); 10293b11a16aSHongbin Zheng 10303b11a16aSHongbin Zheng VectorMap[Load] = NewLoad; 10313b11a16aSHongbin Zheng } 10323b11a16aSHongbin Zheng 10332f1acac6STobias Grosser void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst, 10343b11a16aSHongbin Zheng ValueMapT &VectorMap, 10353b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 10363b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 1037be9c9117SJohannes Doerfert Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap, 10382c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 10393b11a16aSHongbin Zheng 10403b11a16aSHongbin Zheng assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction"); 10413b11a16aSHongbin Zheng 10423b11a16aSHongbin Zheng const CastInst *Cast = dyn_cast<CastInst>(Inst); 10433b11a16aSHongbin Zheng VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth); 10443b11a16aSHongbin Zheng VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType); 10453b11a16aSHongbin Zheng } 10463b11a16aSHongbin Zheng 10472f1acac6STobias Grosser void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst, 10483b11a16aSHongbin Zheng ValueMapT &VectorMap, 10493b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 10502c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 10513b11a16aSHongbin Zheng Value *OpZero = Inst->getOperand(0); 10523b11a16aSHongbin Zheng Value *OpOne = Inst->getOperand(1); 10533b11a16aSHongbin Zheng 10543b11a16aSHongbin Zheng Value *NewOpZero, *NewOpOne; 1055be9c9117SJohannes Doerfert NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L); 1056be9c9117SJohannes Doerfert NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L); 10573b11a16aSHongbin Zheng 10581bb59b0dSTobias Grosser Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne, 10593b11a16aSHongbin Zheng Inst->getName() + "p_vec"); 10603b11a16aSHongbin Zheng VectorMap[Inst] = NewInst; 10613b11a16aSHongbin Zheng } 10623b11a16aSHongbin Zheng 10632d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStore( 10642f1acac6STobias Grosser ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap, 10652d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1066184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Store); 10673b11a16aSHongbin Zheng 10689646e3feSTobias Grosser auto *Pointer = Store->getPointerOperand(); 1069be9c9117SJohannes Doerfert Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap, 10702c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 10713b11a16aSHongbin Zheng 107250fd7010STobias Grosser // Make sure we have scalar values available to access the pointer to 107350fd7010STobias Grosser // the data location. 107450fd7010STobias Grosser extractScalarValues(Store, VectorMap, ScalarMaps); 107550fd7010STobias Grosser 1076d7065e5dSTobias Grosser if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) { 10771947f863SJohannes Doerfert Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth()); 107870131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0], 107970131d34SMichael Kruse VLTS[0], NewAccesses); 10803b11a16aSHongbin Zheng 1081c14582f2STobias Grosser Value *VectorPtr = 1082c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 10833b11a16aSHongbin Zheng StoreInst *Store = Builder.CreateStore(Vector, VectorPtr); 10843b11a16aSHongbin Zheng 10853b11a16aSHongbin Zheng if (!Aligned) 10863b11a16aSHongbin Zheng Store->setAlignment(8); 10873b11a16aSHongbin Zheng } else { 10883b11a16aSHongbin Zheng for (unsigned i = 0; i < ScalarMaps.size(); i++) { 10891bb59b0dSTobias Grosser Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i)); 109070131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i], 109170131d34SMichael Kruse VLTS[i], NewAccesses); 10923b11a16aSHongbin Zheng Builder.CreateStore(Scalar, NewPointer); 10933b11a16aSHongbin Zheng } 10943b11a16aSHongbin Zheng } 10953b11a16aSHongbin Zheng } 10963b11a16aSHongbin Zheng 10973b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst, 10983b11a16aSHongbin Zheng ValueMapT &VectorMap) { 109991f5b262STobias Grosser for (Value *Operand : Inst->operands()) 110091f5b262STobias Grosser if (VectorMap.count(Operand)) 11013b11a16aSHongbin Zheng return true; 11023b11a16aSHongbin Zheng return false; 11033b11a16aSHongbin Zheng } 11043b11a16aSHongbin Zheng 11053b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst, 11063b11a16aSHongbin Zheng ValueMapT &VectorMap, 11073b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 11083b11a16aSHongbin Zheng bool HasVectorOperand = false; 11093b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 11103b11a16aSHongbin Zheng 111191f5b262STobias Grosser for (Value *Operand : Inst->operands()) { 111291f5b262STobias Grosser ValueMapT::iterator VecOp = VectorMap.find(Operand); 11133b11a16aSHongbin Zheng 11143b11a16aSHongbin Zheng if (VecOp == VectorMap.end()) 11153b11a16aSHongbin Zheng continue; 11163b11a16aSHongbin Zheng 11173b11a16aSHongbin Zheng HasVectorOperand = true; 11183b11a16aSHongbin Zheng Value *NewVector = VecOp->second; 11193b11a16aSHongbin Zheng 11203b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; ++i) { 11213b11a16aSHongbin Zheng ValueMapT &SM = ScalarMaps[i]; 11223b11a16aSHongbin Zheng 11233b11a16aSHongbin Zheng // If there is one scalar extracted, all scalar elements should have 11243b11a16aSHongbin Zheng // already been extracted by the code here. So no need to check for the 11252219d157STobias Grosser // existence of all of them. 112691f5b262STobias Grosser if (SM.count(Operand)) 11273b11a16aSHongbin Zheng break; 11283b11a16aSHongbin Zheng 112991f5b262STobias Grosser SM[Operand] = 113091f5b262STobias Grosser Builder.CreateExtractElement(NewVector, Builder.getInt32(i)); 11313b11a16aSHongbin Zheng } 11323b11a16aSHongbin Zheng } 11333b11a16aSHongbin Zheng 11343b11a16aSHongbin Zheng return HasVectorOperand; 11353b11a16aSHongbin Zheng } 11363b11a16aSHongbin Zheng 11372d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstScalarized( 11382f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 11392d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 11403b11a16aSHongbin Zheng bool HasVectorOperand; 11413b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 11423b11a16aSHongbin Zheng 11433b11a16aSHongbin Zheng HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps); 11443b11a16aSHongbin Zheng 11453b11a16aSHongbin Zheng for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++) 1146be9c9117SJohannes Doerfert BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane], 1147bc132607STobias Grosser VLTS[VectorLane], NewAccesses); 11483b11a16aSHongbin Zheng 11493b11a16aSHongbin Zheng if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand) 11503b11a16aSHongbin Zheng return; 11513b11a16aSHongbin Zheng 11523b11a16aSHongbin Zheng // Make the result available as vector value. 11533b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth); 11543b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 11553b11a16aSHongbin Zheng 11563b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) 11573b11a16aSHongbin Zheng Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst], 11583b11a16aSHongbin Zheng Builder.getInt32(i)); 11593b11a16aSHongbin Zheng 11603b11a16aSHongbin Zheng VectorMap[Inst] = Vector; 11613b11a16aSHongbin Zheng } 11623b11a16aSHongbin Zheng 1163bc132607STobias Grosser int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); } 11643b11a16aSHongbin Zheng 11652d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstruction( 11662f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 11672d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 11683b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 11693b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 11703b11a16aSHongbin Zheng if (Inst->isTerminator()) 11713b11a16aSHongbin Zheng return; 11723b11a16aSHongbin Zheng 11735dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 1174e71c6ab5STobias Grosser return; 1175e71c6ab5STobias Grosser 11769646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 11772d1ed0bfSTobias Grosser generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses); 11783b11a16aSHongbin Zheng return; 11793b11a16aSHongbin Zheng } 11803b11a16aSHongbin Zheng 11813b11a16aSHongbin Zheng if (hasVectorOperands(Inst, VectorMap)) { 11829646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 11830446d81eSMichael Kruse // Identified as redundant by -polly-simplify. 11840446d81eSMichael Kruse if (!Stmt.getArrayAccessOrNULLFor(Store)) 11850446d81eSMichael Kruse return; 11860446d81eSMichael Kruse 11872d1ed0bfSTobias Grosser copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses); 11883b11a16aSHongbin Zheng return; 11893b11a16aSHongbin Zheng } 11903b11a16aSHongbin Zheng 11919646e3feSTobias Grosser if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) { 1192be9c9117SJohannes Doerfert copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps); 11933b11a16aSHongbin Zheng return; 11943b11a16aSHongbin Zheng } 11953b11a16aSHongbin Zheng 11969646e3feSTobias Grosser if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) { 1197be9c9117SJohannes Doerfert copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps); 11983b11a16aSHongbin Zheng return; 11993b11a16aSHongbin Zheng } 12003b11a16aSHongbin Zheng 1201a6d48f59SMichael Kruse // Fallthrough: We generate scalar instructions, if we don't know how to 12023b11a16aSHongbin Zheng // generate vector code. 12033b11a16aSHongbin Zheng } 12043b11a16aSHongbin Zheng 12052d1ed0bfSTobias Grosser copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses); 12063b11a16aSHongbin Zheng } 12073b11a16aSHongbin Zheng 1208a69d4f0dSTobias Grosser void VectorBlockGenerator::generateScalarVectorLoads( 1209a69d4f0dSTobias Grosser ScopStmt &Stmt, ValueMapT &VectorBlockMap) { 1210a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1211a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isWrite()) 1212a69d4f0dSTobias Grosser continue; 1213a69d4f0dSTobias Grosser 1214a69d4f0dSTobias Grosser auto *Address = getOrCreateAlloca(*MA); 1215a69d4f0dSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Address, 1); 1216a69d4f0dSTobias Grosser Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType, 1217a69d4f0dSTobias Grosser Address->getName() + "_p_vec_p"); 1218a69d4f0dSTobias Grosser auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload"); 1219a69d4f0dSTobias Grosser Constant *SplatVector = Constant::getNullValue( 1220a69d4f0dSTobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 1221a69d4f0dSTobias Grosser 1222a69d4f0dSTobias Grosser Value *VectorVal = Builder.CreateShuffleVector( 1223a69d4f0dSTobias Grosser Val, Val, SplatVector, Address->getName() + "_p_splat"); 1224583be06fSTobias Grosser VectorBlockMap[MA->getAccessValue()] = VectorVal; 1225a69d4f0dSTobias Grosser } 1226a69d4f0dSTobias Grosser } 1227a69d4f0dSTobias Grosser 1228a69d4f0dSTobias Grosser void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) { 1229a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1230a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isRead()) 1231a69d4f0dSTobias Grosser continue; 1232a69d4f0dSTobias Grosser 1233a69d4f0dSTobias Grosser llvm_unreachable("Scalar stores not expected in vector loop"); 1234a69d4f0dSTobias Grosser } 1235a69d4f0dSTobias Grosser } 1236a69d4f0dSTobias Grosser 12372d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStmt( 12382d1ed0bfSTobias Grosser ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) { 123921a059afSTobias Grosser assert(Stmt.isBlockStmt() && 124021a059afSTobias Grosser "TODO: Only block statements can be copied by the vector block " 124121a059afSTobias Grosser "generator"); 1242275a1756SJohannes Doerfert 1243be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 1244b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 1245b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 12463b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 1247b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 12483b11a16aSHongbin Zheng 12493b11a16aSHongbin Zheng // Create two maps that store the mapping from the original instructions of 12503b11a16aSHongbin Zheng // the old basic block to their copies in the new basic block. Those maps 12513b11a16aSHongbin Zheng // are basic block local. 12523b11a16aSHongbin Zheng // 12533b11a16aSHongbin Zheng // As vector code generation is supported there is one map for scalar values 12543b11a16aSHongbin Zheng // and one for vector values. 12553b11a16aSHongbin Zheng // 12563b11a16aSHongbin Zheng // In case we just do scalar code generation, the vectorMap is not used and 12573b11a16aSHongbin Zheng // the scalarMap has just one dimension, which contains the mapping. 12583b11a16aSHongbin Zheng // 12593b11a16aSHongbin Zheng // In case vector code generation is done, an instruction may either appear 12603b11a16aSHongbin Zheng // in the vector map once (as it is calculating >vectorwidth< values at a 12613b11a16aSHongbin Zheng // time. Or (if the values are calculated using scalar operations), it 12623b11a16aSHongbin Zheng // appears once in every dimension of the scalarMap. 12633b11a16aSHongbin Zheng VectorValueMapT ScalarBlockMap(getVectorWidth()); 12643b11a16aSHongbin Zheng ValueMapT VectorBlockMap; 12653b11a16aSHongbin Zheng 1266a69d4f0dSTobias Grosser generateScalarVectorLoads(Stmt, VectorBlockMap); 1267a69d4f0dSTobias Grosser 126891f5b262STobias Grosser for (Instruction &Inst : *BB) 12692d1ed0bfSTobias Grosser copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses); 1270a69d4f0dSTobias Grosser 1271a69d4f0dSTobias Grosser verifyNoScalarStores(Stmt); 12723b11a16aSHongbin Zheng } 1273275a1756SJohannes Doerfert 1274ecff11dcSJohannes Doerfert BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB, 1275ecff11dcSJohannes Doerfert BasicBlock *BBCopy) { 1276514f6efaSJohannes Doerfert 1277514f6efaSJohannes Doerfert BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock(); 1278deefbcedSTobias Grosser BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom); 1279514f6efaSJohannes Doerfert 1280514f6efaSJohannes Doerfert if (BBCopyIDom) 1281514f6efaSJohannes Doerfert DT.changeImmediateDominator(BBCopy, BBCopyIDom); 1282514f6efaSJohannes Doerfert 1283deefbcedSTobias Grosser return StartBlockMap.lookup(BBIDom); 1284514f6efaSJohannes Doerfert } 1285514f6efaSJohannes Doerfert 1286f33c125dSMichael Kruse // This is to determine whether an llvm::Value (defined in @p BB) is usable when 1287f33c125dSMichael Kruse // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock()) 1288f33c125dSMichael Kruse // does not work in cases where the exit block has edges from outside the 1289f33c125dSMichael Kruse // region. In that case the llvm::Value would never be usable in in the exit 1290f33c125dSMichael Kruse // block. The RegionGenerator however creates an new exit block ('ExitBBCopy') 1291f33c125dSMichael Kruse // for the subregion's exiting edges only. We need to determine whether an 1292f33c125dSMichael Kruse // llvm::Value is usable in there. We do this by checking whether it dominates 1293f33c125dSMichael Kruse // all exiting blocks individually. 1294f33c125dSMichael Kruse static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, 1295f33c125dSMichael Kruse BasicBlock *BB) { 1296f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1297f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1298f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1299f33c125dSMichael Kruse continue; 1300f33c125dSMichael Kruse 1301f33c125dSMichael Kruse if (!DT.dominates(BB, ExitingBB)) 1302f33c125dSMichael Kruse return false; 1303f33c125dSMichael Kruse } 1304f33c125dSMichael Kruse 1305f33c125dSMichael Kruse return true; 1306f33c125dSMichael Kruse } 1307f33c125dSMichael Kruse 1308f33c125dSMichael Kruse // Find the direct dominator of the subregion's exit block if the subregion was 1309f33c125dSMichael Kruse // simplified. 1310f33c125dSMichael Kruse static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) { 1311f33c125dSMichael Kruse BasicBlock *Common = nullptr; 1312f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1313f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1314f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1315f33c125dSMichael Kruse continue; 1316f33c125dSMichael Kruse 1317f33c125dSMichael Kruse // First exiting edge. 1318f33c125dSMichael Kruse if (!Common) { 1319f33c125dSMichael Kruse Common = ExitingBB; 1320f33c125dSMichael Kruse continue; 1321f33c125dSMichael Kruse } 1322f33c125dSMichael Kruse 1323f33c125dSMichael Kruse Common = DT.findNearestCommonDominator(Common, ExitingBB); 1324f33c125dSMichael Kruse } 1325f33c125dSMichael Kruse 1326f33c125dSMichael Kruse assert(Common && R->contains(Common)); 1327f33c125dSMichael Kruse return Common; 1328f33c125dSMichael Kruse } 1329f33c125dSMichael Kruse 1330bc132607STobias Grosser void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 13312d1ed0bfSTobias Grosser isl_id_to_ast_expr *IdToAstExp) { 1332275a1756SJohannes Doerfert assert(Stmt.isRegionStmt() && 1333d3f21833STobias Grosser "Only region statements can be copied by the region generator"); 1334275a1756SJohannes Doerfert 1335ecff11dcSJohannes Doerfert // Forget all old mappings. 1336deefbcedSTobias Grosser StartBlockMap.clear(); 1337deefbcedSTobias Grosser EndBlockMap.clear(); 1338ecff11dcSJohannes Doerfert RegionMaps.clear(); 1339ecff11dcSJohannes Doerfert IncompletePHINodeMap.clear(); 1340ecff11dcSJohannes Doerfert 1341225f0d1eSMichael Kruse // Collection of all values related to this subregion. 1342225f0d1eSMichael Kruse ValueMapT ValueMap; 1343225f0d1eSMichael Kruse 1344275a1756SJohannes Doerfert // The region represented by the statement. 1345275a1756SJohannes Doerfert Region *R = Stmt.getRegion(); 1346275a1756SJohannes Doerfert 1347ecff11dcSJohannes Doerfert // Create a dedicated entry for the region where we can reload all demoted 1348ecff11dcSJohannes Doerfert // inputs. 1349ecff11dcSJohannes Doerfert BasicBlock *EntryBB = R->getEntry(); 1350b8f58b53SDuncan P. N. Exon Smith BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(), 1351b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1352ecff11dcSJohannes Doerfert EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry"); 1353b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&EntryBBCopy->front()); 1354514f6efaSJohannes Doerfert 1355c993739eSMichael Kruse ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy]; 13562fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp); 1357225f0d1eSMichael Kruse 1358ecff11dcSJohannes Doerfert for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI) 1359deefbcedSTobias Grosser if (!R->contains(*PI)) { 1360deefbcedSTobias Grosser StartBlockMap[*PI] = EntryBBCopy; 1361deefbcedSTobias Grosser EndBlockMap[*PI] = EntryBBCopy; 1362deefbcedSTobias Grosser } 1363275a1756SJohannes Doerfert 1364275a1756SJohannes Doerfert // Iterate over all blocks in the region in a breadth-first search. 1365275a1756SJohannes Doerfert std::deque<BasicBlock *> Blocks; 13665b1abfc8SMandeep Singh Grang SmallSetVector<BasicBlock *, 8> SeenBlocks; 1367ecff11dcSJohannes Doerfert Blocks.push_back(EntryBB); 1368ecff11dcSJohannes Doerfert SeenBlocks.insert(EntryBB); 1369275a1756SJohannes Doerfert 1370275a1756SJohannes Doerfert while (!Blocks.empty()) { 1371275a1756SJohannes Doerfert BasicBlock *BB = Blocks.front(); 1372275a1756SJohannes Doerfert Blocks.pop_front(); 1373275a1756SJohannes Doerfert 1374514f6efaSJohannes Doerfert // First split the block and update dominance information. 1375514f6efaSJohannes Doerfert BasicBlock *BBCopy = splitBB(BB); 1376ecff11dcSJohannes Doerfert BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy); 1377ecff11dcSJohannes Doerfert 1378c993739eSMichael Kruse // Get the mapping for this block and initialize it with either the scalar 1379c993739eSMichael Kruse // loads from the generated entering block (which dominates all blocks of 1380c993739eSMichael Kruse // this subregion) or the maps of the immediate dominator, if part of the 1381c993739eSMichael Kruse // subregion. The latter necessarily includes the former. 1382c993739eSMichael Kruse ValueMapT *InitBBMap; 1383c993739eSMichael Kruse if (BBCopyIDom) { 1384c993739eSMichael Kruse assert(RegionMaps.count(BBCopyIDom)); 1385c993739eSMichael Kruse InitBBMap = &RegionMaps[BBCopyIDom]; 1386c993739eSMichael Kruse } else 1387c993739eSMichael Kruse InitBBMap = &EntryBBMap; 1388c993739eSMichael Kruse auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap)); 1389c993739eSMichael Kruse ValueMapT &RegionMap = Inserted.first->second; 1390514f6efaSJohannes Doerfert 1391275a1756SJohannes Doerfert // Copy the block with the BlockGenerator. 1392b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&BBCopy->front()); 1393bc132607STobias Grosser copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp); 1394275a1756SJohannes Doerfert 1395ecff11dcSJohannes Doerfert // In order to remap PHI nodes we store also basic block mappings. 1396deefbcedSTobias Grosser StartBlockMap[BB] = BBCopy; 1397deefbcedSTobias Grosser EndBlockMap[BB] = Builder.GetInsertBlock(); 1398ecff11dcSJohannes Doerfert 1399ecff11dcSJohannes Doerfert // Add values to incomplete PHI nodes waiting for this block to be copied. 1400ecff11dcSJohannes Doerfert for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB]) 1401bc132607STobias Grosser addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS); 1402ecff11dcSJohannes Doerfert IncompletePHINodeMap[BB].clear(); 1403ecff11dcSJohannes Doerfert 1404275a1756SJohannes Doerfert // And continue with new successors inside the region. 1405275a1756SJohannes Doerfert for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++) 14065b1abfc8SMandeep Singh Grang if (R->contains(*SI) && SeenBlocks.insert(*SI)) 1407275a1756SJohannes Doerfert Blocks.push_back(*SI); 1408ebffcbeeSMichael Kruse 1409ebffcbeeSMichael Kruse // Remember value in case it is visible after this subregion. 1410f33c125dSMichael Kruse if (isDominatingSubregionExit(DT, R, BB)) 1411ebffcbeeSMichael Kruse ValueMap.insert(RegionMap.begin(), RegionMap.end()); 1412275a1756SJohannes Doerfert } 1413275a1756SJohannes Doerfert 1414275a1756SJohannes Doerfert // Now create a new dedicated region exit block and add it to the region map. 1415b8f58b53SDuncan P. N. Exon Smith BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(), 1416b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1417ecff11dcSJohannes Doerfert ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit"); 1418deefbcedSTobias Grosser StartBlockMap[R->getExit()] = ExitBBCopy; 1419deefbcedSTobias Grosser EndBlockMap[R->getExit()] = ExitBBCopy; 1420514f6efaSJohannes Doerfert 1421deefbcedSTobias Grosser BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R)); 142221a059afSTobias Grosser assert(ExitDomBBCopy && 142321a059afSTobias Grosser "Common exit dominator must be within region; at least the entry node " 142421a059afSTobias Grosser "must match"); 1425f33c125dSMichael Kruse DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy); 1426275a1756SJohannes Doerfert 1427275a1756SJohannes Doerfert // As the block generator doesn't handle control flow we need to add the 1428275a1756SJohannes Doerfert // region control flow by hand after all blocks have been copied. 1429275a1756SJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1430275a1756SJohannes Doerfert 1431deefbcedSTobias Grosser BasicBlock *BBCopyStart = StartBlockMap[BB]; 1432deefbcedSTobias Grosser BasicBlock *BBCopyEnd = EndBlockMap[BB]; 1433e114dc02SJohannes Doerfert TerminatorInst *TI = BB->getTerminator(); 1434e114dc02SJohannes Doerfert if (isa<UnreachableInst>(TI)) { 1435deefbcedSTobias Grosser while (!BBCopyEnd->empty()) 1436deefbcedSTobias Grosser BBCopyEnd->begin()->eraseFromParent(); 1437deefbcedSTobias Grosser new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd); 1438e114dc02SJohannes Doerfert continue; 1439e114dc02SJohannes Doerfert } 1440e114dc02SJohannes Doerfert 1441deefbcedSTobias Grosser Instruction *BICopy = BBCopyEnd->getTerminator(); 1442275a1756SJohannes Doerfert 1443deefbcedSTobias Grosser ValueMapT &RegionMap = RegionMaps[BBCopyStart]; 1444deefbcedSTobias Grosser RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end()); 1445514f6efaSJohannes Doerfert 144645e7944bSTobias Grosser Builder.SetInsertPoint(BICopy); 14479a132f36SJohannes Doerfert copyInstScalar(Stmt, TI, RegionMap, LTS); 1448275a1756SJohannes Doerfert BICopy->eraseFromParent(); 1449275a1756SJohannes Doerfert } 1450275a1756SJohannes Doerfert 1451ecff11dcSJohannes Doerfert // Add counting PHI nodes to all loops in the region that can be used as 1452a6d48f59SMichael Kruse // replacement for SCEVs referring to the old loop. 1453ecff11dcSJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1454ecff11dcSJohannes Doerfert Loop *L = LI.getLoopFor(BB); 1455bc29e0b2STobias Grosser if (L == nullptr || L->getHeader() != BB || !R->contains(L)) 1456ecff11dcSJohannes Doerfert continue; 1457ecff11dcSJohannes Doerfert 1458deefbcedSTobias Grosser BasicBlock *BBCopy = StartBlockMap[BB]; 1459ecff11dcSJohannes Doerfert Value *NullVal = Builder.getInt32(0); 1460ecff11dcSJohannes Doerfert PHINode *LoopPHI = 1461ecff11dcSJohannes Doerfert PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv"); 1462ecff11dcSJohannes Doerfert Instruction *LoopPHIInc = BinaryOperator::CreateAdd( 1463ecff11dcSJohannes Doerfert LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc"); 1464b8f58b53SDuncan P. N. Exon Smith LoopPHI->insertBefore(&BBCopy->front()); 1465ecff11dcSJohannes Doerfert LoopPHIInc->insertBefore(BBCopy->getTerminator()); 1466ecff11dcSJohannes Doerfert 1467ecff11dcSJohannes Doerfert for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) { 1468ecff11dcSJohannes Doerfert if (!R->contains(PredBB)) 1469ecff11dcSJohannes Doerfert continue; 1470ecff11dcSJohannes Doerfert if (L->contains(PredBB)) 1471deefbcedSTobias Grosser LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]); 1472ecff11dcSJohannes Doerfert else 1473deefbcedSTobias Grosser LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]); 1474ecff11dcSJohannes Doerfert } 1475ecff11dcSJohannes Doerfert 1476ecff11dcSJohannes Doerfert for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy))) 1477ecff11dcSJohannes Doerfert if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0) 1478ecff11dcSJohannes Doerfert LoopPHI->addIncoming(NullVal, PredBBCopy); 1479ecff11dcSJohannes Doerfert 1480ecff11dcSJohannes Doerfert LTS[L] = SE.getUnknown(LoopPHI); 1481ecff11dcSJohannes Doerfert } 1482ecff11dcSJohannes Doerfert 1483225f0d1eSMichael Kruse // Continue generating code in the exit block. 1484b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt()); 1485225f0d1eSMichael Kruse 1486225f0d1eSMichael Kruse // Write values visible to other statements. 14872fa35194SMichael Kruse generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp); 1488deefbcedSTobias Grosser StartBlockMap.clear(); 1489deefbcedSTobias Grosser EndBlockMap.clear(); 14903e956020STobias Grosser RegionMaps.clear(); 14913e956020STobias Grosser IncompletePHINodeMap.clear(); 1492275a1756SJohannes Doerfert } 1493ecff11dcSJohannes Doerfert 1494ee6a4fc6SMichael Kruse PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT <S, 1495ee6a4fc6SMichael Kruse ValueMapT &BBMap, Loop *L) { 1496ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1497ee6a4fc6SMichael Kruse Region *SubR = Stmt->getRegion(); 1498ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1499ee6a4fc6SMichael Kruse 1500ee6a4fc6SMichael Kruse PollyIRBuilder::InsertPointGuard IPGuard(Builder); 1501ee6a4fc6SMichael Kruse PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction()); 1502ee6a4fc6SMichael Kruse BasicBlock *NewSubregionExit = Builder.GetInsertBlock(); 1503ee6a4fc6SMichael Kruse 1504ee6a4fc6SMichael Kruse // This can happen if the subregion is simplified after the ScopStmts 1505ee6a4fc6SMichael Kruse // have been created; simplification happens as part of CodeGeneration. 1506ee6a4fc6SMichael Kruse if (OrigPHI->getParent() != SubR->getExit()) { 1507ee6a4fc6SMichael Kruse BasicBlock *FormerExit = SubR->getExitingBlock(); 1508ee6a4fc6SMichael Kruse if (FormerExit) 1509deefbcedSTobias Grosser NewSubregionExit = StartBlockMap.lookup(FormerExit); 1510ee6a4fc6SMichael Kruse } 1511ee6a4fc6SMichael Kruse 1512ee6a4fc6SMichael Kruse PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(), 1513ee6a4fc6SMichael Kruse "polly." + OrigPHI->getName(), 1514ee6a4fc6SMichael Kruse NewSubregionExit->getFirstNonPHI()); 1515ee6a4fc6SMichael Kruse 1516ee6a4fc6SMichael Kruse // Add the incoming values to the PHI. 1517ee6a4fc6SMichael Kruse for (auto &Pair : Incoming) { 1518ee6a4fc6SMichael Kruse BasicBlock *OrigIncomingBlock = Pair.first; 1519deefbcedSTobias Grosser BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock); 1520deefbcedSTobias Grosser BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock); 1521deefbcedSTobias Grosser Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator()); 1522deefbcedSTobias Grosser assert(RegionMaps.count(NewIncomingBlockStart)); 1523deefbcedSTobias Grosser assert(RegionMaps.count(NewIncomingBlockEnd)); 1524deefbcedSTobias Grosser ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart]; 1525ee6a4fc6SMichael Kruse 1526ee6a4fc6SMichael Kruse Value *OrigIncomingValue = Pair.second; 1527ee6a4fc6SMichael Kruse Value *NewIncomingValue = 1528ee6a4fc6SMichael Kruse getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L); 1529deefbcedSTobias Grosser NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd); 1530ee6a4fc6SMichael Kruse } 1531ee6a4fc6SMichael Kruse 1532ee6a4fc6SMichael Kruse return NewPHI; 1533ee6a4fc6SMichael Kruse } 1534ee6a4fc6SMichael Kruse 1535ee6a4fc6SMichael Kruse Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT <S, 1536ee6a4fc6SMichael Kruse ValueMapT &BBMap) { 1537ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1538ee6a4fc6SMichael Kruse 1539ee6a4fc6SMichael Kruse // TODO: Add some test cases that ensure this is really the right choice. 1540ee6a4fc6SMichael Kruse Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit()); 1541ee6a4fc6SMichael Kruse 1542ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 1543ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1544ee6a4fc6SMichael Kruse assert(!Incoming.empty() && 1545ee6a4fc6SMichael Kruse "PHI WRITEs must have originate from at least one incoming block"); 1546ee6a4fc6SMichael Kruse 1547ee6a4fc6SMichael Kruse // If there is only one incoming value, we do not need to create a PHI. 1548ee6a4fc6SMichael Kruse if (Incoming.size() == 1) { 1549ee6a4fc6SMichael Kruse Value *OldVal = Incoming[0].second; 1550ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1551ee6a4fc6SMichael Kruse } 1552ee6a4fc6SMichael Kruse 1553ee6a4fc6SMichael Kruse return buildExitPHI(MA, LTS, BBMap, L); 1554ee6a4fc6SMichael Kruse } 1555ee6a4fc6SMichael Kruse 15564d5a9172STobias Grosser // MemoryKind::Value accesses leaving the subregion must dominate the exit 15574d5a9172STobias Grosser // block; just pass the copied value. 1558ee6a4fc6SMichael Kruse Value *OldVal = MA->getAccessValue(); 1559ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1560ee6a4fc6SMichael Kruse } 1561ee6a4fc6SMichael Kruse 15622fa35194SMichael Kruse void RegionGenerator::generateScalarStores( 15632fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 15642fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 156575296901STobias Grosser assert(Stmt.getRegion() && 156675296901STobias Grosser "Block statements need to use the generateScalarStores() " 1567ecff11dcSJohannes Doerfert "function in the BlockGenerator"); 1568ecff11dcSJohannes Doerfert 1569ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 15702fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 1571ecff11dcSJohannes Doerfert continue; 1572ecff11dcSJohannes Doerfert 15731515f6b9STobias Grosser isl::set AccDom = MA->getAccessRelation().domain(); 1574fe46c3ffSTobias Grosser std::string Subject = MA->getId().get_name(); 1575fe46c3ffSTobias Grosser generateConditionalExecution( 1576fe46c3ffSTobias Grosser Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 1577706f79abSMichael Kruse 1578ee6a4fc6SMichael Kruse Value *NewVal = getExitScalar(MA, LTS, BBMap); 1579fe46c3ffSTobias Grosser Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 1580fe46c3ffSTobias Grosser BBMap, NewAccesses); 1581eac9726eSMichael Kruse assert((!isa<Instruction>(NewVal) || 1582eac9726eSMichael Kruse DT.dominates(cast<Instruction>(NewVal)->getParent(), 1583eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1584eac9726eSMichael Kruse "Domination violation"); 1585eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 1586eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 1587eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1588eac9726eSMichael Kruse "Domination violation"); 1589ee6a4fc6SMichael Kruse Builder.CreateStore(NewVal, Address); 1590706f79abSMichael Kruse }); 1591ecff11dcSJohannes Doerfert } 1592ecff11dcSJohannes Doerfert } 1593ecff11dcSJohannes Doerfert 1594943c369cSTobias Grosser void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, 1595ecff11dcSJohannes Doerfert PHINode *PHICopy, BasicBlock *IncomingBB, 1596ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1597ecff11dcSJohannes Doerfert // If the incoming block was not yet copied mark this PHI as incomplete. 1598ecff11dcSJohannes Doerfert // Once the block will be copied the incoming value will be added. 1599deefbcedSTobias Grosser BasicBlock *BBCopyStart = StartBlockMap[IncomingBB]; 1600deefbcedSTobias Grosser BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB]; 1601deefbcedSTobias Grosser if (!BBCopyStart) { 1602deefbcedSTobias Grosser assert(!BBCopyEnd); 1603*8d89179eSMichael Kruse assert(Stmt.represents(IncomingBB) && 1604ecff11dcSJohannes Doerfert "Bad incoming block for PHI in non-affine region"); 1605ecff11dcSJohannes Doerfert IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy)); 1606ecff11dcSJohannes Doerfert return; 1607ecff11dcSJohannes Doerfert } 1608ecff11dcSJohannes Doerfert 1609deefbcedSTobias Grosser assert(RegionMaps.count(BBCopyStart) && 1610deefbcedSTobias Grosser "Incoming PHI block did not have a BBMap"); 1611deefbcedSTobias Grosser ValueMapT &BBCopyMap = RegionMaps[BBCopyStart]; 1612ecff11dcSJohannes Doerfert 161375dfaa1dSTobias Grosser Value *OpCopy = nullptr; 161475dfaa1dSTobias Grosser 1615*8d89179eSMichael Kruse if (Stmt.represents(IncomingBB)) { 1616ecff11dcSJohannes Doerfert Value *Op = PHI->getIncomingValueForBlock(IncomingBB); 1617dc122222SMichael Kruse 16186ba92714SJohannes Doerfert // If the current insert block is different from the PHIs incoming block 16196ba92714SJohannes Doerfert // change it, otherwise do not. 16206ba92714SJohannes Doerfert auto IP = Builder.GetInsertPoint(); 1621deefbcedSTobias Grosser if (IP->getParent() != BBCopyEnd) 1622deefbcedSTobias Grosser Builder.SetInsertPoint(BBCopyEnd->getTerminator()); 16232c3ffc04SJohannes Doerfert OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1624deefbcedSTobias Grosser if (IP->getParent() != BBCopyEnd) 16256ba92714SJohannes Doerfert Builder.SetInsertPoint(&*IP); 1626ecff11dcSJohannes Doerfert } else { 162775dfaa1dSTobias Grosser // All edges from outside the non-affine region become a single edge 162875dfaa1dSTobias Grosser // in the new copy of the non-affine region. Make sure to only add the 162975dfaa1dSTobias Grosser // corresponding edge the first time we encounter a basic block from 163075dfaa1dSTobias Grosser // outside the non-affine region. 1631deefbcedSTobias Grosser if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0) 1632ecff11dcSJohannes Doerfert return; 1633ecff11dcSJohannes Doerfert 163475dfaa1dSTobias Grosser // Get the reloaded value. 163575dfaa1dSTobias Grosser OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1636ecff11dcSJohannes Doerfert } 1637ecff11dcSJohannes Doerfert 1638ecff11dcSJohannes Doerfert assert(OpCopy && "Incoming PHI value was not copied properly"); 1639deefbcedSTobias Grosser PHICopy->addIncoming(OpCopy, BBCopyEnd); 1640ecff11dcSJohannes Doerfert } 1641ecff11dcSJohannes Doerfert 16422b809d13STobias Grosser void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI, 1643ecff11dcSJohannes Doerfert ValueMapT &BBMap, 1644ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1645ecff11dcSJohannes Doerfert unsigned NumIncoming = PHI->getNumIncomingValues(); 1646ecff11dcSJohannes Doerfert PHINode *PHICopy = 1647ecff11dcSJohannes Doerfert Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName()); 1648ecff11dcSJohannes Doerfert PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI()); 1649ecff11dcSJohannes Doerfert BBMap[PHI] = PHICopy; 1650ecff11dcSJohannes Doerfert 165197b84909STobias Grosser for (BasicBlock *IncomingBB : PHI->blocks()) 165297b84909STobias Grosser addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS); 1653ecff11dcSJohannes Doerfert } 1654