Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / IR / SafepointIRVerifier.cpp
blob217f10e864d15f2fbd70ed57ddc88ac01e77c0d7
1 //===-- SafepointIRVerifier.cpp - Verify gc.statepoint invariants ---------===//
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 // Run a sanity check on the IR to ensure that Safepoints - if they've been
10 // inserted - were inserted correctly. In particular, look for use of
11 // non-relocated values after a safepoint. It's primary use is to check the
12 // correctness of safepoint insertion immediately after insertion, but it can
13 // also be used to verify that later transforms have not found a way to break
14 // safepoint semenatics.
16 // In its current form, this verify checks a property which is sufficient, but
17 // not neccessary for correctness. There are some cases where an unrelocated
18 // pointer can be used after the safepoint. Consider this example:
20 // a = ...
21 // b = ...
22 // (a',b') = safepoint(a,b)
23 // c = cmp eq a b
24 // br c, ..., ....
26 // Because it is valid to reorder 'c' above the safepoint, this is legal. In
27 // practice, this is a somewhat uncommon transform, but CodeGenPrep does create
28 // idioms like this. The verifier knows about these cases and avoids reporting
29 // false positives.
31 //===----------------------------------------------------------------------===//
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/PostOrderIterator.h"
35 #include "llvm/ADT/SetOperations.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Value.h"
45 #include "llvm/IR/SafepointIRVerifier.h"
46 #include "llvm/IR/Statepoint.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/raw_ostream.h"
51 #define DEBUG_TYPE "safepoint-ir-verifier"
53 using namespace llvm;
55 /// This option is used for writing test cases. Instead of crashing the program
56 /// when verification fails, report a message to the console (for FileCheck
57 /// usage) and continue execution as if nothing happened.
58 static cl::opt<bool> PrintOnly("safepoint-ir-verifier-print-only",
59 cl::init(false));
61 namespace {
63 /// This CFG Deadness finds dead blocks and edges. Algorithm starts with a set
64 /// of blocks unreachable from entry then propagates deadness using foldable
65 /// conditional branches without modifying CFG. So GVN does but it changes CFG
66 /// by splitting critical edges. In most cases passes rely on SimplifyCFG to
67 /// clean up dead blocks, but in some cases, like verification or loop passes
68 /// it's not possible.
69 class CFGDeadness {
70 const DominatorTree *DT = nullptr;
71 SetVector<const BasicBlock *> DeadBlocks;
72 SetVector<const Use *> DeadEdges; // Contains all dead edges from live blocks.
74 public:
75 /// Return the edge that coresponds to the predecessor.
76 static const Use& getEdge(const_pred_iterator &PredIt) {
77 auto &PU = PredIt.getUse();
78 return PU.getUser()->getOperandUse(PU.getOperandNo());
81 /// Return true if there is at least one live edge that corresponds to the
82 /// basic block InBB listed in the phi node.
83 bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
84 assert(!isDeadBlock(InBB) && "block must be live");
85 const BasicBlock* BB = PN->getParent();
86 bool Listed = false;
87 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
88 if (InBB == *PredIt) {
89 if (!isDeadEdge(&getEdge(PredIt)))
90 return true;
91 Listed = true;
94 (void)Listed;
95 assert(Listed && "basic block is not found among incoming blocks");
96 return false;
100 bool isDeadBlock(const BasicBlock *BB) const {
101 return DeadBlocks.count(BB);
104 bool isDeadEdge(const Use *U) const {
105 assert(dyn_cast<Instruction>(U->getUser())->isTerminator() &&
106 "edge must be operand of terminator");
107 assert(cast_or_null<BasicBlock>(U->get()) &&
108 "edge must refer to basic block");
109 assert(!isDeadBlock(dyn_cast<Instruction>(U->getUser())->getParent()) &&
110 "isDeadEdge() must be applied to edge from live block");
111 return DeadEdges.count(U);
114 bool hasLiveIncomingEdges(const BasicBlock *BB) const {
115 // Check if all incoming edges are dead.
116 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
117 auto &PU = PredIt.getUse();
118 const Use &U = PU.getUser()->getOperandUse(PU.getOperandNo());
119 if (!isDeadBlock(*PredIt) && !isDeadEdge(&U))
120 return true; // Found a live edge.
122 return false;
125 void processFunction(const Function &F, const DominatorTree &DT) {
126 this->DT = &DT;
128 // Start with all blocks unreachable from entry.
129 for (const BasicBlock &BB : F)
130 if (!DT.isReachableFromEntry(&BB))
131 DeadBlocks.insert(&BB);
133 // Top-down walk of the dominator tree
134 ReversePostOrderTraversal<const Function *> RPOT(&F);
135 for (const BasicBlock *BB : RPOT) {
136 const Instruction *TI = BB->getTerminator();
137 assert(TI && "blocks must be well formed");
139 // For conditional branches, we can perform simple conditional propagation on
140 // the condition value itself.
141 const BranchInst *BI = dyn_cast<BranchInst>(TI);
142 if (!BI || !BI->isConditional() || !isa<Constant>(BI->getCondition()))
143 continue;
145 // If a branch has two identical successors, we cannot declare either dead.
146 if (BI->getSuccessor(0) == BI->getSuccessor(1))
147 continue;
149 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
150 if (!Cond)
151 continue;
153 addDeadEdge(BI->getOperandUse(Cond->getZExtValue() ? 1 : 2));
157 protected:
158 void addDeadBlock(const BasicBlock *BB) {
159 SmallVector<const BasicBlock *, 4> NewDead;
160 SmallSetVector<const BasicBlock *, 4> DF;
162 NewDead.push_back(BB);
163 while (!NewDead.empty()) {
164 const BasicBlock *D = NewDead.pop_back_val();
165 if (isDeadBlock(D))
166 continue;
168 // All blocks dominated by D are dead.
169 SmallVector<BasicBlock *, 8> Dom;
170 DT->getDescendants(const_cast<BasicBlock*>(D), Dom);
171 // Do not need to mark all in and out edges dead
172 // because BB is marked dead and this is enough
173 // to run further.
174 DeadBlocks.insert(Dom.begin(), Dom.end());
176 // Figure out the dominance-frontier(D).
177 for (BasicBlock *B : Dom)
178 for (BasicBlock *S : successors(B))
179 if (!isDeadBlock(S) && !hasLiveIncomingEdges(S))
180 NewDead.push_back(S);
184 void addDeadEdge(const Use &DeadEdge) {
185 if (!DeadEdges.insert(&DeadEdge))
186 return;
188 BasicBlock *BB = cast_or_null<BasicBlock>(DeadEdge.get());
189 if (hasLiveIncomingEdges(BB))
190 return;
192 addDeadBlock(BB);
195 } // namespace
197 static void Verify(const Function &F, const DominatorTree &DT,
198 const CFGDeadness &CD);
200 namespace {
202 struct SafepointIRVerifier : public FunctionPass {
203 static char ID; // Pass identification, replacement for typeid
204 SafepointIRVerifier() : FunctionPass(ID) {
205 initializeSafepointIRVerifierPass(*PassRegistry::getPassRegistry());
208 bool runOnFunction(Function &F) override {
209 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
210 CFGDeadness CD;
211 CD.processFunction(F, DT);
212 Verify(F, DT, CD);
213 return false; // no modifications
216 void getAnalysisUsage(AnalysisUsage &AU) const override {
217 AU.addRequiredID(DominatorTreeWrapperPass::ID);
218 AU.setPreservesAll();
221 StringRef getPassName() const override { return "safepoint verifier"; }
223 } // namespace
225 void llvm::verifySafepointIR(Function &F) {
226 SafepointIRVerifier pass;
227 pass.runOnFunction(F);
230 char SafepointIRVerifier::ID = 0;
232 FunctionPass *llvm::createSafepointIRVerifierPass() {
233 return new SafepointIRVerifier();
236 INITIALIZE_PASS_BEGIN(SafepointIRVerifier, "verify-safepoint-ir",
237 "Safepoint IR Verifier", false, false)
238 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
239 INITIALIZE_PASS_END(SafepointIRVerifier, "verify-safepoint-ir",
240 "Safepoint IR Verifier", false, false)
242 static bool isGCPointerType(Type *T) {
243 if (auto *PT = dyn_cast<PointerType>(T))
244 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
245 // GC managed heap. We know that a pointer into this heap needs to be
246 // updated and that no other pointer does.
247 return (1 == PT->getAddressSpace());
248 return false;
251 static bool containsGCPtrType(Type *Ty) {
252 if (isGCPointerType(Ty))
253 return true;
254 if (VectorType *VT = dyn_cast<VectorType>(Ty))
255 return isGCPointerType(VT->getScalarType());
256 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
257 return containsGCPtrType(AT->getElementType());
258 if (StructType *ST = dyn_cast<StructType>(Ty))
259 return llvm::any_of(ST->elements(), containsGCPtrType);
260 return false;
263 // Debugging aid -- prints a [Begin, End) range of values.
264 template<typename IteratorTy>
265 static void PrintValueSet(raw_ostream &OS, IteratorTy Begin, IteratorTy End) {
266 OS << "[ ";
267 while (Begin != End) {
268 OS << **Begin << " ";
269 ++Begin;
271 OS << "]";
274 /// The verifier algorithm is phrased in terms of availability. The set of
275 /// values "available" at a given point in the control flow graph is the set of
276 /// correctly relocated value at that point, and is a subset of the set of
277 /// definitions dominating that point.
279 using AvailableValueSet = DenseSet<const Value *>;
281 /// State we compute and track per basic block.
282 struct BasicBlockState {
283 // Set of values available coming in, before the phi nodes
284 AvailableValueSet AvailableIn;
286 // Set of values available going out
287 AvailableValueSet AvailableOut;
289 // AvailableOut minus AvailableIn.
290 // All elements are Instructions
291 AvailableValueSet Contribution;
293 // True if this block contains a safepoint and thus AvailableIn does not
294 // contribute to AvailableOut.
295 bool Cleared = false;
298 /// A given derived pointer can have multiple base pointers through phi/selects.
299 /// This type indicates when the base pointer is exclusively constant
300 /// (ExclusivelySomeConstant), and if that constant is proven to be exclusively
301 /// null, we record that as ExclusivelyNull. In all other cases, the BaseType is
302 /// NonConstant.
303 enum BaseType {
304 NonConstant = 1, // Base pointers is not exclusively constant.
305 ExclusivelyNull,
306 ExclusivelySomeConstant // Base pointers for a given derived pointer is from a
307 // set of constants, but they are not exclusively
308 // null.
311 /// Return the baseType for Val which states whether Val is exclusively
312 /// derived from constant/null, or not exclusively derived from constant.
313 /// Val is exclusively derived off a constant base when all operands of phi and
314 /// selects are derived off a constant base.
315 static enum BaseType getBaseType(const Value *Val) {
317 SmallVector<const Value *, 32> Worklist;
318 DenseSet<const Value *> Visited;
319 bool isExclusivelyDerivedFromNull = true;
320 Worklist.push_back(Val);
321 // Strip through all the bitcasts and geps to get base pointer. Also check for
322 // the exclusive value when there can be multiple base pointers (through phis
323 // or selects).
324 while(!Worklist.empty()) {
325 const Value *V = Worklist.pop_back_val();
326 if (!Visited.insert(V).second)
327 continue;
329 if (const auto *CI = dyn_cast<CastInst>(V)) {
330 Worklist.push_back(CI->stripPointerCasts());
331 continue;
333 if (const auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
334 Worklist.push_back(GEP->getPointerOperand());
335 continue;
337 // Push all the incoming values of phi node into the worklist for
338 // processing.
339 if (const auto *PN = dyn_cast<PHINode>(V)) {
340 for (Value *InV: PN->incoming_values())
341 Worklist.push_back(InV);
342 continue;
344 if (const auto *SI = dyn_cast<SelectInst>(V)) {
345 // Push in the true and false values
346 Worklist.push_back(SI->getTrueValue());
347 Worklist.push_back(SI->getFalseValue());
348 continue;
350 if (isa<Constant>(V)) {
351 // We found at least one base pointer which is non-null, so this derived
352 // pointer is not exclusively derived from null.
353 if (V != Constant::getNullValue(V->getType()))
354 isExclusivelyDerivedFromNull = false;
355 // Continue processing the remaining values to make sure it's exclusively
356 // constant.
357 continue;
359 // At this point, we know that the base pointer is not exclusively
360 // constant.
361 return BaseType::NonConstant;
363 // Now, we know that the base pointer is exclusively constant, but we need to
364 // differentiate between exclusive null constant and non-null constant.
365 return isExclusivelyDerivedFromNull ? BaseType::ExclusivelyNull
366 : BaseType::ExclusivelySomeConstant;
369 static bool isNotExclusivelyConstantDerived(const Value *V) {
370 return getBaseType(V) == BaseType::NonConstant;
373 namespace {
374 class InstructionVerifier;
376 /// Builds BasicBlockState for each BB of the function.
377 /// It can traverse function for verification and provides all required
378 /// information.
380 /// GC pointer may be in one of three states: relocated, unrelocated and
381 /// poisoned.
382 /// Relocated pointer may be used without any restrictions.
383 /// Unrelocated pointer cannot be dereferenced, passed as argument to any call
384 /// or returned. Unrelocated pointer may be safely compared against another
385 /// unrelocated pointer or against a pointer exclusively derived from null.
386 /// Poisoned pointers are produced when we somehow derive pointer from relocated
387 /// and unrelocated pointers (e.g. phi, select). This pointers may be safely
388 /// used in a very limited number of situations. Currently the only way to use
389 /// it is comparison against constant exclusively derived from null. All
390 /// limitations arise due to their undefined state: this pointers should be
391 /// treated as relocated and unrelocated simultaneously.
392 /// Rules of deriving:
393 /// R + U = P - that's where the poisoned pointers come from
394 /// P + X = P
395 /// U + U = U
396 /// R + R = R
397 /// X + C = X
398 /// Where "+" - any operation that somehow derive pointer, U - unrelocated,
399 /// R - relocated and P - poisoned, C - constant, X - U or R or P or C or
400 /// nothing (in case when "+" is unary operation).
401 /// Deriving of pointers by itself is always safe.
402 /// NOTE: when we are making decision on the status of instruction's result:
403 /// a) for phi we need to check status of each input *at the end of
404 /// corresponding predecessor BB*.
405 /// b) for other instructions we need to check status of each input *at the
406 /// current point*.
408 /// FIXME: This works fairly well except one case
409 /// bb1:
410 /// p = *some GC-ptr def*
411 /// p1 = gep p, offset
412 /// / |
413 /// / |
414 /// bb2: |
415 /// safepoint |
416 /// \ |
417 /// \ |
418 /// bb3:
419 /// p2 = phi [p, bb2] [p1, bb1]
420 /// p3 = phi [p, bb2] [p, bb1]
421 /// here p and p1 is unrelocated
422 /// p2 and p3 is poisoned (though they shouldn't be)
424 /// This leads to some weird results:
425 /// cmp eq p, p2 - illegal instruction (false-positive)
426 /// cmp eq p1, p2 - illegal instruction (false-positive)
427 /// cmp eq p, p3 - illegal instruction (false-positive)
428 /// cmp eq p, p1 - ok
429 /// To fix this we need to introduce conception of generations and be able to
430 /// check if two values belong to one generation or not. This way p2 will be
431 /// considered to be unrelocated and no false alarm will happen.
432 class GCPtrTracker {
433 const Function &F;
434 const CFGDeadness &CD;
435 SpecificBumpPtrAllocator<BasicBlockState> BSAllocator;
436 DenseMap<const BasicBlock *, BasicBlockState *> BlockMap;
437 // This set contains defs of unrelocated pointers that are proved to be legal
438 // and don't need verification.
439 DenseSet<const Instruction *> ValidUnrelocatedDefs;
440 // This set contains poisoned defs. They can be safely ignored during
441 // verification too.
442 DenseSet<const Value *> PoisonedDefs;
444 public:
445 GCPtrTracker(const Function &F, const DominatorTree &DT,
446 const CFGDeadness &CD);
448 bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
449 return CD.hasLiveIncomingEdge(PN, InBB);
452 BasicBlockState *getBasicBlockState(const BasicBlock *BB);
453 const BasicBlockState *getBasicBlockState(const BasicBlock *BB) const;
455 bool isValuePoisoned(const Value *V) const { return PoisonedDefs.count(V); }
457 /// Traverse each BB of the function and call
458 /// InstructionVerifier::verifyInstruction for each possibly invalid
459 /// instruction.
460 /// It destructively modifies GCPtrTracker so it's passed via rvalue reference
461 /// in order to prohibit further usages of GCPtrTracker as it'll be in
462 /// inconsistent state.
463 static void verifyFunction(GCPtrTracker &&Tracker,
464 InstructionVerifier &Verifier);
466 /// Returns true for reachable and live blocks.
467 bool isMapped(const BasicBlock *BB) const {
468 return BlockMap.find(BB) != BlockMap.end();
471 private:
472 /// Returns true if the instruction may be safely skipped during verification.
473 bool instructionMayBeSkipped(const Instruction *I) const;
475 /// Iterates over all BBs from BlockMap and recalculates AvailableIn/Out for
476 /// each of them until it converges.
477 void recalculateBBsStates();
479 /// Remove from Contribution all defs that legally produce unrelocated
480 /// pointers and saves them to ValidUnrelocatedDefs.
481 /// Though Contribution should belong to BBS it is passed separately with
482 /// different const-modifier in order to emphasize (and guarantee) that only
483 /// Contribution will be changed.
484 /// Returns true if Contribution was changed otherwise false.
485 bool removeValidUnrelocatedDefs(const BasicBlock *BB,
486 const BasicBlockState *BBS,
487 AvailableValueSet &Contribution);
489 /// Gather all the definitions dominating the start of BB into Result. This is
490 /// simply the defs introduced by every dominating basic block and the
491 /// function arguments.
492 void gatherDominatingDefs(const BasicBlock *BB, AvailableValueSet &Result,
493 const DominatorTree &DT);
495 /// Compute the AvailableOut set for BB, based on the BasicBlockState BBS,
496 /// which is the BasicBlockState for BB.
497 /// ContributionChanged is set when the verifier runs for the first time
498 /// (in this case Contribution was changed from 'empty' to its initial state)
499 /// or when Contribution of this BB was changed since last computation.
500 static void transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
501 bool ContributionChanged);
503 /// Model the effect of an instruction on the set of available values.
504 static void transferInstruction(const Instruction &I, bool &Cleared,
505 AvailableValueSet &Available);
508 /// It is a visitor for GCPtrTracker::verifyFunction. It decides if the
509 /// instruction (which uses heap reference) is legal or not, given our safepoint
510 /// semantics.
511 class InstructionVerifier {
512 bool AnyInvalidUses = false;
514 public:
515 void verifyInstruction(const GCPtrTracker *Tracker, const Instruction &I,
516 const AvailableValueSet &AvailableSet);
518 bool hasAnyInvalidUses() const { return AnyInvalidUses; }
520 private:
521 void reportInvalidUse(const Value &V, const Instruction &I);
523 } // end anonymous namespace
525 GCPtrTracker::GCPtrTracker(const Function &F, const DominatorTree &DT,
526 const CFGDeadness &CD) : F(F), CD(CD) {
527 // Calculate Contribution of each live BB.
528 // Allocate BB states for live blocks.
529 for (const BasicBlock &BB : F)
530 if (!CD.isDeadBlock(&BB)) {
531 BasicBlockState *BBS = new (BSAllocator.Allocate()) BasicBlockState;
532 for (const auto &I : BB)
533 transferInstruction(I, BBS->Cleared, BBS->Contribution);
534 BlockMap[&BB] = BBS;
537 // Initialize AvailableIn/Out sets of each BB using only information about
538 // dominating BBs.
539 for (auto &BBI : BlockMap) {
540 gatherDominatingDefs(BBI.first, BBI.second->AvailableIn, DT);
541 transferBlock(BBI.first, *BBI.second, true);
544 // Simulate the flow of defs through the CFG and recalculate AvailableIn/Out
545 // sets of each BB until it converges. If any def is proved to be an
546 // unrelocated pointer, it will be removed from all BBSs.
547 recalculateBBsStates();
550 BasicBlockState *GCPtrTracker::getBasicBlockState(const BasicBlock *BB) {
551 auto it = BlockMap.find(BB);
552 return it != BlockMap.end() ? it->second : nullptr;
555 const BasicBlockState *GCPtrTracker::getBasicBlockState(
556 const BasicBlock *BB) const {
557 return const_cast<GCPtrTracker *>(this)->getBasicBlockState(BB);
560 bool GCPtrTracker::instructionMayBeSkipped(const Instruction *I) const {
561 // Poisoned defs are skipped since they are always safe by itself by
562 // definition (for details see comment to this class).
563 return ValidUnrelocatedDefs.count(I) || PoisonedDefs.count(I);
566 void GCPtrTracker::verifyFunction(GCPtrTracker &&Tracker,
567 InstructionVerifier &Verifier) {
568 // We need RPO here to a) report always the first error b) report errors in
569 // same order from run to run.
570 ReversePostOrderTraversal<const Function *> RPOT(&Tracker.F);
571 for (const BasicBlock *BB : RPOT) {
572 BasicBlockState *BBS = Tracker.getBasicBlockState(BB);
573 if (!BBS)
574 continue;
576 // We destructively modify AvailableIn as we traverse the block instruction
577 // by instruction.
578 AvailableValueSet &AvailableSet = BBS->AvailableIn;
579 for (const Instruction &I : *BB) {
580 if (Tracker.instructionMayBeSkipped(&I))
581 continue; // This instruction shouldn't be added to AvailableSet.
583 Verifier.verifyInstruction(&Tracker, I, AvailableSet);
585 // Model the effect of current instruction on AvailableSet to keep the set
586 // relevant at each point of BB.
587 bool Cleared = false;
588 transferInstruction(I, Cleared, AvailableSet);
589 (void)Cleared;
594 void GCPtrTracker::recalculateBBsStates() {
595 SetVector<const BasicBlock *> Worklist;
596 // TODO: This order is suboptimal, it's better to replace it with priority
597 // queue where priority is RPO number of BB.
598 for (auto &BBI : BlockMap)
599 Worklist.insert(BBI.first);
601 // This loop iterates the AvailableIn/Out sets until it converges.
602 // The AvailableIn and AvailableOut sets decrease as we iterate.
603 while (!Worklist.empty()) {
604 const BasicBlock *BB = Worklist.pop_back_val();
605 BasicBlockState *BBS = getBasicBlockState(BB);
606 if (!BBS)
607 continue; // Ignore dead successors.
609 size_t OldInCount = BBS->AvailableIn.size();
610 for (const_pred_iterator PredIt(BB), End(BB, true); PredIt != End; ++PredIt) {
611 const BasicBlock *PBB = *PredIt;
612 BasicBlockState *PBBS = getBasicBlockState(PBB);
613 if (PBBS && !CD.isDeadEdge(&CFGDeadness::getEdge(PredIt)))
614 set_intersect(BBS->AvailableIn, PBBS->AvailableOut);
617 assert(OldInCount >= BBS->AvailableIn.size() && "invariant!");
619 bool InputsChanged = OldInCount != BBS->AvailableIn.size();
620 bool ContributionChanged =
621 removeValidUnrelocatedDefs(BB, BBS, BBS->Contribution);
622 if (!InputsChanged && !ContributionChanged)
623 continue;
625 size_t OldOutCount = BBS->AvailableOut.size();
626 transferBlock(BB, *BBS, ContributionChanged);
627 if (OldOutCount != BBS->AvailableOut.size()) {
628 assert(OldOutCount > BBS->AvailableOut.size() && "invariant!");
629 Worklist.insert(succ_begin(BB), succ_end(BB));
634 bool GCPtrTracker::removeValidUnrelocatedDefs(const BasicBlock *BB,
635 const BasicBlockState *BBS,
636 AvailableValueSet &Contribution) {
637 assert(&BBS->Contribution == &Contribution &&
638 "Passed Contribution should be from the passed BasicBlockState!");
639 AvailableValueSet AvailableSet = BBS->AvailableIn;
640 bool ContributionChanged = false;
641 // For explanation why instructions are processed this way see
642 // "Rules of deriving" in the comment to this class.
643 for (const Instruction &I : *BB) {
644 bool ValidUnrelocatedPointerDef = false;
645 bool PoisonedPointerDef = false;
646 // TODO: `select` instructions should be handled here too.
647 if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
648 if (containsGCPtrType(PN->getType())) {
649 // If both is true, output is poisoned.
650 bool HasRelocatedInputs = false;
651 bool HasUnrelocatedInputs = false;
652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
653 const BasicBlock *InBB = PN->getIncomingBlock(i);
654 if (!isMapped(InBB) ||
655 !CD.hasLiveIncomingEdge(PN, InBB))
656 continue; // Skip dead block or dead edge.
658 const Value *InValue = PN->getIncomingValue(i);
660 if (isNotExclusivelyConstantDerived(InValue)) {
661 if (isValuePoisoned(InValue)) {
662 // If any of inputs is poisoned, output is always poisoned too.
663 HasRelocatedInputs = true;
664 HasUnrelocatedInputs = true;
665 break;
667 if (BlockMap[InBB]->AvailableOut.count(InValue))
668 HasRelocatedInputs = true;
669 else
670 HasUnrelocatedInputs = true;
673 if (HasUnrelocatedInputs) {
674 if (HasRelocatedInputs)
675 PoisonedPointerDef = true;
676 else
677 ValidUnrelocatedPointerDef = true;
680 } else if ((isa<GetElementPtrInst>(I) || isa<BitCastInst>(I)) &&
681 containsGCPtrType(I.getType())) {
682 // GEP/bitcast of unrelocated pointer is legal by itself but this def
683 // shouldn't appear in any AvailableSet.
684 for (const Value *V : I.operands())
685 if (containsGCPtrType(V->getType()) &&
686 isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V)) {
687 if (isValuePoisoned(V))
688 PoisonedPointerDef = true;
689 else
690 ValidUnrelocatedPointerDef = true;
691 break;
694 assert(!(ValidUnrelocatedPointerDef && PoisonedPointerDef) &&
695 "Value cannot be both unrelocated and poisoned!");
696 if (ValidUnrelocatedPointerDef) {
697 // Remove def of unrelocated pointer from Contribution of this BB and
698 // trigger update of all its successors.
699 Contribution.erase(&I);
700 PoisonedDefs.erase(&I);
701 ValidUnrelocatedDefs.insert(&I);
702 LLVM_DEBUG(dbgs() << "Removing urelocated " << I
703 << " from Contribution of " << BB->getName() << "\n");
704 ContributionChanged = true;
705 } else if (PoisonedPointerDef) {
706 // Mark pointer as poisoned, remove its def from Contribution and trigger
707 // update of all successors.
708 Contribution.erase(&I);
709 PoisonedDefs.insert(&I);
710 LLVM_DEBUG(dbgs() << "Removing poisoned " << I << " from Contribution of "
711 << BB->getName() << "\n");
712 ContributionChanged = true;
713 } else {
714 bool Cleared = false;
715 transferInstruction(I, Cleared, AvailableSet);
716 (void)Cleared;
719 return ContributionChanged;
722 void GCPtrTracker::gatherDominatingDefs(const BasicBlock *BB,
723 AvailableValueSet &Result,
724 const DominatorTree &DT) {
725 DomTreeNode *DTN = DT[const_cast<BasicBlock *>(BB)];
727 assert(DTN && "Unreachable blocks are ignored");
728 while (DTN->getIDom()) {
729 DTN = DTN->getIDom();
730 auto BBS = getBasicBlockState(DTN->getBlock());
731 assert(BBS && "immediate dominator cannot be dead for a live block");
732 const auto &Defs = BBS->Contribution;
733 Result.insert(Defs.begin(), Defs.end());
734 // If this block is 'Cleared', then nothing LiveIn to this block can be
735 // available after this block completes. Note: This turns out to be
736 // really important for reducing memory consuption of the initial available
737 // sets and thus peak memory usage by this verifier.
738 if (BBS->Cleared)
739 return;
742 for (const Argument &A : BB->getParent()->args())
743 if (containsGCPtrType(A.getType()))
744 Result.insert(&A);
747 void GCPtrTracker::transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
748 bool ContributionChanged) {
749 const AvailableValueSet &AvailableIn = BBS.AvailableIn;
750 AvailableValueSet &AvailableOut = BBS.AvailableOut;
752 if (BBS.Cleared) {
753 // AvailableOut will change only when Contribution changed.
754 if (ContributionChanged)
755 AvailableOut = BBS.Contribution;
756 } else {
757 // Otherwise, we need to reduce the AvailableOut set by things which are no
758 // longer in our AvailableIn
759 AvailableValueSet Temp = BBS.Contribution;
760 set_union(Temp, AvailableIn);
761 AvailableOut = std::move(Temp);
764 LLVM_DEBUG(dbgs() << "Transfered block " << BB->getName() << " from ";
765 PrintValueSet(dbgs(), AvailableIn.begin(), AvailableIn.end());
766 dbgs() << " to ";
767 PrintValueSet(dbgs(), AvailableOut.begin(), AvailableOut.end());
768 dbgs() << "\n";);
771 void GCPtrTracker::transferInstruction(const Instruction &I, bool &Cleared,
772 AvailableValueSet &Available) {
773 if (isStatepoint(I)) {
774 Cleared = true;
775 Available.clear();
776 } else if (containsGCPtrType(I.getType()))
777 Available.insert(&I);
780 void InstructionVerifier::verifyInstruction(
781 const GCPtrTracker *Tracker, const Instruction &I,
782 const AvailableValueSet &AvailableSet) {
783 if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
784 if (containsGCPtrType(PN->getType()))
785 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
786 const BasicBlock *InBB = PN->getIncomingBlock(i);
787 const BasicBlockState *InBBS = Tracker->getBasicBlockState(InBB);
788 if (!InBBS ||
789 !Tracker->hasLiveIncomingEdge(PN, InBB))
790 continue; // Skip dead block or dead edge.
792 const Value *InValue = PN->getIncomingValue(i);
794 if (isNotExclusivelyConstantDerived(InValue) &&
795 !InBBS->AvailableOut.count(InValue))
796 reportInvalidUse(*InValue, *PN);
798 } else if (isa<CmpInst>(I) &&
799 containsGCPtrType(I.getOperand(0)->getType())) {
800 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
801 enum BaseType baseTyLHS = getBaseType(LHS),
802 baseTyRHS = getBaseType(RHS);
804 // Returns true if LHS and RHS are unrelocated pointers and they are
805 // valid unrelocated uses.
806 auto hasValidUnrelocatedUse = [&AvailableSet, Tracker, baseTyLHS, baseTyRHS,
807 &LHS, &RHS] () {
808 // A cmp instruction has valid unrelocated pointer operands only if
809 // both operands are unrelocated pointers.
810 // In the comparison between two pointers, if one is an unrelocated
811 // use, the other *should be* an unrelocated use, for this
812 // instruction to contain valid unrelocated uses. This unrelocated
813 // use can be a null constant as well, or another unrelocated
814 // pointer.
815 if (AvailableSet.count(LHS) || AvailableSet.count(RHS))
816 return false;
817 // Constant pointers (that are not exclusively null) may have
818 // meaning in different VMs, so we cannot reorder the compare
819 // against constant pointers before the safepoint. In other words,
820 // comparison of an unrelocated use against a non-null constant
821 // maybe invalid.
822 if ((baseTyLHS == BaseType::ExclusivelySomeConstant &&
823 baseTyRHS == BaseType::NonConstant) ||
824 (baseTyLHS == BaseType::NonConstant &&
825 baseTyRHS == BaseType::ExclusivelySomeConstant))
826 return false;
828 // If one of pointers is poisoned and other is not exclusively derived
829 // from null it is an invalid expression: it produces poisoned result
830 // and unless we want to track all defs (not only gc pointers) the only
831 // option is to prohibit such instructions.
832 if ((Tracker->isValuePoisoned(LHS) && baseTyRHS != ExclusivelyNull) ||
833 (Tracker->isValuePoisoned(RHS) && baseTyLHS != ExclusivelyNull))
834 return false;
836 // All other cases are valid cases enumerated below:
837 // 1. Comparison between an exclusively derived null pointer and a
838 // constant base pointer.
839 // 2. Comparison between an exclusively derived null pointer and a
840 // non-constant unrelocated base pointer.
841 // 3. Comparison between 2 unrelocated pointers.
842 // 4. Comparison between a pointer exclusively derived from null and a
843 // non-constant poisoned pointer.
844 return true;
846 if (!hasValidUnrelocatedUse()) {
847 // Print out all non-constant derived pointers that are unrelocated
848 // uses, which are invalid.
849 if (baseTyLHS == BaseType::NonConstant && !AvailableSet.count(LHS))
850 reportInvalidUse(*LHS, I);
851 if (baseTyRHS == BaseType::NonConstant && !AvailableSet.count(RHS))
852 reportInvalidUse(*RHS, I);
854 } else {
855 for (const Value *V : I.operands())
856 if (containsGCPtrType(V->getType()) &&
857 isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V))
858 reportInvalidUse(*V, I);
862 void InstructionVerifier::reportInvalidUse(const Value &V,
863 const Instruction &I) {
864 errs() << "Illegal use of unrelocated value found!\n";
865 errs() << "Def: " << V << "\n";
866 errs() << "Use: " << I << "\n";
867 if (!PrintOnly)
868 abort();
869 AnyInvalidUses = true;
872 static void Verify(const Function &F, const DominatorTree &DT,
873 const CFGDeadness &CD) {
874 LLVM_DEBUG(dbgs() << "Verifying gc pointers in function: " << F.getName()
875 << "\n");
876 if (PrintOnly)
877 dbgs() << "Verifying gc pointers in function: " << F.getName() << "\n";
879 GCPtrTracker Tracker(F, DT, CD);
881 // We now have all the information we need to decide if the use of a heap
882 // reference is legal or not, given our safepoint semantics.
884 InstructionVerifier Verifier;
885 GCPtrTracker::verifyFunction(std::move(Tracker), Verifier);
887 if (PrintOnly && !Verifier.hasAnyInvalidUses()) {
888 dbgs() << "No illegal uses found by SafepointIRVerifier in: " << F.getName()
889 << "\n";