LLVM  9.0.0svn
SafepointIRVerifier.cpp
Go to the documentation of this file.
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.
15 //
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:
19 //
20 // a = ...
21 // b = ...
22 // (a',b') = safepoint(a,b)
23 // c = cmp eq a b
24 // br c, ..., ....
25 //
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.
30 //
31 //===----------------------------------------------------------------------===//
32 
33 #include "llvm/ADT/DenseSet.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"
46 #include "llvm/IR/Statepoint.h"
47 #include "llvm/Support/Debug.h"
50 
51 #define DEBUG_TYPE "safepoint-ir-verifier"
52 
53 using namespace llvm;
54 
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));
60 
61 namespace {
62 
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;
72  SetVector<const Use *> DeadEdges; // Contains all dead edges from live blocks.
73 
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());
79  }
80 
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;
92  }
93  }
94  (void)Listed;
95  assert(Listed && "basic block is not found among incoming blocks");
96  return false;
97  }
98 
99 
100  bool isDeadBlock(const BasicBlock *BB) const {
101  return DeadBlocks.count(BB);
102  }
103 
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);
112  }
113 
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.
121  }
122  return false;
123  }
124 
125  void processFunction(const Function &F, const DominatorTree &DT) {
126  this->DT = &DT;
127 
128  // Start with all blocks unreachable from entry.
129  for (const BasicBlock &BB : F)
130  if (!DT.isReachableFromEntry(&BB))
131  DeadBlocks.insert(&BB);
132 
133  // Top-down walk of the dominator tree
135  for (const BasicBlock *BB : RPOT) {
136  const Instruction *TI = BB->getTerminator();
137  assert(TI && "blocks must be well formed");
138 
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;
144 
145  // If a branch has two identical successors, we cannot declare either dead.
146  if (BI->getSuccessor(0) == BI->getSuccessor(1))
147  continue;
148 
150  if (!Cond)
151  continue;
152 
153  addDeadEdge(BI->getOperandUse(Cond->getZExtValue() ? 1 : 2));
154  }
155  }
156 
157 protected:
158  void addDeadBlock(const BasicBlock *BB) {
161 
162  NewDead.push_back(BB);
163  while (!NewDead.empty()) {
164  const BasicBlock *D = NewDead.pop_back_val();
165  if (isDeadBlock(D))
166  continue;
167 
168  // All blocks dominated by D are dead.
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());
175 
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);
181  }
182  }
183 
184  void addDeadEdge(const Use &DeadEdge) {
185  if (!DeadEdges.insert(&DeadEdge))
186  return;
187 
188  BasicBlock *BB = cast_or_null<BasicBlock>(DeadEdge.get());
189  if (hasLiveIncomingEdges(BB))
190  return;
191 
192  addDeadBlock(BB);
193  }
194 };
195 } // namespace
196 
197 static void Verify(const Function &F, const DominatorTree &DT,
198  const CFGDeadness &CD);
199 
200 namespace {
201 
202 struct SafepointIRVerifier : public FunctionPass {
203  static char ID; // Pass identification, replacement for typeid
204  SafepointIRVerifier() : FunctionPass(ID) {
206  }
207 
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
214  }
215 
216  void getAnalysisUsage(AnalysisUsage &AU) const override {
218  AU.setPreservesAll();
219  }
220 
221  StringRef getPassName() const override { return "safepoint verifier"; }
222 };
223 } // namespace
224 
226  SafepointIRVerifier pass;
227  pass.runOnFunction(F);
228 }
229 
230 char SafepointIRVerifier::ID = 0;
231 
233  return new SafepointIRVerifier();
234 }
235 
236 INITIALIZE_PASS_BEGIN(SafepointIRVerifier, "verify-safepoint-ir",
237  "Safepoint IR Verifier", false, false)
239 INITIALIZE_PASS_END(SafepointIRVerifier, "verify-safepoint-ir",
240  "Safepoint IR Verifier", false, false)
241 
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;
249 }
250 
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;
261 }
262 
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;
270  }
271  OS << "]";
272 }
273 
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.
278 
280 
281 /// State we compute and track per basic block.
283  // Set of values available coming in, before the phi nodes
285 
286  // Set of values available going out
288 
289  // AvailableOut minus AvailableIn.
290  // All elements are Instructions
292 
293  // True if this block contains a safepoint and thus AvailableIn does not
294  // contribute to AvailableOut.
295  bool Cleared = false;
296 };
297 
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.
306  ExclusivelySomeConstant // Base pointers for a given derived pointer is from a
307  // set of constants, but they are not exclusively
308  // null.
309 };
310 
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) {
316 
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;
328 
329  if (const auto *CI = dyn_cast<CastInst>(V)) {
330  Worklist.push_back(CI->stripPointerCasts());
331  continue;
332  }
333  if (const auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
334  Worklist.push_back(GEP->getPointerOperand());
335  continue;
336  }
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;
343  }
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;
349  }
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;
358  }
359  // At this point, we know that the base pointer is not exclusively
360  // constant.
361  return BaseType::NonConstant;
362  }
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
367 }
368 
369 static bool isNotExclusivelyConstantDerived(const Value *V) {
370  return getBaseType(V) == BaseType::NonConstant;
371 }
372 
373 namespace {
374 class InstructionVerifier;
375 
376 /// Builds BasicBlockState for each BB of the function.
377 /// It can traverse function for verification and provides all required
378 /// information.
379 ///
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*.
407 ///
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)
423 ///
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;
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;
443 
444 public:
445  GCPtrTracker(const Function &F, const DominatorTree &DT,
446  const CFGDeadness &CD);
447 
448  bool hasLiveIncomingEdge(const PHINode *PN, const BasicBlock *InBB) const {
449  return CD.hasLiveIncomingEdge(PN, InBB);
450  }
451 
452  BasicBlockState *getBasicBlockState(const BasicBlock *BB);
453  const BasicBlockState *getBasicBlockState(const BasicBlock *BB) const;
454 
455  bool isValuePoisoned(const Value *V) const { return PoisonedDefs.count(V); }
456 
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);
465 
466  /// Returns true for reachable and live blocks.
467  bool isMapped(const BasicBlock *BB) const {
468  return BlockMap.find(BB) != BlockMap.end();
469  }
470 
471 private:
472  /// Returns true if the instruction may be safely skipped during verification.
473  bool instructionMayBeSkipped(const Instruction *I) const;
474 
475  /// Iterates over all BBs from BlockMap and recalculates AvailableIn/Out for
476  /// each of them until it converges.
477  void recalculateBBsStates();
478 
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);
488 
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);
494 
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);
502 
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);
506 };
507 
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;
513 
514 public:
515  void verifyInstruction(const GCPtrTracker *Tracker, const Instruction &I,
516  const AvailableValueSet &AvailableSet);
517 
518  bool hasAnyInvalidUses() const { return AnyInvalidUses; }
519 
520 private:
521  void reportInvalidUse(const Value &V, const Instruction &I);
522 };
523 } // end anonymous namespace
524 
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;
535  }
536 
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);
542  }
543 
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();
548 }
549 
550 BasicBlockState *GCPtrTracker::getBasicBlockState(const BasicBlock *BB) {
551  auto it = BlockMap.find(BB);
552  return it != BlockMap.end() ? it->second : nullptr;
553 }
554 
555 const BasicBlockState *GCPtrTracker::getBasicBlockState(
556  const BasicBlock *BB) const {
557  return const_cast<GCPtrTracker *>(this)->getBasicBlockState(BB);
558 }
559 
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);
564 }
565 
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.
571  for (const BasicBlock *BB : RPOT) {
572  BasicBlockState *BBS = Tracker.getBasicBlockState(BB);
573  if (!BBS)
574  continue;
575 
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.
582 
583  Verifier.verifyInstruction(&Tracker, I, AvailableSet);
584 
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;
590  }
591  }
592 }
593 
594 void GCPtrTracker::recalculateBBsStates() {
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);
600 
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.
608 
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)))
615  }
616 
617  assert(OldInCount >= BBS->AvailableIn.size() && "invariant!");
618 
619  bool InputsChanged = OldInCount != BBS->AvailableIn.size();
620  bool ContributionChanged =
621  removeValidUnrelocatedDefs(BB, BBS, BBS->Contribution);
622  if (!InputsChanged && !ContributionChanged)
623  continue;
624 
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));
630  }
631  }
632 }
633 
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.
657 
658  const Value *InValue = PN->getIncomingValue(i);
659 
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;
666  }
667  if (BlockMap[InBB]->AvailableOut.count(InValue))
668  HasRelocatedInputs = true;
669  else
670  HasUnrelocatedInputs = true;
671  }
672  }
673  if (HasUnrelocatedInputs) {
674  if (HasRelocatedInputs)
675  PoisonedPointerDef = true;
676  else
677  ValidUnrelocatedPointerDef = true;
678  }
679  }
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;
692  }
693  }
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;
717  }
718  }
719  return ContributionChanged;
720 }
721 
722 void GCPtrTracker::gatherDominatingDefs(const BasicBlock *BB,
723  AvailableValueSet &Result,
724  const DominatorTree &DT) {
725  DomTreeNode *DTN = DT[const_cast<BasicBlock *>(BB)];
726 
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;
740  }
741 
742  for (const Argument &A : BB->getParent()->args())
743  if (containsGCPtrType(A.getType()))
744  Result.insert(&A);
745 }
746 
747 void GCPtrTracker::transferBlock(const BasicBlock *BB, BasicBlockState &BBS,
748  bool ContributionChanged) {
749  const AvailableValueSet &AvailableIn = BBS.AvailableIn;
750  AvailableValueSet &AvailableOut = BBS.AvailableOut;
751 
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);
762  }
763 
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";);
769 }
770 
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);
778 }
779 
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.
791 
792  const Value *InValue = PN->getIncomingValue(i);
793 
794  if (isNotExclusivelyConstantDerived(InValue) &&
795  !InBBS->AvailableOut.count(InValue))
796  reportInvalidUse(*InValue, *PN);
797  }
798  } else if (isa<CmpInst>(I) &&
800  Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
801  enum BaseType baseTyLHS = getBaseType(LHS),
802  baseTyRHS = getBaseType(RHS);
803 
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;
827 
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;
835 
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;
845  };
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);
853  }
854  } else {
855  for (const Value *V : I.operands())
856  if (containsGCPtrType(V->getType()) &&
857  isNotExclusivelyConstantDerived(V) && !AvailableSet.count(V))
858  reportInvalidUse(*V, I);
859  }
860 }
861 
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;
870 }
871 
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";
878 
879  GCPtrTracker Tracker(F, DT, CD);
880 
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.
883 
884  InstructionVerifier Verifier;
885  GCPtrTracker::verifyFunction(std::move(Tracker), Verifier);
886 
887  if (PrintOnly && !Verifier.hasAnyInvalidUses()) {
888  dbgs() << "No illegal uses found by SafepointIRVerifier in: " << F.getName()
889  << "\n";
890  }
891 }
static void PrintValueSet(raw_ostream &OS, IteratorTy Begin, IteratorTy End)
Safe Stack instrumentation pass
Definition: SafeStack.cpp:908
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVM_NODISCARD T pop_back_val()
Definition: SetVector.h:227
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void initializeSafepointIRVerifierPass(PassRegistry &)
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null, or not exclusively derived from constant.
bool erase(const ValueT &V)
Definition: DenseSet.h:95
const Use & getOperandUse(unsigned i) const
Definition: User.h:182
BasicBlock * getSuccessor(unsigned i) const
F(f)
static bool isNotExclusivelyConstantDerived(const Value *V)
Hexagon Common GEP
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:299
Value * get() const
Definition: Use.h:107
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:264
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
AvailableValueSet AvailableIn
Class to represent struct types.
Definition: DerivedTypes.h:232
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:40
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
bool isStatepoint(const CallBase *Call)
Definition: Statepoint.cpp:20
Class to represent array types.
Definition: DerivedTypes.h:400
verify safepoint Safepoint IR static false bool isGCPointerType(Type *T)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Value * getOperand(unsigned i) const
Definition: User.h:169
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:210
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
Use & getUse() const
getUse - Return the operand Use in the predecessor&#39;s terminator of the successor. ...
Definition: CFG.h:97
AvailableValueSet Contribution
State we compute and track per basic block.
NodeT * getBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
void verifySafepointIR(Function &F)
Run the safepoint verifier over a single function. Crashes on failure.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
FunctionPass * createSafepointIRVerifierPass()
Create an instance of the safepoint verifier pass which can be added to a pass pipeline to check for ...
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
Definition: SetOperations.h:39
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
Conditional or Unconditional Branch instruction.
void getDescendants(NodeT *R, SmallVectorImpl< NodeT *> &Result) const
Get all nodes dominated by R, including R itself.
DomTreeNodeBase * getIDom() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
static bool containsGCPtrType(Type *Ty)
Represent the analysis usage information of a pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1192
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
op_range operands()
Definition: User.h:237
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:297
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
AnalysisUsage & addRequiredID(const void *ID)
Definition: Pass.cpp:298
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
Module.h This file contains the declarations for the Module class.
size_type size() const
Definition: DenseSet.h:75
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:373
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
bool isConditional() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition: Allocator.h:441
AvailableValueSet AvailableOut
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Class to represent vector types.
Definition: DerivedTypes.h:424
void setPreservesAll()
Set by analyses that do not transform their input at all.
INITIALIZE_PASS_BEGIN(SafepointIRVerifier, "verify-safepoint-ir", "Safepoint IR Verifier", false, false) INITIALIZE_PASS_END(SafepointIRVerifier
static cl::opt< bool > PrintOnly("safepoint-ir-verifier-print-only", cl::init(false))
This option is used for writing test cases.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
verify safepoint Safepoint IR Verifier
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:72
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:4850
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
A vector that has set insertion semantics.
Definition: SetVector.h:40
succ_range successors(Instruction *I)
Definition: CFG.h:259
verify safepoint ir
static const Function * getParent(const Value *V)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
#define LLVM_DEBUG(X)
Definition: Debug.h:122
op_range incoming_values()
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
Definition: SetOperations.h:22
Statically lint checks LLVM IR
Definition: Lint.cpp:192
iterator_range< arg_iterator > args()
Definition: Function.h:688
const BasicBlock * getParent() const
Definition: Instruction.h:66
static void Verify(const Function &F, const DominatorTree &DT, const CFGDeadness &CD)