Move a few more APIs back to 2.5 forms. The only remaining ones left to change back are
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
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 all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //                            CallSite Class
28 //===----------------------------------------------------------------------===//
29
30 #define CALLSITE_DELEGATE_GETTER(METHOD) \
31   Instruction *II(getInstruction());     \
32   return isCall()                        \
33     ? cast<CallInst>(II)->METHOD         \
34     : cast<InvokeInst>(II)->METHOD
35
36 #define CALLSITE_DELEGATE_SETTER(METHOD) \
37   Instruction *II(getInstruction());     \
38   if (isCall())                          \
39     cast<CallInst>(II)->METHOD;          \
40   else                                   \
41     cast<InvokeInst>(II)->METHOD
42
43 CallSite::CallSite(Instruction *C) {
44   assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
45   I.setPointer(C);
46   I.setInt(isa<CallInst>(C));
47 }
48 unsigned CallSite::getCallingConv() const {
49   CALLSITE_DELEGATE_GETTER(getCallingConv());
50 }
51 void CallSite::setCallingConv(unsigned CC) {
52   CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
53 }
54 const AttrListPtr &CallSite::getAttributes() const {
55   CALLSITE_DELEGATE_GETTER(getAttributes());
56 }
57 void CallSite::setAttributes(const AttrListPtr &PAL) {
58   CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
59 }
60 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
61   CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
62 }
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64   CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
65 }
66 bool CallSite::doesNotAccessMemory() const {
67   CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
68 }
69 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
70   CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
71 }
72 bool CallSite::onlyReadsMemory() const {
73   CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
74 }
75 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
76   CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
77 }
78 bool CallSite::doesNotReturn() const {
79  CALLSITE_DELEGATE_GETTER(doesNotReturn());
80 }
81 void CallSite::setDoesNotReturn(bool doesNotReturn) {
82   CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
83 }
84 bool CallSite::doesNotThrow() const {
85   CALLSITE_DELEGATE_GETTER(doesNotThrow());
86 }
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88   CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
89 }
90
91 bool CallSite::hasArgument(const Value *Arg) const {
92   for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
93     if (AI->get() == Arg)
94       return true;
95   return false;
96 }
97
98 #undef CALLSITE_DELEGATE_GETTER
99 #undef CALLSITE_DELEGATE_SETTER
100
101 //===----------------------------------------------------------------------===//
102 //                            TerminatorInst Class
103 //===----------------------------------------------------------------------===//
104
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
107 }
108
109 //===----------------------------------------------------------------------===//
110 //                           UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
112
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
115 }
116
117 //===----------------------------------------------------------------------===//
118 //                              SelectInst Class
119 //===----------------------------------------------------------------------===//
120
121 /// areInvalidOperands - Return a string if the specified operands are invalid
122 /// for a select operation, otherwise return null.
123 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
124   if (Op1->getType() != Op2->getType())
125     return "both values to select must have same type";
126   
127   if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
128     // Vector select.
129     if (VT->getElementType() != Type::Int1Ty)
130       return "vector select condition element type must be i1";
131     const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
132     if (ET == 0)
133       return "selected values for vector select must be vectors";
134     if (ET->getNumElements() != VT->getNumElements())
135       return "vector select requires selected vectors to have "
136                    "the same vector length as select condition";
137   } else if (Op0->getType() != Type::Int1Ty) {
138     return "select condition must be i1 or <n x i1>";
139   }
140   return 0;
141 }
142
143
144 //===----------------------------------------------------------------------===//
145 //                               PHINode Class
146 //===----------------------------------------------------------------------===//
147
148 PHINode::PHINode(const PHINode &PN)
149   : Instruction(PN.getType(), Instruction::PHI,
150                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
151     ReservedSpace(PN.getNumOperands()) {
152   Use *OL = OperandList;
153   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
154     OL[i] = PN.getOperand(i);
155     OL[i+1] = PN.getOperand(i+1);
156   }
157 }
158
159 PHINode::~PHINode() {
160   if (OperandList)
161     dropHungoffUses(OperandList);
162 }
163
164 // removeIncomingValue - Remove an incoming value.  This is useful if a
165 // predecessor basic block is deleted.
166 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
167   unsigned NumOps = getNumOperands();
168   Use *OL = OperandList;
169   assert(Idx*2 < NumOps && "BB not in PHI node!");
170   Value *Removed = OL[Idx*2];
171
172   // Move everything after this operand down.
173   //
174   // FIXME: we could just swap with the end of the list, then erase.  However,
175   // client might not expect this to happen.  The code as it is thrashes the
176   // use/def lists, which is kinda lame.
177   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
178     OL[i-2] = OL[i];
179     OL[i-2+1] = OL[i+1];
180   }
181
182   // Nuke the last value.
183   OL[NumOps-2].set(0);
184   OL[NumOps-2+1].set(0);
185   NumOperands = NumOps-2;
186
187   // If the PHI node is dead, because it has zero entries, nuke it now.
188   if (NumOps == 2 && DeletePHIIfEmpty) {
189     // If anyone is using this PHI, make them use a dummy value instead...
190     replaceAllUsesWith(UndefValue::get(getType()));
191     eraseFromParent();
192   }
193   return Removed;
194 }
195
196 /// resizeOperands - resize operands - This adjusts the length of the operands
197 /// list according to the following behavior:
198 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
199 ///      of operation.  This grows the number of ops by 1.5 times.
200 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
201 ///   3. If NumOps == NumOperands, trim the reserved space.
202 ///
203 void PHINode::resizeOperands(unsigned NumOps) {
204   unsigned e = getNumOperands();
205   if (NumOps == 0) {
206     NumOps = e*3/2;
207     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
208   } else if (NumOps*2 > NumOperands) {
209     // No resize needed.
210     if (ReservedSpace >= NumOps) return;
211   } else if (NumOps == NumOperands) {
212     if (ReservedSpace == NumOps) return;
213   } else {
214     return;
215   }
216
217   ReservedSpace = NumOps;
218   Use *OldOps = OperandList;
219   Use *NewOps = allocHungoffUses(NumOps);
220   std::copy(OldOps, OldOps + e, NewOps);
221   OperandList = NewOps;
222   if (OldOps) Use::zap(OldOps, OldOps + e, true);
223 }
224
225 /// hasConstantValue - If the specified PHI node always merges together the same
226 /// value, return the value, otherwise return null.
227 ///
228 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
229   // If the PHI node only has one incoming value, eliminate the PHI node...
230   if (getNumIncomingValues() == 1) {
231     if (getIncomingValue(0) != this)   // not  X = phi X
232       return getIncomingValue(0);
233     else
234       return UndefValue::get(getType());  // Self cycle is dead.
235   }
236       
237   // Otherwise if all of the incoming values are the same for the PHI, replace
238   // the PHI node with the incoming value.
239   //
240   Value *InVal = 0;
241   bool HasUndefInput = false;
242   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
243     if (isa<UndefValue>(getIncomingValue(i))) {
244       HasUndefInput = true;
245     } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
246       if (InVal && getIncomingValue(i) != InVal)
247         return 0;  // Not the same, bail out.
248       else
249         InVal = getIncomingValue(i);
250     }
251   
252   // The only case that could cause InVal to be null is if we have a PHI node
253   // that only has entries for itself.  In this case, there is no entry into the
254   // loop, so kill the PHI.
255   //
256   if (InVal == 0) InVal = UndefValue::get(getType());
257   
258   // If we have a PHI node like phi(X, undef, X), where X is defined by some
259   // instruction, we cannot always return X as the result of the PHI node.  Only
260   // do this if X is not an instruction (thus it must dominate the PHI block),
261   // or if the client is prepared to deal with this possibility.
262   if (HasUndefInput && !AllowNonDominatingInstruction)
263     if (Instruction *IV = dyn_cast<Instruction>(InVal))
264       // If it's in the entry block, it dominates everything.
265       if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
266           isa<InvokeInst>(IV))
267         return 0;   // Cannot guarantee that InVal dominates this PHINode.
268
269   // All of the incoming values are the same, return the value now.
270   return InVal;
271 }
272
273
274 //===----------------------------------------------------------------------===//
275 //                        CallInst Implementation
276 //===----------------------------------------------------------------------===//
277
278 CallInst::~CallInst() {
279 }
280
281 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
282   assert(NumOperands == NumParams+1 && "NumOperands not set up?");
283   Use *OL = OperandList;
284   OL[0] = Func;
285
286   const FunctionType *FTy =
287     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
288   FTy = FTy;  // silence warning.
289
290   assert((NumParams == FTy->getNumParams() ||
291           (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
292          "Calling a function with bad signature!");
293   for (unsigned i = 0; i != NumParams; ++i) {
294     assert((i >= FTy->getNumParams() || 
295             FTy->getParamType(i) == Params[i]->getType()) &&
296            "Calling a function with a bad signature!");
297     OL[i+1] = Params[i];
298   }
299 }
300
301 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
302   assert(NumOperands == 3 && "NumOperands not set up?");
303   Use *OL = OperandList;
304   OL[0] = Func;
305   OL[1] = Actual1;
306   OL[2] = Actual2;
307
308   const FunctionType *FTy =
309     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
310   FTy = FTy;  // silence warning.
311
312   assert((FTy->getNumParams() == 2 ||
313           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
314          "Calling a function with bad signature");
315   assert((0 >= FTy->getNumParams() || 
316           FTy->getParamType(0) == Actual1->getType()) &&
317          "Calling a function with a bad signature!");
318   assert((1 >= FTy->getNumParams() || 
319           FTy->getParamType(1) == Actual2->getType()) &&
320          "Calling a function with a bad signature!");
321 }
322
323 void CallInst::init(Value *Func, Value *Actual) {
324   assert(NumOperands == 2 && "NumOperands not set up?");
325   Use *OL = OperandList;
326   OL[0] = Func;
327   OL[1] = Actual;
328
329   const FunctionType *FTy =
330     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
331   FTy = FTy;  // silence warning.
332
333   assert((FTy->getNumParams() == 1 ||
334           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
335          "Calling a function with bad signature");
336   assert((0 == FTy->getNumParams() || 
337           FTy->getParamType(0) == Actual->getType()) &&
338          "Calling a function with a bad signature!");
339 }
340
341 void CallInst::init(Value *Func) {
342   assert(NumOperands == 1 && "NumOperands not set up?");
343   Use *OL = OperandList;
344   OL[0] = Func;
345
346   const FunctionType *FTy =
347     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
348   FTy = FTy;  // silence warning.
349
350   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
351 }
352
353 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
354                    Instruction *InsertBefore)
355   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
356                                    ->getElementType())->getReturnType(),
357                 Instruction::Call,
358                 OperandTraits<CallInst>::op_end(this) - 2,
359                 2, InsertBefore) {
360   init(Func, Actual);
361   setName(Name);
362 }
363
364 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
365                    BasicBlock  *InsertAtEnd)
366   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
367                                    ->getElementType())->getReturnType(),
368                 Instruction::Call,
369                 OperandTraits<CallInst>::op_end(this) - 2,
370                 2, InsertAtEnd) {
371   init(Func, Actual);
372   setName(Name);
373 }
374 CallInst::CallInst(Value *Func, const Twine &Name,
375                    Instruction *InsertBefore)
376   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
377                                    ->getElementType())->getReturnType(),
378                 Instruction::Call,
379                 OperandTraits<CallInst>::op_end(this) - 1,
380                 1, InsertBefore) {
381   init(Func);
382   setName(Name);
383 }
384
385 CallInst::CallInst(Value *Func, const Twine &Name,
386                    BasicBlock *InsertAtEnd)
387   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
388                                    ->getElementType())->getReturnType(),
389                 Instruction::Call,
390                 OperandTraits<CallInst>::op_end(this) - 1,
391                 1, InsertAtEnd) {
392   init(Func);
393   setName(Name);
394 }
395
396 CallInst::CallInst(const CallInst &CI)
397   : Instruction(CI.getType(), Instruction::Call,
398                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
399                 CI.getNumOperands()) {
400   setAttributes(CI.getAttributes());
401   SubclassData = CI.SubclassData;
402   Use *OL = OperandList;
403   Use *InOL = CI.OperandList;
404   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
405     OL[i] = InOL[i];
406 }
407
408 void CallInst::addAttribute(unsigned i, Attributes attr) {
409   AttrListPtr PAL = getAttributes();
410   PAL = PAL.addAttr(i, attr);
411   setAttributes(PAL);
412 }
413
414 void CallInst::removeAttribute(unsigned i, Attributes attr) {
415   AttrListPtr PAL = getAttributes();
416   PAL = PAL.removeAttr(i, attr);
417   setAttributes(PAL);
418 }
419
420 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
421   if (AttributeList.paramHasAttr(i, attr))
422     return true;
423   if (const Function *F = getCalledFunction())
424     return F->paramHasAttr(i, attr);
425   return false;
426 }
427
428
429 //===----------------------------------------------------------------------===//
430 //                        InvokeInst Implementation
431 //===----------------------------------------------------------------------===//
432
433 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
434                       Value* const *Args, unsigned NumArgs) {
435   assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
436   Use *OL = OperandList;
437   OL[0] = Fn;
438   OL[1] = IfNormal;
439   OL[2] = IfException;
440   const FunctionType *FTy =
441     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
442   FTy = FTy;  // silence warning.
443
444   assert(((NumArgs == FTy->getNumParams()) ||
445           (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
446          "Calling a function with bad signature");
447
448   for (unsigned i = 0, e = NumArgs; i != e; i++) {
449     assert((i >= FTy->getNumParams() || 
450             FTy->getParamType(i) == Args[i]->getType()) &&
451            "Invoking a function with a bad signature!");
452     
453     OL[i+3] = Args[i];
454   }
455 }
456
457 InvokeInst::InvokeInst(const InvokeInst &II)
458   : TerminatorInst(II.getType(), Instruction::Invoke,
459                    OperandTraits<InvokeInst>::op_end(this)
460                    - II.getNumOperands(),
461                    II.getNumOperands()) {
462   setAttributes(II.getAttributes());
463   SubclassData = II.SubclassData;
464   Use *OL = OperandList, *InOL = II.OperandList;
465   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
466     OL[i] = InOL[i];
467 }
468
469 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
470   return getSuccessor(idx);
471 }
472 unsigned InvokeInst::getNumSuccessorsV() const {
473   return getNumSuccessors();
474 }
475 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
476   return setSuccessor(idx, B);
477 }
478
479 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
480   if (AttributeList.paramHasAttr(i, attr))
481     return true;
482   if (const Function *F = getCalledFunction())
483     return F->paramHasAttr(i, attr);
484   return false;
485 }
486
487 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
488   AttrListPtr PAL = getAttributes();
489   PAL = PAL.addAttr(i, attr);
490   setAttributes(PAL);
491 }
492
493 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
494   AttrListPtr PAL = getAttributes();
495   PAL = PAL.removeAttr(i, attr);
496   setAttributes(PAL);
497 }
498
499
500 //===----------------------------------------------------------------------===//
501 //                        ReturnInst Implementation
502 //===----------------------------------------------------------------------===//
503
504 ReturnInst::ReturnInst(const ReturnInst &RI)
505   : TerminatorInst(Type::VoidTy, Instruction::Ret,
506                    OperandTraits<ReturnInst>::op_end(this) -
507                      RI.getNumOperands(),
508                    RI.getNumOperands()) {
509   if (RI.getNumOperands())
510     Op<0>() = RI.Op<0>();
511 }
512
513 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
514   : TerminatorInst(Type::VoidTy, Instruction::Ret,
515                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
516                    InsertBefore) {
517   if (retVal)
518     Op<0>() = retVal;
519 }
520 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
521   : TerminatorInst(Type::VoidTy, Instruction::Ret,
522                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
523                    InsertAtEnd) {
524   if (retVal)
525     Op<0>() = retVal;
526 }
527 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
528   : TerminatorInst(Type::VoidTy, Instruction::Ret,
529                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
530 }
531
532 unsigned ReturnInst::getNumSuccessorsV() const {
533   return getNumSuccessors();
534 }
535
536 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
537 /// emit the vtable for the class in this translation unit.
538 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
539   llvm_unreachable("ReturnInst has no successors!");
540 }
541
542 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
543   llvm_unreachable("ReturnInst has no successors!");
544   return 0;
545 }
546
547 ReturnInst::~ReturnInst() {
548 }
549
550 //===----------------------------------------------------------------------===//
551 //                        UnwindInst Implementation
552 //===----------------------------------------------------------------------===//
553
554 UnwindInst::UnwindInst(Instruction *InsertBefore)
555   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
556 }
557 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
558   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
559 }
560
561
562 unsigned UnwindInst::getNumSuccessorsV() const {
563   return getNumSuccessors();
564 }
565
566 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
567   llvm_unreachable("UnwindInst has no successors!");
568 }
569
570 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
571   llvm_unreachable("UnwindInst has no successors!");
572   return 0;
573 }
574
575 //===----------------------------------------------------------------------===//
576 //                      UnreachableInst Implementation
577 //===----------------------------------------------------------------------===//
578
579 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
580   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
581 }
582 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
583   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
584 }
585
586 unsigned UnreachableInst::getNumSuccessorsV() const {
587   return getNumSuccessors();
588 }
589
590 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
591   llvm_unreachable("UnwindInst has no successors!");
592 }
593
594 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
595   llvm_unreachable("UnwindInst has no successors!");
596   return 0;
597 }
598
599 //===----------------------------------------------------------------------===//
600 //                        BranchInst Implementation
601 //===----------------------------------------------------------------------===//
602
603 void BranchInst::AssertOK() {
604   if (isConditional())
605     assert(getCondition()->getType() == Type::Int1Ty &&
606            "May only branch on boolean predicates!");
607 }
608
609 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
610   : TerminatorInst(Type::VoidTy, Instruction::Br,
611                    OperandTraits<BranchInst>::op_end(this) - 1,
612                    1, InsertBefore) {
613   assert(IfTrue != 0 && "Branch destination may not be null!");
614   Op<-1>() = IfTrue;
615 }
616 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
617                        Instruction *InsertBefore)
618   : TerminatorInst(Type::VoidTy, Instruction::Br,
619                    OperandTraits<BranchInst>::op_end(this) - 3,
620                    3, InsertBefore) {
621   Op<-1>() = IfTrue;
622   Op<-2>() = IfFalse;
623   Op<-3>() = Cond;
624 #ifndef NDEBUG
625   AssertOK();
626 #endif
627 }
628
629 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
630   : TerminatorInst(Type::VoidTy, Instruction::Br,
631                    OperandTraits<BranchInst>::op_end(this) - 1,
632                    1, InsertAtEnd) {
633   assert(IfTrue != 0 && "Branch destination may not be null!");
634   Op<-1>() = IfTrue;
635 }
636
637 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
638            BasicBlock *InsertAtEnd)
639   : TerminatorInst(Type::VoidTy, Instruction::Br,
640                    OperandTraits<BranchInst>::op_end(this) - 3,
641                    3, InsertAtEnd) {
642   Op<-1>() = IfTrue;
643   Op<-2>() = IfFalse;
644   Op<-3>() = Cond;
645 #ifndef NDEBUG
646   AssertOK();
647 #endif
648 }
649
650
651 BranchInst::BranchInst(const BranchInst &BI) :
652   TerminatorInst(Type::VoidTy, Instruction::Br,
653                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
654                  BI.getNumOperands()) {
655   Op<-1>() = BI.Op<-1>();
656   if (BI.getNumOperands() != 1) {
657     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
658     Op<-3>() = BI.Op<-3>();
659     Op<-2>() = BI.Op<-2>();
660   }
661 }
662
663
664 Use* Use::getPrefix() {
665   PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
666   if (PotentialPrefix.getOpaqueValue())
667     return 0;
668
669   return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
670 }
671
672 BranchInst::~BranchInst() {
673   if (NumOperands == 1) {
674     if (Use *Prefix = OperandList->getPrefix()) {
675       Op<-1>() = 0;
676       //
677       // mark OperandList to have a special value for scrutiny
678       // by baseclass destructors and operator delete
679       OperandList = Prefix;
680     } else {
681       NumOperands = 3;
682       OperandList = op_begin();
683     }
684   }
685 }
686
687
688 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
689   return getSuccessor(idx);
690 }
691 unsigned BranchInst::getNumSuccessorsV() const {
692   return getNumSuccessors();
693 }
694 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
695   setSuccessor(idx, B);
696 }
697
698
699 //===----------------------------------------------------------------------===//
700 //                        AllocationInst Implementation
701 //===----------------------------------------------------------------------===//
702
703 static Value *getAISize(LLVMContext &Context, Value *Amt) {
704   if (!Amt)
705     Amt = ConstantInt::get(Type::Int32Ty, 1);
706   else {
707     assert(!isa<BasicBlock>(Amt) &&
708            "Passed basic block into allocation size parameter! Use other ctor");
709     assert(Amt->getType() == Type::Int32Ty &&
710            "Malloc/Allocation array size is not a 32-bit integer!");
711   }
712   return Amt;
713 }
714
715 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
716                                unsigned Align, const Twine &Name,
717                                Instruction *InsertBefore)
718   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
719                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
720   setAlignment(Align);
721   assert(Ty != Type::VoidTy && "Cannot allocate void!");
722   setName(Name);
723 }
724
725 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
726                                unsigned Align, const Twine &Name,
727                                BasicBlock *InsertAtEnd)
728   : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
729                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
730   setAlignment(Align);
731   assert(Ty != Type::VoidTy && "Cannot allocate void!");
732   setName(Name);
733 }
734
735 // Out of line virtual method, so the vtable, etc has a home.
736 AllocationInst::~AllocationInst() {
737 }
738
739 void AllocationInst::setAlignment(unsigned Align) {
740   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
741   SubclassData = Log2_32(Align) + 1;
742   assert(getAlignment() == Align && "Alignment representation error!");
743 }
744
745 bool AllocationInst::isArrayAllocation() const {
746   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
747     return CI->getZExtValue() != 1;
748   return true;
749 }
750
751 const Type *AllocationInst::getAllocatedType() const {
752   return getType()->getElementType();
753 }
754
755 AllocaInst::AllocaInst(const AllocaInst &AI)
756   : AllocationInst(AI.getType()->getElementType(),    
757                    (Value*)AI.getOperand(0), Instruction::Alloca,
758                    AI.getAlignment()) {
759 }
760
761 /// isStaticAlloca - Return true if this alloca is in the entry block of the
762 /// function and is a constant size.  If so, the code generator will fold it
763 /// into the prolog/epilog code, so it is basically free.
764 bool AllocaInst::isStaticAlloca() const {
765   // Must be constant size.
766   if (!isa<ConstantInt>(getArraySize())) return false;
767   
768   // Must be in the entry block.
769   const BasicBlock *Parent = getParent();
770   return Parent == &Parent->getParent()->front();
771 }
772
773 MallocInst::MallocInst(const MallocInst &MI)
774   : AllocationInst(MI.getType()->getElementType(), 
775                    (Value*)MI.getOperand(0), Instruction::Malloc,
776                    MI.getAlignment()) {
777 }
778
779 //===----------------------------------------------------------------------===//
780 //                             FreeInst Implementation
781 //===----------------------------------------------------------------------===//
782
783 void FreeInst::AssertOK() {
784   assert(isa<PointerType>(getOperand(0)->getType()) &&
785          "Can not free something of nonpointer type!");
786 }
787
788 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
789   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
790   AssertOK();
791 }
792
793 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
794   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
795   AssertOK();
796 }
797
798
799 //===----------------------------------------------------------------------===//
800 //                           LoadInst Implementation
801 //===----------------------------------------------------------------------===//
802
803 void LoadInst::AssertOK() {
804   assert(isa<PointerType>(getOperand(0)->getType()) &&
805          "Ptr must have pointer type.");
806 }
807
808 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
809   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
810                      Load, Ptr, InsertBef) {
811   setVolatile(false);
812   setAlignment(0);
813   AssertOK();
814   setName(Name);
815 }
816
817 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
818   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
819                      Load, Ptr, InsertAE) {
820   setVolatile(false);
821   setAlignment(0);
822   AssertOK();
823   setName(Name);
824 }
825
826 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
827                    Instruction *InsertBef)
828   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
829                      Load, Ptr, InsertBef) {
830   setVolatile(isVolatile);
831   setAlignment(0);
832   AssertOK();
833   setName(Name);
834 }
835
836 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
837                    unsigned Align, Instruction *InsertBef)
838   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
839                      Load, Ptr, InsertBef) {
840   setVolatile(isVolatile);
841   setAlignment(Align);
842   AssertOK();
843   setName(Name);
844 }
845
846 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
847                    unsigned Align, BasicBlock *InsertAE)
848   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
849                      Load, Ptr, InsertAE) {
850   setVolatile(isVolatile);
851   setAlignment(Align);
852   AssertOK();
853   setName(Name);
854 }
855
856 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
857                    BasicBlock *InsertAE)
858   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
859                      Load, Ptr, InsertAE) {
860   setVolatile(isVolatile);
861   setAlignment(0);
862   AssertOK();
863   setName(Name);
864 }
865
866
867
868 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
869   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
870                      Load, Ptr, InsertBef) {
871   setVolatile(false);
872   setAlignment(0);
873   AssertOK();
874   if (Name && Name[0]) setName(Name);
875 }
876
877 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
878   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
879                      Load, Ptr, InsertAE) {
880   setVolatile(false);
881   setAlignment(0);
882   AssertOK();
883   if (Name && Name[0]) setName(Name);
884 }
885
886 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
887                    Instruction *InsertBef)
888 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
889                    Load, Ptr, InsertBef) {
890   setVolatile(isVolatile);
891   setAlignment(0);
892   AssertOK();
893   if (Name && Name[0]) setName(Name);
894 }
895
896 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
897                    BasicBlock *InsertAE)
898   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
899                      Load, Ptr, InsertAE) {
900   setVolatile(isVolatile);
901   setAlignment(0);
902   AssertOK();
903   if (Name && Name[0]) setName(Name);
904 }
905
906 void LoadInst::setAlignment(unsigned Align) {
907   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
908   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
909 }
910
911 //===----------------------------------------------------------------------===//
912 //                           StoreInst Implementation
913 //===----------------------------------------------------------------------===//
914
915 void StoreInst::AssertOK() {
916   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
917   assert(isa<PointerType>(getOperand(1)->getType()) &&
918          "Ptr must have pointer type!");
919   assert(getOperand(0)->getType() ==
920                  cast<PointerType>(getOperand(1)->getType())->getElementType()
921          && "Ptr must be a pointer to Val type!");
922 }
923
924
925 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
926   : Instruction(Type::VoidTy, Store,
927                 OperandTraits<StoreInst>::op_begin(this),
928                 OperandTraits<StoreInst>::operands(this),
929                 InsertBefore) {
930   Op<0>() = val;
931   Op<1>() = addr;
932   setVolatile(false);
933   setAlignment(0);
934   AssertOK();
935 }
936
937 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
938   : Instruction(Type::VoidTy, Store,
939                 OperandTraits<StoreInst>::op_begin(this),
940                 OperandTraits<StoreInst>::operands(this),
941                 InsertAtEnd) {
942   Op<0>() = val;
943   Op<1>() = addr;
944   setVolatile(false);
945   setAlignment(0);
946   AssertOK();
947 }
948
949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
950                      Instruction *InsertBefore)
951   : Instruction(Type::VoidTy, Store,
952                 OperandTraits<StoreInst>::op_begin(this),
953                 OperandTraits<StoreInst>::operands(this),
954                 InsertBefore) {
955   Op<0>() = val;
956   Op<1>() = addr;
957   setVolatile(isVolatile);
958   setAlignment(0);
959   AssertOK();
960 }
961
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963                      unsigned Align, Instruction *InsertBefore)
964   : Instruction(Type::VoidTy, Store,
965                 OperandTraits<StoreInst>::op_begin(this),
966                 OperandTraits<StoreInst>::operands(this),
967                 InsertBefore) {
968   Op<0>() = val;
969   Op<1>() = addr;
970   setVolatile(isVolatile);
971   setAlignment(Align);
972   AssertOK();
973 }
974
975 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
976                      unsigned Align, BasicBlock *InsertAtEnd)
977   : Instruction(Type::VoidTy, Store,
978                 OperandTraits<StoreInst>::op_begin(this),
979                 OperandTraits<StoreInst>::operands(this),
980                 InsertAtEnd) {
981   Op<0>() = val;
982   Op<1>() = addr;
983   setVolatile(isVolatile);
984   setAlignment(Align);
985   AssertOK();
986 }
987
988 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
989                      BasicBlock *InsertAtEnd)
990   : Instruction(Type::VoidTy, Store,
991                 OperandTraits<StoreInst>::op_begin(this),
992                 OperandTraits<StoreInst>::operands(this),
993                 InsertAtEnd) {
994   Op<0>() = val;
995   Op<1>() = addr;
996   setVolatile(isVolatile);
997   setAlignment(0);
998   AssertOK();
999 }
1000
1001 void StoreInst::setAlignment(unsigned Align) {
1002   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1003   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1004 }
1005
1006 //===----------------------------------------------------------------------===//
1007 //                       GetElementPtrInst Implementation
1008 //===----------------------------------------------------------------------===//
1009
1010 static unsigned retrieveAddrSpace(const Value *Val) {
1011   return cast<PointerType>(Val->getType())->getAddressSpace();
1012 }
1013
1014 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1015                              const Twine &Name) {
1016   assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1017   Use *OL = OperandList;
1018   OL[0] = Ptr;
1019
1020   for (unsigned i = 0; i != NumIdx; ++i)
1021     OL[i+1] = Idx[i];
1022
1023   setName(Name);
1024 }
1025
1026 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1027   assert(NumOperands == 2 && "NumOperands not initialized?");
1028   Use *OL = OperandList;
1029   OL[0] = Ptr;
1030   OL[1] = Idx;
1031
1032   setName(Name);
1033 }
1034
1035 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1036   : Instruction(GEPI.getType(), GetElementPtr,
1037                 OperandTraits<GetElementPtrInst>::op_end(this)
1038                 - GEPI.getNumOperands(),
1039                 GEPI.getNumOperands()) {
1040   Use *OL = OperandList;
1041   Use *GEPIOL = GEPI.OperandList;
1042   for (unsigned i = 0, E = NumOperands; i != E; ++i)
1043     OL[i] = GEPIOL[i];
1044 }
1045
1046 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1047                                      const Twine &Name, Instruction *InBe)
1048   : Instruction(PointerType::get(
1049       checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1050                 GetElementPtr,
1051                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1052                 2, InBe) {
1053   init(Ptr, Idx, Name);
1054 }
1055
1056 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1057                                      const Twine &Name, BasicBlock *IAE)
1058   : Instruction(PointerType::get(
1059             checkType(getIndexedType(Ptr->getType(),Idx)),  
1060                 retrieveAddrSpace(Ptr)),
1061                 GetElementPtr,
1062                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1063                 2, IAE) {
1064   init(Ptr, Idx, Name);
1065 }
1066
1067 /// getIndexedType - Returns the type of the element that would be accessed with
1068 /// a gep instruction with the specified parameters.
1069 ///
1070 /// The Idxs pointer should point to a continuous piece of memory containing the
1071 /// indices, either as Value* or uint64_t.
1072 ///
1073 /// A null type is returned if the indices are invalid for the specified
1074 /// pointer type.
1075 ///
1076 template <typename IndexTy>
1077 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1078                                           unsigned NumIdx) {
1079   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1080   if (!PTy) return 0;   // Type isn't a pointer type!
1081   const Type *Agg = PTy->getElementType();
1082
1083   // Handle the special case of the empty set index set, which is always valid.
1084   if (NumIdx == 0)
1085     return Agg;
1086   
1087   // If there is at least one index, the top level type must be sized, otherwise
1088   // it cannot be 'stepped over'.  We explicitly allow abstract types (those
1089   // that contain opaque types) under the assumption that it will be resolved to
1090   // a sane type later.
1091   if (!Agg->isSized() && !Agg->isAbstract())
1092     return 0;
1093
1094   unsigned CurIdx = 1;
1095   for (; CurIdx != NumIdx; ++CurIdx) {
1096     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1097     if (!CT || isa<PointerType>(CT)) return 0;
1098     IndexTy Index = Idxs[CurIdx];
1099     if (!CT->indexValid(Index)) return 0;
1100     Agg = CT->getTypeAtIndex(Index);
1101
1102     // If the new type forwards to another type, then it is in the middle
1103     // of being refined to another type (and hence, may have dropped all
1104     // references to what it was using before).  So, use the new forwarded
1105     // type.
1106     if (const Type *Ty = Agg->getForwardedType())
1107       Agg = Ty;
1108   }
1109   return CurIdx == NumIdx ? Agg : 0;
1110 }
1111
1112 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1113                                               Value* const *Idxs,
1114                                               unsigned NumIdx) {
1115   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1116 }
1117
1118 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1119                                               uint64_t const *Idxs,
1120                                               unsigned NumIdx) {
1121   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1122 }
1123
1124 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1125   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1126   if (!PTy) return 0;   // Type isn't a pointer type!
1127
1128   // Check the pointer index.
1129   if (!PTy->indexValid(Idx)) return 0;
1130
1131   return PTy->getElementType();
1132 }
1133
1134
1135 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1136 /// zeros.  If so, the result pointer and the first operand have the same
1137 /// value, just potentially different types.
1138 bool GetElementPtrInst::hasAllZeroIndices() const {
1139   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1140     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1141       if (!CI->isZero()) return false;
1142     } else {
1143       return false;
1144     }
1145   }
1146   return true;
1147 }
1148
1149 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1150 /// constant integers.  If so, the result pointer and the first operand have
1151 /// a constant offset between them.
1152 bool GetElementPtrInst::hasAllConstantIndices() const {
1153   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1154     if (!isa<ConstantInt>(getOperand(i)))
1155       return false;
1156   }
1157   return true;
1158 }
1159
1160
1161 //===----------------------------------------------------------------------===//
1162 //                           ExtractElementInst Implementation
1163 //===----------------------------------------------------------------------===//
1164
1165 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1166                                        const Twine &Name,
1167                                        Instruction *InsertBef)
1168   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1169                 ExtractElement,
1170                 OperandTraits<ExtractElementInst>::op_begin(this),
1171                 2, InsertBef) {
1172   assert(isValidOperands(Val, Index) &&
1173          "Invalid extractelement instruction operands!");
1174   Op<0>() = Val;
1175   Op<1>() = Index;
1176   setName(Name);
1177 }
1178
1179 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1180                                        const Twine &Name,
1181                                        BasicBlock *InsertAE)
1182   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1183                 ExtractElement,
1184                 OperandTraits<ExtractElementInst>::op_begin(this),
1185                 2, InsertAE) {
1186   assert(isValidOperands(Val, Index) &&
1187          "Invalid extractelement instruction operands!");
1188
1189   Op<0>() = Val;
1190   Op<1>() = Index;
1191   setName(Name);
1192 }
1193
1194
1195 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1196   if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1197     return false;
1198   return true;
1199 }
1200
1201
1202 //===----------------------------------------------------------------------===//
1203 //                           InsertElementInst Implementation
1204 //===----------------------------------------------------------------------===//
1205
1206 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1207     : Instruction(IE.getType(), InsertElement,
1208                   OperandTraits<InsertElementInst>::op_begin(this), 3) {
1209   Op<0>() = IE.Op<0>();
1210   Op<1>() = IE.Op<1>();
1211   Op<2>() = IE.Op<2>();
1212 }
1213 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1214                                      const Twine &Name,
1215                                      Instruction *InsertBef)
1216   : Instruction(Vec->getType(), InsertElement,
1217                 OperandTraits<InsertElementInst>::op_begin(this),
1218                 3, InsertBef) {
1219   assert(isValidOperands(Vec, Elt, Index) &&
1220          "Invalid insertelement instruction operands!");
1221   Op<0>() = Vec;
1222   Op<1>() = Elt;
1223   Op<2>() = Index;
1224   setName(Name);
1225 }
1226
1227 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1228                                      const Twine &Name,
1229                                      BasicBlock *InsertAE)
1230   : Instruction(Vec->getType(), InsertElement,
1231                 OperandTraits<InsertElementInst>::op_begin(this),
1232                 3, InsertAE) {
1233   assert(isValidOperands(Vec, Elt, Index) &&
1234          "Invalid insertelement instruction operands!");
1235
1236   Op<0>() = Vec;
1237   Op<1>() = Elt;
1238   Op<2>() = Index;
1239   setName(Name);
1240 }
1241
1242 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1243                                         const Value *Index) {
1244   if (!isa<VectorType>(Vec->getType()))
1245     return false;   // First operand of insertelement must be vector type.
1246   
1247   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1248     return false;// Second operand of insertelement must be vector element type.
1249     
1250   if (Index->getType() != Type::Int32Ty)
1251     return false;  // Third operand of insertelement must be i32.
1252   return true;
1253 }
1254
1255
1256 //===----------------------------------------------------------------------===//
1257 //                      ShuffleVectorInst Implementation
1258 //===----------------------------------------------------------------------===//
1259
1260 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
1261   : Instruction(SV.getType(), ShuffleVector,
1262                 OperandTraits<ShuffleVectorInst>::op_begin(this),
1263                 OperandTraits<ShuffleVectorInst>::operands(this)) {
1264   Op<0>() = SV.Op<0>();
1265   Op<1>() = SV.Op<1>();
1266   Op<2>() = SV.Op<2>();
1267 }
1268
1269 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1270                                      const Twine &Name,
1271                                      Instruction *InsertBefore)
1272 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1273                 cast<VectorType>(Mask->getType())->getNumElements()),
1274               ShuffleVector,
1275               OperandTraits<ShuffleVectorInst>::op_begin(this),
1276               OperandTraits<ShuffleVectorInst>::operands(this),
1277               InsertBefore) {
1278   assert(isValidOperands(V1, V2, Mask) &&
1279          "Invalid shuffle vector instruction operands!");
1280   Op<0>() = V1;
1281   Op<1>() = V2;
1282   Op<2>() = Mask;
1283   setName(Name);
1284 }
1285
1286 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1287                                      const Twine &Name,
1288                                      BasicBlock *InsertAtEnd)
1289   : Instruction(V1->getType(), ShuffleVector,
1290                 OperandTraits<ShuffleVectorInst>::op_begin(this),
1291                 OperandTraits<ShuffleVectorInst>::operands(this),
1292                 InsertAtEnd) {
1293   assert(isValidOperands(V1, V2, Mask) &&
1294          "Invalid shuffle vector instruction operands!");
1295
1296   Op<0>() = V1;
1297   Op<1>() = V2;
1298   Op<2>() = Mask;
1299   setName(Name);
1300 }
1301
1302 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1303                                         const Value *Mask) {
1304   if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1305     return false;
1306   
1307   const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1308   if (!isa<Constant>(Mask) || MaskTy == 0 ||
1309       MaskTy->getElementType() != Type::Int32Ty)
1310     return false;
1311   return true;
1312 }
1313
1314 /// getMaskValue - Return the index from the shuffle mask for the specified
1315 /// output result.  This is either -1 if the element is undef or a number less
1316 /// than 2*numelements.
1317 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1318   const Constant *Mask = cast<Constant>(getOperand(2));
1319   if (isa<UndefValue>(Mask)) return -1;
1320   if (isa<ConstantAggregateZero>(Mask)) return 0;
1321   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1322   assert(i < MaskCV->getNumOperands() && "Index out of range");
1323
1324   if (isa<UndefValue>(MaskCV->getOperand(i)))
1325     return -1;
1326   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1327 }
1328
1329 //===----------------------------------------------------------------------===//
1330 //                             InsertValueInst Class
1331 //===----------------------------------------------------------------------===//
1332
1333 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 
1334                            unsigned NumIdx, const Twine &Name) {
1335   assert(NumOperands == 2 && "NumOperands not initialized?");
1336   Op<0>() = Agg;
1337   Op<1>() = Val;
1338
1339   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1340   setName(Name);
1341 }
1342
1343 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 
1344                            const Twine &Name) {
1345   assert(NumOperands == 2 && "NumOperands not initialized?");
1346   Op<0>() = Agg;
1347   Op<1>() = Val;
1348
1349   Indices.push_back(Idx);
1350   setName(Name);
1351 }
1352
1353 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1354   : Instruction(IVI.getType(), InsertValue,
1355                 OperandTraits<InsertValueInst>::op_begin(this), 2),
1356     Indices(IVI.Indices) {
1357   Op<0>() = IVI.getOperand(0);
1358   Op<1>() = IVI.getOperand(1);
1359 }
1360
1361 InsertValueInst::InsertValueInst(Value *Agg,
1362                                  Value *Val,
1363                                  unsigned Idx, 
1364                                  const Twine &Name,
1365                                  Instruction *InsertBefore)
1366   : Instruction(Agg->getType(), InsertValue,
1367                 OperandTraits<InsertValueInst>::op_begin(this),
1368                 2, InsertBefore) {
1369   init(Agg, Val, Idx, Name);
1370 }
1371
1372 InsertValueInst::InsertValueInst(Value *Agg,
1373                                  Value *Val,
1374                                  unsigned Idx, 
1375                                  const Twine &Name,
1376                                  BasicBlock *InsertAtEnd)
1377   : Instruction(Agg->getType(), InsertValue,
1378                 OperandTraits<InsertValueInst>::op_begin(this),
1379                 2, InsertAtEnd) {
1380   init(Agg, Val, Idx, Name);
1381 }
1382
1383 //===----------------------------------------------------------------------===//
1384 //                             ExtractValueInst Class
1385 //===----------------------------------------------------------------------===//
1386
1387 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1388                             const Twine &Name) {
1389   assert(NumOperands == 1 && "NumOperands not initialized?");
1390
1391   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1392   setName(Name);
1393 }
1394
1395 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1396   assert(NumOperands == 1 && "NumOperands not initialized?");
1397
1398   Indices.push_back(Idx);
1399   setName(Name);
1400 }
1401
1402 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1403   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1404     Indices(EVI.Indices) {
1405 }
1406
1407 // getIndexedType - Returns the type of the element that would be extracted
1408 // with an extractvalue instruction with the specified parameters.
1409 //
1410 // A null type is returned if the indices are invalid for the specified
1411 // pointer type.
1412 //
1413 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1414                                              const unsigned *Idxs,
1415                                              unsigned NumIdx) {
1416   unsigned CurIdx = 0;
1417   for (; CurIdx != NumIdx; ++CurIdx) {
1418     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1419     if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1420     unsigned Index = Idxs[CurIdx];
1421     if (!CT->indexValid(Index)) return 0;
1422     Agg = CT->getTypeAtIndex(Index);
1423
1424     // If the new type forwards to another type, then it is in the middle
1425     // of being refined to another type (and hence, may have dropped all
1426     // references to what it was using before).  So, use the new forwarded
1427     // type.
1428     if (const Type *Ty = Agg->getForwardedType())
1429       Agg = Ty;
1430   }
1431   return CurIdx == NumIdx ? Agg : 0;
1432 }
1433
1434 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1435                                              unsigned Idx) {
1436   return getIndexedType(Agg, &Idx, 1);
1437 }
1438
1439 //===----------------------------------------------------------------------===//
1440 //                             BinaryOperator Class
1441 //===----------------------------------------------------------------------===//
1442
1443 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1444 /// type is floating-point, to help provide compatibility with an older API.
1445 ///
1446 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1447                                              const Type *Ty) {
1448   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1449   if (Ty->isFPOrFPVector()) {
1450     if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1451     else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1452     else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1453   }
1454   return iType;
1455 }
1456
1457 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1458                                const Type *Ty, const Twine &Name,
1459                                Instruction *InsertBefore)
1460   : Instruction(Ty, AdjustIType(iType, Ty),
1461                 OperandTraits<BinaryOperator>::op_begin(this),
1462                 OperandTraits<BinaryOperator>::operands(this),
1463                 InsertBefore) {
1464   Op<0>() = S1;
1465   Op<1>() = S2;
1466   init(AdjustIType(iType, Ty));
1467   setName(Name);
1468 }
1469
1470 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1471                                const Type *Ty, const Twine &Name,
1472                                BasicBlock *InsertAtEnd)
1473   : Instruction(Ty, AdjustIType(iType, Ty),
1474                 OperandTraits<BinaryOperator>::op_begin(this),
1475                 OperandTraits<BinaryOperator>::operands(this),
1476                 InsertAtEnd) {
1477   Op<0>() = S1;
1478   Op<1>() = S2;
1479   init(AdjustIType(iType, Ty));
1480   setName(Name);
1481 }
1482
1483
1484 void BinaryOperator::init(BinaryOps iType) {
1485   Value *LHS = getOperand(0), *RHS = getOperand(1);
1486   LHS = LHS; RHS = RHS; // Silence warnings.
1487   assert(LHS->getType() == RHS->getType() &&
1488          "Binary operator operand types must match!");
1489 #ifndef NDEBUG
1490   switch (iType) {
1491   case Add: case Sub:
1492   case Mul:
1493     assert(getType() == LHS->getType() &&
1494            "Arithmetic operation should return same type as operands!");
1495     assert(getType()->isIntOrIntVector() &&
1496            "Tried to create an integer operation on a non-integer type!");
1497     break;
1498   case FAdd: case FSub:
1499   case FMul:
1500     assert(getType() == LHS->getType() &&
1501            "Arithmetic operation should return same type as operands!");
1502     assert(getType()->isFPOrFPVector() &&
1503            "Tried to create a floating-point operation on a "
1504            "non-floating-point type!");
1505     break;
1506   case UDiv: 
1507   case SDiv: 
1508     assert(getType() == LHS->getType() &&
1509            "Arithmetic operation should return same type as operands!");
1510     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1511             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1512            "Incorrect operand type (not integer) for S/UDIV");
1513     break;
1514   case FDiv:
1515     assert(getType() == LHS->getType() &&
1516            "Arithmetic operation should return same type as operands!");
1517     assert(getType()->isFPOrFPVector() &&
1518            "Incorrect operand type (not floating point) for FDIV");
1519     break;
1520   case URem: 
1521   case SRem: 
1522     assert(getType() == LHS->getType() &&
1523            "Arithmetic operation should return same type as operands!");
1524     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
1525             cast<VectorType>(getType())->getElementType()->isInteger())) &&
1526            "Incorrect operand type (not integer) for S/UREM");
1527     break;
1528   case FRem:
1529     assert(getType() == LHS->getType() &&
1530            "Arithmetic operation should return same type as operands!");
1531     assert(getType()->isFPOrFPVector() &&
1532            "Incorrect operand type (not floating point) for FREM");
1533     break;
1534   case Shl:
1535   case LShr:
1536   case AShr:
1537     assert(getType() == LHS->getType() &&
1538            "Shift operation should return same type as operands!");
1539     assert((getType()->isInteger() ||
1540             (isa<VectorType>(getType()) && 
1541              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1542            "Tried to create a shift operation on a non-integral type!");
1543     break;
1544   case And: case Or:
1545   case Xor:
1546     assert(getType() == LHS->getType() &&
1547            "Logical operation should return same type as operands!");
1548     assert((getType()->isInteger() ||
1549             (isa<VectorType>(getType()) && 
1550              cast<VectorType>(getType())->getElementType()->isInteger())) &&
1551            "Tried to create a logical operation on a non-integral type!");
1552     break;
1553   default:
1554     break;
1555   }
1556 #endif
1557 }
1558
1559 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1560                                        const Twine &Name,
1561                                        Instruction *InsertBefore) {
1562   assert(S1->getType() == S2->getType() &&
1563          "Cannot create binary operator with two operands of differing type!");
1564   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1565 }
1566
1567 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1568                                        const Twine &Name,
1569                                        BasicBlock *InsertAtEnd) {
1570   BinaryOperator *Res = Create(Op, S1, S2, Name);
1571   InsertAtEnd->getInstList().push_back(Res);
1572   return Res;
1573 }
1574
1575 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1576                                           Value *Op, const Twine &Name,
1577                                           Instruction *InsertBefore) {
1578   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1579   return new BinaryOperator(Instruction::Sub,
1580                             zero, Op,
1581                             Op->getType(), Name, InsertBefore);
1582 }
1583
1584 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context, 
1585                                           Value *Op, const Twine &Name,
1586                                           BasicBlock *InsertAtEnd) {
1587   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1588   return new BinaryOperator(Instruction::Sub,
1589                             zero, Op,
1590                             Op->getType(), Name, InsertAtEnd);
1591 }
1592
1593 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1594                                            Value *Op, const Twine &Name,
1595                                            Instruction *InsertBefore) {
1596   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1597   return new BinaryOperator(Instruction::FSub,
1598                             zero, Op,
1599                             Op->getType(), Name, InsertBefore);
1600 }
1601
1602 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1603                                            Value *Op, const Twine &Name,
1604                                            BasicBlock *InsertAtEnd) {
1605   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1606   return new BinaryOperator(Instruction::FSub,
1607                             zero, Op,
1608                             Op->getType(), Name, InsertAtEnd);
1609 }
1610
1611 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1612                                           Value *Op, const Twine &Name,
1613                                           Instruction *InsertBefore) {
1614   Constant *C;
1615   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1616     C = Constant::getAllOnesValue(PTy->getElementType());
1617     C = ConstantVector::get(
1618                               std::vector<Constant*>(PTy->getNumElements(), C));
1619   } else {
1620     C = Constant::getAllOnesValue(Op->getType());
1621   }
1622   
1623   return new BinaryOperator(Instruction::Xor, Op, C,
1624                             Op->getType(), Name, InsertBefore);
1625 }
1626
1627 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1628                                           Value *Op, const Twine &Name,
1629                                           BasicBlock *InsertAtEnd) {
1630   Constant *AllOnes;
1631   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1632     // Create a vector of all ones values.
1633     Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1634     AllOnes = ConstantVector::get(
1635                             std::vector<Constant*>(PTy->getNumElements(), Elt));
1636   } else {
1637     AllOnes = Constant::getAllOnesValue(Op->getType());
1638   }
1639   
1640   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1641                             Op->getType(), Name, InsertAtEnd);
1642 }
1643
1644
1645 // isConstantAllOnes - Helper function for several functions below
1646 static inline bool isConstantAllOnes(const Value *V) {
1647   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1648     return CI->isAllOnesValue();
1649   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1650     return CV->isAllOnesValue();
1651   return false;
1652 }
1653
1654 bool BinaryOperator::isNeg(const Value *V) {
1655   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1656     if (Bop->getOpcode() == Instruction::Sub)
1657       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1658         return C->isNegativeZeroValue();
1659   return false;
1660 }
1661
1662 bool BinaryOperator::isFNeg(const Value *V) {
1663   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1664     if (Bop->getOpcode() == Instruction::FSub)
1665       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1666       return C->isNegativeZeroValue();
1667   return false;
1668 }
1669
1670 bool BinaryOperator::isNot(const Value *V) {
1671   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1672     return (Bop->getOpcode() == Instruction::Xor &&
1673             (isConstantAllOnes(Bop->getOperand(1)) ||
1674              isConstantAllOnes(Bop->getOperand(0))));
1675   return false;
1676 }
1677
1678 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1679   return cast<BinaryOperator>(BinOp)->getOperand(1);
1680 }
1681
1682 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1683   return getNegArgument(const_cast<Value*>(BinOp));
1684 }
1685
1686 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1687   return cast<BinaryOperator>(BinOp)->getOperand(1);
1688 }
1689
1690 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1691   return getFNegArgument(const_cast<Value*>(BinOp));
1692 }
1693
1694 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1695   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1696   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1697   Value *Op0 = BO->getOperand(0);
1698   Value *Op1 = BO->getOperand(1);
1699   if (isConstantAllOnes(Op0)) return Op1;
1700
1701   assert(isConstantAllOnes(Op1));
1702   return Op0;
1703 }
1704
1705 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1706   return getNotArgument(const_cast<Value*>(BinOp));
1707 }
1708
1709
1710 // swapOperands - Exchange the two operands to this instruction.  This
1711 // instruction is safe to use on any binary instruction and does not
1712 // modify the semantics of the instruction.  If the instruction is
1713 // order dependent (SetLT f.e.) the opcode is changed.
1714 //
1715 bool BinaryOperator::swapOperands() {
1716   if (!isCommutative())
1717     return true; // Can't commute operands
1718   Op<0>().swap(Op<1>());
1719   return false;
1720 }
1721
1722 //===----------------------------------------------------------------------===//
1723 //                                CastInst Class
1724 //===----------------------------------------------------------------------===//
1725
1726 // Just determine if this cast only deals with integral->integral conversion.
1727 bool CastInst::isIntegerCast() const {
1728   switch (getOpcode()) {
1729     default: return false;
1730     case Instruction::ZExt:
1731     case Instruction::SExt:
1732     case Instruction::Trunc:
1733       return true;
1734     case Instruction::BitCast:
1735       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1736   }
1737 }
1738
1739 bool CastInst::isLosslessCast() const {
1740   // Only BitCast can be lossless, exit fast if we're not BitCast
1741   if (getOpcode() != Instruction::BitCast)
1742     return false;
1743
1744   // Identity cast is always lossless
1745   const Type* SrcTy = getOperand(0)->getType();
1746   const Type* DstTy = getType();
1747   if (SrcTy == DstTy)
1748     return true;
1749   
1750   // Pointer to pointer is always lossless.
1751   if (isa<PointerType>(SrcTy))
1752     return isa<PointerType>(DstTy);
1753   return false;  // Other types have no identity values
1754 }
1755
1756 /// This function determines if the CastInst does not require any bits to be
1757 /// changed in order to effect the cast. Essentially, it identifies cases where
1758 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
1759 /// example, the following are all no-op casts:
1760 /// # bitcast i32* %x to i8*
1761 /// # bitcast <2 x i32> %x to <4 x i16> 
1762 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
1763 /// @brief Determine if a cast is a no-op.
1764 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1765   switch (getOpcode()) {
1766     default:
1767       assert(!"Invalid CastOp");
1768     case Instruction::Trunc:
1769     case Instruction::ZExt:
1770     case Instruction::SExt: 
1771     case Instruction::FPTrunc:
1772     case Instruction::FPExt:
1773     case Instruction::UIToFP:
1774     case Instruction::SIToFP:
1775     case Instruction::FPToUI:
1776     case Instruction::FPToSI:
1777       return false; // These always modify bits
1778     case Instruction::BitCast:
1779       return true;  // BitCast never modifies bits.
1780     case Instruction::PtrToInt:
1781       return IntPtrTy->getScalarSizeInBits() ==
1782              getType()->getScalarSizeInBits();
1783     case Instruction::IntToPtr:
1784       return IntPtrTy->getScalarSizeInBits() ==
1785              getOperand(0)->getType()->getScalarSizeInBits();
1786   }
1787 }
1788
1789 /// This function determines if a pair of casts can be eliminated and what 
1790 /// opcode should be used in the elimination. This assumes that there are two 
1791 /// instructions like this:
1792 /// *  %F = firstOpcode SrcTy %x to MidTy
1793 /// *  %S = secondOpcode MidTy %F to DstTy
1794 /// The function returns a resultOpcode so these two casts can be replaced with:
1795 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
1796 /// If no such cast is permited, the function returns 0.
1797 unsigned CastInst::isEliminableCastPair(
1798   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1799   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1800 {
1801   // Define the 144 possibilities for these two cast instructions. The values
1802   // in this matrix determine what to do in a given situation and select the
1803   // case in the switch below.  The rows correspond to firstOp, the columns 
1804   // correspond to secondOp.  In looking at the table below, keep in  mind
1805   // the following cast properties:
1806   //
1807   //          Size Compare       Source               Destination
1808   // Operator  Src ? Size   Type       Sign         Type       Sign
1809   // -------- ------------ -------------------   ---------------------
1810   // TRUNC         >       Integer      Any        Integral     Any
1811   // ZEXT          <       Integral   Unsigned     Integer      Any
1812   // SEXT          <       Integral    Signed      Integer      Any
1813   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
1814   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
1815   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
1816   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
1817   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
1818   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
1819   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
1820   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
1821   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
1822   //
1823   // NOTE: some transforms are safe, but we consider them to be non-profitable.
1824   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1825   // into "fptoui double to i64", but this loses information about the range
1826   // of the produced value (we no longer know the top-part is all zeros). 
1827   // Further this conversion is often much more expensive for typical hardware,
1828   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
1829   // same reason.
1830   const unsigned numCastOps = 
1831     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1832   static const uint8_t CastResults[numCastOps][numCastOps] = {
1833     // T        F  F  U  S  F  F  P  I  B   -+
1834     // R  Z  S  P  P  I  I  T  P  2  N  T    |
1835     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
1836     // N  X  X  U  S  F  F  N  X  N  2  V    |
1837     // C  T  T  I  I  P  P  C  T  T  P  T   -+
1838     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
1839     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
1840     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
1841     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
1842     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
1843     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
1844     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
1845     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
1846     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
1847     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
1848     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
1849     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
1850   };
1851
1852   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1853                             [secondOp-Instruction::CastOpsBegin];
1854   switch (ElimCase) {
1855     case 0: 
1856       // categorically disallowed
1857       return 0;
1858     case 1: 
1859       // allowed, use first cast's opcode
1860       return firstOp;
1861     case 2: 
1862       // allowed, use second cast's opcode
1863       return secondOp;
1864     case 3: 
1865       // no-op cast in second op implies firstOp as long as the DestTy 
1866       // is integer
1867       if (DstTy->isInteger())
1868         return firstOp;
1869       return 0;
1870     case 4:
1871       // no-op cast in second op implies firstOp as long as the DestTy
1872       // is floating point
1873       if (DstTy->isFloatingPoint())
1874         return firstOp;
1875       return 0;
1876     case 5: 
1877       // no-op cast in first op implies secondOp as long as the SrcTy
1878       // is an integer
1879       if (SrcTy->isInteger())
1880         return secondOp;
1881       return 0;
1882     case 6:
1883       // no-op cast in first op implies secondOp as long as the SrcTy
1884       // is a floating point
1885       if (SrcTy->isFloatingPoint())
1886         return secondOp;
1887       return 0;
1888     case 7: { 
1889       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1890       if (!IntPtrTy)
1891         return 0;
1892       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1893       unsigned MidSize = MidTy->getScalarSizeInBits();
1894       if (MidSize >= PtrSize)
1895         return Instruction::BitCast;
1896       return 0;
1897     }
1898     case 8: {
1899       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
1900       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
1901       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
1902       unsigned SrcSize = SrcTy->getScalarSizeInBits();
1903       unsigned DstSize = DstTy->getScalarSizeInBits();
1904       if (SrcSize == DstSize)
1905         return Instruction::BitCast;
1906       else if (SrcSize < DstSize)
1907         return firstOp;
1908       return secondOp;
1909     }
1910     case 9: // zext, sext -> zext, because sext can't sign extend after zext
1911       return Instruction::ZExt;
1912     case 10:
1913       // fpext followed by ftrunc is allowed if the bit size returned to is
1914       // the same as the original, in which case its just a bitcast
1915       if (SrcTy == DstTy)
1916         return Instruction::BitCast;
1917       return 0; // If the types are not the same we can't eliminate it.
1918     case 11:
1919       // bitcast followed by ptrtoint is allowed as long as the bitcast
1920       // is a pointer to pointer cast.
1921       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1922         return secondOp;
1923       return 0;
1924     case 12:
1925       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
1926       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1927         return firstOp;
1928       return 0;
1929     case 13: {
1930       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1931       if (!IntPtrTy)
1932         return 0;
1933       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1934       unsigned SrcSize = SrcTy->getScalarSizeInBits();
1935       unsigned DstSize = DstTy->getScalarSizeInBits();
1936       if (SrcSize <= PtrSize && SrcSize == DstSize)
1937         return Instruction::BitCast;
1938       return 0;
1939     }
1940     case 99: 
1941       // cast combination can't happen (error in input). This is for all cases
1942       // where the MidTy is not the same for the two cast instructions.
1943       assert(!"Invalid Cast Combination");
1944       return 0;
1945     default:
1946       assert(!"Error in CastResults table!!!");
1947       return 0;
1948   }
1949   return 0;
1950 }
1951
1952 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 
1953   const Twine &Name, Instruction *InsertBefore) {
1954   // Construct and return the appropriate CastInst subclass
1955   switch (op) {
1956     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
1957     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
1958     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
1959     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
1960     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
1961     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
1962     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
1963     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
1964     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
1965     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1966     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1967     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
1968     default:
1969       assert(!"Invalid opcode provided");
1970   }
1971   return 0;
1972 }
1973
1974 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1975   const Twine &Name, BasicBlock *InsertAtEnd) {
1976   // Construct and return the appropriate CastInst subclass
1977   switch (op) {
1978     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
1979     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
1980     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
1981     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
1982     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
1983     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
1984     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
1985     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
1986     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
1987     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1988     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1989     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
1990     default:
1991       assert(!"Invalid opcode provided");
1992   }
1993   return 0;
1994 }
1995
1996 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
1997                                         const Twine &Name,
1998                                         Instruction *InsertBefore) {
1999   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2000     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2001   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2002 }
2003
2004 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
2005                                         const Twine &Name,
2006                                         BasicBlock *InsertAtEnd) {
2007   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2008     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2009   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2010 }
2011
2012 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
2013                                         const Twine &Name,
2014                                         Instruction *InsertBefore) {
2015   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2016     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2017   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2018 }
2019
2020 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
2021                                         const Twine &Name,
2022                                         BasicBlock *InsertAtEnd) {
2023   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2024     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2025   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2026 }
2027
2028 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2029                                          const Twine &Name,
2030                                          Instruction *InsertBefore) {
2031   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2032     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2033   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2034 }
2035
2036 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2037                                          const Twine &Name, 
2038                                          BasicBlock *InsertAtEnd) {
2039   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2040     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2041   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2042 }
2043
2044 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2045                                       const Twine &Name,
2046                                       BasicBlock *InsertAtEnd) {
2047   assert(isa<PointerType>(S->getType()) && "Invalid cast");
2048   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2049          "Invalid cast");
2050
2051   if (Ty->isInteger())
2052     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2053   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2054 }
2055
2056 /// @brief Create a BitCast or a PtrToInt cast instruction
2057 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 
2058                                       const Twine &Name, 
2059                                       Instruction *InsertBefore) {
2060   assert(isa<PointerType>(S->getType()) && "Invalid cast");
2061   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2062          "Invalid cast");
2063
2064   if (Ty->isInteger())
2065     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2066   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2067 }
2068
2069 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
2070                                       bool isSigned, const Twine &Name,
2071                                       Instruction *InsertBefore) {
2072   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2073   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2074   unsigned DstBits = Ty->getScalarSizeInBits();
2075   Instruction::CastOps opcode =
2076     (SrcBits == DstBits ? Instruction::BitCast :
2077      (SrcBits > DstBits ? Instruction::Trunc :
2078       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2079   return Create(opcode, C, Ty, Name, InsertBefore);
2080 }
2081
2082 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
2083                                       bool isSigned, const Twine &Name,
2084                                       BasicBlock *InsertAtEnd) {
2085   assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2086          "Invalid cast");
2087   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2088   unsigned DstBits = Ty->getScalarSizeInBits();
2089   Instruction::CastOps opcode =
2090     (SrcBits == DstBits ? Instruction::BitCast :
2091      (SrcBits > DstBits ? Instruction::Trunc :
2092       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2093   return Create(opcode, C, Ty, Name, InsertAtEnd);
2094 }
2095
2096 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
2097                                  const Twine &Name, 
2098                                  Instruction *InsertBefore) {
2099   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2100          "Invalid cast");
2101   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2102   unsigned DstBits = Ty->getScalarSizeInBits();
2103   Instruction::CastOps opcode =
2104     (SrcBits == DstBits ? Instruction::BitCast :
2105      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2106   return Create(opcode, C, Ty, Name, InsertBefore);
2107 }
2108
2109 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
2110                                  const Twine &Name, 
2111                                  BasicBlock *InsertAtEnd) {
2112   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2113          "Invalid cast");
2114   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2115   unsigned DstBits = Ty->getScalarSizeInBits();
2116   Instruction::CastOps opcode =
2117     (SrcBits == DstBits ? Instruction::BitCast :
2118      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2119   return Create(opcode, C, Ty, Name, InsertAtEnd);
2120 }
2121
2122 // Check whether it is valid to call getCastOpcode for these types.
2123 // This routine must be kept in sync with getCastOpcode.
2124 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2125   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2126     return false;
2127
2128   if (SrcTy == DestTy)
2129     return true;
2130
2131   // Get the bit sizes, we'll need these
2132   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
2133   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2134
2135   // Run through the possibilities ...
2136   if (DestTy->isInteger()) {                   // Casting to integral
2137     if (SrcTy->isInteger()) {                  // Casting from integral
2138         return true;
2139     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
2140       return true;
2141     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2142                                                // Casting from vector
2143       return DestBits == PTy->getBitWidth();
2144     } else {                                   // Casting from something else
2145       return isa<PointerType>(SrcTy);
2146     }
2147   } else if (DestTy->isFloatingPoint()) {      // Casting to floating pt
2148     if (SrcTy->isInteger()) {                  // Casting from integral
2149       return true;
2150     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
2151       return true;
2152     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2153                                                // Casting from vector
2154       return DestBits == PTy->getBitWidth();
2155     } else {                                   // Casting from something else
2156       return false;
2157     }
2158   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2159                                                 // Casting to vector
2160     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2161                                                 // Casting from vector
2162       return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2163     } else {                                    // Casting from something else
2164       return DestPTy->getBitWidth() == SrcBits;
2165     }
2166   } else if (isa<PointerType>(DestTy)) {        // Casting to pointer
2167     if (isa<PointerType>(SrcTy)) {              // Casting from pointer
2168       return true;
2169     } else if (SrcTy->isInteger()) {            // Casting from integral
2170       return true;
2171     } else {                                    // Casting from something else
2172       return false;
2173     }
2174   } else {                                      // Casting to something else
2175     return false;
2176   }
2177 }
2178
2179 // Provide a way to get a "cast" where the cast opcode is inferred from the 
2180 // types and size of the operand. This, basically, is a parallel of the 
2181 // logic in the castIsValid function below.  This axiom should hold:
2182 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2183 // should not assert in castIsValid. In other words, this produces a "correct"
2184 // casting opcode for the arguments passed to it.
2185 // This routine must be kept in sync with isCastable.
2186 Instruction::CastOps
2187 CastInst::getCastOpcode(
2188   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2189   // Get the bit sizes, we'll need these
2190   const Type *SrcTy = Src->getType();
2191   unsigned SrcBits = SrcTy->getScalarSizeInBits();   // 0 for ptr
2192   unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2193
2194   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2195          "Only first class types are castable!");
2196
2197   // Run through the possibilities ...
2198   if (DestTy->isInteger()) {                       // Casting to integral
2199     if (SrcTy->isInteger()) {                      // Casting from integral
2200       if (DestBits < SrcBits)
2201         return Trunc;                               // int -> smaller int
2202       else if (DestBits > SrcBits) {                // its an extension
2203         if (SrcIsSigned)
2204           return SExt;                              // signed -> SEXT
2205         else
2206           return ZExt;                              // unsigned -> ZEXT
2207       } else {
2208         return BitCast;                             // Same size, No-op cast
2209       }
2210     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
2211       if (DestIsSigned) 
2212         return FPToSI;                              // FP -> sint
2213       else
2214         return FPToUI;                              // FP -> uint 
2215     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2216       assert(DestBits == PTy->getBitWidth() &&
2217                "Casting vector to integer of different width");
2218       PTy = NULL;
2219       return BitCast;                             // Same size, no-op cast
2220     } else {
2221       assert(isa<PointerType>(SrcTy) &&
2222              "Casting from a value that is not first-class type");
2223       return PtrToInt;                              // ptr -> int
2224     }
2225   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
2226     if (SrcTy->isInteger()) {                      // Casting from integral
2227       if (SrcIsSigned)
2228         return SIToFP;                              // sint -> FP
2229       else
2230         return UIToFP;                              // uint -> FP
2231     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
2232       if (DestBits < SrcBits) {
2233         return FPTrunc;                             // FP -> smaller FP
2234       } else if (DestBits > SrcBits) {
2235         return FPExt;                               // FP -> larger FP
2236       } else  {
2237         return BitCast;                             // same size, no-op cast
2238       }
2239     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2240       assert(DestBits == PTy->getBitWidth() &&
2241              "Casting vector to floating point of different width");
2242       PTy = NULL;
2243       return BitCast;                             // same size, no-op cast
2244     } else {
2245       llvm_unreachable("Casting pointer or non-first class to float");
2246     }
2247   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2248     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2249       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2250              "Casting vector to vector of different widths");
2251       SrcPTy = NULL;
2252       return BitCast;                             // vector -> vector
2253     } else if (DestPTy->getBitWidth() == SrcBits) {
2254       return BitCast;                               // float/int -> vector
2255     } else {
2256       assert(!"Illegal cast to vector (wrong type or size)");
2257     }
2258   } else if (isa<PointerType>(DestTy)) {
2259     if (isa<PointerType>(SrcTy)) {
2260       return BitCast;                               // ptr -> ptr
2261     } else if (SrcTy->isInteger()) {
2262       return IntToPtr;                              // int -> ptr
2263     } else {
2264       assert(!"Casting pointer to other than pointer or int");
2265     }
2266   } else {
2267     assert(!"Casting to type that is not first-class");
2268   }
2269
2270   // If we fall through to here we probably hit an assertion cast above
2271   // and assertions are not turned on. Anything we return is an error, so
2272   // BitCast is as good a choice as any.
2273   return BitCast;
2274 }
2275
2276 //===----------------------------------------------------------------------===//
2277 //                    CastInst SubClass Constructors
2278 //===----------------------------------------------------------------------===//
2279
2280 /// Check that the construction parameters for a CastInst are correct. This
2281 /// could be broken out into the separate constructors but it is useful to have
2282 /// it in one place and to eliminate the redundant code for getting the sizes
2283 /// of the types involved.
2284 bool 
2285 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2286
2287   // Check for type sanity on the arguments
2288   const Type *SrcTy = S->getType();
2289   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2290     return false;
2291
2292   // Get the size of the types in bits, we'll need this later
2293   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2294   unsigned DstBitSize = DstTy->getScalarSizeInBits();
2295
2296   // Switch on the opcode provided
2297   switch (op) {
2298   default: return false; // This is an input error
2299   case Instruction::Trunc:
2300     return SrcTy->isIntOrIntVector() &&
2301            DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2302   case Instruction::ZExt:
2303     return SrcTy->isIntOrIntVector() &&
2304            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2305   case Instruction::SExt: 
2306     return SrcTy->isIntOrIntVector() &&
2307            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2308   case Instruction::FPTrunc:
2309     return SrcTy->isFPOrFPVector() &&
2310            DstTy->isFPOrFPVector() && 
2311            SrcBitSize > DstBitSize;
2312   case Instruction::FPExt:
2313     return SrcTy->isFPOrFPVector() &&
2314            DstTy->isFPOrFPVector() && 
2315            SrcBitSize < DstBitSize;
2316   case Instruction::UIToFP:
2317   case Instruction::SIToFP:
2318     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2319       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2320         return SVTy->getElementType()->isIntOrIntVector() &&
2321                DVTy->getElementType()->isFPOrFPVector() &&
2322                SVTy->getNumElements() == DVTy->getNumElements();
2323       }
2324     }
2325     return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2326   case Instruction::FPToUI:
2327   case Instruction::FPToSI:
2328     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2329       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2330         return SVTy->getElementType()->isFPOrFPVector() &&
2331                DVTy->getElementType()->isIntOrIntVector() &&
2332                SVTy->getNumElements() == DVTy->getNumElements();
2333       }
2334     }
2335     return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2336   case Instruction::PtrToInt:
2337     return isa<PointerType>(SrcTy) && DstTy->isInteger();
2338   case Instruction::IntToPtr:
2339     return SrcTy->isInteger() && isa<PointerType>(DstTy);
2340   case Instruction::BitCast:
2341     // BitCast implies a no-op cast of type only. No bits change.
2342     // However, you can't cast pointers to anything but pointers.
2343     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2344       return false;
2345
2346     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2347     // these cases, the cast is okay if the source and destination bit widths
2348     // are identical.
2349     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2350   }
2351 }
2352
2353 TruncInst::TruncInst(
2354   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2355 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2356   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2357 }
2358
2359 TruncInst::TruncInst(
2360   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2361 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2362   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2363 }
2364
2365 ZExtInst::ZExtInst(
2366   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2367 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2368   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2369 }
2370
2371 ZExtInst::ZExtInst(
2372   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2373 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2374   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2375 }
2376 SExtInst::SExtInst(
2377   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2378 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2379   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2380 }
2381
2382 SExtInst::SExtInst(
2383   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2384 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2385   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2386 }
2387
2388 FPTruncInst::FPTruncInst(
2389   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2390 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2391   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2392 }
2393
2394 FPTruncInst::FPTruncInst(
2395   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2396 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2397   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2398 }
2399
2400 FPExtInst::FPExtInst(
2401   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2402 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2403   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2404 }
2405
2406 FPExtInst::FPExtInst(
2407   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2408 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2409   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2410 }
2411
2412 UIToFPInst::UIToFPInst(
2413   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2414 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2415   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2416 }
2417
2418 UIToFPInst::UIToFPInst(
2419   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2420 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2421   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2422 }
2423
2424 SIToFPInst::SIToFPInst(
2425   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2426 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2427   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2428 }
2429
2430 SIToFPInst::SIToFPInst(
2431   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2432 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2433   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2434 }
2435
2436 FPToUIInst::FPToUIInst(
2437   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2438 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2439   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2440 }
2441
2442 FPToUIInst::FPToUIInst(
2443   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2444 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2445   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2446 }
2447
2448 FPToSIInst::FPToSIInst(
2449   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2450 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2451   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2452 }
2453
2454 FPToSIInst::FPToSIInst(
2455   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2456 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2457   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2458 }
2459
2460 PtrToIntInst::PtrToIntInst(
2461   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2462 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2463   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2464 }
2465
2466 PtrToIntInst::PtrToIntInst(
2467   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2468 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2469   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2470 }
2471
2472 IntToPtrInst::IntToPtrInst(
2473   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2474 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2475   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2476 }
2477
2478 IntToPtrInst::IntToPtrInst(
2479   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2480 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2481   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2482 }
2483
2484 BitCastInst::BitCastInst(
2485   Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2486 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2487   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2488 }
2489
2490 BitCastInst::BitCastInst(
2491   Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2492 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2493   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2494 }
2495
2496 //===----------------------------------------------------------------------===//
2497 //                               CmpInst Classes
2498 //===----------------------------------------------------------------------===//
2499
2500 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2501                  Value *LHS, Value *RHS, const Twine &Name,
2502                  Instruction *InsertBefore)
2503   : Instruction(ty, op,
2504                 OperandTraits<CmpInst>::op_begin(this),
2505                 OperandTraits<CmpInst>::operands(this),
2506                 InsertBefore) {
2507     Op<0>() = LHS;
2508     Op<1>() = RHS;
2509   SubclassData = predicate;
2510   setName(Name);
2511 }
2512
2513 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2514                  Value *LHS, Value *RHS, const Twine &Name,
2515                  BasicBlock *InsertAtEnd)
2516   : Instruction(ty, op,
2517                 OperandTraits<CmpInst>::op_begin(this),
2518                 OperandTraits<CmpInst>::operands(this),
2519                 InsertAtEnd) {
2520   Op<0>() = LHS;
2521   Op<1>() = RHS;
2522   SubclassData = predicate;
2523   setName(Name);
2524 }
2525
2526 CmpInst *
2527 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
2528                 Value *S1, Value *S2, 
2529                 const Twine &Name, Instruction *InsertBefore) {
2530   if (Op == Instruction::ICmp) {
2531     if (InsertBefore)
2532       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2533                           S1, S2, Name);
2534     else
2535       return new ICmpInst(Context, CmpInst::Predicate(predicate),
2536                           S1, S2, Name);
2537   }
2538   
2539   if (InsertBefore)
2540     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2541                         S1, S2, Name);
2542   else
2543     return new FCmpInst(Context, CmpInst::Predicate(predicate),
2544                         S1, S2, Name);
2545 }
2546
2547 CmpInst *
2548 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2549                 const Twine &Name, BasicBlock *InsertAtEnd) {
2550   if (Op == Instruction::ICmp) {
2551     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2552                         S1, S2, Name);
2553   }
2554   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2555                       S1, S2, Name);
2556 }
2557
2558 void CmpInst::swapOperands() {
2559   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2560     IC->swapOperands();
2561   else
2562     cast<FCmpInst>(this)->swapOperands();
2563 }
2564
2565 bool CmpInst::isCommutative() {
2566   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2567     return IC->isCommutative();
2568   return cast<FCmpInst>(this)->isCommutative();
2569 }
2570
2571 bool CmpInst::isEquality() {
2572   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2573     return IC->isEquality();
2574   return cast<FCmpInst>(this)->isEquality();
2575 }
2576
2577
2578 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2579   switch (pred) {
2580     default: assert(!"Unknown cmp predicate!");
2581     case ICMP_EQ: return ICMP_NE;
2582     case ICMP_NE: return ICMP_EQ;
2583     case ICMP_UGT: return ICMP_ULE;
2584     case ICMP_ULT: return ICMP_UGE;
2585     case ICMP_UGE: return ICMP_ULT;
2586     case ICMP_ULE: return ICMP_UGT;
2587     case ICMP_SGT: return ICMP_SLE;
2588     case ICMP_SLT: return ICMP_SGE;
2589     case ICMP_SGE: return ICMP_SLT;
2590     case ICMP_SLE: return ICMP_SGT;
2591
2592     case FCMP_OEQ: return FCMP_UNE;
2593     case FCMP_ONE: return FCMP_UEQ;
2594     case FCMP_OGT: return FCMP_ULE;
2595     case FCMP_OLT: return FCMP_UGE;
2596     case FCMP_OGE: return FCMP_ULT;
2597     case FCMP_OLE: return FCMP_UGT;
2598     case FCMP_UEQ: return FCMP_ONE;
2599     case FCMP_UNE: return FCMP_OEQ;
2600     case FCMP_UGT: return FCMP_OLE;
2601     case FCMP_ULT: return FCMP_OGE;
2602     case FCMP_UGE: return FCMP_OLT;
2603     case FCMP_ULE: return FCMP_OGT;
2604     case FCMP_ORD: return FCMP_UNO;
2605     case FCMP_UNO: return FCMP_ORD;
2606     case FCMP_TRUE: return FCMP_FALSE;
2607     case FCMP_FALSE: return FCMP_TRUE;
2608   }
2609 }
2610
2611 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2612   switch (pred) {
2613     default: assert(! "Unknown icmp predicate!");
2614     case ICMP_EQ: case ICMP_NE: 
2615     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2616        return pred;
2617     case ICMP_UGT: return ICMP_SGT;
2618     case ICMP_ULT: return ICMP_SLT;
2619     case ICMP_UGE: return ICMP_SGE;
2620     case ICMP_ULE: return ICMP_SLE;
2621   }
2622 }
2623
2624 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2625   switch (pred) {
2626     default: assert(! "Unknown icmp predicate!");
2627     case ICMP_EQ: case ICMP_NE: 
2628     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
2629        return pred;
2630     case ICMP_SGT: return ICMP_UGT;
2631     case ICMP_SLT: return ICMP_ULT;
2632     case ICMP_SGE: return ICMP_UGE;
2633     case ICMP_SLE: return ICMP_ULE;
2634   }
2635 }
2636
2637 bool ICmpInst::isSignedPredicate(Predicate pred) {
2638   switch (pred) {
2639     default: assert(! "Unknown icmp predicate!");
2640     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2641       return true;
2642     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
2643     case ICMP_UGE: case ICMP_ULE:
2644       return false;
2645   }
2646 }
2647
2648 /// Initialize a set of values that all satisfy the condition with C.
2649 ///
2650 ConstantRange 
2651 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2652   APInt Lower(C);
2653   APInt Upper(C);
2654   uint32_t BitWidth = C.getBitWidth();
2655   switch (pred) {
2656   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2657   case ICmpInst::ICMP_EQ: Upper++; break;
2658   case ICmpInst::ICMP_NE: Lower++; break;
2659   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2660   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2661   case ICmpInst::ICMP_UGT: 
2662     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2663     break;
2664   case ICmpInst::ICMP_SGT:
2665     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2666     break;
2667   case ICmpInst::ICMP_ULE: 
2668     Lower = APInt::getMinValue(BitWidth); Upper++; 
2669     break;
2670   case ICmpInst::ICMP_SLE: 
2671     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2672     break;
2673   case ICmpInst::ICMP_UGE:
2674     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2675     break;
2676   case ICmpInst::ICMP_SGE:
2677     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2678     break;
2679   }
2680   return ConstantRange(Lower, Upper);
2681 }
2682
2683 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2684   switch (pred) {
2685     default: assert(!"Unknown cmp predicate!");
2686     case ICMP_EQ: case ICMP_NE:
2687       return pred;
2688     case ICMP_SGT: return ICMP_SLT;
2689     case ICMP_SLT: return ICMP_SGT;
2690     case ICMP_SGE: return ICMP_SLE;
2691     case ICMP_SLE: return ICMP_SGE;
2692     case ICMP_UGT: return ICMP_ULT;
2693     case ICMP_ULT: return ICMP_UGT;
2694     case ICMP_UGE: return ICMP_ULE;
2695     case ICMP_ULE: return ICMP_UGE;
2696   
2697     case FCMP_FALSE: case FCMP_TRUE:
2698     case FCMP_OEQ: case FCMP_ONE:
2699     case FCMP_UEQ: case FCMP_UNE:
2700     case FCMP_ORD: case FCMP_UNO:
2701       return pred;
2702     case FCMP_OGT: return FCMP_OLT;
2703     case FCMP_OLT: return FCMP_OGT;
2704     case FCMP_OGE: return FCMP_OLE;
2705     case FCMP_OLE: return FCMP_OGE;
2706     case FCMP_UGT: return FCMP_ULT;
2707     case FCMP_ULT: return FCMP_UGT;
2708     case FCMP_UGE: return FCMP_ULE;
2709     case FCMP_ULE: return FCMP_UGE;
2710   }
2711 }
2712
2713 bool CmpInst::isUnsigned(unsigned short predicate) {
2714   switch (predicate) {
2715     default: return false;
2716     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
2717     case ICmpInst::ICMP_UGE: return true;
2718   }
2719 }
2720
2721 bool CmpInst::isSigned(unsigned short predicate){
2722   switch (predicate) {
2723     default: return false;
2724     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
2725     case ICmpInst::ICMP_SGE: return true;
2726   }
2727 }
2728
2729 bool CmpInst::isOrdered(unsigned short predicate) {
2730   switch (predicate) {
2731     default: return false;
2732     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
2733     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
2734     case FCmpInst::FCMP_ORD: return true;
2735   }
2736 }
2737       
2738 bool CmpInst::isUnordered(unsigned short predicate) {
2739   switch (predicate) {
2740     default: return false;
2741     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
2742     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
2743     case FCmpInst::FCMP_UNO: return true;
2744   }
2745 }
2746
2747 //===----------------------------------------------------------------------===//
2748 //                        SwitchInst Implementation
2749 //===----------------------------------------------------------------------===//
2750
2751 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2752   assert(Value && Default);
2753   ReservedSpace = 2+NumCases*2;
2754   NumOperands = 2;
2755   OperandList = allocHungoffUses(ReservedSpace);
2756
2757   OperandList[0] = Value;
2758   OperandList[1] = Default;
2759 }
2760
2761 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2762 /// switch on and a default destination.  The number of additional cases can
2763 /// be specified here to make memory allocation more efficient.  This
2764 /// constructor can also autoinsert before another instruction.
2765 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2766                        Instruction *InsertBefore)
2767   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2768   init(Value, Default, NumCases);
2769 }
2770
2771 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2772 /// switch on and a default destination.  The number of additional cases can
2773 /// be specified here to make memory allocation more efficient.  This
2774 /// constructor also autoinserts at the end of the specified BasicBlock.
2775 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2776                        BasicBlock *InsertAtEnd)
2777   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2778   init(Value, Default, NumCases);
2779 }
2780
2781 SwitchInst::SwitchInst(const SwitchInst &SI)
2782   : TerminatorInst(Type::VoidTy, Instruction::Switch,
2783                    allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2784   Use *OL = OperandList, *InOL = SI.OperandList;
2785   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2786     OL[i] = InOL[i];
2787     OL[i+1] = InOL[i+1];
2788   }
2789 }
2790
2791 SwitchInst::~SwitchInst() {
2792   dropHungoffUses(OperandList);
2793 }
2794
2795
2796 /// addCase - Add an entry to the switch instruction...
2797 ///
2798 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2799   unsigned OpNo = NumOperands;
2800   if (OpNo+2 > ReservedSpace)
2801     resizeOperands(0);  // Get more space!
2802   // Initialize some new operands.
2803   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2804   NumOperands = OpNo+2;
2805   OperandList[OpNo] = OnVal;
2806   OperandList[OpNo+1] = Dest;
2807 }
2808
2809 /// removeCase - This method removes the specified successor from the switch
2810 /// instruction.  Note that this cannot be used to remove the default
2811 /// destination (successor #0).
2812 ///
2813 void SwitchInst::removeCase(unsigned idx) {
2814   assert(idx != 0 && "Cannot remove the default case!");
2815   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2816
2817   unsigned NumOps = getNumOperands();
2818   Use *OL = OperandList;
2819
2820   // Move everything after this operand down.
2821   //
2822   // FIXME: we could just swap with the end of the list, then erase.  However,
2823   // client might not expect this to happen.  The code as it is thrashes the
2824   // use/def lists, which is kinda lame.
2825   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2826     OL[i-2] = OL[i];
2827     OL[i-2+1] = OL[i+1];
2828   }
2829
2830   // Nuke the last value.
2831   OL[NumOps-2].set(0);
2832   OL[NumOps-2+1].set(0);
2833   NumOperands = NumOps-2;
2834 }
2835
2836 /// resizeOperands - resize operands - This adjusts the length of the operands
2837 /// list according to the following behavior:
2838 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
2839 ///      of operation.  This grows the number of ops by 3 times.
2840 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
2841 ///   3. If NumOps == NumOperands, trim the reserved space.
2842 ///
2843 void SwitchInst::resizeOperands(unsigned NumOps) {
2844   unsigned e = getNumOperands();
2845   if (NumOps == 0) {
2846     NumOps = e*3;
2847   } else if (NumOps*2 > NumOperands) {
2848     // No resize needed.
2849     if (ReservedSpace >= NumOps) return;
2850   } else if (NumOps == NumOperands) {
2851     if (ReservedSpace == NumOps) return;
2852   } else {
2853     return;
2854   }
2855
2856   ReservedSpace = NumOps;
2857   Use *NewOps = allocHungoffUses(NumOps);
2858   Use *OldOps = OperandList;
2859   for (unsigned i = 0; i != e; ++i) {
2860       NewOps[i] = OldOps[i];
2861   }
2862   OperandList = NewOps;
2863   if (OldOps) Use::zap(OldOps, OldOps + e, true);
2864 }
2865
2866
2867 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2868   return getSuccessor(idx);
2869 }
2870 unsigned SwitchInst::getNumSuccessorsV() const {
2871   return getNumSuccessors();
2872 }
2873 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2874   setSuccessor(idx, B);
2875 }
2876
2877 // Define these methods here so vtables don't get emitted into every translation
2878 // unit that uses these classes.
2879
2880 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2881   return new(getNumOperands()) GetElementPtrInst(*this);
2882 }
2883
2884 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2885   return Create(getOpcode(), Op<0>(), Op<1>());
2886 }
2887
2888 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2889   return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2890 }
2891 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2892   return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2893 }
2894
2895 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2896   return new ExtractValueInst(*this);
2897 }
2898 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2899   return new InsertValueInst(*this);
2900 }
2901
2902 MallocInst *MallocInst::clone(LLVMContext&) const {
2903   return new MallocInst(*this);
2904 }
2905
2906 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2907   return new AllocaInst(*this);
2908 }
2909
2910 FreeInst *FreeInst::clone(LLVMContext&) const {
2911   return new FreeInst(getOperand(0));
2912 }
2913
2914 LoadInst *LoadInst::clone(LLVMContext&) const {
2915   return new LoadInst(*this);
2916 }
2917
2918 StoreInst *StoreInst::clone(LLVMContext&) const {
2919   return new StoreInst(*this);
2920 }
2921
2922 CastInst *TruncInst::clone(LLVMContext&) const {
2923   return new TruncInst(*this);
2924 }
2925
2926 CastInst *ZExtInst::clone(LLVMContext&) const {
2927   return new ZExtInst(*this);
2928 }
2929
2930 CastInst *SExtInst::clone(LLVMContext&) const {
2931   return new SExtInst(*this);
2932 }
2933
2934 CastInst *FPTruncInst::clone(LLVMContext&) const {
2935   return new FPTruncInst(*this);
2936 }
2937
2938 CastInst *FPExtInst::clone(LLVMContext&) const {
2939   return new FPExtInst(*this);
2940 }
2941
2942 CastInst *UIToFPInst::clone(LLVMContext&) const {
2943   return new UIToFPInst(*this);
2944 }
2945
2946 CastInst *SIToFPInst::clone(LLVMContext&) const {
2947   return new SIToFPInst(*this);
2948 }
2949
2950 CastInst *FPToUIInst::clone(LLVMContext&) const {
2951   return new FPToUIInst(*this);
2952 }
2953
2954 CastInst *FPToSIInst::clone(LLVMContext&) const {
2955   return new FPToSIInst(*this);
2956 }
2957
2958 CastInst *PtrToIntInst::clone(LLVMContext&) const {
2959   return new PtrToIntInst(*this);
2960 }
2961
2962 CastInst *IntToPtrInst::clone(LLVMContext&) const {
2963   return new IntToPtrInst(*this);
2964 }
2965
2966 CastInst *BitCastInst::clone(LLVMContext&) const {
2967   return new BitCastInst(*this);
2968 }
2969
2970 CallInst *CallInst::clone(LLVMContext&) const {
2971   return new(getNumOperands()) CallInst(*this);
2972 }
2973
2974 SelectInst *SelectInst::clone(LLVMContext&)   const {
2975   return new(getNumOperands()) SelectInst(*this);
2976 }
2977
2978 VAArgInst *VAArgInst::clone(LLVMContext&) const {
2979   return new VAArgInst(*this);
2980 }
2981
2982 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
2983   return ExtractElementInst::Create(*this);
2984 }
2985
2986 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
2987   return InsertElementInst::Create(*this);
2988 }
2989
2990 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
2991   return new ShuffleVectorInst(*this);
2992 }
2993
2994 PHINode *PHINode::clone(LLVMContext&) const {
2995   return new PHINode(*this);
2996 }
2997
2998 ReturnInst *ReturnInst::clone(LLVMContext&) const {
2999   return new(getNumOperands()) ReturnInst(*this);
3000 }
3001
3002 BranchInst *BranchInst::clone(LLVMContext&) const {
3003   unsigned Ops(getNumOperands());
3004   return new(Ops, Ops == 1) BranchInst(*this);
3005 }
3006
3007 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3008   return new SwitchInst(*this);
3009 }
3010
3011 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3012   return new(getNumOperands()) InvokeInst(*this);
3013 }
3014
3015 UnwindInst *UnwindInst::clone(LLVMContext&) const {
3016   return new UnwindInst();
3017 }
3018
3019 UnreachableInst *UnreachableInst::clone(LLVMContext&) const {
3020   return new UnreachableInst();
3021 }