1 //===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the guard widening pass. The semantics of the
10 // @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
11 // more often that it did before the transform. This optimization is called
12 // "widening" and can be used hoist and common runtime checks in situations like
15 // %cmp0 = 7 u< Length
16 // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
17 // call @unknown_side_effects()
18 // %cmp1 = 9 u< Length
19 // call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
24 // %cmp0 = 9 u< Length
25 // call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
26 // call @unknown_side_effects()
29 // If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
30 // generic implementation of the same function, which will have the correct
31 // semantics from that point onward. It is always _legal_ to deoptimize (so
32 // replacing %cmp0 with false is "correct"), though it may not always be
33 // profitable to do so.
35 // NB! This pass is a work in progress. It hasn't been tuned to be "production
36 // ready" yet. It is known to have quadriatic running time and will not scale
37 // to large numbers of guards
39 //===----------------------------------------------------------------------===//
41 #include "llvm/Transforms/Scalar/GuardWidening.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/DepthFirstIterator.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Analysis/AssumptionCache.h"
46 #include "llvm/Analysis/GuardUtils.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Analysis/MemorySSAUpdater.h"
50 #include "llvm/Analysis/PostDominators.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/ConstantRange.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/IntrinsicInst.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/InitializePasses.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Transforms/Scalar.h"
63 #include "llvm/Transforms/Utils/GuardUtils.h"
64 #include "llvm/Transforms/Utils/LoopUtils.h"
69 #define DEBUG_TYPE "guard-widening"
71 STATISTIC(GuardsEliminated
, "Number of eliminated guards");
72 STATISTIC(CondBranchEliminated
, "Number of eliminated conditional branches");
73 STATISTIC(FreezeAdded
, "Number of freeze instruction introduced");
76 WidenBranchGuards("guard-widening-widen-branch-guards", cl::Hidden
,
77 cl::desc("Whether or not we should widen guards "
78 "expressed as branches by widenable conditions"),
83 // Get the condition of \p I. It can either be a guard or a conditional branch.
84 static Value
*getCondition(Instruction
*I
) {
85 if (IntrinsicInst
*GI
= dyn_cast
<IntrinsicInst
>(I
)) {
86 assert(GI
->getIntrinsicID() == Intrinsic::experimental_guard
&&
87 "Bad guard intrinsic?");
88 return GI
->getArgOperand(0);
91 BasicBlock
*IfTrueBB
, *IfFalseBB
;
92 if (parseWidenableBranch(I
, Cond
, WC
, IfTrueBB
, IfFalseBB
))
95 return cast
<BranchInst
>(I
)->getCondition();
98 // Set the condition for \p I to \p NewCond. \p I can either be a guard or a
99 // conditional branch.
100 static void setCondition(Instruction
*I
, Value
*NewCond
) {
101 if (IntrinsicInst
*GI
= dyn_cast
<IntrinsicInst
>(I
)) {
102 assert(GI
->getIntrinsicID() == Intrinsic::experimental_guard
&&
103 "Bad guard intrinsic?");
104 GI
->setArgOperand(0, NewCond
);
107 cast
<BranchInst
>(I
)->setCondition(NewCond
);
110 // Eliminates the guard instruction properly.
111 static void eliminateGuard(Instruction
*GuardInst
, MemorySSAUpdater
*MSSAU
) {
112 GuardInst
->eraseFromParent();
114 MSSAU
->removeMemoryAccess(GuardInst
);
118 /// Find a point at which the widened condition of \p Guard should be inserted.
119 /// When it is represented as intrinsic call, we can do it right before the call
120 /// instruction. However, when we are dealing with widenable branch, we must
121 /// account for the following situation: widening should not turn a
122 /// loop-invariant condition into a loop-variant. It means that if
123 /// widenable.condition() call is invariant (w.r.t. any loop), the new wide
124 /// condition should stay invariant. Otherwise there can be a miscompile, like
125 /// the one described at https://github.com/llvm/llvm-project/issues/60234. The
126 /// safest way to do it is to expand the new condition at WC's block.
127 static Instruction
*findInsertionPointForWideCondition(Instruction
*WCOrGuard
) {
128 if (isGuard(WCOrGuard
))
130 if (auto WC
= extractWidenableCondition(WCOrGuard
))
131 return cast
<Instruction
>(WC
);
135 class GuardWideningImpl
{
137 PostDominatorTree
*PDT
;
140 MemorySSAUpdater
*MSSAU
;
142 /// Together, these describe the region of interest. This might be all of
143 /// the blocks within a function, or only a given loop's blocks and preheader.
145 std::function
<bool(BasicBlock
*)> BlockFilter
;
147 /// The set of guards and conditional branches whose conditions have been
148 /// widened into dominating guards.
149 SmallVector
<Instruction
*, 16> EliminatedGuardsAndBranches
;
151 /// The set of guards which have been widened to include conditions to other
153 DenseSet
<Instruction
*> WidenedGuards
;
155 /// Try to eliminate instruction \p Instr by widening it into an earlier
156 /// dominating guard. \p DFSI is the DFS iterator on the dominator tree that
157 /// is currently visiting the block containing \p Guard, and \p GuardsPerBlock
158 /// maps BasicBlocks to the set of guards seen in that block.
159 bool eliminateInstrViaWidening(
160 Instruction
*Instr
, const df_iterator
<DomTreeNode
*> &DFSI
,
161 const DenseMap
<BasicBlock
*, SmallVector
<Instruction
*, 8>>
164 /// Used to keep track of which widening potential is more effective.
167 WS_IllegalOrNegative
,
169 /// Widening is performance neutral as far as the cycles spent in check
170 /// conditions goes (but can still help, e.g., code layout, having less
174 /// Widening is profitable.
177 /// Widening is very profitable. Not significantly different from \c
178 /// WS_Positive, except by the order.
182 static StringRef
scoreTypeToString(WideningScore WS
);
184 /// Compute the score for widening the condition in \p DominatedInstr
185 /// into \p WideningPoint.
186 WideningScore
computeWideningScore(Instruction
*DominatedInstr
,
187 Instruction
*ToWiden
,
188 Instruction
*WideningPoint
,
189 SmallVectorImpl
<Value
*> &ChecksToHoist
,
190 SmallVectorImpl
<Value
*> &ChecksToWiden
);
192 /// Helper to check if \p V can be hoisted to \p InsertPos.
193 bool canBeHoistedTo(const Value
*V
, const Instruction
*InsertPos
) const {
194 SmallPtrSet
<const Instruction
*, 8> Visited
;
195 return canBeHoistedTo(V
, InsertPos
, Visited
);
198 bool canBeHoistedTo(const Value
*V
, const Instruction
*InsertPos
,
199 SmallPtrSetImpl
<const Instruction
*> &Visited
) const;
201 bool canBeHoistedTo(const SmallVectorImpl
<Value
*> &Checks
,
202 const Instruction
*InsertPos
) const {
203 return all_of(Checks
,
204 [&](const Value
*V
) { return canBeHoistedTo(V
, InsertPos
); });
206 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
207 /// canBeHoistedTo returned true.
208 void makeAvailableAt(Value
*V
, Instruction
*InsertPos
) const;
210 void makeAvailableAt(const SmallVectorImpl
<Value
*> &Checks
,
211 Instruction
*InsertPos
) const {
212 for (Value
*V
: Checks
)
213 makeAvailableAt(V
, InsertPos
);
216 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
217 /// to generate an expression computing the logical AND of \p ChecksToHoist
218 /// and \p ChecksToWiden. Return true if the expression computing the AND is
219 /// only as expensive as computing one of the set of expressions. If \p
220 /// InsertPt is true then actually generate the resulting expression, make it
221 /// available at \p InsertPt and return it in \p Result (else no change to the
223 std::optional
<Value
*> mergeChecks(SmallVectorImpl
<Value
*> &ChecksToHoist
,
224 SmallVectorImpl
<Value
*> &ChecksToWiden
,
225 Instruction
*InsertPt
);
227 /// Generate the logical AND of \p ChecksToHoist and \p OldCondition and make
228 /// it available at InsertPt
229 Value
*hoistChecks(SmallVectorImpl
<Value
*> &ChecksToHoist
,
230 Value
*OldCondition
, Instruction
*InsertPt
);
232 /// Adds freeze to Orig and push it as far as possible very aggressively.
233 /// Also replaces all uses of frozen instruction with frozen version.
234 Value
*freezeAndPush(Value
*Orig
, Instruction
*InsertPt
);
236 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
237 /// with the constraint that \c Length is not negative. \c CheckInst is the
238 /// pre-existing instruction in the IR that computes the result of this range
242 const ConstantInt
*Offset
;
247 explicit RangeCheck(const Value
*Base
, const ConstantInt
*Offset
,
248 const Value
*Length
, ICmpInst
*CheckInst
)
249 : Base(Base
), Offset(Offset
), Length(Length
), CheckInst(CheckInst
) {}
251 void setBase(const Value
*NewBase
) { Base
= NewBase
; }
252 void setOffset(const ConstantInt
*NewOffset
) { Offset
= NewOffset
; }
254 const Value
*getBase() const { return Base
; }
255 const ConstantInt
*getOffset() const { return Offset
; }
256 const APInt
&getOffsetValue() const { return getOffset()->getValue(); }
257 const Value
*getLength() const { return Length
; };
258 ICmpInst
*getCheckInst() const { return CheckInst
; }
260 void print(raw_ostream
&OS
, bool PrintTypes
= false) {
262 Base
->printAsOperand(OS
, PrintTypes
);
264 Offset
->printAsOperand(OS
, PrintTypes
);
266 Length
->printAsOperand(OS
, PrintTypes
);
269 LLVM_DUMP_METHOD
void dump() {
275 /// Parse \p ToParse into a conjunction (logical-and) of range checks; and
276 /// append them to \p Checks. Returns true on success, may clobber \c Checks
278 bool parseRangeChecks(SmallVectorImpl
<Value
*> &ToParse
,
279 SmallVectorImpl
<RangeCheck
> &Checks
) {
280 for (auto CheckCond
: ToParse
) {
281 if (!parseRangeChecks(CheckCond
, Checks
))
287 bool parseRangeChecks(Value
*CheckCond
, SmallVectorImpl
<RangeCheck
> &Checks
);
289 /// Combine the checks in \p Checks into a smaller set of checks and append
290 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
291 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
292 /// and \p CombinedChecks on success and on failure.
293 bool combineRangeChecks(SmallVectorImpl
<RangeCheck
> &Checks
,
294 SmallVectorImpl
<RangeCheck
> &CombinedChecks
) const;
296 /// Can we compute the logical AND of \p ChecksToHoist and \p ChecksToWiden
297 /// for the price of computing only one of the set of expressions?
298 bool isWideningCondProfitable(SmallVectorImpl
<Value
*> &ChecksToHoist
,
299 SmallVectorImpl
<Value
*> &ChecksToWiden
) {
300 return mergeChecks(ChecksToHoist
, ChecksToWiden
, /*InsertPt=*/nullptr)
304 /// Widen \p ChecksToWiden to fail if any of \p ChecksToHoist is false
305 void widenGuard(SmallVectorImpl
<Value
*> &ChecksToHoist
,
306 SmallVectorImpl
<Value
*> &ChecksToWiden
,
307 Instruction
*ToWiden
) {
308 Instruction
*InsertPt
= findInsertionPointForWideCondition(ToWiden
);
309 auto MergedCheck
= mergeChecks(ChecksToHoist
, ChecksToWiden
, InsertPt
);
310 Value
*Result
= MergedCheck
? *MergedCheck
311 : hoistChecks(ChecksToHoist
,
312 getCondition(ToWiden
), InsertPt
);
314 if (isGuardAsWidenableBranch(ToWiden
)) {
315 setWidenableBranchCond(cast
<BranchInst
>(ToWiden
), Result
);
318 setCondition(ToWiden
, Result
);
322 explicit GuardWideningImpl(DominatorTree
&DT
, PostDominatorTree
*PDT
,
323 LoopInfo
&LI
, AssumptionCache
&AC
,
324 MemorySSAUpdater
*MSSAU
, DomTreeNode
*Root
,
325 std::function
<bool(BasicBlock
*)> BlockFilter
)
326 : DT(DT
), PDT(PDT
), LI(LI
), AC(AC
), MSSAU(MSSAU
), Root(Root
),
327 BlockFilter(BlockFilter
) {}
329 /// The entry point for this pass.
334 static bool isSupportedGuardInstruction(const Instruction
*Insn
) {
337 if (WidenBranchGuards
&& isGuardAsWidenableBranch(Insn
))
342 bool GuardWideningImpl::run() {
343 DenseMap
<BasicBlock
*, SmallVector
<Instruction
*, 8>> GuardsInBlock
;
344 bool Changed
= false;
345 for (auto DFI
= df_begin(Root
), DFE
= df_end(Root
);
347 auto *BB
= (*DFI
)->getBlock();
348 if (!BlockFilter(BB
))
351 auto &CurrentList
= GuardsInBlock
[BB
];
354 if (isSupportedGuardInstruction(&I
))
355 CurrentList
.push_back(cast
<Instruction
>(&I
));
357 for (auto *II
: CurrentList
)
358 Changed
|= eliminateInstrViaWidening(II
, DFI
, GuardsInBlock
);
361 assert(EliminatedGuardsAndBranches
.empty() || Changed
);
362 for (auto *I
: EliminatedGuardsAndBranches
)
363 if (!WidenedGuards
.count(I
)) {
364 assert(isa
<ConstantInt
>(getCondition(I
)) && "Should be!");
365 if (isSupportedGuardInstruction(I
))
366 eliminateGuard(I
, MSSAU
);
368 assert(isa
<BranchInst
>(I
) &&
369 "Eliminated something other than guard or branch?");
370 ++CondBranchEliminated
;
377 bool GuardWideningImpl::eliminateInstrViaWidening(
378 Instruction
*Instr
, const df_iterator
<DomTreeNode
*> &DFSI
,
379 const DenseMap
<BasicBlock
*, SmallVector
<Instruction
*, 8>>
381 SmallVector
<Value
*> ChecksToHoist
;
382 parseWidenableGuard(Instr
, ChecksToHoist
);
383 // Ignore trivial true or false conditions. These instructions will be
384 // trivially eliminated by any cleanup pass. Do not erase them because other
385 // guards can possibly be widened into them.
386 if (ChecksToHoist
.empty() ||
387 (ChecksToHoist
.size() == 1 && isa
<ConstantInt
>(ChecksToHoist
.front())))
390 Instruction
*BestSoFar
= nullptr;
391 auto BestScoreSoFar
= WS_IllegalOrNegative
;
393 // In the set of dominating guards, find the one we can merge GuardInst with
394 // for the most profit.
395 for (unsigned i
= 0, e
= DFSI
.getPathLength(); i
!= e
; ++i
) {
396 auto *CurBB
= DFSI
.getPath(i
)->getBlock();
397 if (!BlockFilter(CurBB
))
399 assert(GuardsInBlock
.count(CurBB
) && "Must have been populated by now!");
400 const auto &GuardsInCurBB
= GuardsInBlock
.find(CurBB
)->second
;
402 auto I
= GuardsInCurBB
.begin();
403 auto E
= Instr
->getParent() == CurBB
? find(GuardsInCurBB
, Instr
)
404 : GuardsInCurBB
.end();
409 for (auto &I
: *CurBB
) {
410 if (Index
== GuardsInCurBB
.size())
412 if (GuardsInCurBB
[Index
] == &I
)
415 assert(Index
== GuardsInCurBB
.size() &&
416 "Guards expected to be in order!");
420 assert((i
== (e
- 1)) == (Instr
->getParent() == CurBB
) && "Bad DFS?");
422 for (auto *Candidate
: make_range(I
, E
)) {
423 auto *WideningPoint
= findInsertionPointForWideCondition(Candidate
);
426 SmallVector
<Value
*> CandidateChecks
;
427 parseWidenableGuard(Candidate
, CandidateChecks
);
428 auto Score
= computeWideningScore(Instr
, Candidate
, WideningPoint
,
429 ChecksToHoist
, CandidateChecks
);
430 LLVM_DEBUG(dbgs() << "Score between " << *Instr
<< " and " << *Candidate
431 << " is " << scoreTypeToString(Score
) << "\n");
432 if (Score
> BestScoreSoFar
) {
433 BestScoreSoFar
= Score
;
434 BestSoFar
= Candidate
;
439 if (BestScoreSoFar
== WS_IllegalOrNegative
) {
440 LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *Instr
<< "\n");
444 assert(BestSoFar
!= Instr
&& "Should have never visited same guard!");
445 assert(DT
.dominates(BestSoFar
, Instr
) && "Should be!");
447 LLVM_DEBUG(dbgs() << "Widening " << *Instr
<< " into " << *BestSoFar
448 << " with score " << scoreTypeToString(BestScoreSoFar
)
450 SmallVector
<Value
*> ChecksToWiden
;
451 parseWidenableGuard(BestSoFar
, ChecksToWiden
);
452 widenGuard(ChecksToHoist
, ChecksToWiden
, BestSoFar
);
453 auto NewGuardCondition
= ConstantInt::getTrue(Instr
->getContext());
454 setCondition(Instr
, NewGuardCondition
);
455 EliminatedGuardsAndBranches
.push_back(Instr
);
456 WidenedGuards
.insert(BestSoFar
);
460 GuardWideningImpl::WideningScore
GuardWideningImpl::computeWideningScore(
461 Instruction
*DominatedInstr
, Instruction
*ToWiden
,
462 Instruction
*WideningPoint
, SmallVectorImpl
<Value
*> &ChecksToHoist
,
463 SmallVectorImpl
<Value
*> &ChecksToWiden
) {
464 Loop
*DominatedInstrLoop
= LI
.getLoopFor(DominatedInstr
->getParent());
465 Loop
*DominatingGuardLoop
= LI
.getLoopFor(WideningPoint
->getParent());
466 bool HoistingOutOfLoop
= false;
468 if (DominatingGuardLoop
!= DominatedInstrLoop
) {
469 // Be conservative and don't widen into a sibling loop. TODO: If the
470 // sibling is colder, we should consider allowing this.
471 if (DominatingGuardLoop
&&
472 !DominatingGuardLoop
->contains(DominatedInstrLoop
))
473 return WS_IllegalOrNegative
;
475 HoistingOutOfLoop
= true;
478 if (!canBeHoistedTo(ChecksToHoist
, WideningPoint
))
479 return WS_IllegalOrNegative
;
480 // Further in the GuardWideningImpl::hoistChecks the entire condition might be
481 // widened, not the parsed list of checks. So we need to check the possibility
482 // of that condition hoisting.
483 if (!canBeHoistedTo(getCondition(ToWiden
), WideningPoint
))
484 return WS_IllegalOrNegative
;
486 // If the guard was conditional executed, it may never be reached
487 // dynamically. There are two potential downsides to hoisting it out of the
488 // conditionally executed region: 1) we may spuriously deopt without need and
489 // 2) we have the extra cost of computing the guard condition in the common
490 // case. At the moment, we really only consider the second in our heuristic
491 // here. TODO: evaluate cost model for spurious deopt
492 // NOTE: As written, this also lets us hoist right over another guard which
493 // is essentially just another spelling for control flow.
494 if (isWideningCondProfitable(ChecksToHoist
, ChecksToWiden
))
495 return HoistingOutOfLoop
? WS_VeryPositive
: WS_Positive
;
497 if (HoistingOutOfLoop
)
500 // For a given basic block \p BB, return its successor which is guaranteed or
501 // highly likely will be taken as its successor.
502 auto GetLikelySuccessor
= [](const BasicBlock
* BB
)->const BasicBlock
* {
503 if (auto *UniqueSucc
= BB
->getUniqueSuccessor())
505 auto *Term
= BB
->getTerminator();
506 Value
*Cond
= nullptr;
507 const BasicBlock
*IfTrue
= nullptr, *IfFalse
= nullptr;
508 using namespace PatternMatch
;
509 if (!match(Term
, m_Br(m_Value(Cond
), m_BasicBlock(IfTrue
),
510 m_BasicBlock(IfFalse
))))
512 // For constant conditions, only one dynamical successor is possible
513 if (auto *ConstCond
= dyn_cast
<ConstantInt
>(Cond
))
514 return ConstCond
->isAllOnesValue() ? IfTrue
: IfFalse
;
515 // If one of successors ends with deopt, another one is likely.
516 if (IfFalse
->getPostdominatingDeoptimizeCall())
518 if (IfTrue
->getPostdominatingDeoptimizeCall())
520 // TODO: Use branch frequency metatada to allow hoisting through non-deopt
525 // Returns true if we might be hoisting above explicit control flow into a
526 // considerably hotter block. Note that this completely ignores implicit
527 // control flow (guards, calls which throw, etc...). That choice appears
528 // arbitrary (we assume that implicit control flow exits are all rare).
529 auto MaybeHoistingToHotterBlock
= [&]() {
530 const auto *DominatingBlock
= WideningPoint
->getParent();
531 const auto *DominatedBlock
= DominatedInstr
->getParent();
533 // Descend as low as we can, always taking the likely successor.
534 assert(DT
.isReachableFromEntry(DominatingBlock
) && "Unreached code");
535 assert(DT
.isReachableFromEntry(DominatedBlock
) && "Unreached code");
536 assert(DT
.dominates(DominatingBlock
, DominatedBlock
) && "No dominance");
537 while (DominatedBlock
!= DominatingBlock
) {
538 auto *LikelySucc
= GetLikelySuccessor(DominatingBlock
);
539 // No likely successor?
542 // Only go down the dominator tree.
543 if (!DT
.properlyDominates(DominatingBlock
, LikelySucc
))
545 DominatingBlock
= LikelySucc
;
549 if (DominatedBlock
== DominatingBlock
)
551 // We followed the likely successor chain and went past the dominated
552 // block. It means that the dominated guard is in dead/very cold code.
553 if (!DT
.dominates(DominatingBlock
, DominatedBlock
))
555 // TODO: diamond, triangle cases
558 return !PDT
->dominates(DominatedBlock
, DominatingBlock
);
561 return MaybeHoistingToHotterBlock() ? WS_IllegalOrNegative
: WS_Neutral
;
564 bool GuardWideningImpl::canBeHoistedTo(
565 const Value
*V
, const Instruction
*Loc
,
566 SmallPtrSetImpl
<const Instruction
*> &Visited
) const {
567 auto *Inst
= dyn_cast
<Instruction
>(V
);
568 if (!Inst
|| DT
.dominates(Inst
, Loc
) || Visited
.count(Inst
))
571 if (!isSafeToSpeculativelyExecute(Inst
, Loc
, &AC
, &DT
) ||
572 Inst
->mayReadFromMemory())
575 Visited
.insert(Inst
);
577 // We only want to go _up_ the dominance chain when recursing.
578 assert(!isa
<PHINode
>(Loc
) &&
579 "PHIs should return false for isSafeToSpeculativelyExecute");
580 assert(DT
.isReachableFromEntry(Inst
->getParent()) &&
581 "We did a DFS from the block entry!");
582 return all_of(Inst
->operands(),
583 [&](Value
*Op
) { return canBeHoistedTo(Op
, Loc
, Visited
); });
586 void GuardWideningImpl::makeAvailableAt(Value
*V
, Instruction
*Loc
) const {
587 auto *Inst
= dyn_cast
<Instruction
>(V
);
588 if (!Inst
|| DT
.dominates(Inst
, Loc
))
591 assert(isSafeToSpeculativelyExecute(Inst
, Loc
, &AC
, &DT
) &&
592 !Inst
->mayReadFromMemory() &&
593 "Should've checked with canBeHoistedTo!");
595 for (Value
*Op
: Inst
->operands())
596 makeAvailableAt(Op
, Loc
);
598 Inst
->moveBefore(Loc
);
601 // Return Instruction before which we can insert freeze for the value V as close
602 // to def as possible. If there is no place to add freeze, return nullptr.
603 static Instruction
*getFreezeInsertPt(Value
*V
, const DominatorTree
&DT
) {
604 auto *I
= dyn_cast
<Instruction
>(V
);
606 return &*DT
.getRoot()->getFirstNonPHIOrDbgOrAlloca();
608 auto *Res
= I
->getInsertionPointAfterDef();
609 // If there is no place to add freeze - return nullptr.
610 if (!Res
|| !DT
.dominates(I
, Res
))
613 // If there is a User dominated by original I, then it should be dominated
614 // by Freeze instruction as well.
615 if (any_of(I
->users(), [&](User
*U
) {
616 Instruction
*User
= cast
<Instruction
>(U
);
617 return Res
!= User
&& DT
.dominates(I
, User
) && !DT
.dominates(Res
, User
);
623 Value
*GuardWideningImpl::freezeAndPush(Value
*Orig
, Instruction
*InsertPt
) {
624 if (isGuaranteedNotToBePoison(Orig
, nullptr, InsertPt
, &DT
))
626 Instruction
*InsertPtAtDef
= getFreezeInsertPt(Orig
, DT
);
628 return new FreezeInst(Orig
, "gw.freeze", InsertPt
);
629 if (isa
<Constant
>(Orig
) || isa
<GlobalValue
>(Orig
))
630 return new FreezeInst(Orig
, "gw.freeze", InsertPtAtDef
);
632 SmallSet
<Value
*, 16> Visited
;
633 SmallVector
<Value
*, 16> Worklist
;
634 SmallSet
<Instruction
*, 16> DropPoisonFlags
;
635 SmallVector
<Value
*, 16> NeedFreeze
;
636 DenseMap
<Value
*, FreezeInst
*> CacheOfFreezes
;
638 // A bit overloaded data structures. Visited contains constant/GV
639 // if we already met it. In this case CacheOfFreezes has a freeze if it is
641 auto handleConstantOrGlobal
= [&](Use
&U
) {
642 Value
*Def
= U
.get();
643 if (!isa
<Constant
>(Def
) && !isa
<GlobalValue
>(Def
))
646 if (Visited
.insert(Def
).second
) {
647 if (isGuaranteedNotToBePoison(Def
, nullptr, InsertPt
, &DT
))
649 CacheOfFreezes
[Def
] = new FreezeInst(Def
, Def
->getName() + ".gw.fr",
650 getFreezeInsertPt(Def
, DT
));
653 if (CacheOfFreezes
.count(Def
))
654 U
.set(CacheOfFreezes
[Def
]);
658 Worklist
.push_back(Orig
);
659 while (!Worklist
.empty()) {
660 Value
*V
= Worklist
.pop_back_val();
661 if (!Visited
.insert(V
).second
)
664 if (isGuaranteedNotToBePoison(V
, nullptr, InsertPt
, &DT
))
667 Instruction
*I
= dyn_cast
<Instruction
>(V
);
668 if (!I
|| canCreateUndefOrPoison(cast
<Operator
>(I
),
669 /*ConsiderFlagsAndMetadata*/ false)) {
670 NeedFreeze
.push_back(V
);
673 // Check all operands. If for any of them we cannot insert Freeze,
674 // stop here. Otherwise, iterate.
675 if (any_of(I
->operands(), [&](Value
*Op
) {
676 return isa
<Instruction
>(Op
) && !getFreezeInsertPt(Op
, DT
);
678 NeedFreeze
.push_back(I
);
681 DropPoisonFlags
.insert(I
);
682 for (Use
&U
: I
->operands())
683 if (!handleConstantOrGlobal(U
))
684 Worklist
.push_back(U
.get());
686 for (Instruction
*I
: DropPoisonFlags
)
687 I
->dropPoisonGeneratingFlagsAndMetadata();
689 Value
*Result
= Orig
;
690 for (Value
*V
: NeedFreeze
) {
691 auto *FreezeInsertPt
= getFreezeInsertPt(V
, DT
);
692 FreezeInst
*FI
= new FreezeInst(V
, V
->getName() + ".gw.fr", FreezeInsertPt
);
696 V
->replaceUsesWithIf(
697 FI
, [&](const Use
& U
)->bool { return U
.getUser() != FI
; });
703 std::optional
<Value
*>
704 GuardWideningImpl::mergeChecks(SmallVectorImpl
<Value
*> &ChecksToHoist
,
705 SmallVectorImpl
<Value
*> &ChecksToWiden
,
706 Instruction
*InsertPt
) {
707 using namespace llvm::PatternMatch
;
709 Value
*Result
= nullptr;
711 // L >u C0 && L >u C1 -> L >u max(C0, C1)
712 ConstantInt
*RHS0
, *RHS1
;
714 ICmpInst::Predicate Pred0
, Pred1
;
715 // TODO: Support searching for pairs to merge from both whole lists of
716 // ChecksToHoist and ChecksToWiden.
717 if (ChecksToWiden
.size() == 1 && ChecksToHoist
.size() == 1 &&
718 match(ChecksToWiden
.front(),
719 m_ICmp(Pred0
, m_Value(LHS
), m_ConstantInt(RHS0
))) &&
720 match(ChecksToHoist
.front(),
721 m_ICmp(Pred1
, m_Specific(LHS
), m_ConstantInt(RHS1
)))) {
724 ConstantRange::makeExactICmpRegion(Pred0
, RHS0
->getValue());
726 ConstantRange::makeExactICmpRegion(Pred1
, RHS1
->getValue());
728 // Given what we're doing here and the semantics of guards, it would
729 // be correct to use a subset intersection, but that may be too
730 // aggressive in cases we care about.
731 if (std::optional
<ConstantRange
> Intersect
=
732 CR0
.exactIntersectWith(CR1
)) {
734 CmpInst::Predicate Pred
;
735 if (Intersect
->getEquivalentICmp(Pred
, NewRHSAP
)) {
737 ConstantInt
*NewRHS
=
738 ConstantInt::get(InsertPt
->getContext(), NewRHSAP
);
739 assert(canBeHoistedTo(LHS
, InsertPt
) && "must be");
740 makeAvailableAt(LHS
, InsertPt
);
741 Result
= new ICmpInst(InsertPt
, Pred
, LHS
, NewRHS
, "wide.chk");
750 SmallVector
<GuardWideningImpl::RangeCheck
, 4> Checks
, CombinedChecks
;
751 if (parseRangeChecks(ChecksToWiden
, Checks
) &&
752 parseRangeChecks(ChecksToHoist
, Checks
) &&
753 combineRangeChecks(Checks
, CombinedChecks
)) {
755 for (auto &RC
: CombinedChecks
) {
756 makeAvailableAt(RC
.getCheckInst(), InsertPt
);
758 Result
= BinaryOperator::CreateAnd(RC
.getCheckInst(), Result
, "",
761 Result
= RC
.getCheckInst();
763 assert(Result
&& "Failed to find result value");
764 Result
->setName("wide.chk");
765 Result
= freezeAndPush(Result
, InsertPt
);
770 // We were not able to compute ChecksToHoist AND ChecksToWiden for the price
775 Value
*GuardWideningImpl::hoistChecks(SmallVectorImpl
<Value
*> &ChecksToHoist
,
777 Instruction
*InsertPt
) {
778 assert(!ChecksToHoist
.empty());
779 IRBuilder
<> Builder(InsertPt
);
780 makeAvailableAt(ChecksToHoist
, InsertPt
);
781 makeAvailableAt(OldCondition
, InsertPt
);
782 Value
*Result
= Builder
.CreateAnd(ChecksToHoist
);
783 Result
= freezeAndPush(Result
, InsertPt
);
784 Result
= Builder
.CreateAnd(OldCondition
, Result
);
785 Result
->setName("wide.chk");
789 bool GuardWideningImpl::parseRangeChecks(
790 Value
*CheckCond
, SmallVectorImpl
<GuardWideningImpl::RangeCheck
> &Checks
) {
791 using namespace llvm::PatternMatch
;
793 auto *IC
= dyn_cast
<ICmpInst
>(CheckCond
);
794 if (!IC
|| !IC
->getOperand(0)->getType()->isIntegerTy() ||
795 (IC
->getPredicate() != ICmpInst::ICMP_ULT
&&
796 IC
->getPredicate() != ICmpInst::ICMP_UGT
))
799 const Value
*CmpLHS
= IC
->getOperand(0), *CmpRHS
= IC
->getOperand(1);
800 if (IC
->getPredicate() == ICmpInst::ICMP_UGT
)
801 std::swap(CmpLHS
, CmpRHS
);
803 auto &DL
= IC
->getModule()->getDataLayout();
805 GuardWideningImpl::RangeCheck
Check(
806 CmpLHS
, cast
<ConstantInt
>(ConstantInt::getNullValue(CmpRHS
->getType())),
809 if (!isKnownNonNegative(Check
.getLength(), DL
))
812 // What we have in \c Check now is a correct interpretation of \p CheckCond.
813 // Try to see if we can move some constant offsets into the \c Offset field.
816 auto &Ctx
= CheckCond
->getContext();
824 auto *BaseInst
= dyn_cast
<Instruction
>(Check
.getBase());
825 assert((!BaseInst
|| DT
.isReachableFromEntry(BaseInst
->getParent())) &&
826 "Unreachable instruction?");
829 if (match(Check
.getBase(), m_Add(m_Value(OpLHS
), m_ConstantInt(OpRHS
)))) {
830 Check
.setBase(OpLHS
);
831 APInt NewOffset
= Check
.getOffsetValue() + OpRHS
->getValue();
832 Check
.setOffset(ConstantInt::get(Ctx
, NewOffset
));
834 } else if (match(Check
.getBase(),
835 m_Or(m_Value(OpLHS
), m_ConstantInt(OpRHS
)))) {
836 KnownBits Known
= computeKnownBits(OpLHS
, DL
);
837 if ((OpRHS
->getValue() & Known
.Zero
) == OpRHS
->getValue()) {
838 Check
.setBase(OpLHS
);
839 APInt NewOffset
= Check
.getOffsetValue() + OpRHS
->getValue();
840 Check
.setOffset(ConstantInt::get(Ctx
, NewOffset
));
846 Checks
.push_back(Check
);
850 bool GuardWideningImpl::combineRangeChecks(
851 SmallVectorImpl
<GuardWideningImpl::RangeCheck
> &Checks
,
852 SmallVectorImpl
<GuardWideningImpl::RangeCheck
> &RangeChecksOut
) const {
853 unsigned OldCount
= Checks
.size();
854 while (!Checks
.empty()) {
855 // Pick all of the range checks with a specific base and length, and try to
857 const Value
*CurrentBase
= Checks
.front().getBase();
858 const Value
*CurrentLength
= Checks
.front().getLength();
860 SmallVector
<GuardWideningImpl::RangeCheck
, 3> CurrentChecks
;
862 auto IsCurrentCheck
= [&](GuardWideningImpl::RangeCheck
&RC
) {
863 return RC
.getBase() == CurrentBase
&& RC
.getLength() == CurrentLength
;
866 copy_if(Checks
, std::back_inserter(CurrentChecks
), IsCurrentCheck
);
867 erase_if(Checks
, IsCurrentCheck
);
869 assert(CurrentChecks
.size() != 0 && "We know we have at least one!");
871 if (CurrentChecks
.size() < 3) {
872 llvm::append_range(RangeChecksOut
, CurrentChecks
);
876 // CurrentChecks.size() will typically be 3 here, but so far there has been
877 // no need to hard-code that fact.
879 llvm::sort(CurrentChecks
, [&](const GuardWideningImpl::RangeCheck
&LHS
,
880 const GuardWideningImpl::RangeCheck
&RHS
) {
881 return LHS
.getOffsetValue().slt(RHS
.getOffsetValue());
884 // Note: std::sort should not invalidate the ChecksStart iterator.
886 const ConstantInt
*MinOffset
= CurrentChecks
.front().getOffset();
887 const ConstantInt
*MaxOffset
= CurrentChecks
.back().getOffset();
889 unsigned BitWidth
= MaxOffset
->getValue().getBitWidth();
890 if ((MaxOffset
->getValue() - MinOffset
->getValue())
891 .ugt(APInt::getSignedMinValue(BitWidth
)))
894 APInt MaxDiff
= MaxOffset
->getValue() - MinOffset
->getValue();
895 const APInt
&HighOffset
= MaxOffset
->getValue();
896 auto OffsetOK
= [&](const GuardWideningImpl::RangeCheck
&RC
) {
897 return (HighOffset
- RC
.getOffsetValue()).ult(MaxDiff
);
900 if (MaxDiff
.isMinValue() || !all_of(drop_begin(CurrentChecks
), OffsetOK
))
903 // We have a series of f+1 checks as:
905 // I+k_0 u< L ... Chk_0
906 // I+k_1 u< L ... Chk_1
908 // I+k_f u< L ... Chk_f
910 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
911 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
912 // k_f != k_0 ... Precond_2
915 // Chk_0 AND Chk_f implies all the other checks
917 // Informal proof sketch:
919 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
920 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
921 // thus I+k_f is the greatest unsigned value in that range.
923 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
924 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
925 // lie in [I+k_0,I+k_f], this proving our claim.
927 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
928 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
929 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
930 // range by definition, and the latter case is impossible:
932 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
933 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
935 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
936 // with 'x' above) to be at least >u INT_MIN.
938 RangeChecksOut
.emplace_back(CurrentChecks
.front());
939 RangeChecksOut
.emplace_back(CurrentChecks
.back());
942 assert(RangeChecksOut
.size() <= OldCount
&& "We pessimized!");
943 return RangeChecksOut
.size() != OldCount
;
947 StringRef
GuardWideningImpl::scoreTypeToString(WideningScore WS
) {
949 case WS_IllegalOrNegative
:
950 return "IllegalOrNegative";
955 case WS_VeryPositive
:
956 return "VeryPositive";
959 llvm_unreachable("Fully covered switch above!");
963 PreservedAnalyses
GuardWideningPass::run(Function
&F
,
964 FunctionAnalysisManager
&AM
) {
965 // Avoid requesting analyses if there are no guards or widenable conditions.
966 auto *GuardDecl
= F
.getParent()->getFunction(
967 Intrinsic::getName(Intrinsic::experimental_guard
));
968 bool HasIntrinsicGuards
= GuardDecl
&& !GuardDecl
->use_empty();
969 auto *WCDecl
= F
.getParent()->getFunction(
970 Intrinsic::getName(Intrinsic::experimental_widenable_condition
));
971 bool HasWidenableConditions
= WCDecl
&& !WCDecl
->use_empty();
972 if (!HasIntrinsicGuards
&& !HasWidenableConditions
)
973 return PreservedAnalyses::all();
974 auto &DT
= AM
.getResult
<DominatorTreeAnalysis
>(F
);
975 auto &LI
= AM
.getResult
<LoopAnalysis
>(F
);
976 auto &PDT
= AM
.getResult
<PostDominatorTreeAnalysis
>(F
);
977 auto &AC
= AM
.getResult
<AssumptionAnalysis
>(F
);
978 auto *MSSAA
= AM
.getCachedResult
<MemorySSAAnalysis
>(F
);
979 std::unique_ptr
<MemorySSAUpdater
> MSSAU
;
981 MSSAU
= std::make_unique
<MemorySSAUpdater
>(&MSSAA
->getMSSA());
982 if (!GuardWideningImpl(DT
, &PDT
, LI
, AC
, MSSAU
? MSSAU
.get() : nullptr,
983 DT
.getRootNode(), [](BasicBlock
*) { return true; })
985 return PreservedAnalyses::all();
987 PreservedAnalyses PA
;
988 PA
.preserveSet
<CFGAnalyses
>();
989 PA
.preserve
<MemorySSAAnalysis
>();
993 PreservedAnalyses
GuardWideningPass::run(Loop
&L
, LoopAnalysisManager
&AM
,
994 LoopStandardAnalysisResults
&AR
,
996 BasicBlock
*RootBB
= L
.getLoopPredecessor();
998 RootBB
= L
.getHeader();
999 auto BlockFilter
= [&](BasicBlock
*BB
) {
1000 return BB
== RootBB
|| L
.contains(BB
);
1002 std::unique_ptr
<MemorySSAUpdater
> MSSAU
;
1004 MSSAU
= std::make_unique
<MemorySSAUpdater
>(AR
.MSSA
);
1005 if (!GuardWideningImpl(AR
.DT
, nullptr, AR
.LI
, AR
.AC
,
1006 MSSAU
? MSSAU
.get() : nullptr, AR
.DT
.getNode(RootBB
),
1009 return PreservedAnalyses::all();
1011 auto PA
= getLoopPassPreservedAnalyses();
1013 PA
.preserve
<MemorySSAAnalysis
>();
1018 /// Restricted to a single loop at a time. Can be
1019 /// scheduled with other loop passes w/o breaking out of LPM
1020 struct LoopGuardWideningLegacyPass
: public LoopPass
{
1023 LoopGuardWideningLegacyPass() : LoopPass(ID
) {
1024 initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
1027 bool runOnLoop(Loop
*L
, LPPassManager
&LPM
) override
{
1030 auto &DT
= getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
1031 auto &LI
= getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
1032 auto &AC
= getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(
1033 *L
->getHeader()->getParent());
1034 auto *PDTWP
= getAnalysisIfAvailable
<PostDominatorTreeWrapperPass
>();
1035 auto *PDT
= PDTWP
? &PDTWP
->getPostDomTree() : nullptr;
1036 auto *MSSAWP
= getAnalysisIfAvailable
<MemorySSAWrapperPass
>();
1037 std::unique_ptr
<MemorySSAUpdater
> MSSAU
;
1039 MSSAU
= std::make_unique
<MemorySSAUpdater
>(&MSSAWP
->getMSSA());
1041 BasicBlock
*RootBB
= L
->getLoopPredecessor();
1043 RootBB
= L
->getHeader();
1044 auto BlockFilter
= [&](BasicBlock
*BB
) {
1045 return BB
== RootBB
|| L
->contains(BB
);
1047 return GuardWideningImpl(DT
, PDT
, LI
, AC
, MSSAU
? MSSAU
.get() : nullptr,
1048 DT
.getNode(RootBB
), BlockFilter
)
1052 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
1053 AU
.setPreservesCFG();
1054 getLoopAnalysisUsage(AU
);
1055 AU
.addPreserved
<PostDominatorTreeWrapperPass
>();
1056 AU
.addPreserved
<MemorySSAWrapperPass
>();
1061 char LoopGuardWideningLegacyPass::ID
= 0;
1063 INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass
, "loop-guard-widening",
1064 "Widen guards (within a single loop, as a loop pass)",
1066 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
1067 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass
)
1068 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass
)
1069 INITIALIZE_PASS_END(LoopGuardWideningLegacyPass
, "loop-guard-widening",
1070 "Widen guards (within a single loop, as a loop pass)",
1073 Pass
*llvm::createLoopGuardWideningPass() {
1074 return new LoopGuardWideningLegacyPass();