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