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   /// @brief Build the runtime condition.
70   ///
71   /// Build the condition that evaluates at run-time to true iff all
72   /// assumptions taken for the SCoP hold, and to false otherwise.
73   ///
74   /// @return A value evaluating to true/false if execution is save/unsafe.
75   Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
76     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
77     Value *RTC = ExprBuilder.create(AI->getRunCondition());
78     if (!RTC->getType()->isIntegerTy(1))
79       RTC = Builder.CreateIsNotNull(RTC);
80     return RTC;
81   }
82 
83   void verifyGeneratedFunction(Scop &S, Function &F) {
84     if (!verifyFunction(F, &errs()) || !Verify)
85       return;
86 
87     DEBUG({
88       errs() << "== ISL Codegen created an invalid function ==\n\n== The "
89                 "SCoP ==\n";
90       S.print(errs());
91       errs() << "\n== The isl AST ==\n";
92       AI->printScop(errs(), S);
93       errs() << "\n== The invalid function ==\n";
94       F.print(errs());
95     });
96 
97     llvm_unreachable("Polly generated function could not be verified. Add "
98                      "-polly-codegen-verify=false to disable this assertion.");
99   }
100 
101   // CodeGeneration adds a lot of BBs without updating the RegionInfo
102   // We make all created BBs belong to the scop's parent region without any
103   // nested structure to keep the RegionInfo verifier happy.
104   void fixRegionInfo(Function *F, Region *ParentRegion) {
105     for (BasicBlock &BB : *F) {
106       if (RI->getRegionFor(&BB))
107         continue;
108 
109       RI->setRegionFor(&BB, ParentRegion);
110     }
111   }
112 
113   /// @brief Generate LLVM-IR for the SCoP @p S.
114   bool runOnScop(Scop &S) override {
115     AI = &getAnalysis<IslAstInfo>();
116 
117     // Check if we created an isl_ast root node, otherwise exit.
118     isl_ast_node *AstRoot = AI->getAst();
119     if (!AstRoot)
120       return false;
121 
122     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
123     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
124     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
125     DL = &S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
126     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
127     Region *R = &S.getRegion();
128     assert(!R->isTopLevelRegion() && "Top level regions are not supported");
129 
130     ScopAnnotator Annotator;
131     Annotator.buildAliasScopes(S);
132 
133     simplifyRegion(R, DT, LI, RI);
134     assert(R->isSimple());
135     BasicBlock *EnteringBB = S.getRegion().getEnteringBlock();
136     assert(EnteringBB);
137     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
138 
139     IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
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     // First generate code for the hoisted invariant loads and transitively the
152     // parameters they reference. Afterwards, for the remaining parameters that
153     // might reference the hoisted loads. Finally, build the runtime check
154     // that might reference both hoisted loads as well as parameters.
155     // If the hoisting fails we have to bail and execute the original code.
156     Builder.SetInsertPoint(SplitBlock->getTerminator());
157     if (!NodeBuilder.preloadInvariantLoads()) {
158 
159       auto *FalseI1 = Builder.getFalse();
160       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
161       SplitBBTerm->setOperand(0, FalseI1);
162       auto *StartBBTerm = StartBlock->getTerminator();
163       Builder.SetInsertPoint(StartBBTerm);
164       Builder.CreateUnreachable();
165       StartBBTerm->eraseFromParent();
166       isl_ast_node_free(AstRoot);
167 
168     } else {
169 
170       NodeBuilder.addParameters(S.getContext());
171 
172       Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
173       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
174       Builder.SetInsertPoint(&StartBlock->front());
175 
176       NodeBuilder.create(AstRoot);
177 
178       NodeBuilder.finalizeSCoP(S);
179       fixRegionInfo(EnteringBB->getParent(), R->getParent());
180     }
181 
182     verifyGeneratedFunction(S, *EnteringBB->getParent());
183 
184     // Mark the function such that we run additional cleanup passes on this
185     // function (e.g. mem2reg to rediscover phi nodes).
186     Function *F = EnteringBB->getParent();
187     F->addFnAttr("polly-optimized");
188 
189     return true;
190   }
191 
192   /// @brief Register all analyses and transformation required.
193   void getAnalysisUsage(AnalysisUsage &AU) const override {
194     AU.addRequired<DominatorTreeWrapperPass>();
195     AU.addRequired<IslAstInfo>();
196     AU.addRequired<RegionInfoPass>();
197     AU.addRequired<ScalarEvolutionWrapperPass>();
198     AU.addRequired<ScopDetection>();
199     AU.addRequired<ScopInfo>();
200     AU.addRequired<LoopInfoWrapperPass>();
201 
202     AU.addPreserved<DependenceInfo>();
203 
204     AU.addPreserved<AAResultsWrapperPass>();
205     AU.addPreserved<BasicAAWrapperPass>();
206     AU.addPreserved<LoopInfoWrapperPass>();
207     AU.addPreserved<DominatorTreeWrapperPass>();
208     AU.addPreserved<GlobalsAAWrapperPass>();
209     AU.addPreserved<PostDominatorTreeWrapperPass>();
210     AU.addPreserved<IslAstInfo>();
211     AU.addPreserved<ScopDetection>();
212     AU.addPreserved<ScalarEvolutionWrapperPass>();
213     AU.addPreserved<SCEVAAWrapperPass>();
214 
215     // FIXME: We do not yet add regions for the newly generated code to the
216     //        region tree.
217     AU.addPreserved<RegionInfoPass>();
218     AU.addPreserved<ScopInfo>();
219   }
220 };
221 }
222 
223 char CodeGeneration::ID = 1;
224 
225 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
226 
227 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
228                       "Polly - Create LLVM-IR from SCoPs", false, false);
229 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
230 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
231 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
232 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
233 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
234 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
235 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
236                     "Polly - Create LLVM-IR from SCoPs", false, false)
237