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/IslNodeBuilder.h"
23 #include "polly/CodeGen/IslAst.h"
24 #include "polly/CodeGen/Utils.h"
25 #include "polly/DependenceInfo.h"
26 #include "polly/LinkAllPasses.h"
27 #include "polly/ScopInfo.h"
28 #include "polly/Support/ScopHelper.h"
29 #include "polly/TempScopInfo.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Support/Debug.h"
33 
34 using namespace polly;
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "polly-codegen"
38 
39 namespace {
40 class CodeGeneration : public ScopPass {
41 public:
42   static char ID;
43 
44   CodeGeneration() : ScopPass(ID) {}
45 
46   /// @brief The datalayout used
47   const DataLayout *DL;
48 
49   /// @name The analysis passes we need to generate code.
50   ///
51   ///{
52   LoopInfo *LI;
53   IslAstInfo *AI;
54   DominatorTree *DT;
55   ScalarEvolution *SE;
56   ///}
57 
58   /// @brief The loop annotator to generate llvm.loop metadata.
59   ScopAnnotator Annotator;
60 
61   /// @brief Build the runtime condition.
62   ///
63   /// Build the condition that evaluates at run-time to true iff all
64   /// assumptions taken for the SCoP hold, and to false otherwise.
65   ///
66   /// @return A value evaluating to true/false if execution is save/unsafe.
67   Value *buildRTC(PollyIRBuilder &Builder, IslExprBuilder &ExprBuilder) {
68     Builder.SetInsertPoint(Builder.GetInsertBlock()->getTerminator());
69     Value *RTC = ExprBuilder.create(AI->getRunCondition());
70     if (!RTC->getType()->isIntegerTy(1))
71       RTC = Builder.CreateIsNotNull(RTC);
72     return RTC;
73   }
74 
75   bool verifyGeneratedFunction(Scop &S, Function &F) {
76     if (!verifyFunction(F))
77       return false;
78 
79     DEBUG({
80       errs() << "== ISL Codegen created an invalid function ==\n\n== The "
81                 "SCoP ==\n";
82       S.print(errs());
83       errs() << "\n== The isl AST ==\n";
84       AI->printScop(errs(), S);
85       errs() << "\n== The invalid function ==\n";
86       F.print(errs());
87       errs() << "\n== The errors ==\n";
88       verifyFunction(F, &errs());
89     });
90 
91     return true;
92   }
93 
94   bool runOnScop(Scop &S) override {
95     AI = &getAnalysis<IslAstInfo>();
96 
97     // Check if we created an isl_ast root node, otherwise exit.
98     isl_ast_node *AstRoot = AI->getAst();
99     if (!AstRoot)
100       return false;
101 
102     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
103     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
104     SE = &getAnalysis<ScalarEvolution>();
105     DL = &S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
106 
107     assert(!S.getRegion().isTopLevelRegion() &&
108            "Top level regions are not supported");
109 
110     Annotator.buildAliasScopes(S);
111 
112     BasicBlock *EnteringBB = simplifyRegion(&S, this);
113     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
114 
115     IslNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, S);
116 
117     // Only build the run-time condition and parameters _after_ having
118     // introduced the conditional branch. This is important as the conditional
119     // branch will guard the original scop from new induction variables that
120     // the SCEVExpander may introduce while code generating the parameters and
121     // which may introduce scalar dependences that prevent us from correctly
122     // code generating this scop.
123     BasicBlock *StartBlock =
124         executeScopConditionally(S, this, Builder.getTrue());
125     auto SplitBlock = StartBlock->getSinglePredecessor();
126     Builder.SetInsertPoint(SplitBlock->getTerminator());
127     NodeBuilder.addParameters(S.getContext());
128     Value *RTC = buildRTC(Builder, NodeBuilder.getExprBuilder());
129     SplitBlock->getTerminator()->setOperand(0, RTC);
130     Builder.SetInsertPoint(StartBlock->begin());
131 
132     NodeBuilder.create(AstRoot);
133 
134     NodeBuilder.finalizeSCoP(S);
135 
136     assert(!verifyGeneratedFunction(S, *EnteringBB->getParent()) &&
137            "Verification of generated function failed");
138     return true;
139   }
140 
141   void printScop(raw_ostream &, Scop &) const override {}
142 
143   void getAnalysisUsage(AnalysisUsage &AU) const override {
144     AU.addRequired<DominatorTreeWrapperPass>();
145     AU.addRequired<IslAstInfo>();
146     AU.addRequired<RegionInfoPass>();
147     AU.addRequired<ScalarEvolution>();
148     AU.addRequired<ScopDetection>();
149     AU.addRequired<ScopInfo>();
150     AU.addRequired<LoopInfoWrapperPass>();
151 
152     AU.addPreserved<DependenceInfo>();
153 
154     AU.addPreserved<LoopInfoWrapperPass>();
155     AU.addPreserved<DominatorTreeWrapperPass>();
156     AU.addPreserved<IslAstInfo>();
157     AU.addPreserved<ScopDetection>();
158     AU.addPreserved<ScalarEvolution>();
159 
160     // FIXME: We do not yet add regions for the newly generated code to the
161     //        region tree.
162     AU.addPreserved<RegionInfoPass>();
163     AU.addPreserved<TempScopInfo>();
164     AU.addPreserved<ScopInfo>();
165     AU.addPreservedID(IndependentBlocksID);
166   }
167 };
168 }
169 
170 char CodeGeneration::ID = 1;
171 
172 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
173 
174 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
175                       "Polly - Create LLVM-IR from SCoPs", false, false);
176 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
177 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
178 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
179 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
180 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
181 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
182 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
183                     "Polly - Create LLVM-IR from SCoPs", false, false)
184