9d6af5a334eebaabaa350b5a45793427e5dc1694
[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 "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Module.h"
21 #include "llvm/MDNode.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/Support/raw_ostream.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include <algorithm>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 //                                Value Class
38 //===----------------------------------------------------------------------===//
39
40 static inline const Type *checkType(const Type *Ty) {
41   assert(Ty && "Value defined with a null type: Error!");
42   return Ty;
43 }
44
45 Value::Value(const Type *ty, unsigned scid)
46   : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
47     SubclassData(0), VTy(checkType(ty)),
48     UseList(0), Name(0) {
49   if (isa<CallInst>(this) || isa<InvokeInst>(this))
50     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
51             isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
52            "invalid CallInst  type!");
53   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
54     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
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 (isa<MDString>(V))
146     return true;
147   else {
148     assert(isa<Constant>(V) && "Unknown value type!");
149     return true;  // no name is setable for this.
150   }
151   return false;
152 }
153
154 /// getNameStart - Return a pointer to a null terminated string for this name.
155 /// Note that names can have null characters within the string as well as at
156 /// their end.  This always returns a non-null pointer.
157 const char *Value::getNameStart() const {
158   if (Name == 0) return "";
159   return Name->getKeyData();
160 }
161
162 /// getNameLen - Return the length of the string, correctly handling nul
163 /// characters embedded into them.
164 unsigned Value::getNameLen() const {
165   return Name ? Name->getKeyLength() : 0;
166 }
167
168
169 std::string Value::getNameStr() const {
170   if (Name == 0) return "";
171   return std::string(Name->getKeyData(),
172                      Name->getKeyData()+Name->getKeyLength());
173 }
174
175 void Value::setName(const Twine &Name) {
176   SmallString<32> NameData;
177   Name.toVector(NameData);
178   setName(NameData.begin(), NameData.size());
179 }
180
181 void Value::setName(const char *Name) {
182   setName(Name, Name ? strlen(Name) : 0);
183 }
184
185 void Value::setName(const char *NameStr, unsigned NameLen) {
186   if (NameLen == 0 && !hasName()) return;
187   assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
188   
189   // Get the symbol table to update for this object.
190   ValueSymbolTable *ST;
191   if (getSymTab(this, ST))
192     return;  // Cannot set a name on this value (e.g. constant).
193
194   if (!ST) { // No symbol table to update?  Just do the change.
195     if (NameLen == 0) {
196       // Free the name for this value.
197       Name->Destroy();
198       Name = 0;
199       return;
200     }
201     
202     if (Name) {
203       // Name isn't changing?
204       if (NameLen == Name->getKeyLength() &&
205           !memcmp(Name->getKeyData(), NameStr, NameLen))
206         return;
207       Name->Destroy();
208     }
209     
210     // NOTE: Could optimize for the case the name is shrinking to not deallocate
211     // then reallocated.
212       
213     // Create the new name.
214     Name = ValueName::Create(NameStr, NameStr+NameLen);
215     Name->setValue(this);
216     return;
217   }
218   
219   // NOTE: Could optimize for the case the name is shrinking to not deallocate
220   // then reallocated.
221   if (hasName()) {
222     // Name isn't changing?
223     if (NameLen == Name->getKeyLength() &&
224         !memcmp(Name->getKeyData(), NameStr, NameLen))
225       return;
226
227     // Remove old name.
228     ST->removeValueName(Name);
229     Name->Destroy();
230     Name = 0;
231
232     if (NameLen == 0)
233       return;
234   }
235
236   // Name is changing to something new.
237   Name = ST->createValueName(StringRef(NameStr, NameLen), this);
238 }
239
240
241 /// takeName - transfer the name from V to this value, setting V's name to
242 /// empty.  It is an error to call V->takeName(V). 
243 void Value::takeName(Value *V) {
244   ValueSymbolTable *ST = 0;
245   // If this value has a name, drop it.
246   if (hasName()) {
247     // Get the symtab this is in.
248     if (getSymTab(this, ST)) {
249       // We can't set a name on this value, but we need to clear V's name if
250       // it has one.
251       if (V->hasName()) V->setName(0, 0);
252       return;  // Cannot set a name on this value (e.g. constant).
253     }
254     
255     // Remove old name.
256     if (ST)
257       ST->removeValueName(Name);
258     Name->Destroy();
259     Name = 0;
260   } 
261   
262   // Now we know that this has no name.
263   
264   // If V has no name either, we're done.
265   if (!V->hasName()) return;
266    
267   // Get this's symtab if we didn't before.
268   if (!ST) {
269     if (getSymTab(this, ST)) {
270       // Clear V's name.
271       V->setName(0, 0);
272       return;  // Cannot set a name on this value (e.g. constant).
273     }
274   }
275   
276   // Get V's ST, this should always succed, because V has a name.
277   ValueSymbolTable *VST;
278   bool Failure = getSymTab(V, VST);
279   assert(!Failure && "V has a name, so it should have a ST!"); Failure=Failure;
280   
281   // If these values are both in the same symtab, we can do this very fast.
282   // This works even if both values have no symtab yet.
283   if (ST == VST) {
284     // Take the name!
285     Name = V->Name;
286     V->Name = 0;
287     Name->setValue(this);
288     return;
289   }
290   
291   // Otherwise, things are slightly more complex.  Remove V's name from VST and
292   // then reinsert it into ST.
293   
294   if (VST)
295     VST->removeValueName(V->Name);
296   Name = V->Name;
297   V->Name = 0;
298   Name->setValue(this);
299   
300   if (ST)
301     ST->reinsertValue(this);
302 }
303
304
305 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
306 // except that it doesn't have all of the asserts.  The asserts fail because we
307 // are half-way done resolving types, which causes some types to exist as two
308 // different Type*'s at the same time.  This is a sledgehammer to work around
309 // this problem.
310 //
311 void Value::uncheckedReplaceAllUsesWith(Value *New) {
312   // Notify all ValueHandles (if present) that this value is going away.
313   if (HasValueHandle)
314     ValueHandleBase::ValueIsRAUWd(this, New);
315  
316   while (!use_empty()) {
317     Use &U = *UseList;
318     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
319     // constant because they are uniqued.
320     if (Constant *C = dyn_cast<Constant>(U.getUser())) {
321       if (!isa<GlobalValue>(C)) {
322         C->replaceUsesOfWithOnConstant(this, New, &U);
323         continue;
324       }
325     }
326     
327     U.set(New);
328   }
329 }
330
331 void Value::replaceAllUsesWith(Value *New) {
332   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
333   assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
334   assert(New->getType() == getType() &&
335          "replaceAllUses of value with new value of different type!");
336
337   uncheckedReplaceAllUsesWith(New);
338 }
339
340 Value *Value::stripPointerCasts() {
341   if (!isa<PointerType>(getType()))
342     return this;
343   Value *V = this;
344   do {
345     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
346       if (!GEP->hasAllZeroIndices())
347         return V;
348       V = GEP->getPointerOperand();
349     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
350       V = cast<Operator>(V)->getOperand(0);
351     } else {
352       return V;
353     }
354     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
355   } while (1);
356 }
357
358 Value *Value::getUnderlyingObject() {
359   if (!isa<PointerType>(getType()))
360     return this;
361   Value *V = this;
362   unsigned MaxLookup = 6;
363   do {
364     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
365       V = GEP->getPointerOperand();
366     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
367       V = cast<Operator>(V)->getOperand(0);
368     } else {
369       return V;
370     }
371     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
372   } while (--MaxLookup);
373   return V;
374 }
375
376 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
377 /// return the value in the PHI node corresponding to PredBB.  If not, return
378 /// ourself.  This is useful if you want to know the value something has in a
379 /// predecessor block.
380 Value *Value::DoPHITranslation(const BasicBlock *CurBB, 
381                                const BasicBlock *PredBB) {
382   PHINode *PN = dyn_cast<PHINode>(this);
383   if (PN && PN->getParent() == CurBB)
384     return PN->getIncomingValueForBlock(PredBB);
385   return this;
386 }
387
388 LLVMContext &Value::getContext() const { return VTy->getContext(); }
389
390 //===----------------------------------------------------------------------===//
391 //                             ValueHandleBase Class
392 //===----------------------------------------------------------------------===//
393
394 /// ValueHandles - This map keeps track of all of the value handles that are
395 /// watching a Value*.  The Value::HasValueHandle bit is used to know whether or
396 /// not a value has an entry in this map.
397 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
398 static ManagedStatic<ValueHandlesTy> ValueHandles;
399 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
400
401 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
402 /// List is known to point into the existing use list.
403 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
404   assert(List && "Handle list is null?");
405   
406   // Splice ourselves into the list.
407   Next = *List;
408   *List = this;
409   setPrevPtr(List);
410   if (Next) {
411     Next->setPrevPtr(&Next);
412     assert(VP == Next->VP && "Added to wrong list?");
413   }
414 }
415
416 /// AddToUseList - Add this ValueHandle to the use list for VP.
417 void ValueHandleBase::AddToUseList() {
418   assert(VP && "Null pointer doesn't have a use list!");
419   if (VP->HasValueHandle) {
420     // If this value already has a ValueHandle, then it must be in the
421     // ValueHandles map already.
422     sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
423     ValueHandleBase *&Entry = (*ValueHandles)[VP];
424     assert(Entry != 0 && "Value doesn't have any handles?");
425     AddToExistingUseList(&Entry);
426     return;
427   }
428   
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   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
435   ValueHandlesTy &Handles = *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 (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
452        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   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
477   ValueHandlesTy &Handles = *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   ValueHandlesLock->reader_acquire();
491   ValueHandleBase *Entry = (*ValueHandles)[V];
492   ValueHandlesLock->reader_release();
493   assert(Entry && "Value bit set but no entries exist");
494   
495   while (Entry) {
496     // Advance pointer to avoid invalidation.
497     ValueHandleBase *ThisNode = Entry;
498     Entry = Entry->Next;
499     
500     switch (ThisNode->getKind()) {
501     case Assert:
502 #ifndef NDEBUG      // Only in -g mode...
503       errs() << "While deleting: " << *V->getType() << " %" << V->getNameStr()
504              << "\n";
505 #endif
506       llvm_unreachable("An asserting value handle still pointed to this"
507                        " value!");
508     case Weak:
509       // Weak just goes to null, which will unlink it from the list.
510       ThisNode->operator=(0);
511       break;
512     case Callback:
513       // Forward to the subclass's implementation.
514       static_cast<CallbackVH*>(ThisNode)->deleted();
515       break;
516     }
517   }
518   
519   // All callbacks and weak references should be dropped by now.
520   assert(!V->HasValueHandle && "All references to V were not removed?");
521 }
522
523
524 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
525   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
526   assert(Old != New && "Changing value into itself!");
527   
528   // Get the linked list base, which is guaranteed to exist since the
529   // HasValueHandle flag is set.
530   ValueHandlesLock->reader_acquire();
531   ValueHandleBase *Entry = (*ValueHandles)[Old];
532   ValueHandlesLock->reader_release();
533   assert(Entry && "Value bit set but no entries exist");
534   
535   while (Entry) {
536     // Advance pointer to avoid invalidation.
537     ValueHandleBase *ThisNode = Entry;
538     Entry = Entry->Next;
539     
540     switch (ThisNode->getKind()) {
541     case Assert:
542       // Asserting handle does not follow RAUW implicitly.
543       break;
544     case Weak:
545       // Weak goes to the new value, which will unlink it from Old's list.
546       ThisNode->operator=(New);
547       break;
548     case Callback:
549       // Forward to the subclass's implementation.
550       static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
551       break;
552     }
553   }
554 }
555
556 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
557 /// more than once.
558 CallbackVH::~CallbackVH() {}
559
560
561 //===----------------------------------------------------------------------===//
562 //                                 User Class
563 //===----------------------------------------------------------------------===//
564
565 // replaceUsesOfWith - Replaces all references to the "From" definition with
566 // references to the "To" definition.
567 //
568 void User::replaceUsesOfWith(Value *From, Value *To) {
569   if (From == To) return;   // Duh what?
570
571   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
572          "Cannot call User::replaceUsesofWith on a constant!");
573
574   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
575     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
576       // The side effects of this setOperand call include linking to
577       // "To", adding "this" to the uses list of To, and
578       // most importantly, removing "this" from the use list of "From".
579       setOperand(i, To); // Fix it now...
580     }
581 }