1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Value, ValueHandle, and User classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Value.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GetElementPtrTypeIterator.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LeakDetector.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/IR/ValueSymbolTable.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 static inline Type *checkType(Type *Ty) {
40 assert(Ty && "Value defined with a null type: Error!");
44 Value::Value(Type *ty, unsigned scid)
45 : VTy(checkType(ty)), UseList(nullptr), Name(nullptr), SubclassID(scid),
46 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0) {
47 // FIXME: Why isn't this in the subclass gunk??
48 // Note, we cannot call isa<CallInst> before the CallInst has been
50 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
51 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
52 "invalid CallInst type!");
53 else if (SubclassID != BasicBlockVal &&
54 (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
55 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
56 "Cannot create non-first-class values except for constants!");
60 // Notify all ValueHandles (if present) that this value is going away.
62 ValueHandleBase::ValueIsDeleted(this);
64 #ifndef NDEBUG // Only in -g mode...
65 // Check to make sure that there are no uses of this value that are still
66 // around when the value is destroyed. If there are, then we have a dangling
67 // reference and something is wrong. This code is here to print out what is
68 // still being referenced. The value in question should be printed as
72 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
73 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
74 dbgs() << "Use still stuck around after Def is destroyed:"
78 assert(use_empty() && "Uses remain when a value is destroyed!");
80 // If this value is named, destroy the name. This should not be in a symtab
82 if (Name && SubclassID != MDStringVal)
85 // There should be no uses of this object anymore, remove it.
86 LeakDetector::removeGarbageObject(this);
89 /// hasNUses - Return true if this Value has exactly N users.
91 bool Value::hasNUses(unsigned N) const {
92 const_use_iterator UI = use_begin(), E = use_end();
95 if (UI == E) return false; // Too few.
99 /// hasNUsesOrMore - Return true if this value has N users or more. This is
100 /// logically equivalent to getNumUses() >= N.
102 bool Value::hasNUsesOrMore(unsigned N) const {
103 const_use_iterator UI = use_begin(), E = use_end();
106 if (UI == E) return false; // Too few.
111 /// isUsedInBasicBlock - Return true if this value is used in the specified
113 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
114 // This can be computed either by scanning the instructions in BB, or by
115 // scanning the use list of this Value. Both lists can be very long, but
116 // usually one is quite short.
118 // Scan both lists simultaneously until one is exhausted. This limits the
119 // search to the shorter list.
120 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
121 const_user_iterator UI = user_begin(), UE = user_end();
122 for (; BI != BE && UI != UE; ++BI, ++UI) {
123 // Scan basic block: Check if this Value is used by the instruction at BI.
124 if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
126 // Scan use list: Check if the use at UI is in BB.
127 const Instruction *User = dyn_cast<Instruction>(*UI);
128 if (User && User->getParent() == BB)
135 /// getNumUses - This method computes the number of uses of this Value. This
136 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
138 unsigned Value::getNumUses() const {
139 return (unsigned)std::distance(use_begin(), use_end());
142 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
144 if (Instruction *I = dyn_cast<Instruction>(V)) {
145 if (BasicBlock *P = I->getParent())
146 if (Function *PP = P->getParent())
147 ST = &PP->getValueSymbolTable();
148 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
149 if (Function *P = BB->getParent())
150 ST = &P->getValueSymbolTable();
151 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
152 if (Module *P = GV->getParent())
153 ST = &P->getValueSymbolTable();
154 } else if (Argument *A = dyn_cast<Argument>(V)) {
155 if (Function *P = A->getParent())
156 ST = &P->getValueSymbolTable();
157 } else if (isa<MDString>(V))
160 assert(isa<Constant>(V) && "Unknown value type!");
161 return true; // no name is setable for this.
166 StringRef Value::getName() const {
167 // Make sure the empty string is still a C string. For historical reasons,
168 // some clients want to call .data() on the result and expect it to be null
170 if (!Name) return StringRef("", 0);
171 return Name->getKey();
174 void Value::setName(const Twine &NewName) {
175 assert(SubclassID != MDStringVal &&
176 "Cannot set the name of MDString with this method!");
178 // Fast path for common IRBuilder case of setName("") when there is no name.
179 if (NewName.isTriviallyEmpty() && !hasName())
182 SmallString<256> NameData;
183 StringRef NameRef = NewName.toStringRef(NameData);
184 assert(NameRef.find_first_of(0) == StringRef::npos &&
185 "Null bytes are not allowed in names");
187 // Name isn't changing?
188 if (getName() == NameRef)
191 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
193 // Get the symbol table to update for this object.
194 ValueSymbolTable *ST;
195 if (getSymTab(this, ST))
196 return; // Cannot set a name on this value (e.g. constant).
198 if (Function *F = dyn_cast<Function>(this))
199 getContext().pImpl->IntrinsicIDCache.erase(F);
201 if (!ST) { // No symbol table to update? Just do the change.
202 if (NameRef.empty()) {
203 // Free the name for this value.
212 // NOTE: Could optimize for the case the name is shrinking to not deallocate
215 // Create the new name.
216 Name = ValueName::Create(NameRef);
217 Name->setValue(this);
221 // NOTE: Could optimize for the case the name is shrinking to not deallocate
225 ST->removeValueName(Name);
233 // Name is changing to something new.
234 Name = ST->createValueName(NameRef, this);
238 /// takeName - transfer the name from V to this value, setting V's name to
239 /// empty. It is an error to call V->takeName(V).
240 void Value::takeName(Value *V) {
241 assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
243 ValueSymbolTable *ST = nullptr;
244 // If this value has a name, drop it.
246 // Get the symtab this is in.
247 if (getSymTab(this, ST)) {
248 // We can't set a name on this value, but we need to clear V's name if
250 if (V->hasName()) V->setName("");
251 return; // Cannot set a name on this value (e.g. constant).
256 ST->removeValueName(Name);
261 // Now we know that this has no name.
263 // If V has no name either, we're done.
264 if (!V->hasName()) return;
266 // Get this's symtab if we didn't before.
268 if (getSymTab(this, ST)) {
271 return; // Cannot set a name on this value (e.g. constant).
275 // Get V's ST, this should always succed, because V has a name.
276 ValueSymbolTable *VST;
277 bool Failure = getSymTab(V, VST);
278 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
280 // If these values are both in the same symtab, we can do this very fast.
281 // This works even if both values have no symtab yet.
286 Name->setValue(this);
290 // Otherwise, things are slightly more complex. Remove V's name from VST and
291 // then reinsert it into ST.
294 VST->removeValueName(V->Name);
297 Name->setValue(this);
300 ST->reinsertValue(this);
304 static bool contains(SmallPtrSet<ConstantExpr *, 4> &Cache, ConstantExpr *Expr,
306 if (!Cache.insert(Expr))
309 for (auto &O : Expr->operands()) {
312 auto *CE = dyn_cast<ConstantExpr>(O);
315 if (contains(Cache, CE, C))
321 static bool contains(Value *Expr, Value *V) {
325 auto *C = dyn_cast<Constant>(V);
329 auto *CE = dyn_cast<ConstantExpr>(Expr);
333 SmallPtrSet<ConstantExpr *, 4> Cache;
334 return contains(Cache, CE, C);
338 void Value::replaceAllUsesWith(Value *New) {
339 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
340 assert(!contains(New, this) &&
341 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
342 assert(New->getType() == getType() &&
343 "replaceAllUses of value with new value of different type!");
345 // Notify all ValueHandles (if present) that this value is going away.
347 ValueHandleBase::ValueIsRAUWd(this, New);
349 while (!use_empty()) {
351 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
352 // constant because they are uniqued.
353 if (auto *C = dyn_cast<Constant>(U.getUser())) {
354 if (!isa<GlobalValue>(C)) {
355 C->replaceUsesOfWithOnConstant(this, New, &U);
363 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
364 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
368 // Various metrics for how much to strip off of pointers.
369 enum PointerStripKind {
371 PSK_ZeroIndicesAndAliases,
372 PSK_InBoundsConstantIndices,
376 template <PointerStripKind StripKind>
377 static Value *stripPointerCastsAndOffsets(Value *V) {
378 if (!V->getType()->isPointerTy())
381 // Even though we don't look through PHI nodes, we could be called on an
382 // instruction in an unreachable block, which may be on a cycle.
383 SmallPtrSet<Value *, 4> Visited;
387 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
389 case PSK_ZeroIndicesAndAliases:
390 case PSK_ZeroIndices:
391 if (!GEP->hasAllZeroIndices())
394 case PSK_InBoundsConstantIndices:
395 if (!GEP->hasAllConstantIndices())
399 if (!GEP->isInBounds())
403 V = GEP->getPointerOperand();
404 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
405 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
406 V = cast<Operator>(V)->getOperand(0);
407 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
408 if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
410 V = GA->getAliasee();
414 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
415 } while (Visited.insert(V));
421 Value *Value::stripPointerCasts() {
422 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
425 Value *Value::stripPointerCastsNoFollowAliases() {
426 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
429 Value *Value::stripInBoundsConstantOffsets() {
430 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
433 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
435 if (!getType()->isPointerTy())
438 assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
439 getType())->getAddressSpace()) &&
440 "The offset must have exactly as many bits as our pointer.");
442 // Even though we don't look through PHI nodes, we could be called on an
443 // instruction in an unreachable block, which may be on a cycle.
444 SmallPtrSet<Value *, 4> Visited;
445 Visited.insert(this);
448 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
449 if (!GEP->isInBounds())
451 APInt GEPOffset(Offset);
452 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
455 V = GEP->getPointerOperand();
456 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
457 V = cast<Operator>(V)->getOperand(0);
458 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
459 V = GA->getAliasee();
463 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
464 } while (Visited.insert(V));
469 Value *Value::stripInBoundsOffsets() {
470 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
473 /// isDereferenceablePointer - Test if this value is always a pointer to
474 /// allocated and suitably aligned memory for a simple load or store.
475 static bool isDereferenceablePointer(const Value *V,
476 SmallPtrSet<const Value *, 32> &Visited) {
477 // Note that it is not safe to speculate into a malloc'd region because
478 // malloc may return null.
479 // It's also not always safe to follow a bitcast, for example:
480 // bitcast i8* (alloca i8) to i32*
481 // would result in a 4-byte load from a 1-byte alloca. Some cases could
482 // be handled using DataLayout to check sizes and alignments though.
484 // These are obviously ok.
485 if (isa<AllocaInst>(V)) return true;
487 // Global variables which can't collapse to null are ok.
488 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
489 return !GV->hasExternalWeakLinkage();
491 // byval arguments are ok.
492 if (const Argument *A = dyn_cast<Argument>(V))
493 return A->hasByValAttr();
495 // For GEPs, determine if the indexing lands within the allocated object.
496 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
497 // Conservatively require that the base pointer be fully dereferenceable.
498 if (!Visited.insert(GEP->getOperand(0)))
500 if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
502 // Check the indices.
503 gep_type_iterator GTI = gep_type_begin(GEP);
504 for (User::const_op_iterator I = GEP->op_begin()+1,
505 E = GEP->op_end(); I != E; ++I) {
508 // Struct indices can't be out of bounds.
509 if (isa<StructType>(Ty))
511 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
514 // Zero is always ok.
517 // Check to see that it's within the bounds of an array.
518 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
521 if (CI->getValue().getActiveBits() > 64)
523 if (CI->getZExtValue() >= ATy->getNumElements())
526 // Indices check out; this is dereferenceable.
530 // If we don't know, assume the worst.
534 /// isDereferenceablePointer - Test if this value is always a pointer to
535 /// allocated and suitably aligned memory for a simple load or store.
536 bool Value::isDereferenceablePointer() const {
537 SmallPtrSet<const Value *, 32> Visited;
538 return ::isDereferenceablePointer(this, Visited);
541 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
542 /// return the value in the PHI node corresponding to PredBB. If not, return
543 /// ourself. This is useful if you want to know the value something has in a
544 /// predecessor block.
545 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
546 const BasicBlock *PredBB) {
547 PHINode *PN = dyn_cast<PHINode>(this);
548 if (PN && PN->getParent() == CurBB)
549 return PN->getIncomingValueForBlock(PredBB);
553 LLVMContext &Value::getContext() const { return VTy->getContext(); }
555 //===----------------------------------------------------------------------===//
556 // ValueHandleBase Class
557 //===----------------------------------------------------------------------===//
559 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
560 /// List is known to point into the existing use list.
561 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
562 assert(List && "Handle list is null?");
564 // Splice ourselves into the list.
569 Next->setPrevPtr(&Next);
570 assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
574 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
575 assert(List && "Must insert after existing node");
578 setPrevPtr(&List->Next);
581 Next->setPrevPtr(&Next);
584 /// AddToUseList - Add this ValueHandle to the use list for VP.
585 void ValueHandleBase::AddToUseList() {
586 assert(VP.getPointer() && "Null pointer doesn't have a use list!");
588 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
590 if (VP.getPointer()->HasValueHandle) {
591 // If this value already has a ValueHandle, then it must be in the
592 // ValueHandles map already.
593 ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
594 assert(Entry && "Value doesn't have any handles?");
595 AddToExistingUseList(&Entry);
599 // Ok, it doesn't have any handles yet, so we must insert it into the
600 // DenseMap. However, doing this insertion could cause the DenseMap to
601 // reallocate itself, which would invalidate all of the PrevP pointers that
602 // point into the old table. Handle this by checking for reallocation and
603 // updating the stale pointers only if needed.
604 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
605 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
607 ValueHandleBase *&Entry = Handles[VP.getPointer()];
608 assert(!Entry && "Value really did already have handles?");
609 AddToExistingUseList(&Entry);
610 VP.getPointer()->HasValueHandle = true;
612 // If reallocation didn't happen or if this was the first insertion, don't
614 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
615 Handles.size() == 1) {
619 // Okay, reallocation did happen. Fix the Prev Pointers.
620 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
621 E = Handles.end(); I != E; ++I) {
622 assert(I->second && I->first == I->second->VP.getPointer() &&
623 "List invariant broken!");
624 I->second->setPrevPtr(&I->second);
628 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
629 void ValueHandleBase::RemoveFromUseList() {
630 assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
631 "Pointer doesn't have a use list!");
633 // Unlink this from its use list.
634 ValueHandleBase **PrevPtr = getPrevPtr();
635 assert(*PrevPtr == this && "List invariant broken");
639 assert(Next->getPrevPtr() == &Next && "List invariant broken");
640 Next->setPrevPtr(PrevPtr);
644 // If the Next pointer was null, then it is possible that this was the last
645 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
647 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
648 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
649 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
650 Handles.erase(VP.getPointer());
651 VP.getPointer()->HasValueHandle = false;
656 void ValueHandleBase::ValueIsDeleted(Value *V) {
657 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
659 // Get the linked list base, which is guaranteed to exist since the
660 // HasValueHandle flag is set.
661 LLVMContextImpl *pImpl = V->getContext().pImpl;
662 ValueHandleBase *Entry = pImpl->ValueHandles[V];
663 assert(Entry && "Value bit set but no entries exist");
665 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
666 // and remove themselves from the list without breaking our iteration. This
667 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
668 // Note that we deliberately do not the support the case when dropping a value
669 // handle results in a new value handle being permanently added to the list
670 // (as might occur in theory for CallbackVH's): the new value handle will not
671 // be processed and the checking code will mete out righteous punishment if
672 // the handle is still present once we have finished processing all the other
673 // value handles (it is fine to momentarily add then remove a value handle).
674 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
675 Iterator.RemoveFromUseList();
676 Iterator.AddToExistingUseListAfter(Entry);
677 assert(Entry->Next == &Iterator && "Loop invariant broken.");
679 switch (Entry->getKind()) {
683 // Mark that this value has been deleted by setting it to an invalid Value
685 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
688 // Weak just goes to null, which will unlink it from the list.
689 Entry->operator=(nullptr);
692 // Forward to the subclass's implementation.
693 static_cast<CallbackVH*>(Entry)->deleted();
698 // All callbacks, weak references, and assertingVHs should be dropped by now.
699 if (V->HasValueHandle) {
700 #ifndef NDEBUG // Only in +Asserts mode...
701 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
703 if (pImpl->ValueHandles[V]->getKind() == Assert)
704 llvm_unreachable("An asserting value handle still pointed to this"
708 llvm_unreachable("All references to V were not removed?");
713 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
714 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
715 assert(Old != New && "Changing value into itself!");
717 // Get the linked list base, which is guaranteed to exist since the
718 // HasValueHandle flag is set.
719 LLVMContextImpl *pImpl = Old->getContext().pImpl;
720 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
722 assert(Entry && "Value bit set but no entries exist");
724 // We use a local ValueHandleBase as an iterator so that
725 // ValueHandles can add and remove themselves from the list without
726 // breaking our iteration. This is not really an AssertingVH; we
727 // just have to give ValueHandleBase some kind.
728 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
729 Iterator.RemoveFromUseList();
730 Iterator.AddToExistingUseListAfter(Entry);
731 assert(Entry->Next == &Iterator && "Loop invariant broken.");
733 switch (Entry->getKind()) {
735 // Asserting handle does not follow RAUW implicitly.
738 // Tracking goes to new value like a WeakVH. Note that this may make it
739 // something incompatible with its templated type. We don't want to have a
740 // virtual (or inline) interface to handle this though, so instead we make
741 // the TrackingVH accessors guarantee that a client never sees this value.
745 // Weak goes to the new value, which will unlink it from Old's list.
746 Entry->operator=(New);
749 // Forward to the subclass's implementation.
750 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
756 // If any new tracking or weak value handles were added while processing the
757 // list, then complain about it now.
758 if (Old->HasValueHandle)
759 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
760 switch (Entry->getKind()) {
763 dbgs() << "After RAUW from " << *Old->getType() << " %"
764 << Old->getName() << " to " << *New->getType() << " %"
765 << New->getName() << "\n";
766 llvm_unreachable("A tracking or weak value handle still pointed to the"
774 // Pin the vtable to this file.
775 void CallbackVH::anchor() {}