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