1 //===- CodeGeneration.cpp - Code generate the Scops using ISL. ---------======//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The CodeGeneration pass takes a Scop created by ScopInfo and translates it
10 // back to LLVM-IR using the ISL code generator.
11 //
12 // The Scop describes the high level memory behavior of a control flow region.
13 // Transformation passes can update the schedule (execution order) of statements
14 // in the Scop. ISL is used to generate an abstract syntax tree that reflects
15 // the updated execution order. This clast is used to create new LLVM-IR that is
16 // computationally equivalent to the original control flow region, but executes
17 // its code in the new execution order defined by the changed schedule.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "polly/CodeGen/CodeGeneration.h"
22 #include "polly/CodeGen/IRBuilder.h"
23 #include "polly/CodeGen/IslAst.h"
24 #include "polly/CodeGen/IslNodeBuilder.h"
25 #include "polly/CodeGen/PerfMonitor.h"
26 #include "polly/CodeGen/Utils.h"
27 #include "polly/DependenceInfo.h"
28 #include "polly/LinkAllPasses.h"
29 #include "polly/Options.h"
30 #include "polly/ScopInfo.h"
31 #include "polly/Support/ScopHelper.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/Analysis/RegionInfo.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/PassManager.h"
39 #include "llvm/IR/Verifier.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "isl/ast.h"
45 #include <cassert>
46
47 using namespace llvm;
48 using namespace polly;
49
50 #define DEBUG_TYPE "polly-codegen"
51
52 static cl::opt<bool> Verify("polly-codegen-verify",
53 cl::desc("Verify the function generated by Polly"),
54 cl::Hidden, cl::init(false), cl::ZeroOrMore,
55 cl::cat(PollyCategory));
56
57 bool polly::PerfMonitoring;
58
59 static cl::opt<bool, true>
60 XPerfMonitoring("polly-codegen-perf-monitoring",
61 cl::desc("Add run-time performance monitoring"), cl::Hidden,
62 cl::location(polly::PerfMonitoring), cl::init(false),
63 cl::ZeroOrMore, cl::cat(PollyCategory));
64
65 STATISTIC(ScopsProcessed, "Number of SCoP processed");
66 STATISTIC(CodegenedScops, "Number of successfully generated SCoPs");
67 STATISTIC(CodegenedAffineLoops,
68 "Number of original affine loops in SCoPs that have been generated");
69 STATISTIC(CodegenedBoxedLoops,
70 "Number of original boxed loops in SCoPs that have been generated");
71
72 namespace polly {
73
74 /// Mark a basic block unreachable.
75 ///
76 /// Marks the basic block @p Block unreachable by equipping it with an
77 /// UnreachableInst.
markBlockUnreachable(BasicBlock & Block,PollyIRBuilder & Builder)78 void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) {
79 auto *OrigTerminator = Block.getTerminator();
80 Builder.SetInsertPoint(OrigTerminator);
81 Builder.CreateUnreachable();
82 OrigTerminator->eraseFromParent();
83 }
84 } // namespace polly
85
verifyGeneratedFunction(Scop & S,Function & F,IslAstInfo & AI)86 static void verifyGeneratedFunction(Scop &S, Function &F, IslAstInfo &AI) {
87 if (!Verify || !verifyFunction(F, &errs()))
88 return;
89
90 LLVM_DEBUG({
91 errs() << "== ISL Codegen created an invalid function ==\n\n== The "
92 "SCoP ==\n";
93 errs() << S;
94 errs() << "\n== The isl AST ==\n";
95 AI.print(errs());
96 errs() << "\n== The invalid function ==\n";
97 F.print(errs());
98 });
99
100 llvm_unreachable("Polly generated function could not be verified. Add "
101 "-polly-codegen-verify=false to disable this assertion.");
102 }
103
104 // CodeGeneration adds a lot of BBs without updating the RegionInfo
105 // We make all created BBs belong to the scop's parent region without any
106 // nested structure to keep the RegionInfo verifier happy.
fixRegionInfo(Function & F,Region & ParentRegion,RegionInfo & RI)107 static void fixRegionInfo(Function &F, Region &ParentRegion, RegionInfo &RI) {
108 for (BasicBlock &BB : F) {
109 if (RI.getRegionFor(&BB))
110 continue;
111
112 RI.setRegionFor(&BB, &ParentRegion);
113 }
114 }
115
116 /// Remove all lifetime markers (llvm.lifetime.start, llvm.lifetime.end) from
117 /// @R.
118 ///
119 /// CodeGeneration does not copy lifetime markers into the optimized SCoP,
120 /// which would leave the them only in the original path. This can transform
121 /// code such as
122 ///
123 /// llvm.lifetime.start(%p)
124 /// llvm.lifetime.end(%p)
125 ///
126 /// into
127 ///
128 /// if (RTC) {
129 /// // generated code
130 /// } else {
131 /// // original code
132 /// llvm.lifetime.start(%p)
133 /// }
134 /// llvm.lifetime.end(%p)
135 ///
136 /// The current StackColoring algorithm cannot handle if some, but not all,
137 /// paths from the end marker to the entry block cross the start marker. Same
138 /// for start markers that do not always cross the end markers. We avoid any
139 /// issues by removing all lifetime markers, even from the original code.
140 ///
141 /// A better solution could be to hoist all llvm.lifetime.start to the split
142 /// node and all llvm.lifetime.end to the merge node, which should be
143 /// conservatively correct.
removeLifetimeMarkers(Region * R)144 static void removeLifetimeMarkers(Region *R) {
145 for (auto *BB : R->blocks()) {
146 auto InstIt = BB->begin();
147 auto InstEnd = BB->end();
148
149 while (InstIt != InstEnd) {
150 auto NextIt = InstIt;
151 ++NextIt;
152
153 if (auto *IT = dyn_cast<IntrinsicInst>(&*InstIt)) {
154 switch (IT->getIntrinsicID()) {
155 case Intrinsic::lifetime_start:
156 case Intrinsic::lifetime_end:
157 BB->getInstList().erase(InstIt);
158 break;
159 default:
160 break;
161 }
162 }
163
164 InstIt = NextIt;
165 }
166 }
167 }
168
CodeGen(Scop & S,IslAstInfo & AI,LoopInfo & LI,DominatorTree & DT,ScalarEvolution & SE,RegionInfo & RI)169 static bool CodeGen(Scop &S, IslAstInfo &AI, LoopInfo &LI, DominatorTree &DT,
170 ScalarEvolution &SE, RegionInfo &RI) {
171 // Check whether IslAstInfo uses the same isl_ctx. Since -polly-codegen
172 // reports itself to preserve DependenceInfo and IslAstInfo, we might get
173 // those analysis that were computed by a different ScopInfo for a different
174 // Scop structure. When the ScopInfo/Scop object is freed, there is a high
175 // probability that the new ScopInfo/Scop object will be created at the same
176 // heap position with the same address. Comparing whether the Scop or ScopInfo
177 // address is the expected therefore is unreliable.
178 // Instead, we compare the address of the isl_ctx object. Both, DependenceInfo
179 // and IslAstInfo must hold a reference to the isl_ctx object to ensure it is
180 // not freed before the destruction of those analyses which might happen after
181 // the destruction of the Scop/ScopInfo they refer to. Hence, the isl_ctx
182 // will not be freed and its space not reused as long there is a
183 // DependenceInfo or IslAstInfo around.
184 IslAst &Ast = AI.getIslAst();
185 if (Ast.getSharedIslCtx() != S.getSharedIslCtx()) {
186 LLVM_DEBUG(dbgs() << "Got an IstAst for a different Scop/isl_ctx\n");
187 return false;
188 }
189
190 // Check if we created an isl_ast root node, otherwise exit.
191 isl_ast_node *AstRoot = Ast.getAst();
192 if (!AstRoot)
193 return false;
194
195 // Collect statistics. Do it before we modify the IR to avoid having it any
196 // influence on the result.
197 auto ScopStats = S.getStatistics();
198 ScopsProcessed++;
199
200 auto &DL = S.getFunction().getParent()->getDataLayout();
201 Region *R = &S.getRegion();
202 assert(!R->isTopLevelRegion() && "Top level regions are not supported");
203
204 ScopAnnotator Annotator;
205
206 simplifyRegion(R, &DT, &LI, &RI);
207 assert(R->isSimple());
208 BasicBlock *EnteringBB = S.getEnteringBlock();
209 assert(EnteringBB);
210 PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(),
211 IRInserter(Annotator));
212 Builder.SetInsertPoint(EnteringBB->getTerminator());
213
214 // Only build the run-time condition and parameters _after_ having
215 // introduced the conditional branch. This is important as the conditional
216 // branch will guard the original scop from new induction variables that
217 // the SCEVExpander may introduce while code generating the parameters and
218 // which may introduce scalar dependences that prevent us from correctly
219 // code generating this scop.
220 BBPair StartExitBlocks =
221 std::get<0>(executeScopConditionally(S, Builder.getTrue(), DT, RI, LI));
222 BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
223 BasicBlock *ExitBlock = std::get<1>(StartExitBlocks);
224
225 removeLifetimeMarkers(R);
226 auto *SplitBlock = StartBlock->getSinglePredecessor();
227
228 IslNodeBuilder NodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock);
229
230 // All arrays must have their base pointers known before
231 // ScopAnnotator::buildAliasScopes.
232 NodeBuilder.allocateNewArrays(StartExitBlocks);
233 Annotator.buildAliasScopes(S);
234
235 if (PerfMonitoring) {
236 PerfMonitor P(S, EnteringBB->getParent()->getParent());
237 P.initialize();
238 P.insertRegionStart(SplitBlock->getTerminator());
239
240 BasicBlock *MergeBlock = ExitBlock->getUniqueSuccessor();
241 P.insertRegionEnd(MergeBlock->getTerminator());
242 }
243
244 // First generate code for the hoisted invariant loads and transitively the
245 // parameters they reference. Afterwards, for the remaining parameters that
246 // might reference the hoisted loads. Finally, build the runtime check
247 // that might reference both hoisted loads as well as parameters.
248 // If the hoisting fails we have to bail and execute the original code.
249 Builder.SetInsertPoint(SplitBlock->getTerminator());
250 if (!NodeBuilder.preloadInvariantLoads()) {
251 // Patch the introduced branch condition to ensure that we always execute
252 // the original SCoP.
253 auto *FalseI1 = Builder.getFalse();
254 auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
255 SplitBBTerm->setOperand(0, FalseI1);
256
257 // Since the other branch is hence ignored we mark it as unreachable and
258 // adjust the dominator tree accordingly.
259 auto *ExitingBlock = StartBlock->getUniqueSuccessor();
260 assert(ExitingBlock);
261 auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
262 assert(MergeBlock);
263 markBlockUnreachable(*StartBlock, Builder);
264 markBlockUnreachable(*ExitingBlock, Builder);
265 auto *ExitingBB = S.getExitingBlock();
266 assert(ExitingBB);
267 DT.changeImmediateDominator(MergeBlock, ExitingBB);
268 DT.eraseNode(ExitingBlock);
269
270 isl_ast_node_free(AstRoot);
271 } else {
272 NodeBuilder.addParameters(S.getContext().release());
273 Value *RTC = NodeBuilder.createRTC(AI.getRunCondition());
274
275 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
276
277 // Explicitly set the insert point to the end of the block to avoid that a
278 // split at the builder's current
279 // insert position would move the malloc calls to the wrong BasicBlock.
280 // Ideally we would just split the block during allocation of the new
281 // arrays, but this would break the assumption that there are no blocks
282 // between polly.start and polly.exiting (at this point).
283 Builder.SetInsertPoint(StartBlock->getTerminator());
284
285 NodeBuilder.create(AstRoot);
286 NodeBuilder.finalize();
287 fixRegionInfo(*EnteringBB->getParent(), *R->getParent(), RI);
288
289 CodegenedScops++;
290 CodegenedAffineLoops += ScopStats.NumAffineLoops;
291 CodegenedBoxedLoops += ScopStats.NumBoxedLoops;
292 }
293
294 Function *F = EnteringBB->getParent();
295 verifyGeneratedFunction(S, *F, AI);
296 for (auto *SubF : NodeBuilder.getParallelSubfunctions())
297 verifyGeneratedFunction(S, *SubF, AI);
298
299 // Mark the function such that we run additional cleanup passes on this
300 // function (e.g. mem2reg to rediscover phi nodes).
301 F->addFnAttr("polly-optimized");
302 return true;
303 }
304
305 namespace {
306
307 class CodeGeneration : public ScopPass {
308 public:
309 static char ID;
310
311 /// The data layout used.
312 const DataLayout *DL;
313
314 /// @name The analysis passes we need to generate code.
315 ///
316 ///{
317 LoopInfo *LI;
318 IslAstInfo *AI;
319 DominatorTree *DT;
320 ScalarEvolution *SE;
321 RegionInfo *RI;
322 ///}
323
CodeGeneration()324 CodeGeneration() : ScopPass(ID) {}
325
326 /// Generate LLVM-IR for the SCoP @p S.
runOnScop(Scop & S)327 bool runOnScop(Scop &S) override {
328 // Skip SCoPs in case they're already code-generated by PPCGCodeGeneration.
329 if (S.isToBeSkipped())
330 return false;
331
332 AI = &getAnalysis<IslAstInfoWrapperPass>().getAI();
333 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
334 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
335 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
336 DL = &S.getFunction().getParent()->getDataLayout();
337 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
338 return CodeGen(S, *AI, *LI, *DT, *SE, *RI);
339 }
340
341 /// Register all analyses and transformation required.
getAnalysisUsage(AnalysisUsage & AU) const342 void getAnalysisUsage(AnalysisUsage &AU) const override {
343 ScopPass::getAnalysisUsage(AU);
344
345 AU.addRequired<DominatorTreeWrapperPass>();
346 AU.addRequired<IslAstInfoWrapperPass>();
347 AU.addRequired<RegionInfoPass>();
348 AU.addRequired<ScalarEvolutionWrapperPass>();
349 AU.addRequired<ScopDetectionWrapperPass>();
350 AU.addRequired<ScopInfoRegionPass>();
351 AU.addRequired<LoopInfoWrapperPass>();
352
353 AU.addPreserved<DependenceInfo>();
354 AU.addPreserved<IslAstInfoWrapperPass>();
355
356 // FIXME: We do not yet add regions for the newly generated code to the
357 // region tree.
358 }
359 };
360 } // namespace
361
run(Scop & S,ScopAnalysisManager & SAM,ScopStandardAnalysisResults & AR,SPMUpdater & U)362 PreservedAnalyses CodeGenerationPass::run(Scop &S, ScopAnalysisManager &SAM,
363 ScopStandardAnalysisResults &AR,
364 SPMUpdater &U) {
365 auto &AI = SAM.getResult<IslAstAnalysis>(S, AR);
366 if (CodeGen(S, AI, AR.LI, AR.DT, AR.SE, AR.RI)) {
367 U.invalidateScop(S);
368 return PreservedAnalyses::none();
369 }
370
371 return PreservedAnalyses::all();
372 }
373
374 char CodeGeneration::ID = 1;
375
createCodeGenerationPass()376 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
377
378 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
379 "Polly - Create LLVM-IR from SCoPs", false, false);
380 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
381 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
382 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
383 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
384 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
385 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
386 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
387 "Polly - Create LLVM-IR from SCoPs", false, false)
388