xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision bb09ef95)
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
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 // This file implements the Value, ValueHandle, and User classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/Value.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DerivedUser.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/Statepoint.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 
39 using namespace llvm;
40 
41 static cl::opt<unsigned> NonGlobalValueMaxNameSize(
42     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
43     cl::desc("Maximum size for the name of non-global values."));
44 
45 //===----------------------------------------------------------------------===//
46 //                                Value Class
47 //===----------------------------------------------------------------------===//
48 static inline Type *checkType(Type *Ty) {
49   assert(Ty && "Value defined with a null type: Error!");
50   return Ty;
51 }
52 
53 Value::Value(Type *ty, unsigned scid)
54     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
55       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
56       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
57   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58   // FIXME: Why isn't this in the subclass gunk??
59   // Note, we cannot call isa<CallInst> before the CallInst has been
60   // constructed.
61   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
62       SubclassID == Instruction::CallBr)
63     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
64            "invalid CallInst type!");
65   else if (SubclassID != BasicBlockVal &&
66            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
67     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
68            "Cannot create non-first-class values except for constants!");
69   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
70                 "Value too big");
71 }
72 
73 Value::~Value() {
74   // Notify all ValueHandles (if present) that this value is going away.
75   if (HasValueHandle)
76     ValueHandleBase::ValueIsDeleted(this);
77   if (isUsedByMetadata())
78     ValueAsMetadata::handleDeletion(this);
79 
80 #ifndef NDEBUG      // Only in -g mode...
81   // Check to make sure that there are no uses of this value that are still
82   // around when the value is destroyed.  If there are, then we have a dangling
83   // reference and something is wrong.  This code is here to print out where
84   // the value is still being referenced.
85   //
86   // Note that use_empty() cannot be called here, as it eventually downcasts
87   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
88   // been destructed, so accessing it is UB.
89   //
90   if (!materialized_use_empty()) {
91     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
92     for (auto *U : users())
93       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
94   }
95 #endif
96   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
97 
98   // If this value is named, destroy the name.  This should not be in a symtab
99   // at this point.
100   destroyValueName();
101 }
102 
103 void Value::deleteValue() {
104   switch (getValueID()) {
105 #define HANDLE_VALUE(Name)                                                     \
106   case Value::Name##Val:                                                       \
107     delete static_cast<Name *>(this);                                          \
108     break;
109 #define HANDLE_MEMORY_VALUE(Name)                                              \
110   case Value::Name##Val:                                                       \
111     static_cast<DerivedUser *>(this)->DeleteValue(                             \
112         static_cast<DerivedUser *>(this));                                     \
113     break;
114 #define HANDLE_CONSTANT(Name)                                                  \
115   case Value::Name##Val:                                                       \
116     llvm_unreachable("constants should be destroyed with destroyConstant");    \
117     break;
118 #define HANDLE_INSTRUCTION(Name)  /* nothing */
119 #include "llvm/IR/Value.def"
120 
121 #define HANDLE_INST(N, OPC, CLASS)                                             \
122   case Value::InstructionVal + Instruction::OPC:                               \
123     delete static_cast<CLASS *>(this);                                         \
124     break;
125 #define HANDLE_USER_INST(N, OPC, CLASS)
126 #include "llvm/IR/Instruction.def"
127 
128   default:
129     llvm_unreachable("attempting to delete unknown value kind");
130   }
131 }
132 
133 void Value::destroyValueName() {
134   ValueName *Name = getValueName();
135   if (Name) {
136     MallocAllocator Allocator;
137     Name->Destroy(Allocator);
138   }
139   setValueName(nullptr);
140 }
141 
142 bool Value::hasNUses(unsigned N) const {
143   return hasNItems(use_begin(), use_end(), N);
144 }
145 
146 bool Value::hasNUsesOrMore(unsigned N) const {
147   return hasNItemsOrMore(use_begin(), use_end(), N);
148 }
149 
150 bool Value::hasOneUser() const {
151   if (use_empty())
152     return false;
153   if (hasOneUse())
154     return true;
155   return std::equal(++user_begin(), user_end(), user_begin());
156 }
157 
158 static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
159 
160 Use *Value::getSingleUndroppableUse() {
161   Use *Result = nullptr;
162   for (Use &U : uses()) {
163     if (!U.getUser()->isDroppable()) {
164       if (Result)
165         return nullptr;
166       Result = &U;
167     }
168   }
169   return Result;
170 }
171 
172 bool Value::hasNUndroppableUses(unsigned int N) const {
173   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
174 }
175 
176 bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
177   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
178 }
179 
180 void Value::dropDroppableUses(
181     llvm::function_ref<bool(const Use *)> ShouldDrop) {
182   SmallVector<Use *, 8> ToBeEdited;
183   for (Use &U : uses())
184     if (U.getUser()->isDroppable() && ShouldDrop(&U))
185       ToBeEdited.push_back(&U);
186   for (Use *U : ToBeEdited)
187     dropDroppableUse(*U);
188 }
189 
190 void Value::dropDroppableUsesIn(User &Usr) {
191   assert(Usr.isDroppable() && "Expected a droppable user!");
192   for (Use &UsrOp : Usr.operands()) {
193     if (UsrOp.get() == this)
194       dropDroppableUse(UsrOp);
195   }
196 }
197 
198 void Value::dropDroppableUse(Use &U) {
199   U.removeFromList();
200   if (auto *Assume = dyn_cast<IntrinsicInst>(U.getUser())) {
201     assert(Assume->getIntrinsicID() == Intrinsic::assume);
202     unsigned OpNo = U.getOperandNo();
203     if (OpNo == 0)
204       U.set(ConstantInt::getTrue(Assume->getContext()));
205     else {
206       U.set(UndefValue::get(U.get()->getType()));
207       CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
208       BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
209     }
210     return;
211   }
212 
213   llvm_unreachable("unkown droppable use");
214 }
215 
216 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
217   // This can be computed either by scanning the instructions in BB, or by
218   // scanning the use list of this Value. Both lists can be very long, but
219   // usually one is quite short.
220   //
221   // Scan both lists simultaneously until one is exhausted. This limits the
222   // search to the shorter list.
223   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
224   const_user_iterator UI = user_begin(), UE = user_end();
225   for (; BI != BE && UI != UE; ++BI, ++UI) {
226     // Scan basic block: Check if this Value is used by the instruction at BI.
227     if (is_contained(BI->operands(), this))
228       return true;
229     // Scan use list: Check if the use at UI is in BB.
230     const auto *User = dyn_cast<Instruction>(*UI);
231     if (User && User->getParent() == BB)
232       return true;
233   }
234   return false;
235 }
236 
237 unsigned Value::getNumUses() const {
238   return (unsigned)std::distance(use_begin(), use_end());
239 }
240 
241 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
242   ST = nullptr;
243   if (Instruction *I = dyn_cast<Instruction>(V)) {
244     if (BasicBlock *P = I->getParent())
245       if (Function *PP = P->getParent())
246         ST = PP->getValueSymbolTable();
247   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
248     if (Function *P = BB->getParent())
249       ST = P->getValueSymbolTable();
250   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
251     if (Module *P = GV->getParent())
252       ST = &P->getValueSymbolTable();
253   } else if (Argument *A = dyn_cast<Argument>(V)) {
254     if (Function *P = A->getParent())
255       ST = P->getValueSymbolTable();
256   } else {
257     assert(isa<Constant>(V) && "Unknown value type!");
258     return true;  // no name is setable for this.
259   }
260   return false;
261 }
262 
263 ValueName *Value::getValueName() const {
264   if (!HasName) return nullptr;
265 
266   LLVMContext &Ctx = getContext();
267   auto I = Ctx.pImpl->ValueNames.find(this);
268   assert(I != Ctx.pImpl->ValueNames.end() &&
269          "No name entry found!");
270 
271   return I->second;
272 }
273 
274 void Value::setValueName(ValueName *VN) {
275   LLVMContext &Ctx = getContext();
276 
277   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
278          "HasName bit out of sync!");
279 
280   if (!VN) {
281     if (HasName)
282       Ctx.pImpl->ValueNames.erase(this);
283     HasName = false;
284     return;
285   }
286 
287   HasName = true;
288   Ctx.pImpl->ValueNames[this] = VN;
289 }
290 
291 StringRef Value::getName() const {
292   // Make sure the empty string is still a C string. For historical reasons,
293   // some clients want to call .data() on the result and expect it to be null
294   // terminated.
295   if (!hasName())
296     return StringRef("", 0);
297   return getValueName()->getKey();
298 }
299 
300 void Value::setNameImpl(const Twine &NewName) {
301   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
302   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
303     return;
304 
305   // Fast path for common IRBuilder case of setName("") when there is no name.
306   if (NewName.isTriviallyEmpty() && !hasName())
307     return;
308 
309   SmallString<256> NameData;
310   StringRef NameRef = NewName.toStringRef(NameData);
311   assert(NameRef.find_first_of(0) == StringRef::npos &&
312          "Null bytes are not allowed in names");
313 
314   // Name isn't changing?
315   if (getName() == NameRef)
316     return;
317 
318   // Cap the size of non-GlobalValue names.
319   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
320     NameRef =
321         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
322 
323   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
324 
325   // Get the symbol table to update for this object.
326   ValueSymbolTable *ST;
327   if (getSymTab(this, ST))
328     return;  // Cannot set a name on this value (e.g. constant).
329 
330   if (!ST) { // No symbol table to update?  Just do the change.
331     if (NameRef.empty()) {
332       // Free the name for this value.
333       destroyValueName();
334       return;
335     }
336 
337     // NOTE: Could optimize for the case the name is shrinking to not deallocate
338     // then reallocated.
339     destroyValueName();
340 
341     // Create the new name.
342     MallocAllocator Allocator;
343     setValueName(ValueName::Create(NameRef, Allocator));
344     getValueName()->setValue(this);
345     return;
346   }
347 
348   // NOTE: Could optimize for the case the name is shrinking to not deallocate
349   // then reallocated.
350   if (hasName()) {
351     // Remove old name.
352     ST->removeValueName(getValueName());
353     destroyValueName();
354 
355     if (NameRef.empty())
356       return;
357   }
358 
359   // Name is changing to something new.
360   setValueName(ST->createValueName(NameRef, this));
361 }
362 
363 void Value::setName(const Twine &NewName) {
364   setNameImpl(NewName);
365   if (Function *F = dyn_cast<Function>(this))
366     F->recalculateIntrinsicID();
367 }
368 
369 void Value::takeName(Value *V) {
370   ValueSymbolTable *ST = nullptr;
371   // If this value has a name, drop it.
372   if (hasName()) {
373     // Get the symtab this is in.
374     if (getSymTab(this, ST)) {
375       // We can't set a name on this value, but we need to clear V's name if
376       // it has one.
377       if (V->hasName()) V->setName("");
378       return;  // Cannot set a name on this value (e.g. constant).
379     }
380 
381     // Remove old name.
382     if (ST)
383       ST->removeValueName(getValueName());
384     destroyValueName();
385   }
386 
387   // Now we know that this has no name.
388 
389   // If V has no name either, we're done.
390   if (!V->hasName()) return;
391 
392   // Get this's symtab if we didn't before.
393   if (!ST) {
394     if (getSymTab(this, ST)) {
395       // Clear V's name.
396       V->setName("");
397       return;  // Cannot set a name on this value (e.g. constant).
398     }
399   }
400 
401   // Get V's ST, this should always succed, because V has a name.
402   ValueSymbolTable *VST;
403   bool Failure = getSymTab(V, VST);
404   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
405 
406   // If these values are both in the same symtab, we can do this very fast.
407   // This works even if both values have no symtab yet.
408   if (ST == VST) {
409     // Take the name!
410     setValueName(V->getValueName());
411     V->setValueName(nullptr);
412     getValueName()->setValue(this);
413     return;
414   }
415 
416   // Otherwise, things are slightly more complex.  Remove V's name from VST and
417   // then reinsert it into ST.
418 
419   if (VST)
420     VST->removeValueName(V->getValueName());
421   setValueName(V->getValueName());
422   V->setValueName(nullptr);
423   getValueName()->setValue(this);
424 
425   if (ST)
426     ST->reinsertValue(this);
427 }
428 
429 void Value::assertModuleIsMaterializedImpl() const {
430 #ifndef NDEBUG
431   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
432   if (!GV)
433     return;
434   const Module *M = GV->getParent();
435   if (!M)
436     return;
437   assert(M->isMaterialized());
438 #endif
439 }
440 
441 #ifndef NDEBUG
442 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
443                      Constant *C) {
444   if (!Cache.insert(Expr).second)
445     return false;
446 
447   for (auto &O : Expr->operands()) {
448     if (O == C)
449       return true;
450     auto *CE = dyn_cast<ConstantExpr>(O);
451     if (!CE)
452       continue;
453     if (contains(Cache, CE, C))
454       return true;
455   }
456   return false;
457 }
458 
459 static bool contains(Value *Expr, Value *V) {
460   if (Expr == V)
461     return true;
462 
463   auto *C = dyn_cast<Constant>(V);
464   if (!C)
465     return false;
466 
467   auto *CE = dyn_cast<ConstantExpr>(Expr);
468   if (!CE)
469     return false;
470 
471   SmallPtrSet<ConstantExpr *, 4> Cache;
472   return contains(Cache, CE, C);
473 }
474 #endif // NDEBUG
475 
476 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
477   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
478   assert(!contains(New, this) &&
479          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
480   assert(New->getType() == getType() &&
481          "replaceAllUses of value with new value of different type!");
482 
483   // Notify all ValueHandles (if present) that this value is going away.
484   if (HasValueHandle)
485     ValueHandleBase::ValueIsRAUWd(this, New);
486   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
487     ValueAsMetadata::handleRAUW(this, New);
488 
489   while (!materialized_use_empty()) {
490     Use &U = *UseList;
491     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
492     // constant because they are uniqued.
493     if (auto *C = dyn_cast<Constant>(U.getUser())) {
494       if (!isa<GlobalValue>(C)) {
495         C->handleOperandChange(this, New);
496         continue;
497       }
498     }
499 
500     U.set(New);
501   }
502 
503   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
504     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
505 }
506 
507 void Value::replaceAllUsesWith(Value *New) {
508   doRAUW(New, ReplaceMetadataUses::Yes);
509 }
510 
511 void Value::replaceNonMetadataUsesWith(Value *New) {
512   doRAUW(New, ReplaceMetadataUses::No);
513 }
514 
515 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
516 // This routine leaves uses within BB.
517 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
518   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
519   assert(!contains(New, this) &&
520          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
521   assert(New->getType() == getType() &&
522          "replaceUses of value with new value of different type!");
523   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
524 
525   replaceUsesWithIf(New, [BB](Use &U) {
526     auto *I = dyn_cast<Instruction>(U.getUser());
527     // Don't replace if it's an instruction in the BB basic block.
528     return !I || I->getParent() != BB;
529   });
530 }
531 
532 namespace {
533 // Various metrics for how much to strip off of pointers.
534 enum PointerStripKind {
535   PSK_ZeroIndices,
536   PSK_ZeroIndicesAndAliases,
537   PSK_ZeroIndicesSameRepresentation,
538   PSK_ZeroIndicesAndInvariantGroups,
539   PSK_InBoundsConstantIndices,
540   PSK_InBounds
541 };
542 
543 template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
544 
545 template <PointerStripKind StripKind>
546 static const Value *stripPointerCastsAndOffsets(
547     const Value *V,
548     function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
549   if (!V->getType()->isPointerTy())
550     return V;
551 
552   // Even though we don't look through PHI nodes, we could be called on an
553   // instruction in an unreachable block, which may be on a cycle.
554   SmallPtrSet<const Value *, 4> Visited;
555 
556   Visited.insert(V);
557   do {
558     Func(V);
559     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
560       switch (StripKind) {
561       case PSK_ZeroIndices:
562       case PSK_ZeroIndicesAndAliases:
563       case PSK_ZeroIndicesSameRepresentation:
564       case PSK_ZeroIndicesAndInvariantGroups:
565         if (!GEP->hasAllZeroIndices())
566           return V;
567         break;
568       case PSK_InBoundsConstantIndices:
569         if (!GEP->hasAllConstantIndices())
570           return V;
571         LLVM_FALLTHROUGH;
572       case PSK_InBounds:
573         if (!GEP->isInBounds())
574           return V;
575         break;
576       }
577       V = GEP->getPointerOperand();
578     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
579       V = cast<Operator>(V)->getOperand(0);
580       if (!V->getType()->isPointerTy())
581         return V;
582     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
583                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
584       // TODO: If we know an address space cast will not change the
585       //       representation we could look through it here as well.
586       V = cast<Operator>(V)->getOperand(0);
587     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
588       V = cast<GlobalAlias>(V)->getAliasee();
589     } else {
590       if (const auto *Call = dyn_cast<CallBase>(V)) {
591         if (const Value *RV = Call->getReturnedArgOperand()) {
592           V = RV;
593           continue;
594         }
595         // The result of launder.invariant.group must alias it's argument,
596         // but it can't be marked with returned attribute, that's why it needs
597         // special case.
598         if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
599             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
600              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
601           V = Call->getArgOperand(0);
602           continue;
603         }
604       }
605       return V;
606     }
607     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
608   } while (Visited.insert(V).second);
609 
610   return V;
611 }
612 } // end anonymous namespace
613 
614 const Value *Value::stripPointerCasts() const {
615   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
616 }
617 
618 const Value *Value::stripPointerCastsAndAliases() const {
619   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
620 }
621 
622 const Value *Value::stripPointerCastsSameRepresentation() const {
623   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
624 }
625 
626 const Value *Value::stripInBoundsConstantOffsets() const {
627   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
628 }
629 
630 const Value *Value::stripPointerCastsAndInvariantGroups() const {
631   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
632 }
633 
634 const Value *Value::stripAndAccumulateConstantOffsets(
635     const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
636     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
637   if (!getType()->isPtrOrPtrVectorTy())
638     return this;
639 
640   unsigned BitWidth = Offset.getBitWidth();
641   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
642          "The offset bit width does not match the DL specification.");
643 
644   // Even though we don't look through PHI nodes, we could be called on an
645   // instruction in an unreachable block, which may be on a cycle.
646   SmallPtrSet<const Value *, 4> Visited;
647   Visited.insert(this);
648   const Value *V = this;
649   do {
650     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
651       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
652       if (!AllowNonInbounds && !GEP->isInBounds())
653         return V;
654 
655       // If one of the values we have visited is an addrspacecast, then
656       // the pointer type of this GEP may be different from the type
657       // of the Ptr parameter which was passed to this function.  This
658       // means when we construct GEPOffset, we need to use the size
659       // of GEP's pointer type rather than the size of the original
660       // pointer type.
661       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
662       if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
663         return V;
664 
665       // Stop traversal if the pointer offset wouldn't fit in the bit-width
666       // provided by the Offset argument. This can happen due to AddrSpaceCast
667       // stripping.
668       if (GEPOffset.getMinSignedBits() > BitWidth)
669         return V;
670 
671       // External Analysis can return a result higher/lower than the value
672       // represents. We need to detect overflow/underflow.
673       APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
674       if (!ExternalAnalysis) {
675         Offset += GEPOffsetST;
676       } else {
677         bool Overflow = false;
678         APInt OldOffset = Offset;
679         Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
680         if (Overflow) {
681           Offset = OldOffset;
682           return V;
683         }
684       }
685       V = GEP->getPointerOperand();
686     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
687                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
688       V = cast<Operator>(V)->getOperand(0);
689     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
690       if (!GA->isInterposable())
691         V = GA->getAliasee();
692     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
693         if (const Value *RV = Call->getReturnedArgOperand())
694           V = RV;
695     }
696     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
697   } while (Visited.insert(V).second);
698 
699   return V;
700 }
701 
702 const Value *
703 Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
704   return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
705 }
706 
707 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
708                                                bool &CanBeNull) const {
709   assert(getType()->isPointerTy() && "must be pointer");
710 
711   uint64_t DerefBytes = 0;
712   CanBeNull = false;
713   if (const Argument *A = dyn_cast<Argument>(this)) {
714     DerefBytes = A->getDereferenceableBytes();
715     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
716       Type *PT = cast<PointerType>(A->getType())->getElementType();
717       if (PT->isSized())
718         DerefBytes = DL.getTypeStoreSize(PT).getKnownMinSize();
719     }
720     if (DerefBytes == 0) {
721       DerefBytes = A->getDereferenceableOrNullBytes();
722       CanBeNull = true;
723     }
724   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
725     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
726     if (DerefBytes == 0) {
727       DerefBytes =
728           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
729       CanBeNull = true;
730     }
731   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
732     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
733       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
734       DerefBytes = CI->getLimitedValue();
735     }
736     if (DerefBytes == 0) {
737       if (MDNode *MD =
738               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
739         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
740         DerefBytes = CI->getLimitedValue();
741       }
742       CanBeNull = true;
743     }
744   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
745     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
746       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
747       DerefBytes = CI->getLimitedValue();
748     }
749     if (DerefBytes == 0) {
750       if (MDNode *MD =
751               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
752         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
753         DerefBytes = CI->getLimitedValue();
754       }
755       CanBeNull = true;
756     }
757   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
758     if (!AI->isArrayAllocation()) {
759       DerefBytes =
760           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
761       CanBeNull = false;
762     }
763   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
764     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
765       // TODO: Don't outright reject hasExternalWeakLinkage but set the
766       // CanBeNull flag.
767       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
768       CanBeNull = false;
769     }
770   }
771   return DerefBytes;
772 }
773 
774 Align Value::getPointerAlignment(const DataLayout &DL) const {
775   assert(getType()->isPointerTy() && "must be pointer");
776   if (auto *GO = dyn_cast<GlobalObject>(this)) {
777     if (isa<Function>(GO)) {
778       Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
779       switch (DL.getFunctionPtrAlignType()) {
780       case DataLayout::FunctionPtrAlignType::Independent:
781         return FunctionPtrAlign;
782       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
783         return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
784       }
785       llvm_unreachable("Unhandled FunctionPtrAlignType");
786     }
787     const MaybeAlign Alignment(GO->getAlignment());
788     if (!Alignment) {
789       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
790         Type *ObjectType = GVar->getValueType();
791         if (ObjectType->isSized()) {
792           // If the object is defined in the current Module, we'll be giving
793           // it the preferred alignment. Otherwise, we have to assume that it
794           // may only have the minimum ABI alignment.
795           if (GVar->isStrongDefinitionForLinker())
796             return DL.getPreferredAlign(GVar);
797           else
798             return DL.getABITypeAlign(ObjectType);
799         }
800       }
801     }
802     return Alignment.valueOrOne();
803   } else if (const Argument *A = dyn_cast<Argument>(this)) {
804     const MaybeAlign Alignment = A->getParamAlign();
805     if (!Alignment && A->hasStructRetAttr()) {
806       // An sret parameter has at least the ABI alignment of the return type.
807       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
808       if (EltTy->isSized())
809         return DL.getABITypeAlign(EltTy);
810     }
811     return Alignment.valueOrOne();
812   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
813     return AI->getAlign();
814   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
815     MaybeAlign Alignment = Call->getRetAlign();
816     if (!Alignment && Call->getCalledFunction())
817       Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
818     return Alignment.valueOrOne();
819   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
820     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
821       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
822       return Align(CI->getLimitedValue());
823     }
824   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
825     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
826             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
827             /*OnlyIfReduced=*/true))) {
828       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
829       // While the actual alignment may be large, elsewhere we have
830       // an arbitrary upper alignmet limit, so let's clamp to it.
831       return Align(TrailingZeros < Value::MaxAlignmentExponent
832                        ? uint64_t(1) << TrailingZeros
833                        : Value::MaximumAlignment);
834     }
835   }
836   return Align(1);
837 }
838 
839 const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
840                                      const BasicBlock *PredBB) const {
841   auto *PN = dyn_cast<PHINode>(this);
842   if (PN && PN->getParent() == CurBB)
843     return PN->getIncomingValueForBlock(PredBB);
844   return this;
845 }
846 
847 LLVMContext &Value::getContext() const { return VTy->getContext(); }
848 
849 void Value::reverseUseList() {
850   if (!UseList || !UseList->Next)
851     // No need to reverse 0 or 1 uses.
852     return;
853 
854   Use *Head = UseList;
855   Use *Current = UseList->Next;
856   Head->Next = nullptr;
857   while (Current) {
858     Use *Next = Current->Next;
859     Current->Next = Head;
860     Head->Prev = &Current->Next;
861     Head = Current;
862     Current = Next;
863   }
864   UseList = Head;
865   Head->Prev = &UseList;
866 }
867 
868 bool Value::isSwiftError() const {
869   auto *Arg = dyn_cast<Argument>(this);
870   if (Arg)
871     return Arg->hasSwiftErrorAttr();
872   auto *Alloca = dyn_cast<AllocaInst>(this);
873   if (!Alloca)
874     return false;
875   return Alloca->isSwiftError();
876 }
877 
878 //===----------------------------------------------------------------------===//
879 //                             ValueHandleBase Class
880 //===----------------------------------------------------------------------===//
881 
882 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
883   assert(List && "Handle list is null?");
884 
885   // Splice ourselves into the list.
886   Next = *List;
887   *List = this;
888   setPrevPtr(List);
889   if (Next) {
890     Next->setPrevPtr(&Next);
891     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
892   }
893 }
894 
895 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
896   assert(List && "Must insert after existing node");
897 
898   Next = List->Next;
899   setPrevPtr(&List->Next);
900   List->Next = this;
901   if (Next)
902     Next->setPrevPtr(&Next);
903 }
904 
905 void ValueHandleBase::AddToUseList() {
906   assert(getValPtr() && "Null pointer doesn't have a use list!");
907 
908   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
909 
910   if (getValPtr()->HasValueHandle) {
911     // If this value already has a ValueHandle, then it must be in the
912     // ValueHandles map already.
913     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
914     assert(Entry && "Value doesn't have any handles?");
915     AddToExistingUseList(&Entry);
916     return;
917   }
918 
919   // Ok, it doesn't have any handles yet, so we must insert it into the
920   // DenseMap.  However, doing this insertion could cause the DenseMap to
921   // reallocate itself, which would invalidate all of the PrevP pointers that
922   // point into the old table.  Handle this by checking for reallocation and
923   // updating the stale pointers only if needed.
924   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
925   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
926 
927   ValueHandleBase *&Entry = Handles[getValPtr()];
928   assert(!Entry && "Value really did already have handles?");
929   AddToExistingUseList(&Entry);
930   getValPtr()->HasValueHandle = true;
931 
932   // If reallocation didn't happen or if this was the first insertion, don't
933   // walk the table.
934   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
935       Handles.size() == 1) {
936     return;
937   }
938 
939   // Okay, reallocation did happen.  Fix the Prev Pointers.
940   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
941        E = Handles.end(); I != E; ++I) {
942     assert(I->second && I->first == I->second->getValPtr() &&
943            "List invariant broken!");
944     I->second->setPrevPtr(&I->second);
945   }
946 }
947 
948 void ValueHandleBase::RemoveFromUseList() {
949   assert(getValPtr() && getValPtr()->HasValueHandle &&
950          "Pointer doesn't have a use list!");
951 
952   // Unlink this from its use list.
953   ValueHandleBase **PrevPtr = getPrevPtr();
954   assert(*PrevPtr == this && "List invariant broken");
955 
956   *PrevPtr = Next;
957   if (Next) {
958     assert(Next->getPrevPtr() == &Next && "List invariant broken");
959     Next->setPrevPtr(PrevPtr);
960     return;
961   }
962 
963   // If the Next pointer was null, then it is possible that this was the last
964   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
965   // map.
966   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
967   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
968   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
969     Handles.erase(getValPtr());
970     getValPtr()->HasValueHandle = false;
971   }
972 }
973 
974 void ValueHandleBase::ValueIsDeleted(Value *V) {
975   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
976 
977   // Get the linked list base, which is guaranteed to exist since the
978   // HasValueHandle flag is set.
979   LLVMContextImpl *pImpl = V->getContext().pImpl;
980   ValueHandleBase *Entry = pImpl->ValueHandles[V];
981   assert(Entry && "Value bit set but no entries exist");
982 
983   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
984   // and remove themselves from the list without breaking our iteration.  This
985   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
986   // Note that we deliberately do not the support the case when dropping a value
987   // handle results in a new value handle being permanently added to the list
988   // (as might occur in theory for CallbackVH's): the new value handle will not
989   // be processed and the checking code will mete out righteous punishment if
990   // the handle is still present once we have finished processing all the other
991   // value handles (it is fine to momentarily add then remove a value handle).
992   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
993     Iterator.RemoveFromUseList();
994     Iterator.AddToExistingUseListAfter(Entry);
995     assert(Entry->Next == &Iterator && "Loop invariant broken.");
996 
997     switch (Entry->getKind()) {
998     case Assert:
999       break;
1000     case Weak:
1001     case WeakTracking:
1002       // WeakTracking and Weak just go to null, which unlinks them
1003       // from the list.
1004       Entry->operator=(nullptr);
1005       break;
1006     case Callback:
1007       // Forward to the subclass's implementation.
1008       static_cast<CallbackVH*>(Entry)->deleted();
1009       break;
1010     }
1011   }
1012 
1013   // All callbacks, weak references, and assertingVHs should be dropped by now.
1014   if (V->HasValueHandle) {
1015 #ifndef NDEBUG      // Only in +Asserts mode...
1016     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1017            << "\n";
1018     if (pImpl->ValueHandles[V]->getKind() == Assert)
1019       llvm_unreachable("An asserting value handle still pointed to this"
1020                        " value!");
1021 
1022 #endif
1023     llvm_unreachable("All references to V were not removed?");
1024   }
1025 }
1026 
1027 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1028   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1029   assert(Old != New && "Changing value into itself!");
1030   assert(Old->getType() == New->getType() &&
1031          "replaceAllUses of value with new value of different type!");
1032 
1033   // Get the linked list base, which is guaranteed to exist since the
1034   // HasValueHandle flag is set.
1035   LLVMContextImpl *pImpl = Old->getContext().pImpl;
1036   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1037 
1038   assert(Entry && "Value bit set but no entries exist");
1039 
1040   // We use a local ValueHandleBase as an iterator so that
1041   // ValueHandles can add and remove themselves from the list without
1042   // breaking our iteration.  This is not really an AssertingVH; we
1043   // just have to give ValueHandleBase some kind.
1044   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1045     Iterator.RemoveFromUseList();
1046     Iterator.AddToExistingUseListAfter(Entry);
1047     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1048 
1049     switch (Entry->getKind()) {
1050     case Assert:
1051     case Weak:
1052       // Asserting and Weak handles do not follow RAUW implicitly.
1053       break;
1054     case WeakTracking:
1055       // Weak goes to the new value, which will unlink it from Old's list.
1056       Entry->operator=(New);
1057       break;
1058     case Callback:
1059       // Forward to the subclass's implementation.
1060       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1061       break;
1062     }
1063   }
1064 
1065 #ifndef NDEBUG
1066   // If any new weak value handles were added while processing the
1067   // list, then complain about it now.
1068   if (Old->HasValueHandle)
1069     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1070       switch (Entry->getKind()) {
1071       case WeakTracking:
1072         dbgs() << "After RAUW from " << *Old->getType() << " %"
1073                << Old->getName() << " to " << *New->getType() << " %"
1074                << New->getName() << "\n";
1075         llvm_unreachable(
1076             "A weak tracking value handle still pointed to the old value!\n");
1077       default:
1078         break;
1079       }
1080 #endif
1081 }
1082 
1083 // Pin the vtable to this file.
1084 void CallbackVH::anchor() {}
1085