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/Support/raw_ostream.h"
27 #include "llvm/System/RWMutex.h"
28 #include "llvm/System/Threading.h"
29 #include "llvm/ADT/DenseMap.h"
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
37 static inline const Type *checkType(const Type *Ty) {
38 assert(Ty && "Value defined with a null type: Error!");
42 Value::Value(const Type *ty, unsigned scid)
43 : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
44 SubclassData(0), VTy(checkType(ty)),
46 if (isa<CallInst>(this) || isa<InvokeInst>(this))
47 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
48 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
49 "invalid CallInst type!");
50 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
51 assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
52 isa<OpaqueType>(ty)) &&
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 cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
70 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
71 cerr << "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 use_const_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 use_const_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 (use_const_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();
143 assert(isa<Constant>(V) && "Unknown value type!");
144 return true; // no name is setable for this.
149 /// getNameStart - Return a pointer to a null terminated string for this name.
150 /// Note that names can have null characters within the string as well as at
151 /// their end. This always returns a non-null pointer.
152 const char *Value::getNameStart() const {
153 if (Name == 0) return "";
154 return Name->getKeyData();
157 /// getNameLen - Return the length of the string, correctly handling nul
158 /// characters embedded into them.
159 unsigned Value::getNameLen() const {
160 return Name ? Name->getKeyLength() : 0;
163 /// isName - Return true if this value has the name specified by the provided
164 /// nul terminated string.
165 bool Value::isName(const char *N) const {
166 unsigned InLen = strlen(N);
167 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
171 std::string Value::getNameStr() const {
172 if (Name == 0) return "";
173 return std::string(Name->getKeyData(),
174 Name->getKeyData()+Name->getKeyLength());
177 void Value::setName(const std::string &name) {
178 setName(&name[0], name.size());
181 void Value::setName(const char *Name) {
182 setName(Name, Name ? strlen(Name) : 0);
185 void Value::setName(const char *NameStr, unsigned NameLen) {
186 if (NameLen == 0 && !hasName()) return;
187 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
189 // Get the symbol table to update for this object.
190 ValueSymbolTable *ST;
191 if (getSymTab(this, ST))
192 return; // Cannot set a name on this value (e.g. constant).
194 if (!ST) { // No symbol table to update? Just do the change.
196 // Free the name for this value.
203 // Name isn't changing?
204 if (NameLen == Name->getKeyLength() &&
205 !memcmp(Name->getKeyData(), NameStr, NameLen))
210 // NOTE: Could optimize for the case the name is shrinking to not deallocate
213 // Create the new name.
214 Name = ValueName::Create(NameStr, NameStr+NameLen);
215 Name->setValue(this);
219 // NOTE: Could optimize for the case the name is shrinking to not deallocate
222 // Name isn't changing?
223 if (NameLen == Name->getKeyLength() &&
224 !memcmp(Name->getKeyData(), NameStr, NameLen))
228 ST->removeValueName(Name);
236 // Name is changing to something new.
237 Name = ST->createValueName(NameStr, NameLen, this);
241 /// takeName - transfer the name from V to this value, setting V's name to
242 /// empty. It is an error to call V->takeName(V).
243 void Value::takeName(Value *V) {
244 ValueSymbolTable *ST = 0;
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(0, 0);
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!"); Failure=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 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
306 // except that it doesn't have all of the asserts. The asserts fail because we
307 // are half-way done resolving types, which causes some types to exist as two
308 // different Type*'s at the same time. This is a sledgehammer to work around
311 void Value::uncheckedReplaceAllUsesWith(Value *New) {
312 // Notify all ValueHandles (if present) that this value is going away.
314 ValueHandleBase::ValueIsRAUWd(this, New);
316 while (!use_empty()) {
318 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
319 // constant because they are uniqued.
320 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
321 if (!isa<GlobalValue>(C)) {
322 C->replaceUsesOfWithOnConstant(this, New, &U);
331 void Value::replaceAllUsesWith(Value *New) {
332 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
333 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
334 assert(New->getType() == getType() &&
335 "replaceAllUses of value with new value of different type!");
337 uncheckedReplaceAllUsesWith(New);
340 Value *Value::stripPointerCasts() {
341 if (!isa<PointerType>(getType()))
345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
346 if (CE->getOpcode() == Instruction::GetElementPtr) {
347 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
348 if (!CE->getOperand(i)->isNullValue())
350 V = CE->getOperand(0);
351 } else if (CE->getOpcode() == Instruction::BitCast) {
352 V = CE->getOperand(0);
356 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
357 if (!GEP->hasAllZeroIndices())
359 V = GEP->getOperand(0);
360 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
361 V = CI->getOperand(0);
365 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
369 Value *Value::getUnderlyingObject() {
370 if (!isa<PointerType>(getType()))
373 unsigned MaxLookup = 6;
375 if (Instruction *I = dyn_cast<Instruction>(V)) {
376 if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
378 V = I->getOperand(0);
379 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
380 if (CE->getOpcode() != Instruction::BitCast &&
381 CE->getOpcode() != Instruction::GetElementPtr)
383 V = CE->getOperand(0);
387 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
388 } while (--MaxLookup);
392 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
393 /// return the value in the PHI node corresponding to PredBB. If not, return
394 /// ourself. This is useful if you want to know the value something has in a
395 /// predecessor block.
396 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
397 const BasicBlock *PredBB) {
398 PHINode *PN = dyn_cast<PHINode>(this);
399 if (PN && PN->getParent() == CurBB)
400 return PN->getIncomingValueForBlock(PredBB);
404 //===----------------------------------------------------------------------===//
405 // ValueHandleBase Class
406 //===----------------------------------------------------------------------===//
408 /// ValueHandles - This map keeps track of all of the value handles that are
409 /// watching a Value*. The Value::HasValueHandle bit is used to know whether or
410 /// not a value has an entry in this map.
411 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
412 static ManagedStatic<ValueHandlesTy> ValueHandles;
413 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
415 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
416 /// List is known to point into the existing use list.
417 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
418 assert(List && "Handle list is null?");
420 // Splice ourselves into the list.
425 Next->setPrevPtr(&Next);
426 assert(VP == Next->VP && "Added to wrong list?");
430 /// AddToUseList - Add this ValueHandle to the use list for VP.
431 void ValueHandleBase::AddToUseList() {
432 assert(VP && "Null pointer doesn't have a use list!");
433 if (VP->HasValueHandle) {
434 // If this value already has a ValueHandle, then it must be in the
435 // ValueHandles map already.
436 sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
437 ValueHandleBase *&Entry = (*ValueHandles)[VP];
438 assert(Entry != 0 && "Value doesn't have any handles?");
439 AddToExistingUseList(&Entry);
443 // Ok, it doesn't have any handles yet, so we must insert it into the
444 // DenseMap. However, doing this insertion could cause the DenseMap to
445 // reallocate itself, which would invalidate all of the PrevP pointers that
446 // point into the old table. Handle this by checking for reallocation and
447 // updating the stale pointers only if needed.
448 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
449 ValueHandlesTy &Handles = *ValueHandles;
450 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
452 ValueHandleBase *&Entry = Handles[VP];
453 assert(Entry == 0 && "Value really did already have handles?");
454 AddToExistingUseList(&Entry);
455 VP->HasValueHandle = true;
457 // If reallocation didn't happen or if this was the first insertion, don't
459 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
460 Handles.size() == 1) {
464 // Okay, reallocation did happen. Fix the Prev Pointers.
465 for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
467 assert(I->second && I->first == I->second->VP && "List invariant broken!");
468 I->second->setPrevPtr(&I->second);
472 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
473 void ValueHandleBase::RemoveFromUseList() {
474 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
476 // Unlink this from its use list.
477 ValueHandleBase **PrevPtr = getPrevPtr();
478 assert(*PrevPtr == this && "List invariant broken");
482 assert(Next->getPrevPtr() == &Next && "List invariant broken");
483 Next->setPrevPtr(PrevPtr);
487 // If the Next pointer was null, then it is possible that this was the last
488 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
490 sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
491 ValueHandlesTy &Handles = *ValueHandles;
492 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
494 VP->HasValueHandle = false;
499 void ValueHandleBase::ValueIsDeleted(Value *V) {
500 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
502 // Get the linked list base, which is guaranteed to exist since the
503 // HasValueHandle flag is set.
504 ValueHandlesLock->reader_acquire();
505 ValueHandleBase *Entry = (*ValueHandles)[V];
506 ValueHandlesLock->reader_release();
507 assert(Entry && "Value bit set but no entries exist");
510 // Advance pointer to avoid invalidation.
511 ValueHandleBase *ThisNode = Entry;
514 switch (ThisNode->getKind()) {
516 #ifndef NDEBUG // Only in -g mode...
517 cerr << "While deleting: " << *V->getType() << " %" << V->getNameStr()
520 llvm_unreachable("An asserting value handle still pointed to this"
523 // Weak just goes to null, which will unlink it from the list.
524 ThisNode->operator=(0);
527 // Forward to the subclass's implementation.
528 static_cast<CallbackVH*>(ThisNode)->deleted();
533 // All callbacks and weak references should be dropped by now.
534 assert(!V->HasValueHandle && "All references to V were not removed?");
538 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
539 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
540 assert(Old != New && "Changing value into itself!");
542 // Get the linked list base, which is guaranteed to exist since the
543 // HasValueHandle flag is set.
544 ValueHandlesLock->reader_acquire();
545 ValueHandleBase *Entry = (*ValueHandles)[Old];
546 ValueHandlesLock->reader_release();
547 assert(Entry && "Value bit set but no entries exist");
550 // Advance pointer to avoid invalidation.
551 ValueHandleBase *ThisNode = Entry;
554 switch (ThisNode->getKind()) {
556 // Asserting handle does not follow RAUW implicitly.
559 // Weak goes to the new value, which will unlink it from Old's list.
560 ThisNode->operator=(New);
563 // Forward to the subclass's implementation.
564 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
570 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
572 CallbackVH::~CallbackVH() {}
575 //===----------------------------------------------------------------------===//
577 //===----------------------------------------------------------------------===//
579 // replaceUsesOfWith - Replaces all references to the "From" definition with
580 // references to the "To" definition.
582 void User::replaceUsesOfWith(Value *From, Value *To) {
583 if (From == To) return; // Duh what?
585 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
586 "Cannot call User::replaceUsesofWith on a constant!");
588 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
589 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
590 // The side effects of this setOperand call include linking to
591 // "To", adding "this" to the uses list of To, and
592 // most importantly, removing "this" from the use list of "From".
593 setOperand(i, To); // Fix it now...