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