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