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