GetElementPtr instructions default to having no overflow.
[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/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LeakDetector.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/RWMutex.h"
28 #include "llvm/System/Threading.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), SubclassOptionalData(0),
44     SubclassData(0), VTy(checkType(ty)),
45     UseList(0), Name(0) {
46   if (isa<CallInst>(this) || isa<InvokeInst>(this))
47     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
48             isa<OpaqueType>(ty) || VTy->getTypeID() == Type::StructTyID) &&
49            "invalid CallInst  type!");
50   else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
51     assert((VTy->isFirstClassType() || VTy == Type::VoidTy ||
52            isa<OpaqueType>(ty)) &&
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     cerr << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
70     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
71       cerr << "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   use_const_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   use_const_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 (use_const_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 {
143     assert(isa<Constant>(V) && "Unknown value type!");
144     return true;  // no name is setable for this.
145   }
146   return false;
147 }
148
149 /// getNameStart - Return a pointer to a null terminated string for this name.
150 /// Note that names can have null characters within the string as well as at
151 /// their end.  This always returns a non-null pointer.
152 const char *Value::getNameStart() const {
153   if (Name == 0) return "";
154   return Name->getKeyData();
155 }
156
157 /// getNameLen - Return the length of the string, correctly handling nul
158 /// characters embedded into them.
159 unsigned Value::getNameLen() const {
160   return Name ? Name->getKeyLength() : 0;
161 }
162
163 /// isName - Return true if this value has the name specified by the provided
164 /// nul terminated string.
165 bool Value::isName(const char *N) const {
166   unsigned InLen = strlen(N);
167   return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
168 }
169
170
171 std::string Value::getNameStr() const {
172   if (Name == 0) return "";
173   return std::string(Name->getKeyData(),
174                      Name->getKeyData()+Name->getKeyLength());
175 }
176
177 void Value::setName(const std::string &name) {
178   setName(&name[0], name.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(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 (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
346       if (CE->getOpcode() == Instruction::GetElementPtr) {
347         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
348           if (!CE->getOperand(i)->isNullValue())
349             return V;
350         V = CE->getOperand(0);
351       } else if (CE->getOpcode() == Instruction::BitCast) {
352         V = CE->getOperand(0);
353       } else {
354         return V;
355       }
356     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
357       if (!GEP->hasAllZeroIndices())
358         return V;
359       V = GEP->getOperand(0);
360     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(V)) {
361       V = CI->getOperand(0);
362     } else {
363       return V;
364     }
365     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
366   } while (1);
367 }
368
369 Value *Value::getUnderlyingObject() {
370   if (!isa<PointerType>(getType()))
371     return this;
372   Value *V = this;
373   unsigned MaxLookup = 6;
374   do {
375     if (Instruction *I = dyn_cast<Instruction>(V)) {
376       if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
377         return V;
378       V = I->getOperand(0);
379     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
380       if (CE->getOpcode() != Instruction::BitCast &&
381           CE->getOpcode() != Instruction::GetElementPtr)
382         return V;
383       V = CE->getOperand(0);
384     } else {
385       return V;
386     }
387     assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
388   } while (--MaxLookup);
389   return V;
390 }
391
392 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
393 /// return the value in the PHI node corresponding to PredBB.  If not, return
394 /// ourself.  This is useful if you want to know the value something has in a
395 /// predecessor block.
396 Value *Value::DoPHITranslation(const BasicBlock *CurBB, 
397                                const BasicBlock *PredBB) {
398   PHINode *PN = dyn_cast<PHINode>(this);
399   if (PN && PN->getParent() == CurBB)
400     return PN->getIncomingValueForBlock(PredBB);
401   return this;
402 }
403
404 //===----------------------------------------------------------------------===//
405 //                             ValueHandleBase Class
406 //===----------------------------------------------------------------------===//
407
408 /// ValueHandles - This map keeps track of all of the value handles that are
409 /// watching a Value*.  The Value::HasValueHandle bit is used to know whether or
410 /// not a value has an entry in this map.
411 typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
412 static ManagedStatic<ValueHandlesTy> ValueHandles;
413 static ManagedStatic<sys::SmartRWMutex<true> > ValueHandlesLock;
414
415 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
416 /// List is known to point into the existing use list.
417 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
418   assert(List && "Handle list is null?");
419   
420   // Splice ourselves into the list.
421   Next = *List;
422   *List = this;
423   setPrevPtr(List);
424   if (Next) {
425     Next->setPrevPtr(&Next);
426     assert(VP == Next->VP && "Added to wrong list?");
427   }
428 }
429
430 /// AddToUseList - Add this ValueHandle to the use list for VP.
431 void ValueHandleBase::AddToUseList() {
432   assert(VP && "Null pointer doesn't have a use list!");
433   if (VP->HasValueHandle) {
434     // If this value already has a ValueHandle, then it must be in the
435     // ValueHandles map already.
436     sys::SmartScopedReader<true> Reader(*ValueHandlesLock);
437     ValueHandleBase *&Entry = (*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   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
449   ValueHandlesTy &Handles = *ValueHandles;
450   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
451   
452   ValueHandleBase *&Entry = Handles[VP];
453   assert(Entry == 0 && "Value really did already have handles?");
454   AddToExistingUseList(&Entry);
455   VP->HasValueHandle = true;
456   
457   // If reallocation didn't happen or if this was the first insertion, don't
458   // walk the table.
459   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 
460       Handles.size() == 1) {
461     return;
462   }
463   
464   // Okay, reallocation did happen.  Fix the Prev Pointers.
465   for (ValueHandlesTy::iterator I = Handles.begin(), E = Handles.end();
466        I != E; ++I) {
467     assert(I->second && I->first == I->second->VP && "List invariant broken!");
468     I->second->setPrevPtr(&I->second);
469   }
470 }
471
472 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
473 void ValueHandleBase::RemoveFromUseList() {
474   assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
475
476   // Unlink this from its use list.
477   ValueHandleBase **PrevPtr = getPrevPtr();
478   assert(*PrevPtr == this && "List invariant broken");
479   
480   *PrevPtr = Next;
481   if (Next) {
482     assert(Next->getPrevPtr() == &Next && "List invariant broken");
483     Next->setPrevPtr(PrevPtr);
484     return;
485   }
486   
487   // If the Next pointer was null, then it is possible that this was the last
488   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
489   // map.
490   sys::SmartScopedWriter<true> Writer(*ValueHandlesLock);
491   ValueHandlesTy &Handles = *ValueHandles;
492   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
493     Handles.erase(VP);
494     VP->HasValueHandle = false;
495   }
496 }
497
498
499 void ValueHandleBase::ValueIsDeleted(Value *V) {
500   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
501
502   // Get the linked list base, which is guaranteed to exist since the
503   // HasValueHandle flag is set.
504   ValueHandlesLock->reader_acquire();
505   ValueHandleBase *Entry = (*ValueHandles)[V];
506   ValueHandlesLock->reader_release();
507   assert(Entry && "Value bit set but no entries exist");
508   
509   while (Entry) {
510     // Advance pointer to avoid invalidation.
511     ValueHandleBase *ThisNode = Entry;
512     Entry = Entry->Next;
513     
514     switch (ThisNode->getKind()) {
515     case Assert:
516 #ifndef NDEBUG      // Only in -g mode...
517       cerr << "While deleting: " << *V->getType() << " %" << V->getNameStr()
518            << "\n";
519 #endif
520       llvm_unreachable("An asserting value handle still pointed to this"
521                        " value!");
522     case Weak:
523       // Weak just goes to null, which will unlink it from the list.
524       ThisNode->operator=(0);
525       break;
526     case Callback:
527       // Forward to the subclass's implementation.
528       static_cast<CallbackVH*>(ThisNode)->deleted();
529       break;
530     }
531   }
532   
533   // All callbacks and weak references should be dropped by now.
534   assert(!V->HasValueHandle && "All references to V were not removed?");
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   ValueHandlesLock->reader_acquire();
545   ValueHandleBase *Entry = (*ValueHandles)[Old];
546   ValueHandlesLock->reader_release();
547   assert(Entry && "Value bit set but no entries exist");
548   
549   while (Entry) {
550     // Advance pointer to avoid invalidation.
551     ValueHandleBase *ThisNode = Entry;
552     Entry = Entry->Next;
553     
554     switch (ThisNode->getKind()) {
555     case Assert:
556       // Asserting handle does not follow RAUW implicitly.
557       break;
558     case Weak:
559       // Weak goes to the new value, which will unlink it from Old's list.
560       ThisNode->operator=(New);
561       break;
562     case Callback:
563       // Forward to the subclass's implementation.
564       static_cast<CallbackVH*>(ThisNode)->allUsesReplacedWith(New);
565       break;
566     }
567   }
568 }
569
570 /// ~CallbackVH. Empty, but defined here to avoid emitting the vtable
571 /// more than once.
572 CallbackVH::~CallbackVH() {}
573
574
575 //===----------------------------------------------------------------------===//
576 //                                 User Class
577 //===----------------------------------------------------------------------===//
578
579 // replaceUsesOfWith - Replaces all references to the "From" definition with
580 // references to the "To" definition.
581 //
582 void User::replaceUsesOfWith(Value *From, Value *To) {
583   if (From == To) return;   // Duh what?
584
585   assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
586          "Cannot call User::replaceUsesofWith on a constant!");
587
588   for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
589     if (getOperand(i) == From) {  // Is This operand is pointing to oldval?
590       // The side effects of this setOperand call include linking to
591       // "To", adding "this" to the uses list of To, and
592       // most importantly, removing "this" from the use list of "From".
593       setOperand(i, To); // Fix it now...
594     }
595 }