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