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