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