switch to TrackingVH instead of WeakVH, since these can never
[oota-llvm.git] / lib / VMCore / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Value, ValueHandle, and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
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/ErrorHandling.h"
26 #include "llvm/Support/LeakDetector.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/ValueHandle.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 //===----------------------------------------------------------------------===//
34 //                                Value Class
35 //===----------------------------------------------------------------------===//
36
37 static inline const Type *checkType(const Type *Ty) {
38   assert(Ty && "Value defined with a null type: Error!");
39   return Ty;
40 }
41
42 Value::Value(const Type *ty, unsigned scid)
43   : SubclassID(scid), HasValueHandle(0),
44     SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
45     UseList(0), Name(0) {
46   if (isa<CallInst>(this) || isa<InvokeInst>(this))
47     assert((VTy->isFirstClassType() ||
48             VTy == Type::getVoidTy(ty->getContext()) ||
49             isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
50            "invalid CallInst  type!");
51   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
52     assert((VTy->isFirstClassType() ||
53             VTy == Type::getVoidTy(ty->getContext()) ||
54            isa<OpaqueType>(ty)) &&
55            "Cannot create non-first-class values except for constants!");
56 }
57
58 Value::~Value() {
59   // Notify all ValueHandles (if present) that this value is going away.
60   if (HasValueHandle)
61     ValueHandleBase::ValueIsDeleted(this);
62
63 #ifndef NDEBUG      // Only in -g mode...
64   // Check to make sure that there are no uses of this value that are still
65   // around when the value is destroyed.  If there are, then we have a dangling
66   // reference and something is wrong.  This code is here to print out what is
67   // still being referenced.  The value in question should be printed as
68   // a <badref>
69   //
70   if (!use_empty()) {
71     errs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
72     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
73       errs() << "Use still stuck around after Def is destroyed:"
74            << **I << "\n";
75   }
76 #endif
77   assert(use_empty() && "Uses remain when a value is destroyed!");
78
79   // If this value is named, destroy the name.  This should not be in a symtab
80   // at this point.
81   if (Name)
82     Name->Destroy();
83
84   // There should be no uses of this object anymore, remove it.
85   LeakDetector::removeGarbageObject(this);
86 }
87
88 /// hasNUses - Return true if this Value has exactly N users.
89 ///
90 bool Value::hasNUses(unsigned N) const {
91   use_const_iterator UI = use_begin(), E = use_end();
92
93   for (; N; --N, ++UI)
94     if (UI == E) return false;  // Too few.
95   return UI == E;
96 }
97
98 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
99 /// logically equivalent to getNumUses() >= N.
100 ///
101 bool Value::hasNUsesOrMore(unsigned N) const {
102   use_const_iterator UI = use_begin(), E = use_end();
103
104   for (; N; --N, ++UI)
105     if (UI == E) return false;  // Too few.
106
107   return true;
108 }
109
110 /// isUsedInBasicBlock - Return true if this value is used in the specified
111 /// basic block.
112 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
113   for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I) {
114     const Instruction *User = dyn_cast<Instruction>(*I);
115     if (User && User->getParent() == BB)
116       return true;
117   }
118   return false;
119 }
120
121
122 /// getNumUses - This method computes the number of uses of this Value.  This
123 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
124 /// values.
125 unsigned Value::getNumUses() const {
126   return (unsigned)std::distance(use_begin(), use_end());
127 }
128
129 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
130   ST = 0;
131   if (Instruction *I = dyn_cast<Instruction>(V)) {
132     if (BasicBlock *P = I->getParent())
133       if (Function *PP = P->getParent())
134         ST = &PP->getValueSymbolTable();
135   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
136     if (Function *P = BB->getParent())
137       ST = &P->getValueSymbolTable();
138   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
139     if (Module *P = GV->getParent())
140       ST = &P->getValueSymbolTable();
141   } else if (Argument *A = dyn_cast<Argument>(V)) {
142     if (Function *P = A->getParent())
143       ST = &P->getValueSymbolTable();
144   } else if (NamedMDNode *N = dyn_cast<NamedMDNode>(V)) {
145     if (Module *P = N->getParent()) {
146       ST = &P->getValueSymbolTable();
147     }
148   } else if (isa<MDString>(V))
149     return true;
150   else {
151     assert(isa<Constant>(V) && "Unknown value type!");
152     return true;  // no name is setable for this.
153   }
154   return false;
155 }
156
157 StringRef Value::getName() const {
158   // Make sure the empty string is still a C string. For historical reasons,
159   // some clients want to call .data() on the result and expect it to be null
160   // terminated.
161   if (!Name) return StringRef("", 0);
162   return Name->getKey();
163 }
164
165 std::string Value::getNameStr() const {
166   return getName().str();
167 }
168
169 void Value::setName(const Twine &NewName) {
170   // Fast path for common IRBuilder case of setName("") when there is no name.
171   if (NewName.isTriviallyEmpty() && !hasName())
172     return;
173
174   SmallString<256> NameData;
175   NewName.toVector(NameData);
176
177   const char *NameStr = NameData.data();
178   unsigned NameLen = NameData.size();
179
180   // Name isn't changing?
181   if (getName() == StringRef(NameStr, NameLen))
182     return;
183
184   assert(getType() != Type::getVoidTy(getContext()) &&
185          "Cannot assign a name to void values!");
186
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).
191
192   if (!ST) { // No symbol table to update?  Just do the change.
193     if (NameLen == 0) {
194       // Free the name for this value.
195       Name->Destroy();
196       Name = 0;
197       return;
198     }
199
200     if (Name)
201       Name->Destroy();
202
203     // NOTE: Could optimize for the case the name is shrinking to not deallocate
204     // then reallocated.
205
206     // Create the new name.
207     Name = ValueName::Create(NameStr, NameStr+NameLen);
208     Name->setValue(this);
209     return;
210   }
211
212   // NOTE: Could optimize for the case the name is shrinking to not deallocate
213   // then reallocated.
214   if (hasName()) {
215     // Remove old name.
216     ST->removeValueName(Name);
217     Name->Destroy();
218     Name = 0;
219
220     if (NameLen == 0)
221       return;
222   }
223
224   // Name is changing to something new.
225   Name = ST->createValueName(StringRef(NameStr, NameLen), this);
226 }
227
228
229 /// takeName - transfer the name from V to this value, setting V's name to
230 /// empty.  It is an error to call V->takeName(V).
231 void Value::takeName(Value *V) {
232   ValueSymbolTable *ST = 0;
233   // If this value has a name, drop it.
234   if (hasName()) {
235     // Get the symtab this is in.
236     if (getSymTab(this, ST)) {
237       // We can't set a name on this value, but we need to clear V's name if
238       // it has one.
239       if (V->hasName()) V->setName("");
240       return;  // Cannot set a name on this value (e.g. constant).
241     }
242
243     // Remove old name.
244     if (ST)
245       ST->removeValueName(Name);
246     Name->Destroy();
247     Name = 0;
248   }
249
250   // Now we know that this has no name.
251
252   // If V has no name either, we're done.
253   if (!V->hasName()) return;
254
255   // Get this's symtab if we didn't before.
256   if (!ST) {
257     if (getSymTab(this, ST)) {
258       // Clear V's name.
259       V->setName("");
260       return;  // Cannot set a name on this value (e.g. constant).
261     }
262   }
263
264   // Get V's ST, this should always succed, because V has a name.
265   ValueSymbolTable *VST;
266   bool Failure = getSymTab(V, VST);
267   assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
268
269   // If these values are both in the same symtab, we can do this very fast.
270   // This works even if both values have no symtab yet.
271   if (ST == VST) {
272     // Take the name!
273     Name = V->Name;
274     V->Name = 0;
275     Name->setValue(this);
276     return;
277   }
278
279   // Otherwise, things are slightly more complex.  Remove V's name from VST and
280   // then reinsert it into ST.
281
282   if (VST)
283     VST->removeValueName(V->Name);
284   Name = V->Name;
285   V->Name = 0;
286   Name->setValue(this);
287
288   if (ST)
289     ST->reinsertValue(this);
290 }
291
292
293 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
294 // except that it doesn't have all of the asserts.  The asserts fail because we
295 // are half-way done resolving types, which causes some types to exist as two
296 // different Type*'s at the same time.  This is a sledgehammer to work around
297 // this problem.
298 //
299 void Value::uncheckedReplaceAllUsesWith(Value *New) {
300   // Notify all ValueHandles (if present) that this value is going away.
301   if (HasValueHandle)
302     ValueHandleBase::ValueIsRAUWd(this, New);
303
304   while (!use_empty()) {
305     Use &U = *UseList;
306     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
307     // constant because they are uniqued.
308     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
309       if (!isa<GlobalValue>(C)) {
310         C->replaceUsesOfWithOnConstant(this, New, &U);
311         continue;
312       }
313     }
314
315     U.set(New);
316   }
317 }
318
319 void Value::replaceAllUsesWith(Value *New) {
320   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
321   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
322   assert(New->getType() == getType() &&
323          "replaceAllUses of value with new value of different type!");
324
325   uncheckedReplaceAllUsesWith(New);
326 }
327
328 Value *Value::stripPointerCasts() {
329   if (!isa<PointerType>(getType()))
330     return this;
331   Value *V = this;
332   do {
333     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
334       if (!GEP->hasAllZeroIndices())
335         return V;
336       V = GEP->getPointerOperand();
337     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
338       V = cast<Operator>(V)->getOperand(0);
339     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
340       if (GA->mayBeOverridden())
341         return V;
342       V = GA->getAliasee();
343     } else {
344       return V;
345     }
346     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
347   } while (1);
348 }
349
350 Value *Value::getUnderlyingObject() {
351   if (!isa<PointerType>(getType()))
352     return this;
353   Value *V = this;
354   unsigned MaxLookup = 6;
355   do {
356     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
357       V = GEP->getPointerOperand();
358     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
359       V = cast<Operator>(V)->getOperand(0);
360     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
361       if (GA->mayBeOverridden())
362         return V;
363       V = GA->getAliasee();
364     } else {
365       return V;
366     }
367     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
368   } while (--MaxLookup);
369   return V;
370 }
371
372 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
373 /// return the value in the PHI node corresponding to PredBB.  If not, return
374 /// ourself.  This is useful if you want to know the value something has in a
375 /// predecessor block.
376 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
377                                const BasicBlock *PredBB) {
378   PHINode *PN = dyn_cast<PHINode>(this);
379   if (PN && PN->getParent() == CurBB)
380     return PN->getIncomingValueForBlock(PredBB);
381   return this;
382 }
383
384 LLVMContext &Value::getContext() const { return VTy->getContext(); }
385
386 //===----------------------------------------------------------------------===//
387 //                             ValueHandleBase Class
388 //===----------------------------------------------------------------------===//
389
390 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
391 /// List is known to point into the existing use list.
392 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
393   assert(List && "Handle list is null?");
394
395   // Splice ourselves into the list.
396   Next = *List;
397   *List = this;
398   setPrevPtr(List);
399   if (Next) {
400     Next->setPrevPtr(&Next);
401     assert(VP == Next->VP && "Added to wrong list?");
402   }
403 }
404
405 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
406   assert(List && "Must insert after existing node");
407
408   Next = List->Next;
409   setPrevPtr(&List->Next);
410   List->Next = this;
411   if (Next)
412     Next->setPrevPtr(&Next);
413 }
414
415 /// AddToUseList - Add this ValueHandle to the use list for VP.
416 void ValueHandleBase::AddToUseList() {
417   assert(VP && "Null pointer doesn't have a use list!");
418
419   LLVMContextImpl *pImpl = VP->getContext().pImpl;
420
421   if (VP->HasValueHandle) {
422     // If this value already has a ValueHandle, then it must be in the
423     // ValueHandles map already.
424     ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
425     assert(Entry != 0 && "Value doesn't have any handles?");
426     AddToExistingUseList(&Entry);
427     return;
428   }
429
430   // Ok, it doesn't have any handles yet, so we must insert it into the
431   // DenseMap.  However, doing this insertion could cause the DenseMap to
432   // reallocate itself, which would invalidate all of the PrevP pointers that
433   // point into the old table.  Handle this by checking for reallocation and
434   // updating the stale pointers only if needed.
435   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
436   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
437
438   ValueHandleBase *&Entry = Handles[VP];
439   assert(Entry == 0 && "Value really did already have handles?");
440   AddToExistingUseList(&Entry);
441   VP->HasValueHandle = true;
442
443   // If reallocation didn't happen or if this was the first insertion, don't
444   // walk the table.
445   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
446       Handles.size() == 1) {
447     return;
448   }
449
450   // Okay, reallocation did happen.  Fix the Prev Pointers.
451   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
452        E = Handles.end(); I != E; ++I) {
453     assert(I->second && I->first == I->second->VP && "List invariant broken!");
454     I->second->setPrevPtr(&I->second);
455   }
456 }
457
458 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
459 void ValueHandleBase::RemoveFromUseList() {
460   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
461
462   // Unlink this from its use list.
463   ValueHandleBase **PrevPtr = getPrevPtr();
464   assert(*PrevPtr == this && "List invariant broken");
465
466   *PrevPtr = Next;
467   if (Next) {
468     assert(Next->getPrevPtr() == &Next && "List invariant broken");
469     Next->setPrevPtr(PrevPtr);
470     return;
471   }
472
473   // If the Next pointer was null, then it is possible that this was the last
474   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
475   // map.
476   LLVMContextImpl *pImpl = VP->getContext().pImpl;
477   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
478   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
479     Handles.erase(VP);
480     VP->HasValueHandle = false;
481   }
482 }
483
484
485 void ValueHandleBase::ValueIsDeleted(Value *V) {
486   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
487
488   // Get the linked list base, which is guaranteed to exist since the
489   // HasValueHandle flag is set.
490   LLVMContextImpl *pImpl = V->getContext().pImpl;
491   ValueHandleBase *Entry = pImpl->ValueHandles[V];
492   assert(Entry && "Value bit set but no entries exist");
493
494   // We use a local ValueHandleBase as an iterator so that
495   // ValueHandles can add and remove themselves from the list without
496   // breaking our iteration.  This is not really an AssertingVH; we
497   // just have to give ValueHandleBase some kind.
498   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
499     Iterator.RemoveFromUseList();
500     Iterator.AddToExistingUseListAfter(Entry);
501     assert(Entry->Next == &Iterator && "Loop invariant broken.");
502
503     switch (Entry->getKind()) {
504     case Assert:
505       break;
506     case Tracking:
507       // Mark that this value has been deleted by setting it to an invalid Value
508       // pointer.
509       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
510       break;
511     case Weak:
512       // Weak just goes to null, which will unlink it from the list.
513       Entry->operator=(0);
514       break;
515     case Callback:
516       // Forward to the subclass's implementation.
517       static_cast<CallbackVH*>(Entry)->deleted();
518       break;
519     }
520   }
521
522   // All callbacks, weak references, and assertingVHs should be dropped by now.
523   if (V->HasValueHandle) {
524 #ifndef NDEBUG      // Only in +Asserts mode...
525     errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
526            << "\n";
527     if (pImpl->ValueHandles[V]->getKind() == Assert)
528       llvm_unreachable("An asserting value handle still pointed to this"
529                        " value!");
530
531 #endif
532     llvm_unreachable("All references to V were not removed?");
533   }
534 }
535
536
537 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
538   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
539   assert(Old != New && "Changing value into itself!");
540
541   // Get the linked list base, which is guaranteed to exist since the
542   // HasValueHandle flag is set.
543   LLVMContextImpl *pImpl = Old->getContext().pImpl;
544   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
545
546   assert(Entry && "Value bit set but no entries exist");
547
548   // We use a local ValueHandleBase as an iterator so that
549   // ValueHandles can add and remove themselves from the list without
550   // breaking our iteration.  This is not really an AssertingVH; we
551   // just have to give ValueHandleBase some kind.
552   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
553     Iterator.RemoveFromUseList();
554     Iterator.AddToExistingUseListAfter(Entry);
555     assert(Entry->Next == &Iterator && "Loop invariant broken.");
556
557     switch (Entry->getKind()) {
558     case Assert:
559       // Asserting handle does not follow RAUW implicitly.
560       break;
561     case Tracking:
562       // Tracking goes to new value like a WeakVH. Note that this may make it
563       // something incompatible with its templated type. We don't want to have a
564       // virtual (or inline) interface to handle this though, so instead we make
565       // the TrackingVH accessors guarantee that a client never sees this value.
566
567       // FALLTHROUGH
568     case Weak:
569       // Weak goes to the new value, which will unlink it from Old's list.
570       Entry->operator=(New);
571       break;
572     case Callback:
573       // Forward to the subclass's implementation.
574       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
575       break;
576     }
577   }
578 }
579
580 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
581 /// more than once.
582 CallbackVH::~CallbackVH() {}
583
584
585 //===----------------------------------------------------------------------===//
586 //                                 User Class
587 //===----------------------------------------------------------------------===//
588
589 // replaceUsesOfWith - Replaces all references to the "From" definition with
590 // references to the "To" definition.
591 //
592 void User::replaceUsesOfWith(Value *From, Value *To) {
593   if (From == To) return;   // Duh what?
594
595   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
596          "Cannot call User::replaceUsesOfWith on a constant!");
597
598   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
599     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
600       // The side effects of this setOperand call include linking to
601       // "To", adding "this" to the uses list of To, and
602       // most importantly, removing "this" from the use list of "From".
603       setOperand(i, To); // Fix it now...
604     }
605 }