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 240188053afSSingapuram Sanjay Srivallabh // When copying the instruction onto the Module meant for the GPU, 241188053afSSingapuram Sanjay Srivallabh // debug metadata attached to an instruction causes all related 242188053afSSingapuram Sanjay Srivallabh // metadata to be pulled into the Module. This includes the DICompileUnit, 243188053afSSingapuram Sanjay Srivallabh // which will not be listed in llvm.dbg.cu of the Module since the Module 244188053afSSingapuram Sanjay Srivallabh // doesn't contain one. This fails the verification of the Module and the 245188053afSSingapuram Sanjay Srivallabh // subsequent generation of the ASM string. 246188053afSSingapuram Sanjay Srivallabh if (NewInst->getModule() != Inst->getModule()) 247188053afSSingapuram Sanjay Srivallabh NewInst->setDebugLoc(llvm::DebugLoc()); 248188053afSSingapuram Sanjay Srivallabh 2493b11a16aSHongbin Zheng if (!NewInst->getType()->isVoidTy()) 2503b11a16aSHongbin Zheng NewInst->setName("p_" + Inst->getName()); 2513b11a16aSHongbin Zheng } 2523b11a16aSHongbin Zheng 25370131d34SMichael Kruse Value * 25470131d34SMichael Kruse BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, 25570131d34SMichael Kruse ValueMapT &BBMap, LoopToScevMapT <S, 25670131d34SMichael Kruse isl_id_to_ast_expr *NewAccesses) { 25709214772STobias Grosser const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst); 2582fa35194SMichael Kruse return generateLocationAccessed( 2592fa35194SMichael Kruse Stmt, getLoopForStmt(Stmt), 2602fa35194SMichael Kruse Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS, 261fe46c3ffSTobias Grosser NewAccesses, MA.getId().release(), MA.getAccessValue()->getType()); 2622fa35194SMichael Kruse } 2633b11a16aSHongbin Zheng 2642fa35194SMichael Kruse Value *BlockGenerator::generateLocationAccessed( 2652fa35194SMichael Kruse ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap, 2662fa35194SMichael Kruse LoopToScevMapT <S, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id, 2672fa35194SMichael Kruse Type *ExpectedType) { 2682fa35194SMichael Kruse isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id); 2693b11a16aSHongbin Zheng 2702d1ed0bfSTobias Grosser if (AccessExpr) { 2712d1ed0bfSTobias Grosser AccessExpr = isl_ast_expr_address_of(AccessExpr); 27298b3ee50STobias Grosser auto Address = ExprBuilder->create(AccessExpr); 27398b3ee50STobias Grosser 27498b3ee50STobias Grosser // Cast the address of this memory access to a pointer type that has the 27598b3ee50STobias Grosser // same element type as the original access, but uses the address space of 27698b3ee50STobias Grosser // the newly generated pointer. 2772fa35194SMichael Kruse auto OldPtrTy = ExpectedType->getPointerTo(); 27898b3ee50STobias Grosser auto NewPtrTy = Address->getType(); 27998b3ee50STobias Grosser OldPtrTy = PointerType::get(OldPtrTy->getElementType(), 28098b3ee50STobias Grosser NewPtrTy->getPointerAddressSpace()); 28198b3ee50STobias Grosser 282d840fc72STobias Grosser if (OldPtrTy != NewPtrTy) 28398b3ee50STobias Grosser Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy); 28498b3ee50STobias Grosser return Address; 2852d1ed0bfSTobias Grosser } 2862fa35194SMichael Kruse assert( 2872fa35194SMichael Kruse Pointer && 2882fa35194SMichael Kruse "If expression was not generated, must use the original pointer value"); 2892fa35194SMichael Kruse return getNewValue(Stmt, Pointer, BBMap, LTS, L); 2902fa35194SMichael Kruse } 2912d1ed0bfSTobias Grosser 2922fa35194SMichael Kruse Value * 2932fa35194SMichael Kruse BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L, 2942fa35194SMichael Kruse LoopToScevMapT <S, ValueMapT &BBMap, 2952fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 2962fa35194SMichael Kruse if (Access.isLatestArrayKind()) 2972fa35194SMichael Kruse return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap, 298fe46c3ffSTobias Grosser LTS, NewAccesses, Access.getId().release(), 2992fa35194SMichael Kruse Access.getAccessValue()->getType()); 3002fa35194SMichael Kruse 301587f1f57STobias Grosser return getOrCreateAlloca(Access); 3023b11a16aSHongbin Zheng } 3033b11a16aSHongbin Zheng 3042c3ffc04SJohannes Doerfert Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const { 305375cb5feSMichael Kruse auto *StmtBB = Stmt.getEntryBlock(); 3062c3ffc04SJohannes Doerfert return LI.getLoopFor(StmtBB); 307369430ffSTobias Grosser } 308369430ffSTobias Grosser 309888ab551SMichael Kruse Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load, 310bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3112d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 312c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) 313c1db67e2SJohannes Doerfert return PreloadLoad; 314c1db67e2SJohannes Doerfert 315bc132607STobias Grosser Value *NewPointer = 31670131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses); 31787901453SJohannes Doerfert Value *ScalarLoad = Builder.CreateAlignedLoad( 31887901453SJohannes Doerfert NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_"); 31986bc93a9STobias Grosser 3201be726a4STobias Grosser if (PollyDebugPrinting) 32186bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer, 32286bc93a9STobias Grosser ": ", ScalarLoad, "\n"); 32386bc93a9STobias Grosser 3243b11a16aSHongbin Zheng return ScalarLoad; 3253b11a16aSHongbin Zheng } 3263b11a16aSHongbin Zheng 327888ab551SMichael Kruse void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store, 328bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3292d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 330706f79abSMichael Kruse MemoryAccess &MA = Stmt.getArrayAccessFor(Store); 3311515f6b9STobias Grosser isl::set AccDom = MA.getAccessRelation().domain(); 332fe46c3ffSTobias Grosser std::string Subject = MA.getId().get_name(); 333706f79abSMichael Kruse 334fe46c3ffSTobias Grosser generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() { 335bc132607STobias Grosser Value *NewPointer = 33670131d34SMichael Kruse generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses); 337706f79abSMichael Kruse Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, 338706f79abSMichael Kruse LTS, getLoopForStmt(Stmt)); 3393b11a16aSHongbin Zheng 3401be726a4STobias Grosser if (PollyDebugPrinting) 34186bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer, 34286bc93a9STobias Grosser ": ", ValueOperand, "\n"); 34386bc93a9STobias Grosser 344c186ac7aSTobias Grosser Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment()); 345706f79abSMichael Kruse }); 3463b11a16aSHongbin Zheng } 3473b11a16aSHongbin Zheng 3485dced269SJohannes Doerfert bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) { 3492c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 3505dced269SJohannes Doerfert return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) && 35111c5e079SMichael Kruse canSynthesize(Inst, *Stmt.getParent(), &SE, L); 3525dced269SJohannes Doerfert } 3535dced269SJohannes Doerfert 3542f1acac6STobias Grosser void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst, 355bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3562d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 3573b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 3583b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 3593b11a16aSHongbin Zheng if (Inst->isTerminator()) 3603b11a16aSHongbin Zheng return; 3613b11a16aSHongbin Zheng 362aff56c8aSTobias Grosser // Synthesizable statements will be generated on-demand. 3635dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 364e71c6ab5STobias Grosser return; 365e71c6ab5STobias Grosser 3669646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 367888ab551SMichael Kruse Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses); 3683d94fedfSSebastian Pop // Compute NewLoad before its insertion in BBMap to make the insertion 3693d94fedfSSebastian Pop // deterministic. 370753d43f9SSebastian Pop BBMap[Load] = NewLoad; 3713b11a16aSHongbin Zheng return; 3723b11a16aSHongbin Zheng } 3733b11a16aSHongbin Zheng 3749646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 3750446d81eSMichael Kruse // Identified as redundant by -polly-simplify. 3760446d81eSMichael Kruse if (!Stmt.getArrayAccessOrNULLFor(Store)) 3770446d81eSMichael Kruse return; 3780446d81eSMichael Kruse 379888ab551SMichael Kruse generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses); 3803b11a16aSHongbin Zheng return; 3813b11a16aSHongbin Zheng } 3823b11a16aSHongbin Zheng 3839646e3feSTobias Grosser if (auto *PHI = dyn_cast<PHINode>(Inst)) { 384bc132607STobias Grosser copyPHIInstruction(Stmt, PHI, BBMap, LTS); 385ecff11dcSJohannes Doerfert return; 386ecff11dcSJohannes Doerfert } 387ecff11dcSJohannes Doerfert 3883f500fa2SJohannes Doerfert // Skip some special intrinsics for which we do not adjust the semantics to 3893f500fa2SJohannes Doerfert // the new schedule. All others are handled like every other instruction. 3909c0ffe3aSTobias Grosser if (isIgnoredIntrinsic(Inst)) 3913f500fa2SJohannes Doerfert return; 3923f500fa2SJohannes Doerfert 393bc132607STobias Grosser copyInstScalar(Stmt, Inst, BBMap, LTS); 3943b11a16aSHongbin Zheng } 3953b11a16aSHongbin Zheng 3969d12d8adSTobias Grosser void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) { 397c59b3ce0STobias Grosser auto NewBB = Builder.GetInsertBlock(); 398c59b3ce0STobias Grosser for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) { 399c59b3ce0STobias Grosser Instruction *NewInst = &*I; 4009d12d8adSTobias Grosser 4019d12d8adSTobias Grosser if (!isInstructionTriviallyDead(NewInst)) 4029d12d8adSTobias Grosser continue; 4039d12d8adSTobias Grosser 404c59b3ce0STobias Grosser for (auto Pair : BBMap) 405c59b3ce0STobias Grosser if (Pair.second == NewInst) { 406c59b3ce0STobias Grosser BBMap.erase(Pair.first); 407c59b3ce0STobias Grosser } 408c59b3ce0STobias Grosser 4099d12d8adSTobias Grosser NewInst->eraseFromParent(); 410c59b3ce0STobias Grosser I = NewBB->rbegin(); 4119d12d8adSTobias Grosser } 4129d12d8adSTobias Grosser } 4139d12d8adSTobias Grosser 414bc132607STobias Grosser void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 4152d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 416275a1756SJohannes Doerfert assert(Stmt.isBlockStmt() && 417275a1756SJohannes Doerfert "Only block statements can be copied by the block generator"); 418275a1756SJohannes Doerfert 419275a1756SJohannes Doerfert ValueMapT BBMap; 420275a1756SJohannes Doerfert 421be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 422bc132607STobias Grosser copyBB(Stmt, BB, BBMap, LTS, NewAccesses); 4239d12d8adSTobias Grosser removeDeadInstructions(BB, BBMap); 424275a1756SJohannes Doerfert } 425275a1756SJohannes Doerfert 426514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) { 427b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 428b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 4293b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 430514f6efaSJohannes Doerfert return CopyBB; 431514f6efaSJohannes Doerfert } 4323b11a16aSHongbin Zheng 433514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, 434bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 4352d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 436514f6efaSJohannes Doerfert BasicBlock *CopyBB = splitBB(BB); 437b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 4382fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, BBMap, NewAccesses); 439225f0d1eSMichael Kruse 440bc132607STobias Grosser copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses); 441225f0d1eSMichael Kruse 442225f0d1eSMichael Kruse // After a basic block was copied store all scalars that escape this block in 443225f0d1eSMichael Kruse // their alloca. 4442fa35194SMichael Kruse generateScalarStores(Stmt, LTS, BBMap, NewAccesses); 445514f6efaSJohannes Doerfert return CopyBB; 446514f6efaSJohannes Doerfert } 447514f6efaSJohannes Doerfert 448514f6efaSJohannes Doerfert void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB, 449bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 4502d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 451ecff11dcSJohannes Doerfert EntryBB = &CopyBB->getParent()->getEntryBlock(); 452ecff11dcSJohannes Doerfert 4533bb48299SMichael Kruse if (Stmt.isBlockStmt()) 4543bb48299SMichael Kruse for (Instruction *Inst : Stmt.getInstructions()) 4553bb48299SMichael Kruse copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses); 4563bb48299SMichael Kruse else 45791f5b262STobias Grosser for (Instruction &Inst : *BB) 458bc132607STobias Grosser copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses); 459ecff11dcSJohannes Doerfert } 460ecff11dcSJohannes Doerfert 461800e17a7SJohannes Doerfert Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) { 462587f1f57STobias Grosser assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind"); 4633216f854STobias Grosser 464587f1f57STobias Grosser return getOrCreateAlloca(Access.getLatestScopArrayInfo()); 465a4f0988dSTobias Grosser } 466a4f0988dSTobias Grosser 467a4f0988dSTobias Grosser Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) { 4683216f854STobias Grosser assert(!Array->isArrayKind() && "Trying to get alloca for array kind"); 4693216f854STobias Grosser 470587f1f57STobias Grosser auto &Addr = ScalarMap[Array]; 471587f1f57STobias Grosser 472587f1f57STobias Grosser if (Addr) { 473587f1f57STobias Grosser // Allow allocas to be (temporarily) redirected once by adding a new 474a6d48f59SMichael Kruse // old-alloca-addr to new-addr mapping to GlobalMap. This functionality 475587f1f57STobias Grosser // is used for example by the OpenMP code generation where a first use 476587f1f57STobias Grosser // of a scalar while still in the host code allocates a normal alloca with 477587f1f57STobias Grosser // getOrCreateAlloca. When the values of this scalar are accessed during 478587f1f57STobias Grosser // the generation of the parallel subfunction, these values are copied over 479587f1f57STobias Grosser // to the parallel subfunction and each request for a scalar alloca slot 480a6d48f59SMichael Kruse // must be forwarded to the temporary in-subfunction slot. This mapping is 481587f1f57STobias Grosser // removed when the subfunction has been generated and again normal host 482682c5114STobias Grosser // code is generated. Due to the following reasons it is not possible to 483682c5114STobias Grosser // perform the GlobalMap lookup right after creating the alloca below, but 484682c5114STobias Grosser // instead we need to check GlobalMap at each call to getOrCreateAlloca: 485682c5114STobias Grosser // 486682c5114STobias Grosser // 1) GlobalMap may be changed multiple times (for each parallel loop), 487682c5114STobias Grosser // 2) The temporary mapping is commonly only known after the initial 488682c5114STobias Grosser // alloca has already been generated, and 489682c5114STobias Grosser // 3) The original alloca value must be restored after leaving the 490682c5114STobias Grosser // sub-function. 491587f1f57STobias Grosser if (Value *NewAddr = GlobalMap.lookup(&*Addr)) 492587f1f57STobias Grosser return NewAddr; 493587f1f57STobias Grosser return Addr; 494587f1f57STobias Grosser } 495587f1f57STobias Grosser 496587f1f57STobias Grosser Type *Ty = Array->getElementType(); 497587f1f57STobias Grosser Value *ScalarBase = Array->getBasePtr(); 498587f1f57STobias Grosser std::string NameExt; 499a535dff4STobias Grosser if (Array->isPHIKind()) 500587f1f57STobias Grosser NameExt = ".phiops"; 501f8d55f7eSTobias Grosser else 502587f1f57STobias Grosser NameExt = ".s2a"; 503587f1f57STobias Grosser 5047b5a4dfdSTobias Grosser const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout(); 505b3e30c32SMatt Arsenault 506b3e30c32SMatt Arsenault Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(), 507b3e30c32SMatt Arsenault ScalarBase->getName() + NameExt); 508587f1f57STobias Grosser EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 509587f1f57STobias Grosser Addr->insertBefore(&*EntryBB->getFirstInsertionPt()); 510587f1f57STobias Grosser 511587f1f57STobias Grosser return Addr; 512f8d55f7eSTobias Grosser } 513f8d55f7eSTobias Grosser 514587f1f57STobias Grosser void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) { 515587f1f57STobias Grosser Instruction *Inst = cast<Instruction>(Array->getBasePtr()); 516b79a67dfSTobias Grosser 5172985400aSTobias Grosser // If there are escape users we get the alloca for this instruction and put it 5182985400aSTobias Grosser // in the EscapeMap for later finalization. Lastly, if the instruction was 5192985400aSTobias Grosser // copied multiple times we already did this and can exit. 520acb6ade7SMichael Kruse if (EscapeMap.count(Inst)) 521acb6ade7SMichael Kruse return; 522e69e1141SJohannes Doerfert 523ecff11dcSJohannes Doerfert EscapeUserVectorTy EscapeUsers; 524ecff11dcSJohannes Doerfert for (User *U : Inst->users()) { 525ecff11dcSJohannes Doerfert 526ecff11dcSJohannes Doerfert // Non-instruction user will never escape. 527ecff11dcSJohannes Doerfert Instruction *UI = dyn_cast<Instruction>(U); 528ecff11dcSJohannes Doerfert if (!UI) 529ecff11dcSJohannes Doerfert continue; 530ecff11dcSJohannes Doerfert 531952b5304SJohannes Doerfert if (S.contains(UI)) 532ecff11dcSJohannes Doerfert continue; 533ecff11dcSJohannes Doerfert 534ecff11dcSJohannes Doerfert EscapeUsers.push_back(UI); 535ecff11dcSJohannes Doerfert } 536ecff11dcSJohannes Doerfert 537ecff11dcSJohannes Doerfert // Exit if no escape uses were found. 538ecff11dcSJohannes Doerfert if (EscapeUsers.empty()) 539ecff11dcSJohannes Doerfert return; 540ecff11dcSJohannes Doerfert 541ecff11dcSJohannes Doerfert // Get or create an escape alloca for this instruction. 542587f1f57STobias Grosser auto *ScalarAddr = getOrCreateAlloca(Array); 543ecff11dcSJohannes Doerfert 544ecff11dcSJohannes Doerfert // Remember that this instruction has escape uses and the escape alloca. 545ecff11dcSJohannes Doerfert EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers)); 546ecff11dcSJohannes Doerfert } 547ecff11dcSJohannes Doerfert 5482fa35194SMichael Kruse void BlockGenerator::generateScalarLoads( 5492fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 5502fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 551225f0d1eSMichael Kruse for (MemoryAccess *MA : Stmt) { 5522fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isWrite()) 553ecff11dcSJohannes Doerfert continue; 554ecff11dcSJohannes Doerfert 55577394f13SMichael Kruse #ifndef NDEBUG 556dcf8d696STobias Grosser auto *StmtDom = Stmt.getDomain().release(); 5571515f6b9STobias Grosser auto *AccDom = isl_map_domain(MA->getAccessRelation().release()); 55877394f13SMichael Kruse assert(isl_set_is_subset(StmtDom, AccDom) && 55977394f13SMichael Kruse "Scalar must be loaded in all statement instances"); 56077394f13SMichael Kruse isl_set_free(StmtDom); 56177394f13SMichael Kruse isl_set_free(AccDom); 56277394f13SMichael Kruse #endif 56377394f13SMichael Kruse 5642fa35194SMichael Kruse auto *Address = 5652fa35194SMichael Kruse getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 566eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 567eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 568eac9726eSMichael Kruse Builder.GetInsertBlock())) && 569eac9726eSMichael Kruse "Domination violation"); 570583be06fSTobias Grosser BBMap[MA->getAccessValue()] = 5712fc50df9STobias Grosser Builder.CreateLoad(Address, Address->getName() + ".reload"); 572ecff11dcSJohannes Doerfert } 573ecff11dcSJohannes Doerfert } 574ecff11dcSJohannes Doerfert 575706f79abSMichael Kruse Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt, 576706f79abSMichael Kruse const isl::set &Subdomain) { 577132860afSTobias Grosser isl::ast_build AstBuild = Stmt.getAstBuild(); 578dcf8d696STobias Grosser isl::set Domain = Stmt.getDomain(); 579706f79abSMichael Kruse 5806b6ac900STobias Grosser isl::union_map USchedule = AstBuild.get_schedule(); 5816b6ac900STobias Grosser USchedule = USchedule.intersect_domain(Domain); 582706f79abSMichael Kruse 5836b6ac900STobias Grosser assert(!USchedule.is_empty()); 5846b6ac900STobias Grosser isl::map Schedule = isl::map::from_union_map(USchedule); 585706f79abSMichael Kruse 5866b6ac900STobias Grosser isl::set ScheduledDomain = Schedule.range(); 5876b6ac900STobias Grosser isl::set ScheduledSet = Subdomain.apply(Schedule); 588706f79abSMichael Kruse 5896b6ac900STobias Grosser isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain); 5906b6ac900STobias Grosser 5916b6ac900STobias Grosser isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet); 592706f79abSMichael Kruse Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy()); 593706f79abSMichael Kruse IsInSetExpr = Builder.CreateICmpNE( 594706f79abSMichael Kruse IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0)); 595706f79abSMichael Kruse 596706f79abSMichael Kruse return IsInSetExpr; 597706f79abSMichael Kruse } 598706f79abSMichael Kruse 599706f79abSMichael Kruse void BlockGenerator::generateConditionalExecution( 600706f79abSMichael Kruse ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject, 601706f79abSMichael Kruse const std::function<void()> &GenThenFunc) { 602dcf8d696STobias Grosser isl::set StmtDom = Stmt.getDomain(); 603706f79abSMichael Kruse 604706f79abSMichael Kruse // Don't call GenThenFunc if it is never executed. An ast index expression 605706f79abSMichael Kruse // might not be defined in this case. 6066b6ac900STobias Grosser if (Subdomain.is_empty()) 607706f79abSMichael Kruse return; 608706f79abSMichael Kruse 609706f79abSMichael Kruse // If the condition is a tautology, don't generate a condition around the 610706f79abSMichael Kruse // code. 611f51decb5STobias Grosser bool IsPartialWrite = 612*8ea1fc19STobias Grosser !StmtDom.intersect_params(Stmt.getParent()->getContext()) 613f51decb5STobias Grosser .is_subset(Subdomain); 614f51decb5STobias Grosser if (!IsPartialWrite) { 615706f79abSMichael Kruse GenThenFunc(); 616706f79abSMichael Kruse return; 617706f79abSMichael Kruse } 618706f79abSMichael Kruse 619706f79abSMichael Kruse // Generate the condition. 620706f79abSMichael Kruse Value *Cond = buildContainsCondition(Stmt, Subdomain); 621706f79abSMichael Kruse BasicBlock *HeadBlock = Builder.GetInsertBlock(); 622706f79abSMichael Kruse StringRef BlockName = HeadBlock->getName(); 623706f79abSMichael Kruse 624706f79abSMichael Kruse // Generate the conditional block. 625706f79abSMichael Kruse SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr, 626706f79abSMichael Kruse &DT, &LI); 627706f79abSMichael Kruse BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator()); 628706f79abSMichael Kruse BasicBlock *ThenBlock = Branch->getSuccessor(0); 629706f79abSMichael Kruse BasicBlock *TailBlock = Branch->getSuccessor(1); 630706f79abSMichael Kruse 631706f79abSMichael Kruse // Assign descriptive names. 632706f79abSMichael Kruse if (auto *CondInst = dyn_cast<Instruction>(Cond)) 633706f79abSMichael Kruse CondInst->setName("polly." + Subject + ".cond"); 634706f79abSMichael Kruse ThenBlock->setName(BlockName + "." + Subject + ".partial"); 635706f79abSMichael Kruse TailBlock->setName(BlockName + ".cont"); 636706f79abSMichael Kruse 637706f79abSMichael Kruse // Put the client code into the conditional block and continue in the merge 638706f79abSMichael Kruse // block afterwards. 639706f79abSMichael Kruse Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt()); 640706f79abSMichael Kruse GenThenFunc(); 641706f79abSMichael Kruse Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt()); 642706f79abSMichael Kruse } 643706f79abSMichael Kruse 6442fa35194SMichael Kruse void BlockGenerator::generateScalarStores( 6452fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 6462fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 647f2cdd144STobias Grosser Loop *L = LI.getLoopFor(Stmt.getBasicBlock()); 648ecff11dcSJohannes Doerfert 64921a059afSTobias Grosser assert(Stmt.isBlockStmt() && 65021a059afSTobias Grosser "Region statements need to use the generateScalarStores() function in " 65121a059afSTobias Grosser "the RegionGenerator"); 652ecff11dcSJohannes Doerfert 653ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 6542fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 655ecff11dcSJohannes Doerfert continue; 656ecff11dcSJohannes Doerfert 6571515f6b9STobias Grosser isl::set AccDom = MA->getAccessRelation().domain(); 658fe46c3ffSTobias Grosser std::string Subject = MA->getId().get_name(); 65977394f13SMichael Kruse 660fe46c3ffSTobias Grosser generateConditionalExecution( 661fe46c3ffSTobias Grosser Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 662d86f2157SJohannes Doerfert Value *Val = MA->getAccessValue(); 663ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 664fe46c3ffSTobias Grosser assert(MA->getIncoming().size() >= 1 && 665fe46c3ffSTobias Grosser "Block statements have exactly one exiting block, or " 666fe46c3ffSTobias Grosser "multiple but " 667ee6a4fc6SMichael Kruse "with same incoming block and value"); 668fe46c3ffSTobias Grosser assert(std::all_of(MA->getIncoming().begin(), 669fe46c3ffSTobias Grosser MA->getIncoming().end(), 670ee6a4fc6SMichael Kruse [&](std::pair<BasicBlock *, Value *> p) -> bool { 671ee6a4fc6SMichael Kruse return p.first == Stmt.getBasicBlock(); 672ee6a4fc6SMichael Kruse }) && 673ee6a4fc6SMichael Kruse "Incoming block must be statement's block"); 674ee6a4fc6SMichael Kruse Val = MA->getIncoming()[0].second; 675ee6a4fc6SMichael Kruse } 676fe46c3ffSTobias Grosser auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 677fe46c3ffSTobias Grosser BBMap, NewAccesses); 678d86f2157SJohannes Doerfert 679f2cdd144STobias Grosser Val = getNewValue(Stmt, Val, BBMap, LTS, L); 680eac9726eSMichael Kruse assert((!isa<Instruction>(Val) || 681eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Val)->getParent(), 682eac9726eSMichael Kruse Builder.GetInsertBlock())) && 683eac9726eSMichael Kruse "Domination violation"); 684eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 685eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 686eac9726eSMichael Kruse Builder.GetInsertBlock())) && 687eac9726eSMichael Kruse "Domination violation"); 68892245228STobias Grosser Builder.CreateStore(Val, Address); 689706f79abSMichael Kruse 690706f79abSMichael Kruse }); 691ecff11dcSJohannes Doerfert } 692ecff11dcSJohannes Doerfert } 693ecff11dcSJohannes Doerfert 694c0091a77STobias Grosser void BlockGenerator::createScalarInitialization(Scop &S) { 695ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExit(); 696acf80064SEli Friedman BasicBlock *PreEntryBB = S.getEnteringBlock(); 697188542fdSJohannes Doerfert 698acf80064SEli Friedman Builder.SetInsertPoint(&*StartBlock->begin()); 699ecff11dcSJohannes Doerfert 700d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 701c0091a77STobias Grosser if (Array->getNumberOfDimensions() != 0) 702c0091a77STobias Grosser continue; 703a535dff4STobias Grosser if (Array->isPHIKind()) { 704c0091a77STobias Grosser // For PHI nodes, the only values we need to store are the ones that 705c0091a77STobias Grosser // reach the PHI node from outside the region. In general there should 706c0091a77STobias Grosser // only be one such incoming edge and this edge should enter through 707acf80064SEli Friedman // 'PreEntryBB'. 708c0091a77STobias Grosser auto PHI = cast<PHINode>(Array->getBasePtr()); 709ecff11dcSJohannes Doerfert 710c0091a77STobias Grosser for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++) 711acf80064SEli Friedman if (!S.contains(*BI) && *BI != PreEntryBB) 712c0091a77STobias Grosser llvm_unreachable("Incoming edges from outside the scop should always " 713acf80064SEli Friedman "come from PreEntryBB"); 714c0091a77STobias Grosser 715acf80064SEli Friedman int Idx = PHI->getBasicBlockIndex(PreEntryBB); 716c0091a77STobias Grosser if (Idx < 0) 717ecff11dcSJohannes Doerfert continue; 718ecff11dcSJohannes Doerfert 719c0091a77STobias Grosser Value *ScalarValue = PHI->getIncomingValue(Idx); 720ecff11dcSJohannes Doerfert 721587f1f57STobias Grosser Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array)); 722c0091a77STobias Grosser continue; 723c0091a77STobias Grosser } 724c0091a77STobias Grosser 725c0091a77STobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 726c0091a77STobias Grosser 727952b5304SJohannes Doerfert if (Inst && S.contains(Inst)) 728c0091a77STobias Grosser continue; 729c0091a77STobias Grosser 730188542fdSJohannes Doerfert // PHI nodes that are not marked as such in their SAI object are either exit 731188542fdSJohannes Doerfert // PHI nodes we model as common scalars but without initialization, or 732188542fdSJohannes Doerfert // incoming phi nodes that need to be initialized. Check if the first is the 733188542fdSJohannes Doerfert // case for Inst and do not create and initialize memory if so. 734188542fdSJohannes Doerfert if (auto *PHI = dyn_cast_or_null<PHINode>(Inst)) 735188542fdSJohannes Doerfert if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0) 736717b8667SJohannes Doerfert continue; 737717b8667SJohannes Doerfert 738587f1f57STobias Grosser Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array)); 739ecff11dcSJohannes Doerfert } 740ecff11dcSJohannes Doerfert } 741ecff11dcSJohannes Doerfert 742ef74443cSJohannes Doerfert void BlockGenerator::createScalarFinalization(Scop &S) { 743ecff11dcSJohannes Doerfert // The exit block of the __unoptimized__ region. 744ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExitingBlock(); 745ecff11dcSJohannes Doerfert // The merge block __just after__ the region and the optimized region. 746ef74443cSJohannes Doerfert BasicBlock *MergeBB = S.getExit(); 747ecff11dcSJohannes Doerfert 748ecff11dcSJohannes Doerfert // The exit block of the __optimized__ region. 749ecff11dcSJohannes Doerfert BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 750ecff11dcSJohannes Doerfert if (OptExitBB == ExitBB) 751ecff11dcSJohannes Doerfert OptExitBB = *(++pred_begin(MergeBB)); 752ecff11dcSJohannes Doerfert 753ecff11dcSJohannes Doerfert Builder.SetInsertPoint(OptExitBB->getTerminator()); 754ecff11dcSJohannes Doerfert for (const auto &EscapeMapping : EscapeMap) { 755ecff11dcSJohannes Doerfert // Extract the escaping instruction and the escaping users as well as the 756ecff11dcSJohannes Doerfert // alloca the instruction was demoted to. 757fbde4355SMichael Kruse Instruction *EscapeInst = EscapeMapping.first; 758fbde4355SMichael Kruse const auto &EscapeMappingValue = EscapeMapping.second; 759ecff11dcSJohannes Doerfert const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second; 76064c0ff41STobias Grosser Value *ScalarAddr = EscapeMappingValue.first; 761ecff11dcSJohannes Doerfert 762ecff11dcSJohannes Doerfert // Reload the demoted instruction in the optimized version of the SCoP. 763d8b6ad25SJohannes Doerfert Value *EscapeInstReload = 764ecff11dcSJohannes Doerfert Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload"); 765d8b6ad25SJohannes Doerfert EscapeInstReload = 766d8b6ad25SJohannes Doerfert Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType()); 767ecff11dcSJohannes Doerfert 768ecff11dcSJohannes Doerfert // Create the merge PHI that merges the optimized and unoptimized version. 769ecff11dcSJohannes Doerfert PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2, 770ecff11dcSJohannes Doerfert EscapeInst->getName() + ".merge"); 771b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 772ecff11dcSJohannes Doerfert 773ecff11dcSJohannes Doerfert // Add the respective values to the merge PHI. 774ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInstReload, OptExitBB); 775ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInst, ExitBB); 776ecff11dcSJohannes Doerfert 777ecff11dcSJohannes Doerfert // The information of scalar evolution about the escaping instruction needs 778ecff11dcSJohannes Doerfert // to be revoked so the new merged instruction will be used. 779ecff11dcSJohannes Doerfert if (SE.isSCEVable(EscapeInst->getType())) 780ecff11dcSJohannes Doerfert SE.forgetValue(EscapeInst); 781ecff11dcSJohannes Doerfert 782ecff11dcSJohannes Doerfert // Replace all uses of the demoted instruction with the merge PHI. 783ecff11dcSJohannes Doerfert for (Instruction *EUser : EscapeUsers) 784ecff11dcSJohannes Doerfert EUser->replaceUsesOfWith(EscapeInst, MergePHI); 785ecff11dcSJohannes Doerfert } 786ecff11dcSJohannes Doerfert } 787ecff11dcSJohannes Doerfert 788ffa2446fSTobias Grosser void BlockGenerator::findOutsideUsers(Scop &S) { 789d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 790ffa2446fSTobias Grosser 791ffa2446fSTobias Grosser if (Array->getNumberOfDimensions() != 0) 792ffa2446fSTobias Grosser continue; 793ffa2446fSTobias Grosser 794a535dff4STobias Grosser if (Array->isPHIKind()) 795ffa2446fSTobias Grosser continue; 796ffa2446fSTobias Grosser 797ffa2446fSTobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 798ffa2446fSTobias Grosser 799ffa2446fSTobias Grosser if (!Inst) 800ffa2446fSTobias Grosser continue; 801ffa2446fSTobias Grosser 802ffa2446fSTobias Grosser // Scop invariant hoisting moves some of the base pointers out of the scop. 803ffa2446fSTobias Grosser // We can ignore these, as the invariant load hoisting already registers the 804ffa2446fSTobias Grosser // relevant outside users. 805952b5304SJohannes Doerfert if (!S.contains(Inst)) 806ffa2446fSTobias Grosser continue; 807ffa2446fSTobias Grosser 808587f1f57STobias Grosser handleOutsideUsers(S, Array); 809ffa2446fSTobias Grosser } 810ffa2446fSTobias Grosser } 811ffa2446fSTobias Grosser 81227d742daSTobias Grosser void BlockGenerator::createExitPHINodeMerges(Scop &S) { 81327d742daSTobias Grosser if (S.hasSingleExitEdge()) 81427d742daSTobias Grosser return; 81527d742daSTobias Grosser 816ef74443cSJohannes Doerfert auto *ExitBB = S.getExitingBlock(); 817ef74443cSJohannes Doerfert auto *MergeBB = S.getExit(); 81827d742daSTobias Grosser auto *AfterMergeBB = MergeBB->getSingleSuccessor(); 81927d742daSTobias Grosser BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 82027d742daSTobias Grosser if (OptExitBB == ExitBB) 82127d742daSTobias Grosser OptExitBB = *(++pred_begin(MergeBB)); 82227d742daSTobias Grosser 82327d742daSTobias Grosser Builder.SetInsertPoint(OptExitBB->getTerminator()); 82427d742daSTobias Grosser 825d7754a12SRoman Gareev for (auto &SAI : S.arrays()) { 82627d742daSTobias Grosser auto *Val = SAI->getBasePtr(); 82727d742daSTobias Grosser 828faedfcbfSMichael Kruse // Only Value-like scalars need a merge PHI. Exit block PHIs receive either 829faedfcbfSMichael Kruse // the original PHI's value or the reloaded incoming values from the 830faedfcbfSMichael Kruse // generated code. An llvm::Value is merged between the original code's 831faedfcbfSMichael Kruse // value or the generated one. 832fa53c86dSMichael Kruse if (!SAI->isExitPHIKind()) 833faedfcbfSMichael Kruse continue; 834faedfcbfSMichael Kruse 83527d742daSTobias Grosser PHINode *PHI = dyn_cast<PHINode>(Val); 83627d742daSTobias Grosser if (!PHI) 83727d742daSTobias Grosser continue; 83827d742daSTobias Grosser 839a3f6edaeSTobias Grosser if (PHI->getParent() != AfterMergeBB) 84027d742daSTobias Grosser continue; 84127d742daSTobias Grosser 84227d742daSTobias Grosser std::string Name = PHI->getName(); 843587f1f57STobias Grosser Value *ScalarAddr = getOrCreateAlloca(SAI); 84427d742daSTobias Grosser Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload"); 84527d742daSTobias Grosser Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType()); 84627d742daSTobias Grosser Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB); 847faedfcbfSMichael Kruse assert((!isa<Instruction>(OriginalValue) || 848faedfcbfSMichael Kruse cast<Instruction>(OriginalValue)->getParent() != MergeBB) && 849faedfcbfSMichael Kruse "Original value must no be one we just generated."); 85027d742daSTobias Grosser auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge"); 851b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 85227d742daSTobias Grosser MergePHI->addIncoming(Reload, OptExitBB); 85327d742daSTobias Grosser MergePHI->addIncoming(OriginalValue, ExitBB); 85427d742daSTobias Grosser int Idx = PHI->getBasicBlockIndex(MergeBB); 85527d742daSTobias Grosser PHI->setIncomingValue(Idx, MergePHI); 85627d742daSTobias Grosser } 85727d742daSTobias Grosser } 85827d742daSTobias Grosser 8591c184409STobias Grosser void BlockGenerator::invalidateScalarEvolution(Scop &S) { 8601c184409STobias Grosser for (auto &Stmt : S) 861b3224adfSRoman Gareev if (Stmt.isCopyStmt()) 862b3224adfSRoman Gareev continue; 863b3224adfSRoman Gareev else if (Stmt.isBlockStmt()) 8641c184409STobias Grosser for (auto &Inst : *Stmt.getBasicBlock()) 8651c184409STobias Grosser SE.forgetValue(&Inst); 8661c184409STobias Grosser else if (Stmt.isRegionStmt()) 8671c184409STobias Grosser for (auto *BB : Stmt.getRegion()->blocks()) 8681c184409STobias Grosser for (auto &Inst : *BB) 8691c184409STobias Grosser SE.forgetValue(&Inst); 8701c184409STobias Grosser else 8711c184409STobias Grosser llvm_unreachable("Unexpected statement type found"); 8721aad76c1SMichael Kruse 8731aad76c1SMichael Kruse // Invalidate SCEV of loops surrounding the EscapeUsers. 8741aad76c1SMichael Kruse for (const auto &EscapeMapping : EscapeMap) { 8751aad76c1SMichael Kruse const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second; 8761aad76c1SMichael Kruse for (Instruction *EUser : EscapeUsers) { 8771aad76c1SMichael Kruse if (Loop *L = LI.getLoopFor(EUser->getParent())) 8781aad76c1SMichael Kruse while (L) { 8791aad76c1SMichael Kruse SE.forgetLoop(L); 8801aad76c1SMichael Kruse L = L->getParentLoop(); 8811aad76c1SMichael Kruse } 8821aad76c1SMichael Kruse } 8831aad76c1SMichael Kruse } 8841c184409STobias Grosser } 8851c184409STobias Grosser 886ffa2446fSTobias Grosser void BlockGenerator::finalizeSCoP(Scop &S) { 887ffa2446fSTobias Grosser findOutsideUsers(S); 888c0091a77STobias Grosser createScalarInitialization(S); 88927d742daSTobias Grosser createExitPHINodeMerges(S); 890ef74443cSJohannes Doerfert createScalarFinalization(S); 8911c184409STobias Grosser invalidateScalarEvolution(S); 8923b11a16aSHongbin Zheng } 8933b11a16aSHongbin Zheng 894be9c9117SJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen, 895be9c9117SJohannes Doerfert std::vector<LoopToScevMapT> &VLTS, 896be9c9117SJohannes Doerfert isl_map *Schedule) 897bc132607STobias Grosser : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) { 898a00a0291SSebastian Pop assert(Schedule && "No statement domain provided"); 8993b11a16aSHongbin Zheng } 9003b11a16aSHongbin Zheng 9012f1acac6STobias Grosser Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old, 902e602a076STobias Grosser ValueMapT &VectorMap, 903e602a076STobias Grosser VectorValueMapT &ScalarMaps, 904e602a076STobias Grosser Loop *L) { 905fe11e287SHongbin Zheng if (Value *NewValue = VectorMap.lookup(Old)) 906fe11e287SHongbin Zheng return NewValue; 9073b11a16aSHongbin Zheng 9083b11a16aSHongbin Zheng int Width = getVectorWidth(); 9093b11a16aSHongbin Zheng 9103b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width)); 9113b11a16aSHongbin Zheng 9123b11a16aSHongbin Zheng for (int Lane = 0; Lane < Width; Lane++) 913c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 914bc132607STobias Grosser Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L), 9157242ad92STobias Grosser Builder.getInt32(Lane)); 9163b11a16aSHongbin Zheng 9173b11a16aSHongbin Zheng VectorMap[Old] = Vector; 9183b11a16aSHongbin Zheng 9193b11a16aSHongbin Zheng return Vector; 9203b11a16aSHongbin Zheng } 9213b11a16aSHongbin Zheng 9223b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) { 9233b11a16aSHongbin Zheng PointerType *PointerTy = dyn_cast<PointerType>(Val->getType()); 9243b11a16aSHongbin Zheng assert(PointerTy && "PointerType expected"); 9253b11a16aSHongbin Zheng 9263b11a16aSHongbin Zheng Type *ScalarType = PointerTy->getElementType(); 9273b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(ScalarType, Width); 9283b11a16aSHongbin Zheng 9293b11a16aSHongbin Zheng return PointerType::getUnqual(VectorType); 9303b11a16aSHongbin Zheng } 9313b11a16aSHongbin Zheng 932be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateStrideOneLoad( 9332f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 9342d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) { 9350dd463faSTobias Grosser unsigned VectorWidth = getVectorWidth(); 9369646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9370dd463faSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth); 9380dd463faSTobias Grosser unsigned Offset = NegativeStride ? VectorWidth - 1 : 0; 9390dd463faSTobias Grosser 9408f25b0cbSMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset], 941bc132607STobias Grosser VLTS[Offset], NewAccesses); 942c14582f2STobias Grosser Value *VectorPtr = 943c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 944c14582f2STobias Grosser LoadInst *VecLoad = 945c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full"); 9463b11a16aSHongbin Zheng if (!Aligned) 9473b11a16aSHongbin Zheng VecLoad->setAlignment(8); 9483b11a16aSHongbin Zheng 9490dd463faSTobias Grosser if (NegativeStride) { 9500dd463faSTobias Grosser SmallVector<Constant *, 16> Indices; 9510dd463faSTobias Grosser for (int i = VectorWidth - 1; i >= 0; i--) 9520dd463faSTobias Grosser Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i)); 9530dd463faSTobias Grosser Constant *SV = llvm::ConstantVector::get(Indices); 9540dd463faSTobias Grosser Value *RevVecLoad = Builder.CreateShuffleVector( 9550dd463faSTobias Grosser VecLoad, VecLoad, SV, Load->getName() + "_reverse"); 9560dd463faSTobias Grosser return RevVecLoad; 9570dd463faSTobias Grosser } 9580dd463faSTobias Grosser 9593b11a16aSHongbin Zheng return VecLoad; 9603b11a16aSHongbin Zheng } 9613b11a16aSHongbin Zheng 9622d1ed0bfSTobias Grosser Value *VectorBlockGenerator::generateStrideZeroLoad( 9632f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap, 9642d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses) { 9659646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9663b11a16aSHongbin Zheng Type *VectorPtrType = getVectorPtrTy(Pointer, 1); 96770131d34SMichael Kruse Value *NewPointer = 96870131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses); 9693b11a16aSHongbin Zheng Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType, 9703b11a16aSHongbin Zheng Load->getName() + "_p_vec_p"); 971c14582f2STobias Grosser LoadInst *ScalarLoad = 972c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one"); 9733b11a16aSHongbin Zheng 9743b11a16aSHongbin Zheng if (!Aligned) 9753b11a16aSHongbin Zheng ScalarLoad->setAlignment(8); 9763b11a16aSHongbin Zheng 977c14582f2STobias Grosser Constant *SplatVector = Constant::getNullValue( 978c14582f2STobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 9793b11a16aSHongbin Zheng 980c14582f2STobias Grosser Value *VectorLoad = Builder.CreateShuffleVector( 981c14582f2STobias Grosser ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat"); 9823b11a16aSHongbin Zheng return VectorLoad; 9833b11a16aSHongbin Zheng } 9843b11a16aSHongbin Zheng 985be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateUnknownStrideLoad( 9862f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 98709e3697fSJohannes Doerfert __isl_keep isl_id_to_ast_expr *NewAccesses) { 9883b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 9899646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 9903b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get( 9913b11a16aSHongbin Zheng dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth); 9923b11a16aSHongbin Zheng 9933b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 9943b11a16aSHongbin Zheng 9953b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) { 99670131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i], 99770131d34SMichael Kruse VLTS[i], NewAccesses); 998c14582f2STobias Grosser Value *ScalarLoad = 999c14582f2STobias Grosser Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_"); 1000c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 1001c14582f2STobias Grosser Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_"); 10023b11a16aSHongbin Zheng } 10033b11a16aSHongbin Zheng 10043b11a16aSHongbin Zheng return Vector; 10053b11a16aSHongbin Zheng } 10063b11a16aSHongbin Zheng 10072d1ed0bfSTobias Grosser void VectorBlockGenerator::generateLoad( 10082f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap, 10092d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1010c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) { 1011c1db67e2SJohannes Doerfert VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad, 1012c1db67e2SJohannes Doerfert Load->getName() + "_p"); 1013c1db67e2SJohannes Doerfert return; 1014c1db67e2SJohannes Doerfert } 1015c1db67e2SJohannes Doerfert 10162873645cSTobias Grosser if (!VectorType::isValidElementType(Load->getType())) { 10173b11a16aSHongbin Zheng for (int i = 0; i < getVectorWidth(); i++) 1018bc132607STobias Grosser ScalarMaps[i][Load] = 1019888ab551SMichael Kruse generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses); 10203b11a16aSHongbin Zheng return; 10213b11a16aSHongbin Zheng } 10223b11a16aSHongbin Zheng 1023184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Load); 10243b11a16aSHongbin Zheng 102595493984STobias Grosser // Make sure we have scalar values available to access the pointer to 102695493984STobias Grosser // the data location. 102795493984STobias Grosser extractScalarValues(Load, VectorMap, ScalarMaps); 102895493984STobias Grosser 10293b11a16aSHongbin Zheng Value *NewLoad; 1030d7065e5dSTobias Grosser if (Access.isStrideZero(isl::manage(isl_map_copy(Schedule)))) 10312d1ed0bfSTobias Grosser NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses); 1032d7065e5dSTobias Grosser else if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) 10332d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses); 1034d7065e5dSTobias Grosser else if (Access.isStrideX(isl::manage(isl_map_copy(Schedule)), -1)) 10352d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true); 10363b11a16aSHongbin Zheng else 10372d1ed0bfSTobias Grosser NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses); 10383b11a16aSHongbin Zheng 10393b11a16aSHongbin Zheng VectorMap[Load] = NewLoad; 10403b11a16aSHongbin Zheng } 10413b11a16aSHongbin Zheng 10422f1acac6STobias Grosser void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst, 10433b11a16aSHongbin Zheng ValueMapT &VectorMap, 10443b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 10453b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 1046be9c9117SJohannes Doerfert Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap, 10472c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 10483b11a16aSHongbin Zheng 10493b11a16aSHongbin Zheng assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction"); 10503b11a16aSHongbin Zheng 10513b11a16aSHongbin Zheng const CastInst *Cast = dyn_cast<CastInst>(Inst); 10523b11a16aSHongbin Zheng VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth); 10533b11a16aSHongbin Zheng VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType); 10543b11a16aSHongbin Zheng } 10553b11a16aSHongbin Zheng 10562f1acac6STobias Grosser void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst, 10573b11a16aSHongbin Zheng ValueMapT &VectorMap, 10583b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 10592c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 10603b11a16aSHongbin Zheng Value *OpZero = Inst->getOperand(0); 10613b11a16aSHongbin Zheng Value *OpOne = Inst->getOperand(1); 10623b11a16aSHongbin Zheng 10633b11a16aSHongbin Zheng Value *NewOpZero, *NewOpOne; 1064be9c9117SJohannes Doerfert NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L); 1065be9c9117SJohannes Doerfert NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L); 10663b11a16aSHongbin Zheng 10671bb59b0dSTobias Grosser Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne, 10683b11a16aSHongbin Zheng Inst->getName() + "p_vec"); 10693b11a16aSHongbin Zheng VectorMap[Inst] = NewInst; 10703b11a16aSHongbin Zheng } 10713b11a16aSHongbin Zheng 10722d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStore( 10732f1acac6STobias Grosser ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap, 10742d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 1075184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Store); 10763b11a16aSHongbin Zheng 10779646e3feSTobias Grosser auto *Pointer = Store->getPointerOperand(); 1078be9c9117SJohannes Doerfert Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap, 10792c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 10803b11a16aSHongbin Zheng 108150fd7010STobias Grosser // Make sure we have scalar values available to access the pointer to 108250fd7010STobias Grosser // the data location. 108350fd7010STobias Grosser extractScalarValues(Store, VectorMap, ScalarMaps); 108450fd7010STobias Grosser 1085d7065e5dSTobias Grosser if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) { 10861947f863SJohannes Doerfert Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth()); 108770131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0], 108870131d34SMichael Kruse VLTS[0], NewAccesses); 10893b11a16aSHongbin Zheng 1090c14582f2STobias Grosser Value *VectorPtr = 1091c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 10923b11a16aSHongbin Zheng StoreInst *Store = Builder.CreateStore(Vector, VectorPtr); 10933b11a16aSHongbin Zheng 10943b11a16aSHongbin Zheng if (!Aligned) 10953b11a16aSHongbin Zheng Store->setAlignment(8); 10963b11a16aSHongbin Zheng } else { 10973b11a16aSHongbin Zheng for (unsigned i = 0; i < ScalarMaps.size(); i++) { 10981bb59b0dSTobias Grosser Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i)); 109970131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i], 110070131d34SMichael Kruse VLTS[i], NewAccesses); 11013b11a16aSHongbin Zheng Builder.CreateStore(Scalar, NewPointer); 11023b11a16aSHongbin Zheng } 11033b11a16aSHongbin Zheng } 11043b11a16aSHongbin Zheng } 11053b11a16aSHongbin Zheng 11063b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst, 11073b11a16aSHongbin Zheng ValueMapT &VectorMap) { 110891f5b262STobias Grosser for (Value *Operand : Inst->operands()) 110991f5b262STobias Grosser if (VectorMap.count(Operand)) 11103b11a16aSHongbin Zheng return true; 11113b11a16aSHongbin Zheng return false; 11123b11a16aSHongbin Zheng } 11133b11a16aSHongbin Zheng 11143b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst, 11153b11a16aSHongbin Zheng ValueMapT &VectorMap, 11163b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 11173b11a16aSHongbin Zheng bool HasVectorOperand = false; 11183b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 11193b11a16aSHongbin Zheng 112091f5b262STobias Grosser for (Value *Operand : Inst->operands()) { 112191f5b262STobias Grosser ValueMapT::iterator VecOp = VectorMap.find(Operand); 11223b11a16aSHongbin Zheng 11233b11a16aSHongbin Zheng if (VecOp == VectorMap.end()) 11243b11a16aSHongbin Zheng continue; 11253b11a16aSHongbin Zheng 11263b11a16aSHongbin Zheng HasVectorOperand = true; 11273b11a16aSHongbin Zheng Value *NewVector = VecOp->second; 11283b11a16aSHongbin Zheng 11293b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; ++i) { 11303b11a16aSHongbin Zheng ValueMapT &SM = ScalarMaps[i]; 11313b11a16aSHongbin Zheng 11323b11a16aSHongbin Zheng // If there is one scalar extracted, all scalar elements should have 11333b11a16aSHongbin Zheng // already been extracted by the code here. So no need to check for the 11342219d157STobias Grosser // existence of all of them. 113591f5b262STobias Grosser if (SM.count(Operand)) 11363b11a16aSHongbin Zheng break; 11373b11a16aSHongbin Zheng 113891f5b262STobias Grosser SM[Operand] = 113991f5b262STobias Grosser Builder.CreateExtractElement(NewVector, Builder.getInt32(i)); 11403b11a16aSHongbin Zheng } 11413b11a16aSHongbin Zheng } 11423b11a16aSHongbin Zheng 11433b11a16aSHongbin Zheng return HasVectorOperand; 11443b11a16aSHongbin Zheng } 11453b11a16aSHongbin Zheng 11462d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstScalarized( 11472f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 11482d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 11493b11a16aSHongbin Zheng bool HasVectorOperand; 11503b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 11513b11a16aSHongbin Zheng 11523b11a16aSHongbin Zheng HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps); 11533b11a16aSHongbin Zheng 11543b11a16aSHongbin Zheng for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++) 1155be9c9117SJohannes Doerfert BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane], 1156bc132607STobias Grosser VLTS[VectorLane], NewAccesses); 11573b11a16aSHongbin Zheng 11583b11a16aSHongbin Zheng if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand) 11593b11a16aSHongbin Zheng return; 11603b11a16aSHongbin Zheng 11613b11a16aSHongbin Zheng // Make the result available as vector value. 11623b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth); 11633b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 11643b11a16aSHongbin Zheng 11653b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) 11663b11a16aSHongbin Zheng Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst], 11673b11a16aSHongbin Zheng Builder.getInt32(i)); 11683b11a16aSHongbin Zheng 11693b11a16aSHongbin Zheng VectorMap[Inst] = Vector; 11703b11a16aSHongbin Zheng } 11713b11a16aSHongbin Zheng 1172bc132607STobias Grosser int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); } 11733b11a16aSHongbin Zheng 11742d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstruction( 11752f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 11762d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 11773b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 11783b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 11793b11a16aSHongbin Zheng if (Inst->isTerminator()) 11803b11a16aSHongbin Zheng return; 11813b11a16aSHongbin Zheng 11825dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 1183e71c6ab5STobias Grosser return; 1184e71c6ab5STobias Grosser 11859646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 11862d1ed0bfSTobias Grosser generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses); 11873b11a16aSHongbin Zheng return; 11883b11a16aSHongbin Zheng } 11893b11a16aSHongbin Zheng 11903b11a16aSHongbin Zheng if (hasVectorOperands(Inst, VectorMap)) { 11919646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 11920446d81eSMichael Kruse // Identified as redundant by -polly-simplify. 11930446d81eSMichael Kruse if (!Stmt.getArrayAccessOrNULLFor(Store)) 11940446d81eSMichael Kruse return; 11950446d81eSMichael Kruse 11962d1ed0bfSTobias Grosser copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses); 11973b11a16aSHongbin Zheng return; 11983b11a16aSHongbin Zheng } 11993b11a16aSHongbin Zheng 12009646e3feSTobias Grosser if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) { 1201be9c9117SJohannes Doerfert copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps); 12023b11a16aSHongbin Zheng return; 12033b11a16aSHongbin Zheng } 12043b11a16aSHongbin Zheng 12059646e3feSTobias Grosser if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) { 1206be9c9117SJohannes Doerfert copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps); 12073b11a16aSHongbin Zheng return; 12083b11a16aSHongbin Zheng } 12093b11a16aSHongbin Zheng 1210a6d48f59SMichael Kruse // Fallthrough: We generate scalar instructions, if we don't know how to 12113b11a16aSHongbin Zheng // generate vector code. 12123b11a16aSHongbin Zheng } 12133b11a16aSHongbin Zheng 12142d1ed0bfSTobias Grosser copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses); 12153b11a16aSHongbin Zheng } 12163b11a16aSHongbin Zheng 1217a69d4f0dSTobias Grosser void VectorBlockGenerator::generateScalarVectorLoads( 1218a69d4f0dSTobias Grosser ScopStmt &Stmt, ValueMapT &VectorBlockMap) { 1219a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1220a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isWrite()) 1221a69d4f0dSTobias Grosser continue; 1222a69d4f0dSTobias Grosser 1223a69d4f0dSTobias Grosser auto *Address = getOrCreateAlloca(*MA); 1224a69d4f0dSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Address, 1); 1225a69d4f0dSTobias Grosser Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType, 1226a69d4f0dSTobias Grosser Address->getName() + "_p_vec_p"); 1227a69d4f0dSTobias Grosser auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload"); 1228a69d4f0dSTobias Grosser Constant *SplatVector = Constant::getNullValue( 1229a69d4f0dSTobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 1230a69d4f0dSTobias Grosser 1231a69d4f0dSTobias Grosser Value *VectorVal = Builder.CreateShuffleVector( 1232a69d4f0dSTobias Grosser Val, Val, SplatVector, Address->getName() + "_p_splat"); 1233583be06fSTobias Grosser VectorBlockMap[MA->getAccessValue()] = VectorVal; 1234a69d4f0dSTobias Grosser } 1235a69d4f0dSTobias Grosser } 1236a69d4f0dSTobias Grosser 1237a69d4f0dSTobias Grosser void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) { 1238a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1239a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isRead()) 1240a69d4f0dSTobias Grosser continue; 1241a69d4f0dSTobias Grosser 1242a69d4f0dSTobias Grosser llvm_unreachable("Scalar stores not expected in vector loop"); 1243a69d4f0dSTobias Grosser } 1244a69d4f0dSTobias Grosser } 1245a69d4f0dSTobias Grosser 12462d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStmt( 12472d1ed0bfSTobias Grosser ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) { 124821a059afSTobias Grosser assert(Stmt.isBlockStmt() && 124921a059afSTobias Grosser "TODO: Only block statements can be copied by the vector block " 125021a059afSTobias Grosser "generator"); 1251275a1756SJohannes Doerfert 1252be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 1253b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 1254b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 12553b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 1256b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 12573b11a16aSHongbin Zheng 12583b11a16aSHongbin Zheng // Create two maps that store the mapping from the original instructions of 12593b11a16aSHongbin Zheng // the old basic block to their copies in the new basic block. Those maps 12603b11a16aSHongbin Zheng // are basic block local. 12613b11a16aSHongbin Zheng // 12623b11a16aSHongbin Zheng // As vector code generation is supported there is one map for scalar values 12633b11a16aSHongbin Zheng // and one for vector values. 12643b11a16aSHongbin Zheng // 12653b11a16aSHongbin Zheng // In case we just do scalar code generation, the vectorMap is not used and 12663b11a16aSHongbin Zheng // the scalarMap has just one dimension, which contains the mapping. 12673b11a16aSHongbin Zheng // 12683b11a16aSHongbin Zheng // In case vector code generation is done, an instruction may either appear 12693b11a16aSHongbin Zheng // in the vector map once (as it is calculating >vectorwidth< values at a 12703b11a16aSHongbin Zheng // time. Or (if the values are calculated using scalar operations), it 12713b11a16aSHongbin Zheng // appears once in every dimension of the scalarMap. 12723b11a16aSHongbin Zheng VectorValueMapT ScalarBlockMap(getVectorWidth()); 12733b11a16aSHongbin Zheng ValueMapT VectorBlockMap; 12743b11a16aSHongbin Zheng 1275a69d4f0dSTobias Grosser generateScalarVectorLoads(Stmt, VectorBlockMap); 1276a69d4f0dSTobias Grosser 127791f5b262STobias Grosser for (Instruction &Inst : *BB) 12782d1ed0bfSTobias Grosser copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses); 1279a69d4f0dSTobias Grosser 1280a69d4f0dSTobias Grosser verifyNoScalarStores(Stmt); 12813b11a16aSHongbin Zheng } 1282275a1756SJohannes Doerfert 1283ecff11dcSJohannes Doerfert BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB, 1284ecff11dcSJohannes Doerfert BasicBlock *BBCopy) { 1285514f6efaSJohannes Doerfert 1286514f6efaSJohannes Doerfert BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock(); 1287deefbcedSTobias Grosser BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom); 1288514f6efaSJohannes Doerfert 1289514f6efaSJohannes Doerfert if (BBCopyIDom) 1290514f6efaSJohannes Doerfert DT.changeImmediateDominator(BBCopy, BBCopyIDom); 1291514f6efaSJohannes Doerfert 1292deefbcedSTobias Grosser return StartBlockMap.lookup(BBIDom); 1293514f6efaSJohannes Doerfert } 1294514f6efaSJohannes Doerfert 1295f33c125dSMichael Kruse // This is to determine whether an llvm::Value (defined in @p BB) is usable when 1296f33c125dSMichael Kruse // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock()) 1297f33c125dSMichael Kruse // does not work in cases where the exit block has edges from outside the 1298f33c125dSMichael Kruse // region. In that case the llvm::Value would never be usable in in the exit 1299f33c125dSMichael Kruse // block. The RegionGenerator however creates an new exit block ('ExitBBCopy') 1300f33c125dSMichael Kruse // for the subregion's exiting edges only. We need to determine whether an 1301f33c125dSMichael Kruse // llvm::Value is usable in there. We do this by checking whether it dominates 1302f33c125dSMichael Kruse // all exiting blocks individually. 1303f33c125dSMichael Kruse static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, 1304f33c125dSMichael Kruse BasicBlock *BB) { 1305f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1306f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1307f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1308f33c125dSMichael Kruse continue; 1309f33c125dSMichael Kruse 1310f33c125dSMichael Kruse if (!DT.dominates(BB, ExitingBB)) 1311f33c125dSMichael Kruse return false; 1312f33c125dSMichael Kruse } 1313f33c125dSMichael Kruse 1314f33c125dSMichael Kruse return true; 1315f33c125dSMichael Kruse } 1316f33c125dSMichael Kruse 1317f33c125dSMichael Kruse // Find the direct dominator of the subregion's exit block if the subregion was 1318f33c125dSMichael Kruse // simplified. 1319f33c125dSMichael Kruse static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) { 1320f33c125dSMichael Kruse BasicBlock *Common = nullptr; 1321f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1322f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1323f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1324f33c125dSMichael Kruse continue; 1325f33c125dSMichael Kruse 1326f33c125dSMichael Kruse // First exiting edge. 1327f33c125dSMichael Kruse if (!Common) { 1328f33c125dSMichael Kruse Common = ExitingBB; 1329f33c125dSMichael Kruse continue; 1330f33c125dSMichael Kruse } 1331f33c125dSMichael Kruse 1332f33c125dSMichael Kruse Common = DT.findNearestCommonDominator(Common, ExitingBB); 1333f33c125dSMichael Kruse } 1334f33c125dSMichael Kruse 1335f33c125dSMichael Kruse assert(Common && R->contains(Common)); 1336f33c125dSMichael Kruse return Common; 1337f33c125dSMichael Kruse } 1338f33c125dSMichael Kruse 1339bc132607STobias Grosser void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 13402d1ed0bfSTobias Grosser isl_id_to_ast_expr *IdToAstExp) { 1341275a1756SJohannes Doerfert assert(Stmt.isRegionStmt() && 1342d3f21833STobias Grosser "Only region statements can be copied by the region generator"); 1343275a1756SJohannes Doerfert 1344ecff11dcSJohannes Doerfert // Forget all old mappings. 1345deefbcedSTobias Grosser StartBlockMap.clear(); 1346deefbcedSTobias Grosser EndBlockMap.clear(); 1347ecff11dcSJohannes Doerfert RegionMaps.clear(); 1348ecff11dcSJohannes Doerfert IncompletePHINodeMap.clear(); 1349ecff11dcSJohannes Doerfert 1350225f0d1eSMichael Kruse // Collection of all values related to this subregion. 1351225f0d1eSMichael Kruse ValueMapT ValueMap; 1352225f0d1eSMichael Kruse 1353275a1756SJohannes Doerfert // The region represented by the statement. 1354275a1756SJohannes Doerfert Region *R = Stmt.getRegion(); 1355275a1756SJohannes Doerfert 1356ecff11dcSJohannes Doerfert // Create a dedicated entry for the region where we can reload all demoted 1357ecff11dcSJohannes Doerfert // inputs. 1358ecff11dcSJohannes Doerfert BasicBlock *EntryBB = R->getEntry(); 1359b8f58b53SDuncan P. N. Exon Smith BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(), 1360b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1361ecff11dcSJohannes Doerfert EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry"); 1362b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&EntryBBCopy->front()); 1363514f6efaSJohannes Doerfert 1364c993739eSMichael Kruse ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy]; 13652fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp); 1366225f0d1eSMichael Kruse 1367ecff11dcSJohannes Doerfert for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI) 1368deefbcedSTobias Grosser if (!R->contains(*PI)) { 1369deefbcedSTobias Grosser StartBlockMap[*PI] = EntryBBCopy; 1370deefbcedSTobias Grosser EndBlockMap[*PI] = EntryBBCopy; 1371deefbcedSTobias Grosser } 1372275a1756SJohannes Doerfert 1373275a1756SJohannes Doerfert // Iterate over all blocks in the region in a breadth-first search. 1374275a1756SJohannes Doerfert std::deque<BasicBlock *> Blocks; 13755b1abfc8SMandeep Singh Grang SmallSetVector<BasicBlock *, 8> SeenBlocks; 1376ecff11dcSJohannes Doerfert Blocks.push_back(EntryBB); 1377ecff11dcSJohannes Doerfert SeenBlocks.insert(EntryBB); 1378275a1756SJohannes Doerfert 1379275a1756SJohannes Doerfert while (!Blocks.empty()) { 1380275a1756SJohannes Doerfert BasicBlock *BB = Blocks.front(); 1381275a1756SJohannes Doerfert Blocks.pop_front(); 1382275a1756SJohannes Doerfert 1383514f6efaSJohannes Doerfert // First split the block and update dominance information. 1384514f6efaSJohannes Doerfert BasicBlock *BBCopy = splitBB(BB); 1385ecff11dcSJohannes Doerfert BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy); 1386ecff11dcSJohannes Doerfert 1387c993739eSMichael Kruse // Get the mapping for this block and initialize it with either the scalar 1388c993739eSMichael Kruse // loads from the generated entering block (which dominates all blocks of 1389c993739eSMichael Kruse // this subregion) or the maps of the immediate dominator, if part of the 1390c993739eSMichael Kruse // subregion. The latter necessarily includes the former. 1391c993739eSMichael Kruse ValueMapT *InitBBMap; 1392c993739eSMichael Kruse if (BBCopyIDom) { 1393c993739eSMichael Kruse assert(RegionMaps.count(BBCopyIDom)); 1394c993739eSMichael Kruse InitBBMap = &RegionMaps[BBCopyIDom]; 1395c993739eSMichael Kruse } else 1396c993739eSMichael Kruse InitBBMap = &EntryBBMap; 1397c993739eSMichael Kruse auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap)); 1398c993739eSMichael Kruse ValueMapT &RegionMap = Inserted.first->second; 1399514f6efaSJohannes Doerfert 1400275a1756SJohannes Doerfert // Copy the block with the BlockGenerator. 1401b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&BBCopy->front()); 1402bc132607STobias Grosser copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp); 1403275a1756SJohannes Doerfert 1404ecff11dcSJohannes Doerfert // In order to remap PHI nodes we store also basic block mappings. 1405deefbcedSTobias Grosser StartBlockMap[BB] = BBCopy; 1406deefbcedSTobias Grosser EndBlockMap[BB] = Builder.GetInsertBlock(); 1407ecff11dcSJohannes Doerfert 1408ecff11dcSJohannes Doerfert // Add values to incomplete PHI nodes waiting for this block to be copied. 1409ecff11dcSJohannes Doerfert for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB]) 1410bc132607STobias Grosser addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS); 1411ecff11dcSJohannes Doerfert IncompletePHINodeMap[BB].clear(); 1412ecff11dcSJohannes Doerfert 1413275a1756SJohannes Doerfert // And continue with new successors inside the region. 1414275a1756SJohannes Doerfert for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++) 14155b1abfc8SMandeep Singh Grang if (R->contains(*SI) && SeenBlocks.insert(*SI)) 1416275a1756SJohannes Doerfert Blocks.push_back(*SI); 1417ebffcbeeSMichael Kruse 1418ebffcbeeSMichael Kruse // Remember value in case it is visible after this subregion. 1419f33c125dSMichael Kruse if (isDominatingSubregionExit(DT, R, BB)) 1420ebffcbeeSMichael Kruse ValueMap.insert(RegionMap.begin(), RegionMap.end()); 1421275a1756SJohannes Doerfert } 1422275a1756SJohannes Doerfert 1423275a1756SJohannes Doerfert // Now create a new dedicated region exit block and add it to the region map. 1424b8f58b53SDuncan P. N. Exon Smith BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(), 1425b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1426ecff11dcSJohannes Doerfert ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit"); 1427deefbcedSTobias Grosser StartBlockMap[R->getExit()] = ExitBBCopy; 1428deefbcedSTobias Grosser EndBlockMap[R->getExit()] = ExitBBCopy; 1429514f6efaSJohannes Doerfert 1430deefbcedSTobias Grosser BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R)); 143121a059afSTobias Grosser assert(ExitDomBBCopy && 143221a059afSTobias Grosser "Common exit dominator must be within region; at least the entry node " 143321a059afSTobias Grosser "must match"); 1434f33c125dSMichael Kruse DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy); 1435275a1756SJohannes Doerfert 1436275a1756SJohannes Doerfert // As the block generator doesn't handle control flow we need to add the 1437275a1756SJohannes Doerfert // region control flow by hand after all blocks have been copied. 1438275a1756SJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1439275a1756SJohannes Doerfert 1440deefbcedSTobias Grosser BasicBlock *BBCopyStart = StartBlockMap[BB]; 1441deefbcedSTobias Grosser BasicBlock *BBCopyEnd = EndBlockMap[BB]; 1442e114dc02SJohannes Doerfert TerminatorInst *TI = BB->getTerminator(); 1443e114dc02SJohannes Doerfert if (isa<UnreachableInst>(TI)) { 1444deefbcedSTobias Grosser while (!BBCopyEnd->empty()) 1445deefbcedSTobias Grosser BBCopyEnd->begin()->eraseFromParent(); 1446deefbcedSTobias Grosser new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd); 1447e114dc02SJohannes Doerfert continue; 1448e114dc02SJohannes Doerfert } 1449e114dc02SJohannes Doerfert 1450deefbcedSTobias Grosser Instruction *BICopy = BBCopyEnd->getTerminator(); 1451275a1756SJohannes Doerfert 1452deefbcedSTobias Grosser ValueMapT &RegionMap = RegionMaps[BBCopyStart]; 1453deefbcedSTobias Grosser RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end()); 1454514f6efaSJohannes Doerfert 145545e7944bSTobias Grosser Builder.SetInsertPoint(BICopy); 14569a132f36SJohannes Doerfert copyInstScalar(Stmt, TI, RegionMap, LTS); 1457275a1756SJohannes Doerfert BICopy->eraseFromParent(); 1458275a1756SJohannes Doerfert } 1459275a1756SJohannes Doerfert 1460ecff11dcSJohannes Doerfert // Add counting PHI nodes to all loops in the region that can be used as 1461a6d48f59SMichael Kruse // replacement for SCEVs referring to the old loop. 1462ecff11dcSJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1463ecff11dcSJohannes Doerfert Loop *L = LI.getLoopFor(BB); 1464bc29e0b2STobias Grosser if (L == nullptr || L->getHeader() != BB || !R->contains(L)) 1465ecff11dcSJohannes Doerfert continue; 1466ecff11dcSJohannes Doerfert 1467deefbcedSTobias Grosser BasicBlock *BBCopy = StartBlockMap[BB]; 1468ecff11dcSJohannes Doerfert Value *NullVal = Builder.getInt32(0); 1469ecff11dcSJohannes Doerfert PHINode *LoopPHI = 1470ecff11dcSJohannes Doerfert PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv"); 1471ecff11dcSJohannes Doerfert Instruction *LoopPHIInc = BinaryOperator::CreateAdd( 1472ecff11dcSJohannes Doerfert LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc"); 1473b8f58b53SDuncan P. N. Exon Smith LoopPHI->insertBefore(&BBCopy->front()); 1474ecff11dcSJohannes Doerfert LoopPHIInc->insertBefore(BBCopy->getTerminator()); 1475ecff11dcSJohannes Doerfert 1476ecff11dcSJohannes Doerfert for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) { 1477ecff11dcSJohannes Doerfert if (!R->contains(PredBB)) 1478ecff11dcSJohannes Doerfert continue; 1479ecff11dcSJohannes Doerfert if (L->contains(PredBB)) 1480deefbcedSTobias Grosser LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]); 1481ecff11dcSJohannes Doerfert else 1482deefbcedSTobias Grosser LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]); 1483ecff11dcSJohannes Doerfert } 1484ecff11dcSJohannes Doerfert 1485ecff11dcSJohannes Doerfert for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy))) 1486ecff11dcSJohannes Doerfert if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0) 1487ecff11dcSJohannes Doerfert LoopPHI->addIncoming(NullVal, PredBBCopy); 1488ecff11dcSJohannes Doerfert 1489ecff11dcSJohannes Doerfert LTS[L] = SE.getUnknown(LoopPHI); 1490ecff11dcSJohannes Doerfert } 1491ecff11dcSJohannes Doerfert 1492225f0d1eSMichael Kruse // Continue generating code in the exit block. 1493b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt()); 1494225f0d1eSMichael Kruse 1495225f0d1eSMichael Kruse // Write values visible to other statements. 14962fa35194SMichael Kruse generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp); 1497deefbcedSTobias Grosser StartBlockMap.clear(); 1498deefbcedSTobias Grosser EndBlockMap.clear(); 14993e956020STobias Grosser RegionMaps.clear(); 15003e956020STobias Grosser IncompletePHINodeMap.clear(); 1501275a1756SJohannes Doerfert } 1502ecff11dcSJohannes Doerfert 1503ee6a4fc6SMichael Kruse PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT <S, 1504ee6a4fc6SMichael Kruse ValueMapT &BBMap, Loop *L) { 1505ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1506ee6a4fc6SMichael Kruse Region *SubR = Stmt->getRegion(); 1507ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1508ee6a4fc6SMichael Kruse 1509ee6a4fc6SMichael Kruse PollyIRBuilder::InsertPointGuard IPGuard(Builder); 1510ee6a4fc6SMichael Kruse PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction()); 1511ee6a4fc6SMichael Kruse BasicBlock *NewSubregionExit = Builder.GetInsertBlock(); 1512ee6a4fc6SMichael Kruse 1513ee6a4fc6SMichael Kruse // This can happen if the subregion is simplified after the ScopStmts 1514ee6a4fc6SMichael Kruse // have been created; simplification happens as part of CodeGeneration. 1515ee6a4fc6SMichael Kruse if (OrigPHI->getParent() != SubR->getExit()) { 1516ee6a4fc6SMichael Kruse BasicBlock *FormerExit = SubR->getExitingBlock(); 1517ee6a4fc6SMichael Kruse if (FormerExit) 1518deefbcedSTobias Grosser NewSubregionExit = StartBlockMap.lookup(FormerExit); 1519ee6a4fc6SMichael Kruse } 1520ee6a4fc6SMichael Kruse 1521ee6a4fc6SMichael Kruse PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(), 1522ee6a4fc6SMichael Kruse "polly." + OrigPHI->getName(), 1523ee6a4fc6SMichael Kruse NewSubregionExit->getFirstNonPHI()); 1524ee6a4fc6SMichael Kruse 1525ee6a4fc6SMichael Kruse // Add the incoming values to the PHI. 1526ee6a4fc6SMichael Kruse for (auto &Pair : Incoming) { 1527ee6a4fc6SMichael Kruse BasicBlock *OrigIncomingBlock = Pair.first; 1528deefbcedSTobias Grosser BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock); 1529deefbcedSTobias Grosser BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock); 1530deefbcedSTobias Grosser Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator()); 1531deefbcedSTobias Grosser assert(RegionMaps.count(NewIncomingBlockStart)); 1532deefbcedSTobias Grosser assert(RegionMaps.count(NewIncomingBlockEnd)); 1533deefbcedSTobias Grosser ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart]; 1534ee6a4fc6SMichael Kruse 1535ee6a4fc6SMichael Kruse Value *OrigIncomingValue = Pair.second; 1536ee6a4fc6SMichael Kruse Value *NewIncomingValue = 1537ee6a4fc6SMichael Kruse getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L); 1538deefbcedSTobias Grosser NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd); 1539ee6a4fc6SMichael Kruse } 1540ee6a4fc6SMichael Kruse 1541ee6a4fc6SMichael Kruse return NewPHI; 1542ee6a4fc6SMichael Kruse } 1543ee6a4fc6SMichael Kruse 1544ee6a4fc6SMichael Kruse Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT <S, 1545ee6a4fc6SMichael Kruse ValueMapT &BBMap) { 1546ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1547ee6a4fc6SMichael Kruse 1548ee6a4fc6SMichael Kruse // TODO: Add some test cases that ensure this is really the right choice. 1549ee6a4fc6SMichael Kruse Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit()); 1550ee6a4fc6SMichael Kruse 1551ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 1552ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1553ee6a4fc6SMichael Kruse assert(!Incoming.empty() && 1554ee6a4fc6SMichael Kruse "PHI WRITEs must have originate from at least one incoming block"); 1555ee6a4fc6SMichael Kruse 1556ee6a4fc6SMichael Kruse // If there is only one incoming value, we do not need to create a PHI. 1557ee6a4fc6SMichael Kruse if (Incoming.size() == 1) { 1558ee6a4fc6SMichael Kruse Value *OldVal = Incoming[0].second; 1559ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1560ee6a4fc6SMichael Kruse } 1561ee6a4fc6SMichael Kruse 1562ee6a4fc6SMichael Kruse return buildExitPHI(MA, LTS, BBMap, L); 1563ee6a4fc6SMichael Kruse } 1564ee6a4fc6SMichael Kruse 15654d5a9172STobias Grosser // MemoryKind::Value accesses leaving the subregion must dominate the exit 15664d5a9172STobias Grosser // block; just pass the copied value. 1567ee6a4fc6SMichael Kruse Value *OldVal = MA->getAccessValue(); 1568ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1569ee6a4fc6SMichael Kruse } 1570ee6a4fc6SMichael Kruse 15712fa35194SMichael Kruse void RegionGenerator::generateScalarStores( 15722fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 15732fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 157475296901STobias Grosser assert(Stmt.getRegion() && 157575296901STobias Grosser "Block statements need to use the generateScalarStores() " 1576ecff11dcSJohannes Doerfert "function in the BlockGenerator"); 1577ecff11dcSJohannes Doerfert 1578ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 15792fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 1580ecff11dcSJohannes Doerfert continue; 1581ecff11dcSJohannes Doerfert 15821515f6b9STobias Grosser isl::set AccDom = MA->getAccessRelation().domain(); 1583fe46c3ffSTobias Grosser std::string Subject = MA->getId().get_name(); 1584fe46c3ffSTobias Grosser generateConditionalExecution( 1585fe46c3ffSTobias Grosser Stmt, AccDom, Subject.c_str(), [&, this, MA]() { 1586706f79abSMichael Kruse 1587ee6a4fc6SMichael Kruse Value *NewVal = getExitScalar(MA, LTS, BBMap); 1588fe46c3ffSTobias Grosser Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, 1589fe46c3ffSTobias Grosser BBMap, NewAccesses); 1590eac9726eSMichael Kruse assert((!isa<Instruction>(NewVal) || 1591eac9726eSMichael Kruse DT.dominates(cast<Instruction>(NewVal)->getParent(), 1592eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1593eac9726eSMichael Kruse "Domination violation"); 1594eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 1595eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 1596eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1597eac9726eSMichael Kruse "Domination violation"); 1598ee6a4fc6SMichael Kruse Builder.CreateStore(NewVal, Address); 1599706f79abSMichael Kruse }); 1600ecff11dcSJohannes Doerfert } 1601ecff11dcSJohannes Doerfert } 1602ecff11dcSJohannes Doerfert 1603943c369cSTobias Grosser void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, 1604ecff11dcSJohannes Doerfert PHINode *PHICopy, BasicBlock *IncomingBB, 1605ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1606ecff11dcSJohannes Doerfert // If the incoming block was not yet copied mark this PHI as incomplete. 1607ecff11dcSJohannes Doerfert // Once the block will be copied the incoming value will be added. 1608deefbcedSTobias Grosser BasicBlock *BBCopyStart = StartBlockMap[IncomingBB]; 1609deefbcedSTobias Grosser BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB]; 1610deefbcedSTobias Grosser if (!BBCopyStart) { 1611deefbcedSTobias Grosser assert(!BBCopyEnd); 16128d89179eSMichael Kruse assert(Stmt.represents(IncomingBB) && 1613ecff11dcSJohannes Doerfert "Bad incoming block for PHI in non-affine region"); 1614ecff11dcSJohannes Doerfert IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy)); 1615ecff11dcSJohannes Doerfert return; 1616ecff11dcSJohannes Doerfert } 1617ecff11dcSJohannes Doerfert 1618deefbcedSTobias Grosser assert(RegionMaps.count(BBCopyStart) && 1619deefbcedSTobias Grosser "Incoming PHI block did not have a BBMap"); 1620deefbcedSTobias Grosser ValueMapT &BBCopyMap = RegionMaps[BBCopyStart]; 1621ecff11dcSJohannes Doerfert 162275dfaa1dSTobias Grosser Value *OpCopy = nullptr; 162375dfaa1dSTobias Grosser 16248d89179eSMichael Kruse if (Stmt.represents(IncomingBB)) { 1625ecff11dcSJohannes Doerfert Value *Op = PHI->getIncomingValueForBlock(IncomingBB); 1626dc122222SMichael Kruse 16276ba92714SJohannes Doerfert // If the current insert block is different from the PHIs incoming block 16286ba92714SJohannes Doerfert // change it, otherwise do not. 16296ba92714SJohannes Doerfert auto IP = Builder.GetInsertPoint(); 1630deefbcedSTobias Grosser if (IP->getParent() != BBCopyEnd) 1631deefbcedSTobias Grosser Builder.SetInsertPoint(BBCopyEnd->getTerminator()); 16322c3ffc04SJohannes Doerfert OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1633deefbcedSTobias Grosser if (IP->getParent() != BBCopyEnd) 16346ba92714SJohannes Doerfert Builder.SetInsertPoint(&*IP); 1635ecff11dcSJohannes Doerfert } else { 163675dfaa1dSTobias Grosser // All edges from outside the non-affine region become a single edge 163775dfaa1dSTobias Grosser // in the new copy of the non-affine region. Make sure to only add the 163875dfaa1dSTobias Grosser // corresponding edge the first time we encounter a basic block from 163975dfaa1dSTobias Grosser // outside the non-affine region. 1640deefbcedSTobias Grosser if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0) 1641ecff11dcSJohannes Doerfert return; 1642ecff11dcSJohannes Doerfert 164375dfaa1dSTobias Grosser // Get the reloaded value. 164475dfaa1dSTobias Grosser OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1645ecff11dcSJohannes Doerfert } 1646ecff11dcSJohannes Doerfert 1647ecff11dcSJohannes Doerfert assert(OpCopy && "Incoming PHI value was not copied properly"); 1648deefbcedSTobias Grosser PHICopy->addIncoming(OpCopy, BBCopyEnd); 1649ecff11dcSJohannes Doerfert } 1650ecff11dcSJohannes Doerfert 16512b809d13STobias Grosser void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI, 1652ecff11dcSJohannes Doerfert ValueMapT &BBMap, 1653ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1654ecff11dcSJohannes Doerfert unsigned NumIncoming = PHI->getNumIncomingValues(); 1655ecff11dcSJohannes Doerfert PHINode *PHICopy = 1656ecff11dcSJohannes Doerfert Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName()); 1657ecff11dcSJohannes Doerfert PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI()); 1658ecff11dcSJohannes Doerfert BBMap[PHI] = PHICopy; 1659ecff11dcSJohannes Doerfert 166097b84909STobias Grosser for (BasicBlock *IncomingBB : PHI->blocks()) 166197b84909STobias Grosser addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS); 1662ecff11dcSJohannes Doerfert } 1663