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