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