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!");
41 return const_cast<Type*>(Ty);
44 Value::Value(Type *ty, unsigned scid)
45 : SubclassID(scid), HasValueHandle(0),
46 SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
47 UseList(nullptr), Name(nullptr) {
48 // FIXME: Why isn't this in the subclass gunk??
49 // Note, we cannot call isa<CallInst> before the CallInst has been
51 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
52 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
53 "invalid CallInst type!");
54 else if (SubclassID != BasicBlockVal &&
55 (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
56 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
57 "Cannot create non-first-class values except for constants!");
61 // Notify all ValueHandles (if present) that this value is going away.
63 ValueHandleBase::ValueIsDeleted(this);
65 #ifndef NDEBUG // Only in -g mode...
66 // Check to make sure that there are no uses of this value that are still
67 // around when the value is destroyed. If there are, then we have a dangling
68 // reference and something is wrong. This code is here to print out what is
69 // still being referenced. The value in question should be printed as
73 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
74 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
75 dbgs() << "Use still stuck around after Def is destroyed:"
79 assert(use_empty() && "Uses remain when a value is destroyed!");
81 // If this value is named, destroy the name. This should not be in a symtab
83 if (Name && SubclassID != MDStringVal)
86 // There should be no uses of this object anymore, remove it.
87 LeakDetector::removeGarbageObject(this);
90 /// hasNUses - Return true if this Value has exactly N users.
92 bool Value::hasNUses(unsigned N) const {
93 const_use_iterator UI = use_begin(), E = use_end();
96 if (UI == E) return false; // Too few.
100 /// hasNUsesOrMore - Return true if this value has N users or more. This is
101 /// logically equivalent to getNumUses() >= N.
103 bool Value::hasNUsesOrMore(unsigned N) const {
104 const_use_iterator UI = use_begin(), E = use_end();
107 if (UI == E) return false; // Too few.
112 /// isUsedInBasicBlock - Return true if this value is used in the specified
114 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
115 // This can be computed either by scanning the instructions in BB, or by
116 // scanning the use list of this Value. Both lists can be very long, but
117 // usually one is quite short.
119 // Scan both lists simultaneously until one is exhausted. This limits the
120 // search to the shorter list.
121 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
122 const_user_iterator UI = user_begin(), UE = user_end();
123 for (; BI != BE && UI != UE; ++BI, ++UI) {
124 // Scan basic block: Check if this Value is used by the instruction at BI.
125 if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
127 // Scan use list: Check if the use at UI is in BB.
128 const Instruction *User = dyn_cast<Instruction>(*UI);
129 if (User && User->getParent() == BB)
136 /// getNumUses - This method computes the number of uses of this Value. This
137 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
139 unsigned Value::getNumUses() const {
140 return (unsigned)std::distance(use_begin(), use_end());
143 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
145 if (Instruction *I = dyn_cast<Instruction>(V)) {
146 if (BasicBlock *P = I->getParent())
147 if (Function *PP = P->getParent())
148 ST = &PP->getValueSymbolTable();
149 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
150 if (Function *P = BB->getParent())
151 ST = &P->getValueSymbolTable();
152 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153 if (Module *P = GV->getParent())
154 ST = &P->getValueSymbolTable();
155 } else if (Argument *A = dyn_cast<Argument>(V)) {
156 if (Function *P = A->getParent())
157 ST = &P->getValueSymbolTable();
158 } else if (isa<MDString>(V))
161 assert(isa<Constant>(V) && "Unknown value type!");
162 return true; // no name is setable for this.
167 StringRef Value::getName() const {
168 // Make sure the empty string is still a C string. For historical reasons,
169 // some clients want to call .data() on the result and expect it to be null
171 if (!Name) return StringRef("", 0);
172 return Name->getKey();
175 void Value::setName(const Twine &NewName) {
176 assert(SubclassID != MDStringVal &&
177 "Cannot set the name of MDString with this method!");
179 // Fast path for common IRBuilder case of setName("") when there is no name.
180 if (NewName.isTriviallyEmpty() && !hasName())
183 SmallString<256> NameData;
184 StringRef NameRef = NewName.toStringRef(NameData);
185 assert(NameRef.find_first_of(0) == StringRef::npos &&
186 "Null bytes are not allowed in names");
188 // Name isn't changing?
189 if (getName() == NameRef)
192 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
194 // Get the symbol table to update for this object.
195 ValueSymbolTable *ST;
196 if (getSymTab(this, ST))
197 return; // Cannot set a name on this value (e.g. constant).
199 if (Function *F = dyn_cast<Function>(this))
200 getContext().pImpl->IntrinsicIDCache.erase(F);
202 if (!ST) { // No symbol table to update? Just do the change.
203 if (NameRef.empty()) {
204 // Free the name for this value.
213 // NOTE: Could optimize for the case the name is shrinking to not deallocate
216 // Create the new name.
217 Name = ValueName::Create(NameRef.begin(), NameRef.end());
218 Name->setValue(this);
222 // NOTE: Could optimize for the case the name is shrinking to not deallocate
226 ST->removeValueName(Name);
234 // Name is changing to something new.
235 Name = ST->createValueName(NameRef, this);
239 /// takeName - transfer the name from V to this value, setting V's name to
240 /// empty. It is an error to call V->takeName(V).
241 void Value::takeName(Value *V) {
242 assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
244 ValueSymbolTable *ST = nullptr;
245 // If this value has a name, drop it.
247 // Get the symtab this is in.
248 if (getSymTab(this, ST)) {
249 // We can't set a name on this value, but we need to clear V's name if
251 if (V->hasName()) V->setName("");
252 return; // Cannot set a name on this value (e.g. constant).
257 ST->removeValueName(Name);
262 // Now we know that this has no name.
264 // If V has no name either, we're done.
265 if (!V->hasName()) return;
267 // Get this's symtab if we didn't before.
269 if (getSymTab(this, ST)) {
272 return; // Cannot set a name on this value (e.g. constant).
276 // Get V's ST, this should always succed, because V has a name.
277 ValueSymbolTable *VST;
278 bool Failure = getSymTab(V, VST);
279 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
281 // If these values are both in the same symtab, we can do this very fast.
282 // This works even if both values have no symtab yet.
287 Name->setValue(this);
291 // Otherwise, things are slightly more complex. Remove V's name from VST and
292 // then reinsert it into ST.
295 VST->removeValueName(V->Name);
298 Name->setValue(this);
301 ST->reinsertValue(this);
305 static bool contains(SmallPtrSet<ConstantExpr *, 4> &Cache, ConstantExpr *Expr,
307 if (!Cache.insert(Expr))
310 for (auto &O : Expr->operands()) {
313 auto *CE = dyn_cast<ConstantExpr>(O);
316 if (contains(Cache, CE, C))
322 static bool contains(Value *Expr, Value *V) {
326 auto *C = dyn_cast<Constant>(V);
330 auto *CE = dyn_cast<ConstantExpr>(Expr);
334 SmallPtrSet<ConstantExpr *, 4> Cache;
335 return contains(Cache, CE, C);
339 void Value::replaceAllUsesWith(Value *New) {
340 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
341 assert(!contains(New, this) &&
342 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
343 assert(New->getType() == getType() &&
344 "replaceAllUses of value with new value of different type!");
346 // Notify all ValueHandles (if present) that this value is going away.
348 ValueHandleBase::ValueIsRAUWd(this, New);
350 while (!use_empty()) {
352 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
353 // constant because they are uniqued.
354 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
355 if (!isa<GlobalValue>(C)) {
356 C->replaceUsesOfWithOnConstant(this, New, &U);
364 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
365 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
369 // Various metrics for how much to strip off of pointers.
370 enum PointerStripKind {
372 PSK_ZeroIndicesAndAliases,
373 PSK_InBoundsConstantIndices,
377 template <PointerStripKind StripKind>
378 static Value *stripPointerCastsAndOffsets(Value *V) {
379 if (!V->getType()->isPointerTy())
382 // Even though we don't look through PHI nodes, we could be called on an
383 // instruction in an unreachable block, which may be on a cycle.
384 SmallPtrSet<Value *, 4> Visited;
388 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
390 case PSK_ZeroIndicesAndAliases:
391 case PSK_ZeroIndices:
392 if (!GEP->hasAllZeroIndices())
395 case PSK_InBoundsConstantIndices:
396 if (!GEP->hasAllConstantIndices())
400 if (!GEP->isInBounds())
404 V = GEP->getPointerOperand();
405 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
406 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
407 V = cast<Operator>(V)->getOperand(0);
408 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
409 if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
411 V = GA->getAliasee();
415 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
416 } while (Visited.insert(V));
422 Value *Value::stripPointerCasts() {
423 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
426 Value *Value::stripPointerCastsNoFollowAliases() {
427 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
430 Value *Value::stripInBoundsConstantOffsets() {
431 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
434 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
436 if (!getType()->isPointerTy())
439 assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
440 getType())->getAddressSpace()) &&
441 "The offset must have exactly as many bits as our pointer.");
443 // Even though we don't look through PHI nodes, we could be called on an
444 // instruction in an unreachable block, which may be on a cycle.
445 SmallPtrSet<Value *, 4> Visited;
446 Visited.insert(this);
449 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
450 if (!GEP->isInBounds())
452 APInt GEPOffset(Offset);
453 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
456 V = GEP->getPointerOperand();
457 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
458 V = cast<Operator>(V)->getOperand(0);
459 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
460 V = GA->getAliasee();
464 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
465 } while (Visited.insert(V));
470 Value *Value::stripInBoundsOffsets() {
471 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
474 /// isDereferenceablePointer - Test if this value is always a pointer to
475 /// allocated and suitably aligned memory for a simple load or store.
476 static bool isDereferenceablePointer(const Value *V,
477 SmallPtrSet<const Value *, 32> &Visited) {
478 // Note that it is not safe to speculate into a malloc'd region because
479 // malloc may return null.
480 // It's also not always safe to follow a bitcast, for example:
481 // bitcast i8* (alloca i8) to i32*
482 // would result in a 4-byte load from a 1-byte alloca. Some cases could
483 // be handled using DataLayout to check sizes and alignments though.
485 // These are obviously ok.
486 if (isa<AllocaInst>(V)) return true;
488 // Global variables which can't collapse to null are ok.
489 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
490 return !GV->hasExternalWeakLinkage();
492 // byval arguments are ok.
493 if (const Argument *A = dyn_cast<Argument>(V))
494 return A->hasByValAttr();
496 // For GEPs, determine if the indexing lands within the allocated object.
497 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
498 // Conservatively require that the base pointer be fully dereferenceable.
499 if (!Visited.insert(GEP->getOperand(0)))
501 if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
503 // Check the indices.
504 gep_type_iterator GTI = gep_type_begin(GEP);
505 for (User::const_op_iterator I = GEP->op_begin()+1,
506 E = GEP->op_end(); I != E; ++I) {
509 // Struct indices can't be out of bounds.
510 if (isa<StructType>(Ty))
512 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
515 // Zero is always ok.
518 // Check to see that it's within the bounds of an array.
519 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
522 if (CI->getValue().getActiveBits() > 64)
524 if (CI->getZExtValue() >= ATy->getNumElements())
527 // Indices check out; this is dereferenceable.
531 // If we don't know, assume the worst.
535 /// isDereferenceablePointer - Test if this value is always a pointer to
536 /// allocated and suitably aligned memory for a simple load or store.
537 bool Value::isDereferenceablePointer() const {
538 SmallPtrSet<const Value *, 32> Visited;
539 return ::isDereferenceablePointer(this, Visited);
542 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
543 /// return the value in the PHI node corresponding to PredBB. If not, return
544 /// ourself. This is useful if you want to know the value something has in a
545 /// predecessor block.
546 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
547 const BasicBlock *PredBB) {
548 PHINode *PN = dyn_cast<PHINode>(this);
549 if (PN && PN->getParent() == CurBB)
550 return PN->getIncomingValueForBlock(PredBB);
554 LLVMContext &Value::getContext() const { return VTy->getContext(); }
556 //===----------------------------------------------------------------------===//
557 // ValueHandleBase Class
558 //===----------------------------------------------------------------------===//
560 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
561 /// List is known to point into the existing use list.
562 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
563 assert(List && "Handle list is null?");
565 // Splice ourselves into the list.
570 Next->setPrevPtr(&Next);
571 assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
575 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
576 assert(List && "Must insert after existing node");
579 setPrevPtr(&List->Next);
582 Next->setPrevPtr(&Next);
585 /// AddToUseList - Add this ValueHandle to the use list for VP.
586 void ValueHandleBase::AddToUseList() {
587 assert(VP.getPointer() && "Null pointer doesn't have a use list!");
589 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
591 if (VP.getPointer()->HasValueHandle) {
592 // If this value already has a ValueHandle, then it must be in the
593 // ValueHandles map already.
594 ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
595 assert(Entry && "Value doesn't have any handles?");
596 AddToExistingUseList(&Entry);
600 // Ok, it doesn't have any handles yet, so we must insert it into the
601 // DenseMap. However, doing this insertion could cause the DenseMap to
602 // reallocate itself, which would invalidate all of the PrevP pointers that
603 // point into the old table. Handle this by checking for reallocation and
604 // updating the stale pointers only if needed.
605 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
606 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
608 ValueHandleBase *&Entry = Handles[VP.getPointer()];
609 assert(!Entry && "Value really did already have handles?");
610 AddToExistingUseList(&Entry);
611 VP.getPointer()->HasValueHandle = true;
613 // If reallocation didn't happen or if this was the first insertion, don't
615 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
616 Handles.size() == 1) {
620 // Okay, reallocation did happen. Fix the Prev Pointers.
621 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
622 E = Handles.end(); I != E; ++I) {
623 assert(I->second && I->first == I->second->VP.getPointer() &&
624 "List invariant broken!");
625 I->second->setPrevPtr(&I->second);
629 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
630 void ValueHandleBase::RemoveFromUseList() {
631 assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
632 "Pointer doesn't have a use list!");
634 // Unlink this from its use list.
635 ValueHandleBase **PrevPtr = getPrevPtr();
636 assert(*PrevPtr == this && "List invariant broken");
640 assert(Next->getPrevPtr() == &Next && "List invariant broken");
641 Next->setPrevPtr(PrevPtr);
645 // If the Next pointer was null, then it is possible that this was the last
646 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
648 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
649 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
650 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
651 Handles.erase(VP.getPointer());
652 VP.getPointer()->HasValueHandle = false;
657 void ValueHandleBase::ValueIsDeleted(Value *V) {
658 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
660 // Get the linked list base, which is guaranteed to exist since the
661 // HasValueHandle flag is set.
662 LLVMContextImpl *pImpl = V->getContext().pImpl;
663 ValueHandleBase *Entry = pImpl->ValueHandles[V];
664 assert(Entry && "Value bit set but no entries exist");
666 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
667 // and remove themselves from the list without breaking our iteration. This
668 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
669 // Note that we deliberately do not the support the case when dropping a value
670 // handle results in a new value handle being permanently added to the list
671 // (as might occur in theory for CallbackVH's): the new value handle will not
672 // be processed and the checking code will mete out righteous punishment if
673 // the handle is still present once we have finished processing all the other
674 // value handles (it is fine to momentarily add then remove a value handle).
675 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
676 Iterator.RemoveFromUseList();
677 Iterator.AddToExistingUseListAfter(Entry);
678 assert(Entry->Next == &Iterator && "Loop invariant broken.");
680 switch (Entry->getKind()) {
684 // Mark that this value has been deleted by setting it to an invalid Value
686 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
689 // Weak just goes to null, which will unlink it from the list.
690 Entry->operator=(nullptr);
693 // Forward to the subclass's implementation.
694 static_cast<CallbackVH*>(Entry)->deleted();
699 // All callbacks, weak references, and assertingVHs should be dropped by now.
700 if (V->HasValueHandle) {
701 #ifndef NDEBUG // Only in +Asserts mode...
702 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
704 if (pImpl->ValueHandles[V]->getKind() == Assert)
705 llvm_unreachable("An asserting value handle still pointed to this"
709 llvm_unreachable("All references to V were not removed?");
714 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
715 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
716 assert(Old != New && "Changing value into itself!");
718 // Get the linked list base, which is guaranteed to exist since the
719 // HasValueHandle flag is set.
720 LLVMContextImpl *pImpl = Old->getContext().pImpl;
721 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
723 assert(Entry && "Value bit set but no entries exist");
725 // We use a local ValueHandleBase as an iterator so that
726 // ValueHandles can add and remove themselves from the list without
727 // breaking our iteration. This is not really an AssertingVH; we
728 // just have to give ValueHandleBase some kind.
729 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
730 Iterator.RemoveFromUseList();
731 Iterator.AddToExistingUseListAfter(Entry);
732 assert(Entry->Next == &Iterator && "Loop invariant broken.");
734 switch (Entry->getKind()) {
736 // Asserting handle does not follow RAUW implicitly.
739 // Tracking goes to new value like a WeakVH. Note that this may make it
740 // something incompatible with its templated type. We don't want to have a
741 // virtual (or inline) interface to handle this though, so instead we make
742 // the TrackingVH accessors guarantee that a client never sees this value.
746 // Weak goes to the new value, which will unlink it from Old's list.
747 Entry->operator=(New);
750 // Forward to the subclass's implementation.
751 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
757 // If any new tracking or weak value handles were added while processing the
758 // list, then complain about it now.
759 if (Old->HasValueHandle)
760 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
761 switch (Entry->getKind()) {
764 dbgs() << "After RAUW from " << *Old->getType() << " %"
765 << Old->getName() << " to " << *New->getType() << " %"
766 << New->getName() << "\n";
767 llvm_unreachable("A tracking or weak value handle still pointed to the"
775 // Pin the vtable to this file.
776 void CallbackVH::anchor() {}