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/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LeakDetector.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/System/RWMutex.h"
27 #include "llvm/System/Threading.h"
28 #include "llvm/ADT/DenseMap.h"
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 static inline const Type *checkType(const Type *Ty) {
37 assert(Ty && "Value defined with a null type: Error!");
41 Value::Value(const Type *ty, unsigned scid)
42 : SubclassID(scid), HasValueHandle(0), SubclassData(0), VTy(checkType(ty)),
44 if (isa<CallInst>(this) || isa<InvokeInst>(this))
45 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
46 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
47 "invalid CallInst type!");
48 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
49 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
50 isa<OpaqueType>(ty)) &&
51 "Cannot create non-first-class values except for constants!");
55 // Notify all ValueHandles (if present) that this value is going away.
57 ValueHandleBase::ValueIsDeleted(this);
59 #ifndef NDEBUG // Only in -g mode...
60 // Check to make sure that there are no uses of this value that are still
61 // around when the value is destroyed. If there are, then we have a dangling
62 // reference and something is wrong. This code is here to print out what is
63 // still being referenced. The value in question should be printed as
67 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
68 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
69 cerr << "Use still stuck around after Def is destroyed:"
73 assert(use_empty() && "Uses remain when a value is destroyed!");
75 // If this value is named, destroy the name. This should not be in a symtab
80 // There should be no uses of this object anymore, remove it.
81 LeakDetector::removeGarbageObject(this);
84 /// hasNUses - Return true if this Value has exactly N users.
86 bool Value::hasNUses(unsigned N) const {
87 use_const_iterator UI = use_begin(), E = use_end();
90 if (UI == E) return false; // Too few.
94 /// hasNUsesOrMore - Return true if this value has N users or more. This is
95 /// logically equivalent to getNumUses() >= N.
97 bool Value::hasNUsesOrMore(unsigned N) const {
98 use_const_iterator UI = use_begin(), E = use_end();
101 if (UI == E) return false; // Too few.
106 /// isUsedInBasicBlock - Return true if this value is used in the specified
108 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
109 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
110 const Instruction *User = dyn_cast<Instruction>(*I);
111 if (User && User->getParent() == BB)
118 /// getNumUses - This method computes the number of uses of this Value. This
119 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
121 unsigned Value::getNumUses() const {
122 return (unsigned)std::distance(use_begin(), use_end());
125 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
127 if (Instruction *I = dyn_cast<Instruction>(V)) {
128 if (BasicBlock *P = I->getParent())
129 if (Function *PP = P->getParent())
130 ST = &PP->getValueSymbolTable();
131 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
132 if (Function *P = BB->getParent())
133 ST = &P->getValueSymbolTable();
134 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
135 if (Module *P = GV->getParent())
136 ST = &P->getValueSymbolTable();
137 } else if (Argument *A = dyn_cast<Argument>(V)) {
138 if (Function *P = A->getParent())
139 ST = &P->getValueSymbolTable();
141 assert(isa<Constant>(V) && "Unknown value type!");
142 return true; // no name is setable for this.
147 /// getNameStart - Return a pointer to a null terminated string for this name.
148 /// Note that names can have null characters within the string as well as at
149 /// their end. This always returns a non-null pointer.
150 const char *Value::getNameStart() const {
151 if (Name == 0) return "";
152 return Name->getKeyData();
155 /// getNameLen - Return the length of the string, correctly handling nul
156 /// characters embedded into them.
157 unsigned Value::getNameLen() const {
158 return Name ? Name->getKeyLength() : 0;
161 /// isName - Return true if this value has the name specified by the provided
162 /// nul terminated string.
163 bool Value::isName(const char *N) const {
164 unsigned InLen = strlen(N);
165 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
169 std::string Value::getNameStr() const {
170 if (Name == 0) return "";
171 return std::string(Name->getKeyData(),
172 Name->getKeyData()+Name->getKeyLength());
175 void Value::setName(const std::string &name) {
176 setName(&name[0], name.size());
179 void Value::setName(const char *Name) {
180 setName(Name, Name ? strlen(Name) : 0);
183 void Value::setName(const char *NameStr, unsigned NameLen) {
184 if (NameLen == 0 && !hasName()) return;
185 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
187 // Get the symbol table to update for this object.
188 ValueSymbolTable *ST;
189 if (getSymTab(this, ST))
190 return; // Cannot set a name on this value (e.g. constant).
192 if (!ST) { // No symbol table to update? Just do the change.
194 // Free the name for this value.
201 // Name isn't changing?
202 if (NameLen == Name->getKeyLength() &&
203 !memcmp(Name->getKeyData(), NameStr, NameLen))
208 // NOTE: Could optimize for the case the name is shrinking to not deallocate
211 // Create the new name.
212 Name = ValueName::Create(NameStr, NameStr+NameLen);
213 Name->setValue(this);
217 // NOTE: Could optimize for the case the name is shrinking to not deallocate
220 // Name isn't changing?
221 if (NameLen == Name->getKeyLength() &&
222 !memcmp(Name->getKeyData(), NameStr, NameLen))
226 ST->removeValueName(Name);
234 // Name is changing to something new.
235 Name = ST->createValueName(NameStr, NameLen, 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 ValueSymbolTable *ST = 0;
243 // If this value has a name, drop it.
245 // Get the symtab this is in.
246 if (getSymTab(this, ST)) {
247 // We can't set a name on this value, but we need to clear V's name if
249 if (V->hasName()) V->setName(0, 0);
250 return; // Cannot set a name on this value (e.g. constant).
255 ST->removeValueName(Name);
260 // Now we know that this has no name.
262 // If V has no name either, we're done.
263 if (!V->hasName()) return;
265 // Get this's symtab if we didn't before.
267 if (getSymTab(this, ST)) {
270 return; // Cannot set a name on this value (e.g. constant).
274 // Get V's ST, this should always succed, because V has a name.
275 ValueSymbolTable *VST;
276 bool Failure = getSymTab(V, VST);
277 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
279 // If these values are both in the same symtab, we can do this very fast.
280 // This works even if both values have no symtab yet.
285 Name->setValue(this);
289 // Otherwise, things are slightly more complex. Remove V's name from VST and
290 // then reinsert it into ST.
293 VST->removeValueName(V->Name);
296 Name->setValue(this);
299 ST->reinsertValue(this);
303 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
304 // except that it doesn't have all of the asserts. The asserts fail because we
305 // are half-way done resolving types, which causes some types to exist as two
306 // different Type*'s at the same time. This is a sledgehammer to work around
309 void Value::uncheckedReplaceAllUsesWith(Value *New) {
310 // Notify all ValueHandles (if present) that this value is going away.
312 ValueHandleBase::ValueIsRAUWd(this, New);
314 while (!use_empty()) {
316 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
317 // constant because they are uniqued.
318 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
319 if (!isa<GlobalValue>(C)) {
320 C->replaceUsesOfWithOnConstant(this, New, &U);
329 void Value::replaceAllUsesWith(Value *New) {
330 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
331 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
332 assert(New->getType() == getType() &&
333 "replaceAllUses of value with new value of different type!");
335 uncheckedReplaceAllUsesWith(New);
338 Value *Value::stripPointerCasts() {
339 if (!isa<PointerType>(getType()))
343 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
344 if (CE->getOpcode() == Instruction::GetElementPtr) {
345 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
346 if (!CE->getOperand(i)->isNullValue())
348 V = CE->getOperand(0);
349 } else if (CE->getOpcode() == Instruction::BitCast) {
350 V = CE->getOperand(0);
354 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
355 if (!GEP->hasAllZeroIndices())
357 V = GEP->getOperand(0);
358 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
359 V = CI->getOperand(0);
363 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
367 Value *Value::getUnderlyingObject() {
368 if (!isa<PointerType>(getType()))
371 unsigned MaxLookup = 6;
373 if (Instruction *I = dyn_cast<Instruction>(V)) {
374 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
376 V = I->getOperand(0);
377 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
378 if (CE->getOpcode() != Instruction::BitCast &&
379 CE->getOpcode() != Instruction::GetElementPtr)
381 V = CE->getOperand(0);
385 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
386 } while (--MaxLookup);
390 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
391 /// return the value in the PHI node corresponding to PredBB. If not, return
392 /// ourself. This is useful if you want to know the value something has in a
393 /// predecessor block.
394 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
395 const BasicBlock *PredBB) {
396 PHINode *PN = dyn_cast<PHINode>(this);
397 if (PN && PN->getParent() == CurBB)
398 return PN->getIncomingValueForBlock(PredBB);
402 //===----------------------------------------------------------------------===//
403 // ValueHandleBase Class
404 //===----------------------------------------------------------------------===//
406 /// ValueHandles - This map keeps track of all of the value handles that are
407 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
408 /// not a value has an entry in this map.
409 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
410 static ManagedStatic<ValueHandlesTy> ValueHandles;
411 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
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 /// AddToUseList - Add this ValueHandle to the use list for VP.
429 void ValueHandleBase::AddToUseList() {
430 assert(VP && "Null pointer doesn't have a use list!");
431 if (VP->HasValueHandle) {
432 // If this value already has a ValueHandle, then it must be in the
433 // ValueHandles map already.
434 sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
435 ValueHandleBase *&Entry = (*ValueHandles)[VP];
436 assert(Entry != 0 && "Value doesn't have any handles?");
437 AddToExistingUseList(&Entry);
441 // Ok, it doesn't have any handles yet, so we must insert it into the
442 // DenseMap. However, doing this insertion could cause the DenseMap to
443 // reallocate itself, which would invalidate all of the PrevP pointers that
444 // point into the old table. Handle this by checking for reallocation and
445 // updating the stale pointers only if needed.
446 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
447 ValueHandlesTy &Handles = *ValueHandles;
448 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
450 ValueHandleBase *&Entry = Handles[VP];
451 assert(Entry == 0 && "Value really did already have handles?");
452 AddToExistingUseList(&Entry);
453 VP->HasValueHandle = true;
455 // If reallocation didn't happen or if this was the first insertion, don't
457 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
458 Handles.size() == 1) {
462 // Okay, reallocation did happen. Fix the Prev Pointers.
463 for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
465 assert(I->second && I->first == I->second->VP && "List invariant broken!");
466 I->second->setPrevPtr(&I->second);
470 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
471 void ValueHandleBase::RemoveFromUseList() {
472 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
474 // Unlink this from its use list.
475 ValueHandleBase **PrevPtr = getPrevPtr();
476 assert(*PrevPtr == this && "List invariant broken");
480 assert(Next->getPrevPtr() == &Next && "List invariant broken");
481 Next->setPrevPtr(PrevPtr);
485 // If the Next pointer was null, then it is possible that this was the last
486 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
488 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
489 ValueHandlesTy &Handles = *ValueHandles;
490 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
492 VP->HasValueHandle = false;
497 void ValueHandleBase::ValueIsDeleted(Value *V) {
498 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
500 // Get the linked list base, which is guaranteed to exist since the
501 // HasValueHandle flag is set.
502 ValueHandlesLock->reader_acquire();
503 ValueHandleBase *Entry = (*ValueHandles)[V];
504 ValueHandlesLock->reader_release();
505 assert(Entry && "Value bit set but no entries exist");
508 // Advance pointer to avoid invalidation.
509 ValueHandleBase *ThisNode = Entry;
512 switch (ThisNode->getKind()) {
514 #ifndef NDEBUG // Only in -g mode...
515 cerr << "While deleting: " << *V->getType() << " %" << V->getNameStr()
518 llvm_report_error("An asserting value handle still pointed to this"
521 // Weak just goes to null, which will unlink it from the list.
522 ThisNode->operator=(0);
525 // Forward to the subclass's implementation.
526 static_cast<CallbackVH*>(ThisNode)->deleted();
531 // All callbacks and weak references should be dropped by now.
532 assert(!V->HasValueHandle && "All references to V were not removed?");
536 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
537 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
538 assert(Old != New && "Changing value into itself!");
540 // Get the linked list base, which is guaranteed to exist since the
541 // HasValueHandle flag is set.
542 ValueHandlesLock->reader_acquire();
543 ValueHandleBase *Entry = (*ValueHandles)[Old];
544 ValueHandlesLock->reader_release();
545 assert(Entry && "Value bit set but no entries exist");
548 // Advance pointer to avoid invalidation.
549 ValueHandleBase *ThisNode = Entry;
552 switch (ThisNode->getKind()) {
554 // Asserting handle does not follow RAUW implicitly.
557 // Weak goes to the new value, which will unlink it from Old's list.
558 ThisNode->operator=(New);
561 // Forward to the subclass's implementation.
562 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
568 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
570 CallbackVH::~CallbackVH() {}
573 //===----------------------------------------------------------------------===//
575 //===----------------------------------------------------------------------===//
577 // replaceUsesOfWith - Replaces all references to the "From" definition with
578 // references to the "To" definition.
580 void User::replaceUsesOfWith(Value *From, Value *To) {
581 if (From == To) return; // Duh what?
583 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
584 "Cannot call User::replaceUsesofWith on a constant!");
586 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
587 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
588 // The side effects of this setOperand call include linking to
589 // "To", adding "this" to the uses list of To, and
590 // most importantly, removing "this" from the use list of "From".
591 setOperand(i, To); // Fix it now...