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/Metadata.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/Debug.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 const Type *checkType(const Type *Ty) {
39 assert(Ty && "Value defined with a null type: Error!");
43 Value::Value(const Type *ty, unsigned scid)
44 : SubclassID(scid), HasValueHandle(0),
45 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
47 if (isa<CallInst>(this) || isa<InvokeInst>(this))
48 assert((VTy->isFirstClassType() ||
49 VTy == Type::getVoidTy(ty->getContext()) ||
50 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
51 "invalid CallInst type!");
52 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
53 assert((VTy->isFirstClassType() ||
54 VTy == Type::getVoidTy(ty->getContext()) ||
55 isa<OpaqueType>(ty)) &&
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 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
73 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
74 errs() << "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
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 use_const_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 use_const_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 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
115 const Instruction *User = dyn_cast<Instruction>(*I);
116 if (User && User->getParent() == BB)
123 /// getNumUses - This method computes the number of uses of this Value. This
124 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
126 unsigned Value::getNumUses() const {
127 return (unsigned)std::distance(use_begin(), use_end());
130 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
132 if (Instruction *I = dyn_cast<Instruction>(V)) {
133 if (BasicBlock *P = I->getParent())
134 if (Function *PP = P->getParent())
135 ST = &PP->getValueSymbolTable();
136 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
137 if (Function *P = BB->getParent())
138 ST = &P->getValueSymbolTable();
139 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
140 if (Module *P = GV->getParent())
141 ST = &P->getValueSymbolTable();
142 } else if (Argument *A = dyn_cast<Argument>(V)) {
143 if (Function *P = A->getParent())
144 ST = &P->getValueSymbolTable();
145 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
146 if (Module *P = N->getParent()) {
147 ST = &P->getValueSymbolTable();
149 } else if (isa<MDString>(V))
152 assert(isa<Constant>(V) && "Unknown value type!");
153 return true; // no name is setable for this.
158 StringRef Value::getName() const {
159 // Make sure the empty string is still a C string. For historical reasons,
160 // some clients want to call .data() on the result and expect it to be null
162 if (!Name) return StringRef("", 0);
163 return Name->getKey();
166 std::string Value::getNameStr() const {
167 return getName().str();
170 void Value::setName(const Twine &NewName) {
171 // Fast path for common IRBuilder case of setName("") when there is no name.
172 if (NewName.isTriviallyEmpty() && !hasName())
175 SmallString<256> NameData;
176 NewName.toVector(NameData);
178 const char *NameStr = NameData.data();
179 unsigned NameLen = NameData.size();
181 // Name isn't changing?
182 if (getName() == StringRef(NameStr, NameLen))
185 assert(getType() != Type::getVoidTy(getContext()) &&
186 "Cannot assign a name to void values!");
188 // Get the symbol table to update for this object.
189 ValueSymbolTable *ST;
190 if (getSymTab(this, ST))
191 return; // Cannot set a name on this value (e.g. constant).
193 if (!ST) { // No symbol table to update? Just do the change.
195 // Free the name for this value.
204 // NOTE: Could optimize for the case the name is shrinking to not deallocate
207 // Create the new name.
208 Name = ValueName::Create(NameStr, NameStr+NameLen);
209 Name->setValue(this);
213 // NOTE: Could optimize for the case the name is shrinking to not deallocate
217 ST->removeValueName(Name);
225 // Name is changing to something new.
226 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
230 /// takeName - transfer the name from V to this value, setting V's name to
231 /// empty. It is an error to call V->takeName(V).
232 void Value::takeName(Value *V) {
233 ValueSymbolTable *ST = 0;
234 // If this value has a name, drop it.
236 // Get the symtab this is in.
237 if (getSymTab(this, ST)) {
238 // We can't set a name on this value, but we need to clear V's name if
240 if (V->hasName()) V->setName("");
241 return; // Cannot set a name on this value (e.g. constant).
246 ST->removeValueName(Name);
251 // Now we know that this has no name.
253 // If V has no name either, we're done.
254 if (!V->hasName()) return;
256 // Get this's symtab if we didn't before.
258 if (getSymTab(this, ST)) {
261 return; // Cannot set a name on this value (e.g. constant).
265 // Get V's ST, this should always succed, because V has a name.
266 ValueSymbolTable *VST;
267 bool Failure = getSymTab(V, VST);
268 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
270 // If these values are both in the same symtab, we can do this very fast.
271 // This works even if both values have no symtab yet.
276 Name->setValue(this);
280 // Otherwise, things are slightly more complex. Remove V's name from VST and
281 // then reinsert it into ST.
284 VST->removeValueName(V->Name);
287 Name->setValue(this);
290 ST->reinsertValue(this);
294 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
295 // except that it doesn't have all of the asserts. The asserts fail because we
296 // are half-way done resolving types, which causes some types to exist as two
297 // different Type*'s at the same time. This is a sledgehammer to work around
300 void Value::uncheckedReplaceAllUsesWith(Value *New) {
301 // Notify all ValueHandles (if present) that this value is going away.
303 ValueHandleBase::ValueIsRAUWd(this, New);
305 // FIXME: It doesn't make sense at all for metadata to follow RAUW.
306 if (Instruction *I = dyn_cast<Instruction>(this))
307 if (I->hasMetadata()) {
308 LLVMContext &Context = getContext();
309 // FIXME: NUKE ValueIsRAUWd??
310 Context.pImpl->TheMetadata.ValueIsRAUWd(this, New);
313 while (!use_empty()) {
315 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
316 // constant because they are uniqued.
317 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
318 if (!isa<GlobalValue>(C)) {
319 C->replaceUsesOfWithOnConstant(this, New, &U);
328 void Value::replaceAllUsesWith(Value *New) {
329 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
330 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
331 assert(New->getType() == getType() &&
332 "replaceAllUses of value with new value of different type!");
334 uncheckedReplaceAllUsesWith(New);
337 Value *Value::stripPointerCasts() {
338 if (!isa<PointerType>(getType()))
342 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
343 if (!GEP->hasAllZeroIndices())
345 V = GEP->getPointerOperand();
346 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
347 V = cast<Operator>(V)->getOperand(0);
348 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
349 if (GA->mayBeOverridden())
351 V = GA->getAliasee();
355 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
359 Value *Value::getUnderlyingObject() {
360 if (!isa<PointerType>(getType()))
363 unsigned MaxLookup = 6;
365 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
366 V = GEP->getPointerOperand();
367 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
368 V = cast<Operator>(V)->getOperand(0);
369 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
370 if (GA->mayBeOverridden())
372 V = GA->getAliasee();
376 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
377 } while (--MaxLookup);
381 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
382 /// return the value in the PHI node corresponding to PredBB. If not, return
383 /// ourself. This is useful if you want to know the value something has in a
384 /// predecessor block.
385 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
386 const BasicBlock *PredBB) {
387 PHINode *PN = dyn_cast<PHINode>(this);
388 if (PN && PN->getParent() == CurBB)
389 return PN->getIncomingValueForBlock(PredBB);
393 LLVMContext &Value::getContext() const { return VTy->getContext(); }
395 //===----------------------------------------------------------------------===//
396 // ValueHandleBase Class
397 //===----------------------------------------------------------------------===//
399 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
400 /// List is known to point into the existing use list.
401 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
402 assert(List && "Handle list is null?");
404 // Splice ourselves into the list.
409 Next->setPrevPtr(&Next);
410 assert(VP == Next->VP && "Added to wrong list?");
414 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
415 assert(List && "Must insert after existing node");
418 setPrevPtr(&List->Next);
421 Next->setPrevPtr(&Next);
424 /// AddToUseList - Add this ValueHandle to the use list for VP.
425 void ValueHandleBase::AddToUseList() {
426 assert(VP && "Null pointer doesn't have a use list!");
428 LLVMContextImpl *pImpl = VP->getContext().pImpl;
430 if (VP->HasValueHandle) {
431 // If this value already has a ValueHandle, then it must be in the
432 // ValueHandles map already.
433 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
434 assert(Entry != 0 && "Value doesn't have any handles?");
435 AddToExistingUseList(&Entry);
439 // Ok, it doesn't have any handles yet, so we must insert it into the
440 // DenseMap. However, doing this insertion could cause the DenseMap to
441 // reallocate itself, which would invalidate all of the PrevP pointers that
442 // point into the old table. Handle this by checking for reallocation and
443 // updating the stale pointers only if needed.
444 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
445 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
447 ValueHandleBase *&Entry = Handles[VP];
448 assert(Entry == 0 && "Value really did already have handles?");
449 AddToExistingUseList(&Entry);
450 VP->HasValueHandle = true;
452 // If reallocation didn't happen or if this was the first insertion, don't
454 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
455 Handles.size() == 1) {
459 // Okay, reallocation did happen. Fix the Prev Pointers.
460 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
461 E = Handles.end(); I != E; ++I) {
462 assert(I->second && I->first == I->second->VP && "List invariant broken!");
463 I->second->setPrevPtr(&I->second);
467 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
468 void ValueHandleBase::RemoveFromUseList() {
469 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
471 // Unlink this from its use list.
472 ValueHandleBase **PrevPtr = getPrevPtr();
473 assert(*PrevPtr == this && "List invariant broken");
477 assert(Next->getPrevPtr() == &Next && "List invariant broken");
478 Next->setPrevPtr(PrevPtr);
482 // If the Next pointer was null, then it is possible that this was the last
483 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
485 LLVMContextImpl *pImpl = VP->getContext().pImpl;
486 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
487 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
489 VP->HasValueHandle = false;
494 void ValueHandleBase::ValueIsDeleted(Value *V) {
495 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
497 // Get the linked list base, which is guaranteed to exist since the
498 // HasValueHandle flag is set.
499 LLVMContextImpl *pImpl = V->getContext().pImpl;
500 ValueHandleBase *Entry = pImpl->ValueHandles[V];
501 assert(Entry && "Value bit set but no entries exist");
503 // We use a local ValueHandleBase as an iterator so that
504 // ValueHandles can add and remove themselves from the list without
505 // breaking our iteration. This is not really an AssertingVH; we
506 // just have to give ValueHandleBase some kind.
507 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
508 Iterator.RemoveFromUseList();
509 Iterator.AddToExistingUseListAfter(Entry);
510 assert(Entry->Next == &Iterator && "Loop invariant broken.");
512 switch (Entry->getKind()) {
516 // Mark that this value has been deleted by setting it to an invalid Value
518 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
521 // Weak just goes to null, which will unlink it from the list.
525 // Forward to the subclass's implementation.
526 static_cast<CallbackVH*>(Entry)->deleted();
531 // All callbacks, weak references, and assertingVHs should be dropped by now.
532 if (V->HasValueHandle) {
533 #ifndef NDEBUG // Only in +Asserts mode...
534 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
536 if (pImpl->ValueHandles[V]->getKind() == Assert)
537 llvm_unreachable("An asserting value handle still pointed to this"
541 llvm_unreachable("All references to V were not removed?");
546 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
547 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
548 assert(Old != New && "Changing value into itself!");
550 // Get the linked list base, which is guaranteed to exist since the
551 // HasValueHandle flag is set.
552 LLVMContextImpl *pImpl = Old->getContext().pImpl;
553 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
555 assert(Entry && "Value bit set but no entries exist");
557 // We use a local ValueHandleBase as an iterator so that
558 // ValueHandles can add and remove themselves from the list without
559 // breaking our iteration. This is not really an AssertingVH; we
560 // just have to give ValueHandleBase some kind.
561 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
562 Iterator.RemoveFromUseList();
563 Iterator.AddToExistingUseListAfter(Entry);
564 assert(Entry->Next == &Iterator && "Loop invariant broken.");
566 switch (Entry->getKind()) {
568 // Asserting handle does not follow RAUW implicitly.
571 // Tracking goes to new value like a WeakVH. Note that this may make it
572 // something incompatible with its templated type. We don't want to have a
573 // virtual (or inline) interface to handle this though, so instead we make
574 // the TrackingVH accessors guarantee that a client never sees this value.
578 // Weak goes to the new value, which will unlink it from Old's list.
579 Entry->operator=(New);
582 // Forward to the subclass's implementation.
583 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
589 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
591 CallbackVH::~CallbackVH() {}
594 //===----------------------------------------------------------------------===//
596 //===----------------------------------------------------------------------===//
598 // replaceUsesOfWith - Replaces all references to the "From" definition with
599 // references to the "To" definition.
601 void User::replaceUsesOfWith(Value *From, Value *To) {
602 if (From == To) return; // Duh what?
604 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
605 "Cannot call User::replaceUsesOfWith on a constant!");
607 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
608 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
609 // The side effects of this setOperand call include linking to
610 // "To", adding "this" to the uses list of To, and
611 // most importantly, removing "this" from the use list of "From".
612 setOperand(i, To); // Fix it now...