blob: d2123bd69eb4e0de947f52c1a9c96bea5a5bd0a4 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===- ScopHelper.cpp - Some Helper Functions for Scop. ------------------===//
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// Small functions that help with Scop and LLVM-IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "polly/Support/ScopHelper.h"
Johannes Doerfertf80f3b02015-10-01 23:45:51 +000015#include "polly/Options.h"
Tobias Grosser8edce4e2013-04-16 08:04:42 +000016#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000017#include "llvm/Analysis/LoopInfo.h"
18#include "llvm/Analysis/RegionInfo.h"
19#include "llvm/Analysis/ScalarEvolution.h"
Johannes Doerferte69e1142015-08-18 11:56:00 +000020#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthc3478b92014-03-04 11:47:37 +000022#include "llvm/IR/CFG.h"
Chandler Carruth95fef942014-04-22 03:30:19 +000023#include "llvm/Support/Debug.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
25
Tobias Grosser75805372011-04-29 06:27:02 +000026using namespace llvm;
Johannes Doerferte69e1142015-08-18 11:56:00 +000027using namespace polly;
Tobias Grosser75805372011-04-29 06:27:02 +000028
Chandler Carruth95fef942014-04-22 03:30:19 +000029#define DEBUG_TYPE "polly-scop-helper"
30
Johannes Doerfertf80f3b02015-10-01 23:45:51 +000031static cl::list<std::string>
32 ErrorFunctions("polly-error-functions",
33 cl::desc("A list of error functions"), cl::Hidden,
34 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
35
Tobias Grosser75805372011-04-29 06:27:02 +000036Value *polly::getPointerOperand(Instruction &Inst) {
37 if (LoadInst *load = dyn_cast<LoadInst>(&Inst))
38 return load->getPointerOperand();
39 else if (StoreInst *store = dyn_cast<StoreInst>(&Inst))
40 return store->getPointerOperand();
41 else if (GetElementPtrInst *gep = dyn_cast<GetElementPtrInst>(&Inst))
42 return gep->getPointerOperand();
43
44 return 0;
45}
46
Tobias Grosser75805372011-04-29 06:27:02 +000047bool polly::hasInvokeEdge(const PHINode *PN) {
48 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
49 if (InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i)))
50 if (II->getParent() == PN->getIncomingBlock(i))
51 return true;
52
53 return false;
54}
55
Michael Kruse22370882015-08-11 14:39:21 +000056// Ensures that there is just one predecessor to the entry node from outside the
57// region.
58// The identity of the region entry node is preserved.
59static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI,
60 RegionInfo *RI) {
Johannes Doerfert38262242014-09-10 14:50:23 +000061 BasicBlock *EnteringBB = R->getEnteringBlock();
Michael Kruse22370882015-08-11 14:39:21 +000062 BasicBlock *Entry = R->getEntry();
Johannes Doerfert38262242014-09-10 14:50:23 +000063
Michael Kruse22370882015-08-11 14:39:21 +000064 // Before (one of):
65 //
66 // \ / //
67 // EnteringBB //
68 // | \------> //
69 // \ / | //
70 // Entry <--\ Entry <--\ //
71 // / \ / / \ / //
72 // .... .... //
Chandler Carruth62975f52015-01-19 12:37:33 +000073
Tobias Grosser8edce4e2013-04-16 08:04:42 +000074 // Create single entry edge if the region has multiple entry edges.
Johannes Doerfert38262242014-09-10 14:50:23 +000075 if (!EnteringBB) {
Michael Kruse22370882015-08-11 14:39:21 +000076 SmallVector<BasicBlock *, 4> Preds;
77 for (BasicBlock *P : predecessors(Entry))
78 if (!R->contains(P))
79 Preds.push_back(P);
Johannes Doerfert38262242014-09-10 14:50:23 +000080
Michael Kruse22370882015-08-11 14:39:21 +000081 BasicBlock *NewEntering =
82 SplitBlockPredecessors(Entry, Preds, ".region_entering", DT, LI);
Johannes Doerfert0fe35dd2014-09-15 18:34:45 +000083
Michael Kruse22370882015-08-11 14:39:21 +000084 if (RI) {
85 // The exit block of predecessing regions must be changed to NewEntering
86 for (BasicBlock *ExitPred : predecessors(NewEntering)) {
87 Region *RegionOfPred = RI->getRegionFor(ExitPred);
88 if (RegionOfPred->getExit() != Entry)
89 continue;
Johannes Doerfert0fe35dd2014-09-15 18:34:45 +000090
Michael Kruse22370882015-08-11 14:39:21 +000091 while (!RegionOfPred->isTopLevelRegion() &&
92 RegionOfPred->getExit() == Entry) {
93 RegionOfPred->replaceExit(NewEntering);
94 RegionOfPred = RegionOfPred->getParent();
95 }
96 }
97
98 // Make all ancestors use EnteringBB as entry; there might be edges to it
99 Region *AncestorR = R->getParent();
100 RI->setRegionFor(NewEntering, AncestorR);
101 while (!AncestorR->isTopLevelRegion() && AncestorR->getEntry() == Entry) {
102 AncestorR->replaceEntry(NewEntering);
103 AncestorR = AncestorR->getParent();
104 }
Johannes Doerfert0fe35dd2014-09-15 18:34:45 +0000105 }
106
Michael Kruse22370882015-08-11 14:39:21 +0000107 EnteringBB = NewEntering;
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000108 }
Michael Kruse22370882015-08-11 14:39:21 +0000109 assert(R->getEnteringBlock() == EnteringBB);
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000110
Michael Kruse22370882015-08-11 14:39:21 +0000111 // After:
112 //
113 // \ / //
114 // EnteringBB //
115 // | //
116 // | //
117 // Entry <--\ //
118 // / \ / //
119 // .... //
120}
Johannes Doerfert0fe35dd2014-09-15 18:34:45 +0000121
Michael Kruse22370882015-08-11 14:39:21 +0000122// Ensure that the region has a single block that branches to the exit node.
123static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI,
124 RegionInfo *RI) {
125 BasicBlock *ExitBB = R->getExit();
126 BasicBlock *ExitingBB = R->getExitingBlock();
127
128 // Before:
129 //
130 // (Region) ______/ //
131 // \ | / //
132 // ExitBB //
133 // / \ //
134
135 if (!ExitingBB) {
136 SmallVector<BasicBlock *, 4> Preds;
137 for (BasicBlock *P : predecessors(ExitBB))
138 if (R->contains(P))
139 Preds.push_back(P);
140
141 // Preds[0] Preds[1] otherBB //
142 // \ | ________/ //
143 // \ | / //
144 // BB //
145 ExitingBB =
146 SplitBlockPredecessors(ExitBB, Preds, ".region_exiting", DT, LI);
147 // Preds[0] Preds[1] otherBB //
148 // \ / / //
149 // BB.region_exiting / //
150 // \ / //
151 // BB //
152
153 if (RI)
154 RI->setRegionFor(ExitingBB, R);
155
156 // Change the exit of nested regions, but not the region itself,
157 R->replaceExitRecursive(ExitingBB);
158 R->replaceExit(ExitBB);
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000159 }
Michael Kruse22370882015-08-11 14:39:21 +0000160 assert(ExitingBB == R->getExitingBlock());
Johannes Doerfert38262242014-09-10 14:50:23 +0000161
Michael Kruse22370882015-08-11 14:39:21 +0000162 // After:
163 //
164 // \ / //
165 // ExitingBB _____/ //
166 // \ / //
167 // ExitBB //
168 // / \ //
169}
170
171void polly::simplifyRegion(Region *R, DominatorTree *DT, LoopInfo *LI,
172 RegionInfo *RI) {
173 assert(R && !R->isTopLevelRegion());
174 assert(!RI || RI == R->getRegionInfo());
175 assert((!RI || DT) &&
176 "RegionInfo requires DominatorTree to be updated as well");
177
178 simplifyRegionEntry(R, DT, LI, RI);
179 simplifyRegionExit(R, DT, LI, RI);
180 assert(R->isSimple());
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000181}
182
Michael Kruse23d0e832015-08-11 14:04:06 +0000183// Split the block into two successive blocks.
184//
185// Like llvm::SplitBlock, but also preserves RegionInfo
186static BasicBlock *splitBlock(BasicBlock *Old, Instruction *SplitPt,
187 DominatorTree *DT, llvm::LoopInfo *LI,
188 RegionInfo *RI) {
189 assert(Old && SplitPt);
190
191 // Before:
192 //
193 // \ / //
194 // Old //
195 // / \ //
196
197 BasicBlock *NewBlock = llvm::SplitBlock(Old, SplitPt, DT, LI);
198
199 if (RI) {
200 Region *R = RI->getRegionFor(Old);
201 RI->setRegionFor(NewBlock, R);
202 }
203
204 // After:
205 //
206 // \ / //
207 // Old //
208 // | //
209 // NewBlock //
210 // / \ //
211
212 return NewBlock;
213}
214
Tobias Grosser75805372011-04-29 06:27:02 +0000215void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, Pass *P) {
216 // Find first non-alloca instruction. Every basic block has a non-alloc
217 // instruction, as every well formed basic block has a terminator.
218 BasicBlock::iterator I = EntryBlock->begin();
Tobias Grosserd535f552013-02-14 16:42:45 +0000219 while (isa<AllocaInst>(I))
220 ++I;
Tobias Grosser75805372011-04-29 06:27:02 +0000221
Chandler Carruth5ec33332015-01-18 10:52:23 +0000222 auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
223 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
224 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
225 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Michael Kruse23d0e832015-08-11 14:04:06 +0000226 RegionInfoPass *RIP = P->getAnalysisIfAvailable<RegionInfoPass>();
227 RegionInfo *RI = RIP ? &RIP->getRegionInfo() : nullptr;
Chandler Carruth5ec33332015-01-18 10:52:23 +0000228
Michael Kruse23d0e832015-08-11 14:04:06 +0000229 // splitBlock updates DT, LI and RI.
230 splitBlock(EntryBlock, I, DT, LI, RI);
Tobias Grosser75805372011-04-29 06:27:02 +0000231}
Johannes Doerferte69e1142015-08-18 11:56:00 +0000232
233/// The SCEVExpander will __not__ generate any code for an existing SDiv/SRem
234/// instruction but just use it, if it is referenced as a SCEVUnknown. We want
235/// however to generate new code if the instruction is in the analyzed region
236/// and we generate code outside/in front of that region. Hence, we generate the
237/// code for the SDiv/SRem operands in front of the analyzed region and then
238/// create a new SDiv/SRem operation there too.
239struct ScopExpander : SCEVVisitor<ScopExpander, const SCEV *> {
240 friend struct SCEVVisitor<ScopExpander, const SCEV *>;
241
242 explicit ScopExpander(const Region &R, ScalarEvolution &SE,
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000243 const DataLayout &DL, const char *Name, ValueMapT *VMap)
244 : Expander(SCEVExpander(SE, DL, Name)), SE(SE), Name(Name), R(R),
245 VMap(VMap) {}
Johannes Doerferte69e1142015-08-18 11:56:00 +0000246
247 Value *expandCodeFor(const SCEV *E, Type *Ty, Instruction *I) {
248 // If we generate code in the region we will immediately fall back to the
249 // SCEVExpander, otherwise we will stop at all unknowns in the SCEV and if
250 // needed replace them by copies computed in the entering block.
251 if (!R.contains(I))
252 E = visit(E);
253 return Expander.expandCodeFor(E, Ty, I);
254 }
255
256private:
257 SCEVExpander Expander;
258 ScalarEvolution &SE;
259 const char *Name;
260 const Region &R;
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000261 ValueMapT *VMap;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000262
263 const SCEV *visitUnknown(const SCEVUnknown *E) {
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000264
265 // If a value mapping was given try if the underlying value is remapped.
266 if (VMap)
267 if (Value *NewVal = VMap->lookup(E->getValue()))
Johannes Doerfert59984322015-09-30 21:12:12 +0000268 if (NewVal != E->getValue())
269 return visit(SE.getSCEV(NewVal));
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000270
Johannes Doerferte69e1142015-08-18 11:56:00 +0000271 Instruction *Inst = dyn_cast<Instruction>(E->getValue());
272 if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
273 Inst->getOpcode() != Instruction::SDiv))
274 return E;
275
276 if (!R.contains(Inst))
277 return E;
278
279 Instruction *StartIP = R.getEnteringBlock()->getTerminator();
280
281 const SCEV *LHSScev = visit(SE.getSCEV(Inst->getOperand(0)));
282 const SCEV *RHSScev = visit(SE.getSCEV(Inst->getOperand(1)));
283
284 Value *LHS = Expander.expandCodeFor(LHSScev, E->getType(), StartIP);
285 Value *RHS = Expander.expandCodeFor(RHSScev, E->getType(), StartIP);
286
287 Inst = BinaryOperator::Create((Instruction::BinaryOps)Inst->getOpcode(),
288 LHS, RHS, Inst->getName() + Name, StartIP);
289 return SE.getSCEV(Inst);
290 }
291
292 /// The following functions will just traverse the SCEV and rebuild it with
293 /// the new operands returned by the traversal.
294 ///
295 ///{
296 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
297 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
298 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
299 }
300 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
301 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
302 }
303 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
304 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
305 }
306 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
307 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
308 }
309 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
310 SmallVector<const SCEV *, 4> NewOps;
311 for (const SCEV *Op : E->operands())
312 NewOps.push_back(visit(Op));
313 return SE.getAddExpr(NewOps);
314 }
315 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
316 SmallVector<const SCEV *, 4> NewOps;
317 for (const SCEV *Op : E->operands())
318 NewOps.push_back(visit(Op));
319 return SE.getMulExpr(NewOps);
320 }
321 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
322 SmallVector<const SCEV *, 4> NewOps;
323 for (const SCEV *Op : E->operands())
324 NewOps.push_back(visit(Op));
325 return SE.getUMaxExpr(NewOps);
326 }
327 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
328 SmallVector<const SCEV *, 4> NewOps;
329 for (const SCEV *Op : E->operands())
330 NewOps.push_back(visit(Op));
331 return SE.getSMaxExpr(NewOps);
332 }
333 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
334 SmallVector<const SCEV *, 4> NewOps;
335 for (const SCEV *Op : E->operands())
336 NewOps.push_back(visit(Op));
337 return SE.getAddRecExpr(NewOps, E->getLoop(), E->getNoWrapFlags());
338 }
339 ///}
340};
341
Johannes Doerfert09e36972015-10-07 20:17:36 +0000342Value *polly::expandCodeFor(Scop &S, ScalarEvolution &SE, const DataLayout &DL,
343 const char *Name, const SCEV *E, Type *Ty,
344 Instruction *IP, ValueMapT *VMap) {
Johannes Doerfertc0729a32015-09-30 16:52:03 +0000345 ScopExpander Expander(S.getRegion(), SE, DL, Name, VMap);
Johannes Doerferte69e1142015-08-18 11:56:00 +0000346 return Expander.expandCodeFor(E, Ty, IP);
347}
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000348
349bool polly::isErrorBlock(BasicBlock &BB) {
350
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000351 if (isa<UnreachableInst>(BB.getTerminator()))
352 return true;
353
Johannes Doerfertf80f3b02015-10-01 23:45:51 +0000354 if (ErrorFunctions.empty())
355 return false;
356
357 for (Instruction &Inst : BB)
358 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
359 if (Function *F = CI->getCalledFunction()) {
360 const auto &FnName = F->getName();
361 for (const auto &ErrorFn : ErrorFunctions)
362 if (FnName.equals(ErrorFn))
363 return true;
364 }
365
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000366 return false;
367}
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000368
369Value *polly::getConditionFromTerminator(TerminatorInst *TI) {
370 if (BranchInst *BR = dyn_cast<BranchInst>(TI)) {
371 if (BR->isUnconditional())
372 return ConstantInt::getTrue(Type::getInt1Ty(TI->getContext()));
373
374 return BR->getCondition();
375 }
376
377 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
378 return SI->getCondition();
379
380 return nullptr;
381}
Johannes Doerfert09e36972015-10-07 20:17:36 +0000382
383bool polly::isHoistableLoad(LoadInst *LInst, Region &R, LoopInfo &LI,
384 ScalarEvolution &SE) {
385 Loop *L = LI.getLoopFor(LInst->getParent());
386 const SCEV *PtrSCEV = SE.getSCEVAtScope(LInst->getPointerOperand(), L);
387 while (L && R.contains(L)) {
388 if (!SE.isLoopInvariant(PtrSCEV, L))
389 return false;
390 L = L->getParentLoop();
391 }
392
393 return true;
394}