Polly 24.0.0git
CodeGeneration.cpp
Go to the documentation of this file.
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
26#include "polly/CodeGen/Utils.h"
28#include "polly/Options.h"
29#include "polly/ScopInfo.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/Analysis/RegionInfo.h"
34#include "llvm/Analysis/ValueTracking.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/KnownBits.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Transforms/Utils/LoopUtils.h"
44#include "isl/ast.h"
45#include <cassert>
46
47using namespace llvm;
48using namespace polly;
49
51#define DEBUG_TYPE "polly-codegen"
52
53static cl::opt<bool> Verify("polly-codegen-verify",
54 cl::desc("Verify the function generated by Polly"),
55 cl::Hidden, cl::cat(PollyCategory));
56
58
59static 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),
63 cl::cat(PollyCategory));
64
65STATISTIC(ScopsProcessed, "Number of SCoP processed");
66STATISTIC(CodegenedScops, "Number of successfully generated SCoPs");
67STATISTIC(CodegenedAffineLoops,
68 "Number of original affine loops in SCoPs that have been generated");
69STATISTIC(CodegenedBoxedLoops,
70 "Number of original boxed loops in SCoPs that have been generated");
71
72namespace polly {
73
74/// Mark a basic block unreachable.
75///
76/// Marks the basic block @p Block unreachable by equipping it with an
77/// UnreachableInst.
78void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder) {
79 auto OrigTerminator = Block.getTerminator()->getIterator();
80 Builder.SetInsertPoint(OrigTerminator);
81 Builder.CreateUnreachable();
82 OrigTerminator->eraseFromParent();
83}
84} // namespace polly
85
86static void verifyGeneratedFunction(Scop &S, Function &F, IslAstInfo &AI) {
87 if (!Verify || !verifyFunction(F, &errs()))
88 return;
89
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.
107static 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.
144static 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 IT->eraseFromParent();
158 break;
159 default:
160 break;
161 }
162 }
163
164 InstIt = NextIt;
165 }
166 }
167}
168
169static bool generateCode(Scop &S, IslAstInfo &AI, LoopInfo &LI,
170 DominatorTree &DT, ScalarEvolution &SE,
171 RegionInfo &RI) {
172 // Check whether IslAstInfo uses the same isl_ctx. Since -polly-codegen
173 // reports itself to preserve DependenceInfo and IslAstInfo, we might get
174 // those analysis that were computed by a different ScopInfo for a different
175 // Scop structure. When the ScopInfo/Scop object is freed, there is a high
176 // probability that the new ScopInfo/Scop object will be created at the same
177 // heap position with the same address. Comparing whether the Scop or ScopInfo
178 // address is the expected therefore is unreliable.
179 // Instead, we compare the address of the isl_ctx object. Both, DependenceInfo
180 // and IslAstInfo must hold a reference to the isl_ctx object to ensure it is
181 // not freed before the destruction of those analyses which might happen after
182 // the destruction of the Scop/ScopInfo they refer to. Hence, the isl_ctx
183 // will not be freed and its space not reused as long there is a
184 // DependenceInfo or IslAstInfo around.
185 IslAst &Ast = AI.getIslAst();
186 if (Ast.getSharedIslCtx() != S.getSharedIslCtx()) {
187 POLLY_DEBUG(dbgs() << "Got an IstAst for a different Scop/isl_ctx\n");
188 return false;
189 }
190
191 // Check if we created an isl_ast root node, otherwise exit.
192 isl::ast_node AstRoot = Ast.getAst();
193 if (AstRoot.is_null())
194 return false;
195
196 // Collect statistics. Do it before we modify the IR to avoid having it any
197 // influence on the result.
198 auto ScopStats = S.getStatistics();
199 ScopsProcessed++;
200
201 auto &DL = S.getFunction().getDataLayout();
202 Region *R = &S.getRegion();
203 assert(!R->isTopLevelRegion() && "Top level regions are not supported");
204
205 ScopAnnotator Annotator;
206
207 simplifyRegion(R, &DT, &LI, &RI);
208 assert(R->isSimple());
209 BasicBlock *EnteringBB = S.getEnteringBlock();
210 assert(EnteringBB);
211 PollyIRBuilder Builder(EnteringBB->getTerminator()->getIterator(),
212 ConstantFolder(), IRInserter(Annotator));
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
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()->getIterator());
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 } else {
270 NodeBuilder.addParameters(S.getContext().release());
271 Value *RTC = NodeBuilder.createRTC(AI.getRunCondition().release());
272
273 Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
274
275 // The code below annotates the code flow taken when RTCs fail with
276 // "llvm.loop.vectorize.disable". We do this to avoid that the
277 // Loop Vectorizer comes in later and vectorizes the original fall back
278 // loop when Polly is enabled. If Polly's RTC value is known to be
279 // false (e.g. due to code generation failure), leave it eligible for
280 // vectorization as we are left with only one version of Loop.
281 if (!computeKnownBits(RTC, DL).isZero()) {
282 for (Loop *L : LI.getLoopsInPreorder()) {
283 if (S.contains(L))
284 addStringMetadataToLoop(L, StringRef("llvm.loop.vectorize.disable"));
285 }
286 }
287
288 // Explicitly set the insert point to the end of the block to avoid that a
289 // split at the builder's current
290 // insert position would move the malloc calls to the wrong BasicBlock.
291 // Ideally we would just split the block during allocation of the new
292 // arrays, but this would break the assumption that there are no blocks
293 // between polly.start and polly.exiting (at this point).
294 Builder.SetInsertPoint(StartBlock->getTerminator()->getIterator());
295
296 NodeBuilder.generateBeginScopTrace();
297
298 NodeBuilder.create(AstRoot.release());
299 NodeBuilder.finalize();
300 fixRegionInfo(*EnteringBB->getParent(), *R->getParent(), RI);
301
302 CodegenedScops++;
303 CodegenedAffineLoops += ScopStats.NumAffineLoops;
304 CodegenedBoxedLoops += ScopStats.NumBoxedLoops;
305 }
306
307 Function *F = EnteringBB->getParent();
308 verifyGeneratedFunction(S, *F, AI);
309 for (auto *SubF : NodeBuilder.getParallelSubfunctions())
310 verifyGeneratedFunction(S, *SubF, AI);
311
312 // Mark the function such that we run additional cleanup passes on this
313 // function (e.g. mem2reg to rediscover phi nodes).
314 F->addFnAttr("polly-optimized");
315 return true;
316}
317
318bool polly::runCodeGeneration(Scop &S, RegionInfo &RI, IslAstInfo &AI) {
319 return generateCode(S, AI, *S.getLI(), *S.getDT(), *S.getSE(), RI);
320}
static bool generateCode(Scop &S, IslAstInfo &AI, LoopInfo &LI, DominatorTree &DT, ScalarEvolution &SE, RegionInfo &RI)
STATISTIC(ScopsProcessed, "Number of SCoP processed")
static cl::opt< bool, true > XPerfMonitoring("polly-codegen-perf-monitoring", cl::desc("Add run-time performance monitoring"), cl::Hidden, cl::location(polly::PerfMonitoring), cl::cat(PollyCategory))
static void verifyGeneratedFunction(Scop &S, Function &F, IslAstInfo &AI)
static void fixRegionInfo(Function &F, Region &ParentRegion, RegionInfo &RI)
static cl::opt< bool > Verify("polly-codegen-verify", cl::desc("Verify the function generated by Polly"), cl::Hidden, cl::cat(PollyCategory))
static void removeLifetimeMarkers(Region *R)
Remove all lifetime markers (llvm.lifetime.start, llvm.lifetime.end) from @R.
llvm::cl::OptionCategory PollyCategory
#define POLLY_DEBUG(X)
Definition PollyDebug.h:23
__isl_give isl_ast_expr * release()
__isl_give isl_ast_node * release()
Add Polly specifics when running IRBuilder.
Definition IRBuilder.h:123
isl::ast_expr getRunCondition()
Get the run condition.
Definition IslAst.cpp:592
void print(raw_ostream &O)
Definition IslAst.cpp:739
IslAst & getIslAst()
Return the isl AST computed by this IslAstInfo.
Definition IslAst.h:112
const std::shared_ptr< isl_ctx > getSharedIslCtx() const
Definition IslAst.h:45
isl::ast_node getAst()
Definition IslAst.cpp:588
void addParameters(__isl_take isl_set *Context)
void create(__isl_take isl_ast_node *Node)
virtual void finalize()
Finalize code generation.
bool preloadInvariantLoads()
Preload all memory loads that are invariant.
void allocateNewArrays(BBPair StartExitBlocks)
Allocate memory for all new arrays created by Polly.
ArrayRef< Function * > getParallelSubfunctions() const
Return the parallel subfunctions that have been created.
Value * createRTC(isl_ast_expr *Condition)
Generate code that evaluates Condition at run-time.
void initialize()
Initialize the performance monitor.
void insertRegionEnd(llvm::Instruction *InsertBefore)
Mark the end of a timing region.
void insertRegionStart(llvm::Instruction *InsertBefore)
Mark the beginning of a timing region.
Helper class to annotate newly generated SCoPs with metadata.
Definition IRBuilder.h:44
void buildAliasScopes(Scop &S)
Build all alias scopes for the given SCoP.
Definition IRBuilder.cpp:59
Static Control Part.
Definition ScopInfo.h:1627
#define S(TYPE, NAME)
#define assert(exp)
bool PerfMonitoring
void markBlockUnreachable(BasicBlock &Block, PollyIRBuilder &Builder)
Mark a basic block unreachable.
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
std::pair< BBPair, llvm::CondBrInst * > executeScopConditionally(Scop &S, llvm::Value *RTC, llvm::DominatorTree &DT, llvm::RegionInfo &RI, llvm::LoopInfo &LI)
Execute a Scop conditionally wrt RTC.
llvm::IRBuilder< llvm::ConstantFolder, IRInserter > PollyIRBuilder
Definition IRBuilder.h:143
bool runCodeGeneration(Scop &S, llvm::RegionInfo &RI, IslAstInfo &AI)
void simplifyRegion(llvm::Region *R, llvm::DominatorTree *DT, llvm::LoopInfo *LI, llvm::RegionInfo *RI)
Simplify the region to have a single unconditional entry edge and a single exit edge.
std::pair< llvm::BasicBlock *, llvm::BasicBlock * > BBPair
Type to hold region delimiters (entry & exit block).
Definition Utils.h:31