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