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