1 //===------ CodeGeneration.cpp - Code generate the Scops using ISL. ----======// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The CodeGeneration pass takes a Scop created by ScopInfo and translates it 11 // back to LLVM-IR using the ISL code generator. 12 // 13 // The Scop describes the high level memory behaviour of a control flow region. 14 // Transformation passes can update the schedule (execution order) of statements 15 // in the Scop. ISL is used to generate an abstract syntax tree that reflects 16 // the updated execution order. This clast is used to create new LLVM-IR that is 17 // computationally equivalent to the original control flow region, but executes 18 // its code in the new execution order defined by the changed schedule. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "polly/CodeGen/IslAst.h" 23 #include "polly/CodeGen/IslNodeBuilder.h" 24 #include "polly/CodeGen/Utils.h" 25 #include "polly/DependenceInfo.h" 26 #include "polly/LinkAllPasses.h" 27 #include "polly/Options.h" 28 #include "polly/ScopInfo.h" 29 #include "polly/Support/ScopHelper.h" 30 #include "llvm/Analysis/AliasAnalysis.h" 31 #include "llvm/Analysis/BasicAliasAnalysis.h" 32 #include "llvm/Analysis/GlobalsModRef.h" 33 #include "llvm/Analysis/PostDominators.h" 34 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/Support/Debug.h" 38 39 using namespace polly; 40 using namespace llvm; 41 42 #define DEBUG_TYPE "polly-codegen" 43 44 static cl::opt<bool> Verify("polly-codegen-verify", 45 cl::desc("Verify the function generated by Polly"), 46 cl::Hidden, cl::init(true), cl::ZeroOrMore, 47 cl::cat(PollyCategory)); 48 49 namespace { 50 class CodeGeneration : public ScopPass { 51 public: 52 static char ID; 53 54 CodeGeneration() : ScopPass(ID) {} 55 56 /// @brief The datalayout used 57 const DataLayout *DL; 58 59 /// @name The analysis passes we need to generate code. 60 /// 61 ///{ 62 LoopInfo *LI; 63 IslAstInfo *AI; 64 DominatorTree *DT; 65 ScalarEvolution *SE; 66 RegionInfo *RI; 67 ///} 68 69 void verifyGeneratedFunction(Scop &S, Function &F) { 70 if (!verifyFunction(F, &errs()) || !Verify) 71 return; 72 73 DEBUG({ 74 errs() << "== ISL Codegen created an invalid function ==\n\n== The " 75 "SCoP ==\n"; 76 S.print(errs()); 77 errs() << "\n== The isl AST ==\n"; 78 AI->printScop(errs(), S); 79 errs() << "\n== The invalid function ==\n"; 80 F.print(errs()); 81 }); 82 83 llvm_unreachable("Polly generated function could not be verified. Add " 84 "-polly-codegen-verify=false to disable this assertion."); 85 } 86 87 // CodeGeneration adds a lot of BBs without updating the RegionInfo 88 // We make all created BBs belong to the scop's parent region without any 89 // nested structure to keep the RegionInfo verifier happy. 90 void fixRegionInfo(Function *F, Region *ParentRegion) { 91 for (BasicBlock &BB : *F) { 92 if (RI->getRegionFor(&BB)) 93 continue; 94 95 RI->setRegionFor(&BB, ParentRegion); 96 } 97 } 98 99 /// @brief Mark a basic block unreachable. 100 /// 101 /// Marks the basic block @p Block unreachable by equipping it with an 102 /// UnreachableInst. 103 void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) { 104 auto *OrigTerminator = Block.getTerminator(); 105 Builder.SetInsertPoint(OrigTerminator); 106 Builder.CreateUnreachable(); 107 OrigTerminator->eraseFromParent(); 108 } 109 110 /// @brief Generate LLVM-IR for the SCoP @p S. 111 bool runOnScop(Scop &S) override { 112 AI = &getAnalysis<IslAstInfo>(); 113 114 // Check if we created an isl_ast root node, otherwise exit. 115 isl_ast_node *AstRoot = AI->getAst(); 116 if (!AstRoot) 117 return false; 118 119 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 120 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 121 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 122 DL = &S.getFunction().getParent()->getDataLayout(); 123 RI = &getAnalysis<RegionInfoPass>().getRegionInfo(); 124 Region *R = &S.getRegion(); 125 assert(!R->isTopLevelRegion() && "Top level regions are not supported"); 126 127 ScopAnnotator Annotator; 128 Annotator.buildAliasScopes(S); 129 130 simplifyRegion(R, DT, LI, RI); 131 assert(R->isSimple()); 132 BasicBlock *EnteringBB = S.getEnteringBlock(); 133 assert(EnteringBB); 134 PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator); 135 136 IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S); 137 138 // Only build the run-time condition and parameters _after_ having 139 // introduced the conditional branch. This is important as the conditional 140 // branch will guard the original scop from new induction variables that 141 // the SCEVExpander may introduce while code generating the parameters and 142 // which may introduce scalar dependences that prevent us from correctly 143 // code generating this scop. 144 BasicBlock *StartBlock = 145 executeScopConditionally(S, this, Builder.getTrue()); 146 auto *SplitBlock = StartBlock->getSinglePredecessor(); 147 148 // First generate code for the hoisted invariant loads and transitively the 149 // parameters they reference. Afterwards, for the remaining parameters that 150 // might reference the hoisted loads. Finally, build the runtime check 151 // that might reference both hoisted loads as well as parameters. 152 // If the hoisting fails we have to bail and execute the original code. 153 Builder.SetInsertPoint(SplitBlock->getTerminator()); 154 if (!NodeBuilder.preloadInvariantLoads()) { 155 156 // Patch the introduced branch condition to ensure that we always execute 157 // the original SCoP. 158 auto *FalseI1 = Builder.getFalse(); 159 auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator(); 160 SplitBBTerm->setOperand(0, FalseI1); 161 162 // Since the other branch is hence ignored we mark it as unreachable and 163 // adjust the dominator tree accordingly. 164 auto *ExitingBlock = StartBlock->getUniqueSuccessor(); 165 assert(ExitingBlock); 166 auto *MergeBlock = ExitingBlock->getUniqueSuccessor(); 167 assert(MergeBlock); 168 markBlockUnreachable(*StartBlock, Builder); 169 markBlockUnreachable(*ExitingBlock, Builder); 170 auto *ExitingBB = S.getExitingBlock(); 171 assert(ExitingBB); 172 DT->changeImmediateDominator(MergeBlock, ExitingBB); 173 DT->eraseNode(ExitingBlock); 174 175 isl_ast_node_free(AstRoot); 176 } else { 177 NodeBuilder.allocateNewArrays(); 178 NodeBuilder.addParameters(S.getContext()); 179 Value *RTC = NodeBuilder.createRTC(AI->getRunCondition()); 180 181 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC); 182 Builder.SetInsertPoint(&StartBlock->front()); 183 184 NodeBuilder.create(AstRoot); 185 NodeBuilder.finalize(); 186 fixRegionInfo(EnteringBB->getParent(), R->getParent()); 187 } 188 189 Function *F = EnteringBB->getParent(); 190 verifyGeneratedFunction(S, *F); 191 for (auto *SubF : NodeBuilder.getParallelSubfunctions()) 192 verifyGeneratedFunction(S, *SubF); 193 194 // Mark the function such that we run additional cleanup passes on this 195 // function (e.g. mem2reg to rediscover phi nodes). 196 F->addFnAttr("polly-optimized"); 197 198 return true; 199 } 200 201 /// @brief Register all analyses and transformation required. 202 void getAnalysisUsage(AnalysisUsage &AU) const override { 203 AU.addRequired<DominatorTreeWrapperPass>(); 204 AU.addRequired<IslAstInfo>(); 205 AU.addRequired<RegionInfoPass>(); 206 AU.addRequired<ScalarEvolutionWrapperPass>(); 207 AU.addRequired<ScopDetection>(); 208 AU.addRequired<ScopInfoRegionPass>(); 209 AU.addRequired<LoopInfoWrapperPass>(); 210 211 AU.addPreserved<DependenceInfo>(); 212 213 AU.addPreserved<AAResultsWrapperPass>(); 214 AU.addPreserved<BasicAAWrapperPass>(); 215 AU.addPreserved<LoopInfoWrapperPass>(); 216 AU.addPreserved<DominatorTreeWrapperPass>(); 217 AU.addPreserved<GlobalsAAWrapperPass>(); 218 AU.addPreserved<PostDominatorTreeWrapperPass>(); 219 AU.addPreserved<IslAstInfo>(); 220 AU.addPreserved<ScopDetection>(); 221 AU.addPreserved<ScalarEvolutionWrapperPass>(); 222 AU.addPreserved<SCEVAAWrapperPass>(); 223 224 // FIXME: We do not yet add regions for the newly generated code to the 225 // region tree. 226 AU.addPreserved<RegionInfoPass>(); 227 AU.addPreserved<ScopInfoRegionPass>(); 228 } 229 }; 230 } // namespace 231 232 char CodeGeneration::ID = 1; 233 234 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); } 235 236 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen", 237 "Polly - Create LLVM-IR from SCoPs", false, false); 238 INITIALIZE_PASS_DEPENDENCY(DependenceInfo); 239 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 240 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 241 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 242 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 243 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 244 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen", 245 "Polly - Create LLVM-IR from SCoPs", false, false) 246