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/Support/raw_ostream.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include "llvm/ADT/DenseMap.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 static inline const Type *checkType(const Type *Ty) {
42 assert(Ty && "Value defined with a null type: Error!");
46 Value::Value(const Type *ty, unsigned scid)
47 : SubclassID(scid), HasValueHandle(0), HasMetadata(0),
48 SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
50 if (isa<CallInst>(this) || isa<InvokeInst>(this))
51 assert((VTy->isFirstClassType() ||
52 VTy == Type::getVoidTy(ty->getContext()) ||
53 isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
54 "invalid CallInst type!");
55 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
56 assert((VTy->isFirstClassType() ||
57 VTy == Type::getVoidTy(ty->getContext()) ||
58 isa<OpaqueType>(ty)) &&
59 "Cannot create non-first-class values except for constants!");
64 LLVMContext &Context = getContext();
65 Context.pImpl->TheMetadata.ValueIsDeleted(this);
68 // Notify all ValueHandles (if present) that this value is going away.
70 ValueHandleBase::ValueIsDeleted(this);
72 #ifndef NDEBUG // Only in -g mode...
73 // Check to make sure that there are no uses of this value that are still
74 // around when the value is destroyed. If there are, then we have a dangling
75 // reference and something is wrong. This code is here to print out what is
76 // still being referenced. The value in question should be printed as
80 errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
81 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
82 errs() << "Use still stuck around after Def is destroyed:"
86 assert(use_empty() && "Uses remain when a value is destroyed!");
88 // If this value is named, destroy the name. This should not be in a symtab
93 // There should be no uses of this object anymore, remove it.
94 LeakDetector::removeGarbageObject(this);
97 /// hasNUses - Return true if this Value has exactly N users.
99 bool Value::hasNUses(unsigned N) const {
100 use_const_iterator UI = use_begin(), E = use_end();
103 if (UI == E) return false; // Too few.
107 /// hasNUsesOrMore - Return true if this value has N users or more. This is
108 /// logically equivalent to getNumUses() >= N.
110 bool Value::hasNUsesOrMore(unsigned N) const {
111 use_const_iterator UI = use_begin(), E = use_end();
114 if (UI == E) return false; // Too few.
119 /// isUsedInBasicBlock - Return true if this value is used in the specified
121 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
122 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
123 const Instruction *User = dyn_cast<Instruction>(*I);
124 if (User && User->getParent() == BB)
131 /// getNumUses - This method computes the number of uses of this Value. This
132 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
134 unsigned Value::getNumUses() const {
135 return (unsigned)std::distance(use_begin(), use_end());
138 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
140 if (Instruction *I = dyn_cast<Instruction>(V)) {
141 if (BasicBlock *P = I->getParent())
142 if (Function *PP = P->getParent())
143 ST = &PP->getValueSymbolTable();
144 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
145 if (Function *P = BB->getParent())
146 ST = &P->getValueSymbolTable();
147 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
148 if (Module *P = GV->getParent())
149 ST = &P->getValueSymbolTable();
150 } else if (Argument *A = dyn_cast<Argument>(V)) {
151 if (Function *P = A->getParent())
152 ST = &P->getValueSymbolTable();
153 } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
154 if (Module *P = N->getParent()) {
155 ST = &P->getValueSymbolTable();
157 } else if (isa<MDString>(V))
160 assert(isa<Constant>(V) && "Unknown value type!");
161 return true; // no name is setable for this.
166 StringRef Value::getName() const {
167 // Make sure the empty string is still a C string. For historical reasons,
168 // some clients want to call .data() on the result and expect it to be null
170 if (!Name) return StringRef("", 0);
171 return Name->getKey();
174 std::string Value::getNameStr() const {
175 return getName().str();
178 void Value::setName(const Twine &NewName) {
179 // Fast path for common IRBuilder case of setName("") when there is no name.
180 if (NewName.isTriviallyEmpty() && !hasName())
183 SmallString<256> NameData;
184 NewName.toVector(NameData);
186 const char *NameStr = NameData.data();
187 unsigned NameLen = NameData.size();
189 // Name isn't changing?
190 if (getName() == StringRef(NameStr, NameLen))
193 assert(getType() != Type::getVoidTy(getContext()) &&
194 "Cannot assign a name to void values!");
196 // Get the symbol table to update for this object.
197 ValueSymbolTable *ST;
198 if (getSymTab(this, ST))
199 return; // Cannot set a name on this value (e.g. constant).
201 if (!ST) { // No symbol table to update? Just do the change.
203 // Free the name for this value.
212 // NOTE: Could optimize for the case the name is shrinking to not deallocate
215 // Create the new name.
216 Name = ValueName::Create(NameStr, NameStr+NameLen);
217 Name->setValue(this);
221 // NOTE: Could optimize for the case the name is shrinking to not deallocate
225 ST->removeValueName(Name);
233 // Name is changing to something new.
234 Name = ST->createValueName(StringRef(NameStr, NameLen), this);
238 /// takeName - transfer the name from V to this value, setting V's name to
239 /// empty. It is an error to call V->takeName(V).
240 void Value::takeName(Value *V) {
241 ValueSymbolTable *ST = 0;
242 // If this value has a name, drop it.
244 // Get the symtab this is in.
245 if (getSymTab(this, ST)) {
246 // We can't set a name on this value, but we need to clear V's name if
248 if (V->hasName()) V->setName("");
249 return; // Cannot set a name on this value (e.g. constant).
254 ST->removeValueName(Name);
259 // Now we know that this has no name.
261 // If V has no name either, we're done.
262 if (!V->hasName()) return;
264 // Get this's symtab if we didn't before.
266 if (getSymTab(this, ST)) {
269 return; // Cannot set a name on this value (e.g. constant).
273 // Get V's ST, this should always succed, because V has a name.
274 ValueSymbolTable *VST;
275 bool Failure = getSymTab(V, VST);
276 assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
278 // If these values are both in the same symtab, we can do this very fast.
279 // This works even if both values have no symtab yet.
284 Name->setValue(this);
288 // Otherwise, things are slightly more complex. Remove V's name from VST and
289 // then reinsert it into ST.
292 VST->removeValueName(V->Name);
295 Name->setValue(this);
298 ST->reinsertValue(this);
302 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
303 // except that it doesn't have all of the asserts. The asserts fail because we
304 // are half-way done resolving types, which causes some types to exist as two
305 // different Type*'s at the same time. This is a sledgehammer to work around
308 void Value::uncheckedReplaceAllUsesWith(Value *New) {
309 // Notify all ValueHandles (if present) that this value is going away.
311 ValueHandleBase::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 /// AddToUseList - Add this ValueHandle to the use list for VP.
415 void ValueHandleBase::AddToUseList() {
416 assert(VP && "Null pointer doesn't have a use list!");
418 LLVMContextImpl *pImpl = VP->getContext().pImpl;
420 if (VP->HasValueHandle) {
421 // If this value already has a ValueHandle, then it must be in the
422 // ValueHandles map already.
423 ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
424 assert(Entry != 0 && "Value doesn't have any handles?");
425 AddToExistingUseList(&Entry);
429 // Ok, it doesn't have any handles yet, so we must insert it into the
430 // DenseMap. However, doing this insertion could cause the DenseMap to
431 // reallocate itself, which would invalidate all of the PrevP pointers that
432 // point into the old table. Handle this by checking for reallocation and
433 // updating the stale pointers only if needed.
434 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
435 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
437 ValueHandleBase *&Entry = Handles[VP];
438 assert(Entry == 0 && "Value really did already have handles?");
439 AddToExistingUseList(&Entry);
440 VP->HasValueHandle = true;
442 // If reallocation didn't happen or if this was the first insertion, don't
444 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
445 Handles.size() == 1) {
449 // Okay, reallocation did happen. Fix the Prev Pointers.
450 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
451 E = Handles.end(); I != E; ++I) {
452 assert(I->second && I->first == I->second->VP && "List invariant broken!");
453 I->second->setPrevPtr(&I->second);
457 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
458 void ValueHandleBase::RemoveFromUseList() {
459 assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
461 // Unlink this from its use list.
462 ValueHandleBase **PrevPtr = getPrevPtr();
463 assert(*PrevPtr == this && "List invariant broken");
467 assert(Next->getPrevPtr() == &Next && "List invariant broken");
468 Next->setPrevPtr(PrevPtr);
472 // If the Next pointer was null, then it is possible that this was the last
473 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
475 LLVMContextImpl *pImpl = VP->getContext().pImpl;
476 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
477 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
479 VP->HasValueHandle = false;
484 void ValueHandleBase::ValueIsDeleted(Value *V) {
485 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
487 // Get the linked list base, which is guaranteed to exist since the
488 // HasValueHandle flag is set.
489 LLVMContextImpl *pImpl = V->getContext().pImpl;
490 ValueHandleBase *Entry = pImpl->ValueHandles[V];
491 assert(Entry && "Value bit set but no entries exist");
494 // Advance pointer to avoid invalidation.
495 ValueHandleBase *ThisNode = Entry;
498 switch (ThisNode->getKind()) {
500 #ifndef NDEBUG // Only in -g mode...
501 errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
504 llvm_unreachable("An asserting value handle still pointed to this"
507 // Weak just goes to null, which will unlink it from the list.
508 ThisNode->operator=(0);
511 // Forward to the subclass's implementation.
512 static_cast<CallbackVH*>(ThisNode)->deleted();
517 // All callbacks and weak references should be dropped by now.
518 assert(!V->HasValueHandle && "All references to V were not removed?");
522 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
523 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
524 assert(Old != New && "Changing value into itself!");
526 // Get the linked list base, which is guaranteed to exist since the
527 // HasValueHandle flag is set.
528 LLVMContextImpl *pImpl = Old->getContext().pImpl;
529 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
531 assert(Entry && "Value bit set but no entries exist");
534 // Advance pointer to avoid invalidation.
535 ValueHandleBase *ThisNode = Entry;
538 switch (ThisNode->getKind()) {
540 // Asserting handle does not follow RAUW implicitly.
543 // Weak goes to the new value, which will unlink it from Old's list.
544 ThisNode->operator=(New);
547 // Forward to the subclass's implementation.
548 static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
554 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
556 CallbackVH::~CallbackVH() {}
559 //===----------------------------------------------------------------------===//
561 //===----------------------------------------------------------------------===//
563 // replaceUsesOfWith - Replaces all references to the "From" definition with
564 // references to the "To" definition.
566 void User::replaceUsesOfWith(Value *From, Value *To) {
567 if (From == To) return; // Duh what?
569 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
570 "Cannot call User::replaceUsesOfWith on a constant!");
572 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
573 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
574 // The side effects of this setOperand call include linking to
575 // "To", adding "this" to the uses list of To, and
576 // most importantly, removing "this" from the use list of "From".
577 setOperand(i, To); // Fix it now...