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