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