Copy metadata when value is RAUW'd. It is debatable whether this is the right approac...
[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/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"
34 #include <algorithm>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                                Value Class
39 //===----------------------------------------------------------------------===//
40
41 static inline const Type *checkType(const Type *Ty) {
42   assert(Ty && "Value defined with a null type: Error!");
43   return Ty;
44 }
45
46 Value::Value(const Type *ty, unsigned scid)
47   : SubclassID(scid), HasValueHandle(0), HasMetadata(0),
48     SubclassOptionalData(0), SubclassData(0), VTy(checkType(ty)),
49     UseList(0), Name(0) {
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!");
60 }
61
62 Value::~Value() {
63   if (HasMetadata) {
64     LLVMContext &Context = getContext();
65     Context.pImpl->TheMetadata.ValueIsDeleted(this);
66   }
67
68   // Notify all ValueHandles (if present) that this value is going away.
69   if (HasValueHandle)
70     ValueHandleBase::ValueIsDeleted(this);
71
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
77   // a <badref>
78   //
79   if (!use_empty()) {
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:"
83            << **I << "\n";
84   }
85 #endif
86   assert(use_empty() && "Uses remain when a value is destroyed!");
87
88   // If this value is named, destroy the name.  This should not be in a symtab
89   // at this point.
90   if (Name)
91     Name->Destroy();
92
93   // There should be no uses of this object anymore, remove it.
94   LeakDetector::removeGarbageObject(this);
95 }
96
97 /// hasNUses - Return true if this Value has exactly N users.
98 ///
99 bool Value::hasNUses(unsigned N) const {
100   use_const_iterator UI = use_begin(), E = use_end();
101
102   for (; N; --N, ++UI)
103     if (UI == E) return false;  // Too few.
104   return UI == E;
105 }
106
107 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
108 /// logically equivalent to getNumUses() >= N.
109 ///
110 bool Value::hasNUsesOrMore(unsigned N) const {
111   use_const_iterator UI = use_begin(), E = use_end();
112
113   for (; N; --N, ++UI)
114     if (UI == E) return false;  // Too few.
115
116   return true;
117 }
118
119 /// isUsedInBasicBlock - Return true if this value is used in the specified
120 /// basic block.
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)
125       return true;
126   }
127   return false;
128 }
129
130
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
133 /// values.
134 unsigned Value::getNumUses() const {
135   return (unsigned)std::distance(use_begin(), use_end());
136 }
137
138 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
139   ST = 0;
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();
156     }
157   } else if (isa<MDString>(V))
158     return true;
159   else {
160     assert(isa<Constant>(V) && "Unknown value type!");
161     return true;  // no name is setable for this.
162   }
163   return false;
164 }
165
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
169   // terminated.
170   if (!Name) return StringRef("", 0);
171   return Name->getKey();
172 }
173
174 std::string Value::getNameStr() const {
175   return getName().str();
176 }
177
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())
181     return;
182
183   SmallString<256> NameData;
184   NewName.toVector(NameData);
185
186   const char *NameStr = NameData.data();
187   unsigned NameLen = NameData.size();
188
189   // Name isn't changing?
190   if (getName() == StringRef(NameStr, NameLen))
191     return;
192
193   assert(getType() != Type::getVoidTy(getContext()) &&
194          "Cannot assign a name to void values!");
195
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).
200
201   if (!ST) { // No symbol table to update?  Just do the change.
202     if (NameLen == 0) {
203       // Free the name for this value.
204       Name->Destroy();
205       Name = 0;
206       return;
207     }
208
209     if (Name)
210       Name->Destroy();
211
212     // NOTE: Could optimize for the case the name is shrinking to not deallocate
213     // then reallocated.
214
215     // Create the new name.
216     Name = ValueName::Create(NameStr, NameStr+NameLen);
217     Name->setValue(this);
218     return;
219   }
220
221   // NOTE: Could optimize for the case the name is shrinking to not deallocate
222   // then reallocated.
223   if (hasName()) {
224     // Remove old name.
225     ST->removeValueName(Name);
226     Name->Destroy();
227     Name = 0;
228
229     if (NameLen == 0)
230       return;
231   }
232
233   // Name is changing to something new.
234   Name = ST->createValueName(StringRef(NameStr, NameLen), this);
235 }
236
237
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.
243   if (hasName()) {
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
247       // it has one.
248       if (V->hasName()) V->setName("");
249       return;  // Cannot set a name on this value (e.g. constant).
250     }
251
252     // Remove old name.
253     if (ST)
254       ST->removeValueName(Name);
255     Name->Destroy();
256     Name = 0;
257   }
258
259   // Now we know that this has no name.
260
261   // If V has no name either, we're done.
262   if (!V->hasName()) return;
263
264   // Get this's symtab if we didn't before.
265   if (!ST) {
266     if (getSymTab(this, ST)) {
267       // Clear V's name.
268       V->setName("");
269       return;  // Cannot set a name on this value (e.g. constant).
270     }
271   }
272
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;
277
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.
280   if (ST == VST) {
281     // Take the name!
282     Name = V->Name;
283     V->Name = 0;
284     Name->setValue(this);
285     return;
286   }
287
288   // Otherwise, things are slightly more complex.  Remove V's name from VST and
289   // then reinsert it into ST.
290
291   if (VST)
292     VST->removeValueName(V->Name);
293   Name = V->Name;
294   V->Name = 0;
295   Name->setValue(this);
296
297   if (ST)
298     ST->reinsertValue(this);
299 }
300
301
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
306 // this problem.
307 //
308 void Value::uncheckedReplaceAllUsesWith(Value *New) {
309   // Notify all ValueHandles (if present) that this value is going away.
310   if (HasValueHandle)
311     ValueHandleBase::ValueIsRAUWd(this, New);
312   if (HasMetadata) {
313     LLVMContext &Context = getContext();
314     Context.pImpl->TheMetadata.ValueIsRAUWd(this, New);
315   }
316
317   while (!use_empty()) {
318     Use &U = *UseList;
319     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
320     // constant because they are uniqued.
321     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
322       if (!isa<GlobalValue>(C)) {
323         C->replaceUsesOfWithOnConstant(this, New, &U);
324         continue;
325       }
326     }
327
328     U.set(New);
329   }
330 }
331
332 void Value::replaceAllUsesWith(Value *New) {
333   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
334   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
335   assert(New->getType() == getType() &&
336          "replaceAllUses of value with new value of different type!");
337
338   uncheckedReplaceAllUsesWith(New);
339 }
340
341 Value *Value::stripPointerCasts() {
342   if (!isa<PointerType>(getType()))
343     return this;
344   Value *V = this;
345   do {
346     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
347       if (!GEP->hasAllZeroIndices())
348         return V;
349       V = GEP->getPointerOperand();
350     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
351       V = cast<Operator>(V)->getOperand(0);
352     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
353       if (GA->mayBeOverridden())
354         return V;
355       V = GA->getAliasee();
356     } else {
357       return V;
358     }
359     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
360   } while (1);
361 }
362
363 Value *Value::getUnderlyingObject() {
364   if (!isa<PointerType>(getType()))
365     return this;
366   Value *V = this;
367   unsigned MaxLookup = 6;
368   do {
369     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
370       V = GEP->getPointerOperand();
371     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
372       V = cast<Operator>(V)->getOperand(0);
373     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
374       if (GA->mayBeOverridden())
375         return V;
376       V = GA->getAliasee();
377     } else {
378       return V;
379     }
380     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
381   } while (--MaxLookup);
382   return V;
383 }
384
385 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
386 /// return the value in the PHI node corresponding to PredBB.  If not, return
387 /// ourself.  This is useful if you want to know the value something has in a
388 /// predecessor block.
389 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
390                                const BasicBlock *PredBB) {
391   PHINode *PN = dyn_cast<PHINode>(this);
392   if (PN && PN->getParent() == CurBB)
393     return PN->getIncomingValueForBlock(PredBB);
394   return this;
395 }
396
397 LLVMContext &Value::getContext() const { return VTy->getContext(); }
398
399 //===----------------------------------------------------------------------===//
400 //                             ValueHandleBase Class
401 //===----------------------------------------------------------------------===//
402
403 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
404 /// List is known to point into the existing use list.
405 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
406   assert(List && "Handle list is null?");
407
408   // Splice ourselves into the list.
409   Next = *List;
410   *List = this;
411   setPrevPtr(List);
412   if (Next) {
413     Next->setPrevPtr(&Next);
414     assert(VP == Next->VP && "Added to wrong list?");
415   }
416 }
417
418 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
419   assert(List && "Must insert after existing node");
420
421   Next = List->Next;
422   setPrevPtr(&List->Next);
423   List->Next = this;
424   if (Next)
425     Next->setPrevPtr(&Next);
426 }
427
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
432   LLVMContextImpl *pImpl = VP->getContext().pImpl;
433
434   if (VP->HasValueHandle) {
435     // If this value already has a ValueHandle, then it must be in the
436     // ValueHandles map already.
437     ValueHandleBase *&Entry = pImpl->ValueHandles[VP];
438     assert(Entry != 0 && "Value doesn't have any handles?");
439     AddToExistingUseList(&Entry);
440     return;
441   }
442
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   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
449   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
450
451   ValueHandleBase *&Entry = Handles[VP];
452   assert(Entry == 0 && "Value really did already have handles?");
453   AddToExistingUseList(&Entry);
454   VP->HasValueHandle = true;
455
456   // If reallocation didn't happen or if this was the first insertion, don't
457   // walk the table.
458   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
459       Handles.size() == 1) {
460     return;
461   }
462
463   // Okay, reallocation did happen.  Fix the Prev Pointers.
464   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
465        E = Handles.end(); I != E; ++I) {
466     assert(I->second && I->first == I->second->VP && "List invariant broken!");
467     I->second->setPrevPtr(&I->second);
468   }
469 }
470
471 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
472 void ValueHandleBase::RemoveFromUseList() {
473   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
474
475   // Unlink this from its use list.
476   ValueHandleBase **PrevPtr = getPrevPtr();
477   assert(*PrevPtr == this && "List invariant broken");
478
479   *PrevPtr = Next;
480   if (Next) {
481     assert(Next->getPrevPtr() == &Next && "List invariant broken");
482     Next->setPrevPtr(PrevPtr);
483     return;
484   }
485
486   // If the Next pointer was null, then it is possible that this was the last
487   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
488   // map.
489   LLVMContextImpl *pImpl = VP->getContext().pImpl;
490   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
491   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
492     Handles.erase(VP);
493     VP->HasValueHandle = false;
494   }
495 }
496
497
498 void ValueHandleBase::ValueIsDeleted(Value *V) {
499   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
500
501   // Get the linked list base, which is guaranteed to exist since the
502   // HasValueHandle flag is set.
503   LLVMContextImpl *pImpl = V->getContext().pImpl;
504   ValueHandleBase *Entry = pImpl->ValueHandles[V];
505   assert(Entry && "Value bit set but no entries exist");
506
507   // We use a local ValueHandleBase as an iterator so that
508   // ValueHandles can add and remove themselves from the list without
509   // breaking our iteration.  This is not really an AssertingVH; we
510   // just have to give ValueHandleBase some kind.
511   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
512     Iterator.RemoveFromUseList();
513     Iterator.AddToExistingUseListAfter(Entry);
514     assert(Entry->Next == &Iterator && "Loop invariant broken.");
515
516     switch (Entry->getKind()) {
517     case Assert:
518       break;
519     case Tracking:
520       // Mark that this value has been deleted by setting it to an invalid Value
521       // pointer.
522       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
523       break;
524     case Weak:
525       // Weak just goes to null, which will unlink it from the list.
526       Entry->operator=(0);
527       break;
528     case Callback:
529       // Forward to the subclass's implementation.
530       static_cast<CallbackVH*>(Entry)->deleted();
531       break;
532     }
533   }
534
535   // All callbacks, weak references, and assertingVHs should be dropped by now.
536   if (V->HasValueHandle) {
537 #ifndef NDEBUG      // Only in +Asserts mode...
538     errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
539            << "\n";
540     if (pImpl->ValueHandles[V]->getKind() == Assert)
541       llvm_unreachable("An asserting value handle still pointed to this"
542                        " value!");
543
544 #endif
545     llvm_unreachable("All references to V were not removed?");
546   }
547 }
548
549
550 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
551   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
552   assert(Old != New && "Changing value into itself!");
553
554   // Get the linked list base, which is guaranteed to exist since the
555   // HasValueHandle flag is set.
556   LLVMContextImpl *pImpl = Old->getContext().pImpl;
557   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
558
559   assert(Entry && "Value bit set but no entries exist");
560
561   // We use a local ValueHandleBase as an iterator so that
562   // ValueHandles can add and remove themselves from the list without
563   // breaking our iteration.  This is not really an AssertingVH; we
564   // just have to give ValueHandleBase some kind.
565   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
566     Iterator.RemoveFromUseList();
567     Iterator.AddToExistingUseListAfter(Entry);
568     assert(Entry->Next == &Iterator && "Loop invariant broken.");
569
570     switch (Entry->getKind()) {
571     case Assert:
572       // Asserting handle does not follow RAUW implicitly.
573       break;
574     case Tracking:
575       // Tracking goes to new value like a WeakVH. Note that this may make it
576       // something incompatible with its templated type. We don't want to have a
577       // virtual (or inline) interface to handle this though, so instead we make
578       // the TrackingVH accessors guarantee that a client never sees this value.
579
580       // FALLTHROUGH
581     case Weak:
582       // Weak goes to the new value, which will unlink it from Old's list.
583       Entry->operator=(New);
584       break;
585     case Callback:
586       // Forward to the subclass's implementation.
587       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
588       break;
589     }
590   }
591 }
592
593 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
594 /// more than once.
595 CallbackVH::~CallbackVH() {}
596
597
598 //===----------------------------------------------------------------------===//
599 //                                 User Class
600 //===----------------------------------------------------------------------===//
601
602 // replaceUsesOfWith - Replaces all references to the "From" definition with
603 // references to the "To" definition.
604 //
605 void User::replaceUsesOfWith(Value *From, Value *To) {
606   if (From == To) return;   // Duh what?
607
608   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
609          "Cannot call User::replaceUsesOfWith on a constant!");
610
611   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
612     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
613       // The side effects of this setOperand call include linking to
614       // "To", adding "this" to the uses list of To, and
615       // most importantly, removing "this" from the use list of "From".
616       setOperand(i, To); // Fix it now...
617     }
618 }