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 "LLVMContextImpl.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InstrTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LeakDetector.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/ADT/DenseMap.h"
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 static inline Type *checkType(Type *Ty) {
39 assert(Ty && "Value defined with a null type: Error!");
40 return const_cast<Type*>(Ty);
43 Value::Value(Type *ty, unsigned scid)
44 : SubclassID(scid), HasValueHandle(0),
45 SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
47 // FIXME: Why isn't this in the subclass gunk??
48 if (isa<CallInst>(this) || isa<InvokeInst>(this))
49 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
50 "invalid CallInst type!");
51 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
52 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
53 "Cannot create non-first-class values except for constants!");
57 // Notify all ValueHandles (if present) that this value is going away.
59 ValueHandleBase::ValueIsDeleted(this);
61 #ifndef NDEBUG // Only in -g mode...
62 // Check to make sure that there are no uses of this value that are still
63 // around when the value is destroyed. If there are, then we have a dangling
64 // reference and something is wrong. This code is here to print out what is
65 // still being referenced. The value in question should be printed as
69 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
70 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
71 dbgs() << "Use still stuck around after Def is destroyed:"
75 assert(use_empty() && "Uses remain when a value is destroyed!");
77 // If this value is named, destroy the name. This should not be in a symtab
82 // There should be no uses of this object anymore, remove it.
83 LeakDetector::removeGarbageObject(this);
86 /// hasNUses - Return true if this Value has exactly N users.
88 bool Value::hasNUses(unsigned N) const {
89 const_use_iterator UI = use_begin(), E = use_end();
92 if (UI == E) return false; // Too few.
96 /// hasNUsesOrMore - Return true if this value has N users or more. This is
97 /// logically equivalent to getNumUses() >= N.
99 bool Value::hasNUsesOrMore(unsigned N) const {
100 const_use_iterator UI = use_begin(), E = use_end();
103 if (UI == E) return false; // Too few.
108 /// isUsedInBasicBlock - Return true if this value is used in the specified
110 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
111 for (const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
112 const Instruction *User = dyn_cast<Instruction>(*I);
113 if (User && User->getParent() == BB)
120 /// getNumUses - This method computes the number of uses of this Value. This
121 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
123 unsigned Value::getNumUses() const {
124 return (unsigned)std::distance(use_begin(), use_end());
127 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
129 if (Instruction *I = dyn_cast<Instruction>(V)) {
130 if (BasicBlock *P = I->getParent())
131 if (Function *PP = P->getParent())
132 ST = &PP->getValueSymbolTable();
133 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
134 if (Function *P = BB->getParent())
135 ST = &P->getValueSymbolTable();
136 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
137 if (Module *P = GV->getParent())
138 ST = &P->getValueSymbolTable();
139 } else if (Argument *A = dyn_cast<Argument>(V)) {
140 if (Function *P = A->getParent())
141 ST = &P->getValueSymbolTable();
142 } else if (isa<MDString>(V))
145 assert(isa<Constant>(V) && "Unknown value type!");
146 return true; // no name is setable for this.
151 StringRef Value::getName() const {
152 // Make sure the empty string is still a C string. For historical reasons,
153 // some clients want to call .data() on the result and expect it to be null
155 if (!Name) return StringRef("", 0);
156 return Name->getKey();
159 void Value::setName(const Twine &NewName) {
160 // Fast path for common IRBuilder case of setName("") when there is no name.
161 if (NewName.isTriviallyEmpty() && !hasName())
164 SmallString<256> NameData;
165 StringRef NameRef = NewName.toStringRef(NameData);
167 // Name isn't changing?
168 if (getName() == NameRef)
171 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
173 // Get the symbol table to update for this object.
174 ValueSymbolTable *ST;
175 if (getSymTab(this, ST))
176 return; // Cannot set a name on this value (e.g. constant).
178 if (!ST) { // No symbol table to update? Just do the change.
179 if (NameRef.empty()) {
180 // Free the name for this value.
189 // NOTE: Could optimize for the case the name is shrinking to not deallocate
192 // Create the new name.
193 Name = ValueName::Create(NameRef.begin(), NameRef.end());
194 Name->setValue(this);
198 // NOTE: Could optimize for the case the name is shrinking to not deallocate
202 ST->removeValueName(Name);
210 // Name is changing to something new.
211 Name = ST->createValueName(NameRef, this);
215 /// takeName - transfer the name from V to this value, setting V's name to
216 /// empty. It is an error to call V->takeName(V).
217 void Value::takeName(Value *V) {
218 ValueSymbolTable *ST = 0;
219 // If this value has a name, drop it.
221 // Get the symtab this is in.
222 if (getSymTab(this, ST)) {
223 // We can't set a name on this value, but we need to clear V's name if
225 if (V->hasName()) V->setName("");
226 return; // Cannot set a name on this value (e.g. constant).
231 ST->removeValueName(Name);
236 // Now we know that this has no name.
238 // If V has no name either, we're done.
239 if (!V->hasName()) return;
241 // Get this's symtab if we didn't before.
243 if (getSymTab(this, ST)) {
246 return; // Cannot set a name on this value (e.g. constant).
250 // Get V's ST, this should always succed, because V has a name.
251 ValueSymbolTable *VST;
252 bool Failure = getSymTab(V, VST);
253 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
255 // If these values are both in the same symtab, we can do this very fast.
256 // This works even if both values have no symtab yet.
261 Name->setValue(this);
265 // Otherwise, things are slightly more complex. Remove V's name from VST and
266 // then reinsert it into ST.
269 VST->removeValueName(V->Name);
272 Name->setValue(this);
275 ST->reinsertValue(this);
279 void Value::replaceAllUsesWith(Value *New) {
280 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
281 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
282 assert(New->getType() == getType() &&
283 "replaceAllUses of value with new value of different type!");
285 // Notify all ValueHandles (if present) that this value is going away.
287 ValueHandleBase::ValueIsRAUWd(this, New);
289 while (!use_empty()) {
291 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
292 // constant because they are uniqued.
293 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
294 if (!isa<GlobalValue>(C)) {
295 C->replaceUsesOfWithOnConstant(this, New, &U);
303 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
304 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
307 Value *Value::stripPointerCasts() {
308 if (!getType()->isPointerTy())
311 // Even though we don't look through PHI nodes, we could be called on an
312 // instruction in an unreachable block, which may be on a cycle.
313 SmallPtrSet<Value *, 4> Visited;
318 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
319 if (!GEP->hasAllZeroIndices())
321 V = GEP->getPointerOperand();
322 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
323 V = cast<Operator>(V)->getOperand(0);
324 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
325 if (GA->mayBeOverridden())
327 V = GA->getAliasee();
331 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
332 } while (Visited.insert(V));
337 /// isDereferenceablePointer - Test if this value is always a pointer to
338 /// allocated and suitably aligned memory for a simple load or store.
339 bool Value::isDereferenceablePointer() const {
340 // Note that it is not safe to speculate into a malloc'd region because
341 // malloc may return null.
342 // It's also not always safe to follow a bitcast, for example:
343 // bitcast i8* (alloca i8) to i32*
344 // would result in a 4-byte load from a 1-byte alloca. Some cases could
345 // be handled using TargetData to check sizes and alignments though.
347 // These are obviously ok.
348 if (isa<AllocaInst>(this)) return true;
350 // Global variables which can't collapse to null are ok.
351 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
352 return !GV->hasExternalWeakLinkage();
354 // byval arguments are ok.
355 if (const Argument *A = dyn_cast<Argument>(this))
356 return A->hasByValAttr();
358 // For GEPs, determine if the indexing lands within the allocated object.
359 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(this)) {
360 // Conservatively require that the base pointer be fully dereferenceable.
361 if (!GEP->getOperand(0)->isDereferenceablePointer())
363 // Check the indices.
364 gep_type_iterator GTI = gep_type_begin(GEP);
365 for (User::const_op_iterator I = GEP->op_begin()+1,
366 E = GEP->op_end(); I != E; ++I) {
369 // Struct indices can't be out of bounds.
370 if (isa<StructType>(Ty))
372 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
375 // Zero is always ok.
378 // Check to see that it's within the bounds of an array.
379 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
382 if (CI->getValue().getActiveBits() > 64)
384 if (CI->getZExtValue() >= ATy->getNumElements())
387 // Indices check out; this is dereferenceable.
391 // If we don't know, assume the worst.
395 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
396 /// return the value in the PHI node corresponding to PredBB. If not, return
397 /// ourself. This is useful if you want to know the value something has in a
398 /// predecessor block.
399 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
400 const BasicBlock *PredBB) {
401 PHINode *PN = dyn_cast<PHINode>(this);
402 if (PN && PN->getParent() == CurBB)
403 return PN->getIncomingValueForBlock(PredBB);
407 LLVMContext &Value::getContext() const { return VTy->getContext(); }
409 //===----------------------------------------------------------------------===//
410 // ValueHandleBase Class
411 //===----------------------------------------------------------------------===//
413 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
414 /// List is known to point into the existing use list.
415 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
416 assert(List && "Handle list is null?");
418 // Splice ourselves into the list.
423 Next->setPrevPtr(&Next);
424 assert(VP == Next->VP && "Added to wrong list?");
428 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
429 assert(List && "Must insert after existing node");
432 setPrevPtr(&List->Next);
435 Next->setPrevPtr(&Next);
438 /// AddToUseList - Add this ValueHandle to the use list for VP.
439 void ValueHandleBase::AddToUseList() {
440 assert(VP && "Null pointer doesn't have a use list!");
442 LLVMContextImpl *pImpl = VP->getContext().pImpl;
444 if (VP->HasValueHandle) {
445 // If this value already has a ValueHandle, then it must be in the
446 // ValueHandles map already.
447 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
448 assert(Entry != 0 && "Value doesn't have any handles?");
449 AddToExistingUseList(&Entry);
453 // Ok, it doesn't have any handles yet, so we must insert it into the
454 // DenseMap. However, doing this insertion could cause the DenseMap to
455 // reallocate itself, which would invalidate all of the PrevP pointers that
456 // point into the old table. Handle this by checking for reallocation and
457 // updating the stale pointers only if needed.
458 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
459 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
461 ValueHandleBase *&Entry = Handles[VP];
462 assert(Entry == 0 && "Value really did already have handles?");
463 AddToExistingUseList(&Entry);
464 VP->HasValueHandle = true;
466 // If reallocation didn't happen or if this was the first insertion, don't
468 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
469 Handles.size() == 1) {
473 // Okay, reallocation did happen. Fix the Prev Pointers.
474 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
475 E = Handles.end(); I != E; ++I) {
476 assert(I->second && I->first == I->second->VP && "List invariant broken!");
477 I->second->setPrevPtr(&I->second);
481 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
482 void ValueHandleBase::RemoveFromUseList() {
483 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
485 // Unlink this from its use list.
486 ValueHandleBase **PrevPtr = getPrevPtr();
487 assert(*PrevPtr == this && "List invariant broken");
491 assert(Next->getPrevPtr() == &Next && "List invariant broken");
492 Next->setPrevPtr(PrevPtr);
496 // If the Next pointer was null, then it is possible that this was the last
497 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
499 LLVMContextImpl *pImpl = VP->getContext().pImpl;
500 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
501 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
503 VP->HasValueHandle = false;
508 void ValueHandleBase::ValueIsDeleted(Value *V) {
509 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
511 // Get the linked list base, which is guaranteed to exist since the
512 // HasValueHandle flag is set.
513 LLVMContextImpl *pImpl = V->getContext().pImpl;
514 ValueHandleBase *Entry = pImpl->ValueHandles[V];
515 assert(Entry && "Value bit set but no entries exist");
517 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
518 // and remove themselves from the list without breaking our iteration. This
519 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
520 // Note that we deliberately do not the support the case when dropping a value
521 // handle results in a new value handle being permanently added to the list
522 // (as might occur in theory for CallbackVH's): the new value handle will not
523 // be processed and the checking code will mete out righteous punishment if
524 // the handle is still present once we have finished processing all the other
525 // value handles (it is fine to momentarily add then remove a value handle).
526 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
527 Iterator.RemoveFromUseList();
528 Iterator.AddToExistingUseListAfter(Entry);
529 assert(Entry->Next == &Iterator && "Loop invariant broken.");
531 switch (Entry->getKind()) {
535 // Mark that this value has been deleted by setting it to an invalid Value
537 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
540 // Weak just goes to null, which will unlink it from the list.
544 // Forward to the subclass's implementation.
545 static_cast<CallbackVH*>(Entry)->deleted();
550 // All callbacks, weak references, and assertingVHs should be dropped by now.
551 if (V->HasValueHandle) {
552 #ifndef NDEBUG // Only in +Asserts mode...
553 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
555 if (pImpl->ValueHandles[V]->getKind() == Assert)
556 llvm_unreachable("An asserting value handle still pointed to this"
560 llvm_unreachable("All references to V were not removed?");
565 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
566 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
567 assert(Old != New && "Changing value into itself!");
569 // Get the linked list base, which is guaranteed to exist since the
570 // HasValueHandle flag is set.
571 LLVMContextImpl *pImpl = Old->getContext().pImpl;
572 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
574 assert(Entry && "Value bit set but no entries exist");
576 // We use a local ValueHandleBase as an iterator so that
577 // ValueHandles can add and remove themselves from the list without
578 // breaking our iteration. This is not really an AssertingVH; we
579 // just have to give ValueHandleBase some kind.
580 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
581 Iterator.RemoveFromUseList();
582 Iterator.AddToExistingUseListAfter(Entry);
583 assert(Entry->Next == &Iterator && "Loop invariant broken.");
585 switch (Entry->getKind()) {
587 // Asserting handle does not follow RAUW implicitly.
590 // Tracking goes to new value like a WeakVH. Note that this may make it
591 // something incompatible with its templated type. We don't want to have a
592 // virtual (or inline) interface to handle this though, so instead we make
593 // the TrackingVH accessors guarantee that a client never sees this value.
597 // Weak goes to the new value, which will unlink it from Old's list.
598 Entry->operator=(New);
601 // Forward to the subclass's implementation.
602 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
608 // If any new tracking or weak value handles were added while processing the
609 // list, then complain about it now.
610 if (Old->HasValueHandle)
611 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
612 switch (Entry->getKind()) {
615 dbgs() << "After RAUW from " << *Old->getType() << " %"
616 << Old->getName() << " to " << *New->getType() << " %"
617 << New->getName() << "\n";
618 llvm_unreachable("A tracking or weak value handle still pointed to the"
626 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
628 CallbackVH::~CallbackVH() {}