Fix a fixme in CondPropagate.cpp by moving a PhiNode optimization into
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
21 using namespace llvm;
22
23 unsigned CallSite::getCallingConv() const {
24   if (CallInst *CI = dyn_cast<CallInst>(I))
25     return CI->getCallingConv();
26   else
27     return cast<InvokeInst>(I)->getCallingConv();
28 }
29 void CallSite::setCallingConv(unsigned CC) {
30   if (CallInst *CI = dyn_cast<CallInst>(I))
31     CI->setCallingConv(CC);
32   else
33     cast<InvokeInst>(I)->setCallingConv(CC);
34 }
35
36
37 //===----------------------------------------------------------------------===//
38 //                            TerminatorInst Class
39 //===----------------------------------------------------------------------===//
40
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42                                Use *Ops, unsigned NumOps, Instruction *IB)
43   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
44 }
45
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47                                Use *Ops, unsigned NumOps, BasicBlock *IAE)
48   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
49 }
50
51
52
53 //===----------------------------------------------------------------------===//
54 //                               PHINode Class
55 //===----------------------------------------------------------------------===//
56
57 PHINode::PHINode(const PHINode &PN)
58   : Instruction(PN.getType(), Instruction::PHI,
59                 new Use[PN.getNumOperands()], PN.getNumOperands()),
60     ReservedSpace(PN.getNumOperands()) {
61   Use *OL = OperandList;
62   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
63     OL[i].init(PN.getOperand(i), this);
64     OL[i+1].init(PN.getOperand(i+1), this);
65   }
66 }
67
68 PHINode::~PHINode() {
69   delete [] OperandList;
70 }
71
72 // removeIncomingValue - Remove an incoming value.  This is useful if a
73 // predecessor basic block is deleted.
74 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
75   unsigned NumOps = getNumOperands();
76   Use *OL = OperandList;
77   assert(Idx*2 < NumOps && "BB not in PHI node!");
78   Value *Removed = OL[Idx*2];
79
80   // Move everything after this operand down.
81   //
82   // FIXME: we could just swap with the end of the list, then erase.  However,
83   // client might not expect this to happen.  The code as it is thrashes the
84   // use/def lists, which is kinda lame.
85   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
86     OL[i-2] = OL[i];
87     OL[i-2+1] = OL[i+1];
88   }
89
90   // Nuke the last value.
91   OL[NumOps-2].set(0);
92   OL[NumOps-2+1].set(0);
93   NumOperands = NumOps-2;
94
95   // If the PHI node is dead, because it has zero entries, nuke it now.
96   if (NumOps == 2 && DeletePHIIfEmpty) {
97     // If anyone is using this PHI, make them use a dummy value instead...
98     replaceAllUsesWith(UndefValue::get(getType()));
99     eraseFromParent();
100   }
101   return Removed;
102 }
103
104 /// resizeOperands - resize operands - This adjusts the length of the operands
105 /// list according to the following behavior:
106 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
107 ///      of operation.  This grows the number of ops by 1.5 times.
108 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
109 ///   3. If NumOps == NumOperands, trim the reserved space.
110 ///
111 void PHINode::resizeOperands(unsigned NumOps) {
112   if (NumOps == 0) {
113     NumOps = (getNumOperands())*3/2;
114     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
115   } else if (NumOps*2 > NumOperands) {
116     // No resize needed.
117     if (ReservedSpace >= NumOps) return;
118   } else if (NumOps == NumOperands) {
119     if (ReservedSpace == NumOps) return;
120   } else {
121     return;
122   }
123
124   ReservedSpace = NumOps;
125   Use *NewOps = new Use[NumOps];
126   Use *OldOps = OperandList;
127   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
128       NewOps[i].init(OldOps[i], this);
129       OldOps[i].set(0);
130   }
131   delete [] OldOps;
132   OperandList = NewOps;
133 }
134
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
137 ///
138 Value *PHINode::hasConstantValue() {
139   // If the PHI node only has one incoming value, eliminate the PHI node...
140   if (getNumIncomingValues() == 1)
141     return getIncomingValue(0);
142   
143   // Otherwise if all of the incoming values are the same for the PHI, replace
144   // the PHI node with the incoming value.
145   //
146   Value *InVal = 0;
147   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
148     if (getIncomingValue(i) != this &&  // Not the PHI node itself...
149         !isa<UndefValue>(getIncomingValue(i)))
150       if (InVal && getIncomingValue(i) != InVal)
151         return 0;  // Not the same, bail out.
152       else
153         InVal = getIncomingValue(i);
154   
155   // The only case that could cause InVal to be null is if we have a PHI node
156   // that only has entries for itself.  In this case, there is no entry into the
157   // loop, so kill the PHI.
158   //
159   if (InVal == 0) InVal = UndefValue::get(getType());
160   
161   // All of the incoming values are the same, return the value now.
162   return InVal;
163 }
164
165
166 //===----------------------------------------------------------------------===//
167 //                        CallInst Implementation
168 //===----------------------------------------------------------------------===//
169
170 CallInst::~CallInst() {
171   delete [] OperandList;
172 }
173
174 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
175   NumOperands = Params.size()+1;
176   Use *OL = OperandList = new Use[Params.size()+1];
177   OL[0].init(Func, this);
178
179   const FunctionType *FTy =
180     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
181
182   assert((Params.size() == FTy->getNumParams() ||
183           (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
184          "Calling a function with bad signature");
185   for (unsigned i = 0, e = Params.size(); i != e; ++i)
186     OL[i+1].init(Params[i], this);
187 }
188
189 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
190   NumOperands = 3;
191   Use *OL = OperandList = new Use[3];
192   OL[0].init(Func, this);
193   OL[1].init(Actual1, this);
194   OL[2].init(Actual2, this);
195
196   const FunctionType *FTy =
197     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
198
199   assert((FTy->getNumParams() == 2 ||
200           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
201          "Calling a function with bad signature");
202 }
203
204 void CallInst::init(Value *Func, Value *Actual) {
205   NumOperands = 2;
206   Use *OL = OperandList = new Use[2];
207   OL[0].init(Func, this);
208   OL[1].init(Actual, this);
209
210   const FunctionType *FTy =
211     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
212
213   assert((FTy->getNumParams() == 1 ||
214           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
215          "Calling a function with bad signature");
216 }
217
218 void CallInst::init(Value *Func) {
219   NumOperands = 1;
220   Use *OL = OperandList = new Use[1];
221   OL[0].init(Func, this);
222
223   const FunctionType *MTy =
224     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
225
226   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
227 }
228
229 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
230                    const std::string &Name, Instruction *InsertBefore)
231   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
232                                  ->getElementType())->getReturnType(),
233                 Instruction::Call, 0, 0, Name, InsertBefore) {
234   init(Func, Params);
235 }
236
237 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
238                    const std::string &Name, BasicBlock *InsertAtEnd)
239   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
240                                  ->getElementType())->getReturnType(),
241                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
242   init(Func, Params);
243 }
244
245 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
246                    const std::string &Name, Instruction  *InsertBefore)
247   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
248                                    ->getElementType())->getReturnType(),
249                 Instruction::Call, 0, 0, Name, InsertBefore) {
250   init(Func, Actual1, Actual2);
251 }
252
253 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
254                    const std::string &Name, BasicBlock  *InsertAtEnd)
255   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
256                                    ->getElementType())->getReturnType(),
257                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
258   init(Func, Actual1, Actual2);
259 }
260
261 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
262                    Instruction  *InsertBefore)
263   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
264                                    ->getElementType())->getReturnType(),
265                 Instruction::Call, 0, 0, Name, InsertBefore) {
266   init(Func, Actual);
267 }
268
269 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
270                    BasicBlock  *InsertAtEnd)
271   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
272                                    ->getElementType())->getReturnType(),
273                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
274   init(Func, Actual);
275 }
276
277 CallInst::CallInst(Value *Func, const std::string &Name,
278                    Instruction *InsertBefore)
279   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
280                                    ->getElementType())->getReturnType(),
281                 Instruction::Call, 0, 0, Name, InsertBefore) {
282   init(Func);
283 }
284
285 CallInst::CallInst(Value *Func, const std::string &Name,
286                    BasicBlock *InsertAtEnd)
287   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
288                                    ->getElementType())->getReturnType(),
289                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
290   init(Func);
291 }
292
293 CallInst::CallInst(const CallInst &CI)
294   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
295                 CI.getNumOperands()) {
296   SubclassData = CI.SubclassData;
297   Use *OL = OperandList;
298   Use *InOL = CI.OperandList;
299   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
300     OL[i].init(InOL[i], this);
301 }
302
303
304 //===----------------------------------------------------------------------===//
305 //                        InvokeInst Implementation
306 //===----------------------------------------------------------------------===//
307
308 InvokeInst::~InvokeInst() {
309   delete [] OperandList;
310 }
311
312 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
313                       const std::vector<Value*> &Params) {
314   NumOperands = 3+Params.size();
315   Use *OL = OperandList = new Use[3+Params.size()];
316   OL[0].init(Fn, this);
317   OL[1].init(IfNormal, this);
318   OL[2].init(IfException, this);
319   const FunctionType *FTy =
320     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
321
322   assert((Params.size() == FTy->getNumParams()) ||
323          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
324          "Calling a function with bad signature");
325
326   for (unsigned i = 0, e = Params.size(); i != e; i++)
327     OL[i+3].init(Params[i], this);
328 }
329
330 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
331                        BasicBlock *IfException,
332                        const std::vector<Value*> &Params,
333                        const std::string &Name, Instruction *InsertBefore)
334   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
335                                     ->getElementType())->getReturnType(),
336                    Instruction::Invoke, 0, 0, Name, InsertBefore) {
337   init(Fn, IfNormal, IfException, Params);
338 }
339
340 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
341                        BasicBlock *IfException,
342                        const std::vector<Value*> &Params,
343                        const std::string &Name, BasicBlock *InsertAtEnd)
344   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
345                                     ->getElementType())->getReturnType(),
346                    Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
347   init(Fn, IfNormal, IfException, Params);
348 }
349
350 InvokeInst::InvokeInst(const InvokeInst &II)
351   : TerminatorInst(II.getType(), Instruction::Invoke,
352                    new Use[II.getNumOperands()], II.getNumOperands()) {
353   SubclassData = II.SubclassData;
354   Use *OL = OperandList, *InOL = II.OperandList;
355   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
356     OL[i].init(InOL[i], this);
357 }
358
359 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
360   return getSuccessor(idx);
361 }
362 unsigned InvokeInst::getNumSuccessorsV() const {
363   return getNumSuccessors();
364 }
365 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
366   return setSuccessor(idx, B);
367 }
368
369
370 //===----------------------------------------------------------------------===//
371 //                        ReturnInst Implementation
372 //===----------------------------------------------------------------------===//
373
374 void ReturnInst::init(Value *retVal) {
375   if (retVal && retVal->getType() != Type::VoidTy) {
376     assert(!isa<BasicBlock>(retVal) &&
377            "Cannot return basic block.  Probably using the incorrect ctor");
378     NumOperands = 1;
379     RetVal.init(retVal, this);
380   }
381 }
382
383 unsigned ReturnInst::getNumSuccessorsV() const {
384   return getNumSuccessors();
385 }
386
387 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
388 // emit the vtable for the class in this translation unit.
389 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
390   assert(0 && "ReturnInst has no successors!");
391 }
392
393 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
394   assert(0 && "ReturnInst has no successors!");
395   abort();
396   return 0;
397 }
398
399
400 //===----------------------------------------------------------------------===//
401 //                        UnwindInst Implementation
402 //===----------------------------------------------------------------------===//
403
404 unsigned UnwindInst::getNumSuccessorsV() const {
405   return getNumSuccessors();
406 }
407
408 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
409   assert(0 && "UnwindInst has no successors!");
410 }
411
412 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
413   assert(0 && "UnwindInst has no successors!");
414   abort();
415   return 0;
416 }
417
418 //===----------------------------------------------------------------------===//
419 //                      UnreachableInst Implementation
420 //===----------------------------------------------------------------------===//
421
422 unsigned UnreachableInst::getNumSuccessorsV() const {
423   return getNumSuccessors();
424 }
425
426 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
427   assert(0 && "UnwindInst has no successors!");
428 }
429
430 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
431   assert(0 && "UnwindInst has no successors!");
432   abort();
433   return 0;
434 }
435
436 //===----------------------------------------------------------------------===//
437 //                        BranchInst Implementation
438 //===----------------------------------------------------------------------===//
439
440 void BranchInst::AssertOK() {
441   if (isConditional())
442     assert(getCondition()->getType() == Type::BoolTy &&
443            "May only branch on boolean predicates!");
444 }
445
446 BranchInst::BranchInst(const BranchInst &BI) :
447   TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
448   OperandList[0].init(BI.getOperand(0), this);
449   if (BI.getNumOperands() != 1) {
450     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
451     OperandList[1].init(BI.getOperand(1), this);
452     OperandList[2].init(BI.getOperand(2), this);
453   }
454 }
455
456 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
457   return getSuccessor(idx);
458 }
459 unsigned BranchInst::getNumSuccessorsV() const {
460   return getNumSuccessors();
461 }
462 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
463   setSuccessor(idx, B);
464 }
465
466
467 //===----------------------------------------------------------------------===//
468 //                        AllocationInst Implementation
469 //===----------------------------------------------------------------------===//
470
471 static Value *getAISize(Value *Amt) {
472   if (!Amt)
473     Amt = ConstantUInt::get(Type::UIntTy, 1);
474   else
475     assert(Amt->getType() == Type::UIntTy &&
476            "Malloc/Allocation array size != UIntTy!");
477   return Amt;
478 }
479
480 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
481                                const std::string &Name,
482                                Instruction *InsertBefore)
483   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
484                      Name, InsertBefore) {
485   assert(Ty != Type::VoidTy && "Cannot allocate void!");
486 }
487
488 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
489                                const std::string &Name,
490                                BasicBlock *InsertAtEnd)
491   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
492                      Name, InsertAtEnd) {
493   assert(Ty != Type::VoidTy && "Cannot allocate void!");
494 }
495
496 bool AllocationInst::isArrayAllocation() const {
497   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
498     return CUI->getValue() != 1;
499   return true;
500 }
501
502 const Type *AllocationInst::getAllocatedType() const {
503   return getType()->getElementType();
504 }
505
506 AllocaInst::AllocaInst(const AllocaInst &AI)
507   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
508                    Instruction::Alloca) {
509 }
510
511 MallocInst::MallocInst(const MallocInst &MI)
512   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
513                    Instruction::Malloc) {
514 }
515
516 //===----------------------------------------------------------------------===//
517 //                             FreeInst Implementation
518 //===----------------------------------------------------------------------===//
519
520 void FreeInst::AssertOK() {
521   assert(isa<PointerType>(getOperand(0)->getType()) &&
522          "Can not free something of nonpointer type!");
523 }
524
525 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
526   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
527   AssertOK();
528 }
529
530 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
531   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
532   AssertOK();
533 }
534
535
536 //===----------------------------------------------------------------------===//
537 //                           LoadInst Implementation
538 //===----------------------------------------------------------------------===//
539
540 void LoadInst::AssertOK() {
541   assert(isa<PointerType>(getOperand(0)->getType()) &&
542          "Ptr must have pointer type.");
543 }
544
545 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
546   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
547                      Load, Ptr, Name, InsertBef) {
548   setVolatile(false);
549   AssertOK();
550 }
551
552 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
553   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
554                      Load, Ptr, Name, InsertAE) {
555   setVolatile(false);
556   AssertOK();
557 }
558
559 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
560                    Instruction *InsertBef)
561   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
562                      Load, Ptr, Name, InsertBef) {
563   setVolatile(isVolatile);
564   AssertOK();
565 }
566
567 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
568                    BasicBlock *InsertAE)
569   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
570                      Load, Ptr, Name, InsertAE) {
571   setVolatile(isVolatile);
572   AssertOK();
573 }
574
575
576 //===----------------------------------------------------------------------===//
577 //                           StoreInst Implementation
578 //===----------------------------------------------------------------------===//
579
580 void StoreInst::AssertOK() {
581   assert(isa<PointerType>(getOperand(1)->getType()) &&
582          "Ptr must have pointer type!");
583   assert(getOperand(0)->getType() ==
584                  cast<PointerType>(getOperand(1)->getType())->getElementType()
585          && "Ptr must be a pointer to Val type!");
586 }
587
588
589 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
590   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
591   Ops[0].init(val, this);
592   Ops[1].init(addr, this);
593   setVolatile(false);
594   AssertOK();
595 }
596
597 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
598   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
599   Ops[0].init(val, this);
600   Ops[1].init(addr, this);
601   setVolatile(false);
602   AssertOK();
603 }
604
605 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
606                      Instruction *InsertBefore)
607   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
608   Ops[0].init(val, this);
609   Ops[1].init(addr, this);
610   setVolatile(isVolatile);
611   AssertOK();
612 }
613
614 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
615                      BasicBlock *InsertAtEnd)
616   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
617   Ops[0].init(val, this);
618   Ops[1].init(addr, this);
619   setVolatile(isVolatile);
620   AssertOK();
621 }
622
623 //===----------------------------------------------------------------------===//
624 //                       GetElementPtrInst Implementation
625 //===----------------------------------------------------------------------===//
626
627 // checkType - Simple wrapper function to give a better assertion failure
628 // message on bad indexes for a gep instruction.
629 //
630 static inline const Type *checkType(const Type *Ty) {
631   assert(Ty && "Invalid indices for type!");
632   return Ty;
633 }
634
635 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
636   NumOperands = 1+Idx.size();
637   Use *OL = OperandList = new Use[NumOperands];
638   OL[0].init(Ptr, this);
639
640   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
641     OL[i+1].init(Idx[i], this);
642 }
643
644 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
645   NumOperands = 3;
646   Use *OL = OperandList = new Use[3];
647   OL[0].init(Ptr, this);
648   OL[1].init(Idx0, this);
649   OL[2].init(Idx1, this);
650 }
651
652 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
653   NumOperands = 2;
654   Use *OL = OperandList = new Use[2];
655   OL[0].init(Ptr, this);
656   OL[1].init(Idx, this);
657 }
658
659 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
660                                      const std::string &Name, Instruction *InBe)
661   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
662                                                           Idx, true))),
663                 GetElementPtr, 0, 0, Name, InBe) {
664   init(Ptr, Idx);
665 }
666
667 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
668                                      const std::string &Name, BasicBlock *IAE)
669   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
670                                                           Idx, true))),
671                 GetElementPtr, 0, 0, Name, IAE) {
672   init(Ptr, Idx);
673 }
674
675 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
676                                      const std::string &Name, Instruction *InBe)
677   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
678                 GetElementPtr, 0, 0, Name, InBe) {
679   init(Ptr, Idx);
680 }
681
682 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
683                                      const std::string &Name, BasicBlock *IAE)
684   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
685                 GetElementPtr, 0, 0, Name, IAE) {
686   init(Ptr, Idx);
687 }
688
689 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
690                                      const std::string &Name, Instruction *InBe)
691   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
692                                                           Idx0, Idx1, true))),
693                 GetElementPtr, 0, 0, Name, InBe) {
694   init(Ptr, Idx0, Idx1);
695 }
696
697 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
698                                      const std::string &Name, BasicBlock *IAE)
699   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
700                                                           Idx0, Idx1, true))),
701                 GetElementPtr, 0, 0, Name, IAE) {
702   init(Ptr, Idx0, Idx1);
703 }
704
705 GetElementPtrInst::~GetElementPtrInst() {
706   delete[] OperandList;
707 }
708
709 // getIndexedType - Returns the type of the element that would be loaded with
710 // a load instruction with the specified parameters.
711 //
712 // A null type is returned if the indices are invalid for the specified
713 // pointer type.
714 //
715 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
716                                               const std::vector<Value*> &Idx,
717                                               bool AllowCompositeLeaf) {
718   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
719
720   // Handle the special case of the empty set index set...
721   if (Idx.empty())
722     if (AllowCompositeLeaf ||
723         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
724       return cast<PointerType>(Ptr)->getElementType();
725     else
726       return 0;
727
728   unsigned CurIdx = 0;
729   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
730     if (Idx.size() == CurIdx) {
731       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
732       return 0;   // Can't load a whole structure or array!?!?
733     }
734
735     Value *Index = Idx[CurIdx++];
736     if (isa<PointerType>(CT) && CurIdx != 1)
737       return 0;  // Can only index into pointer types at the first index!
738     if (!CT->indexValid(Index)) return 0;
739     Ptr = CT->getTypeAtIndex(Index);
740
741     // If the new type forwards to another type, then it is in the middle
742     // of being refined to another type (and hence, may have dropped all
743     // references to what it was using before).  So, use the new forwarded
744     // type.
745     if (const Type * Ty = Ptr->getForwardedType()) {
746       Ptr = Ty;
747     }
748   }
749   return CurIdx == Idx.size() ? Ptr : 0;
750 }
751
752 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
753                                               Value *Idx0, Value *Idx1,
754                                               bool AllowCompositeLeaf) {
755   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
756   if (!PTy) return 0;   // Type isn't a pointer type!
757
758   // Check the pointer index.
759   if (!PTy->indexValid(Idx0)) return 0;
760
761   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
762   if (!CT || !CT->indexValid(Idx1)) return 0;
763
764   const Type *ElTy = CT->getTypeAtIndex(Idx1);
765   if (AllowCompositeLeaf || ElTy->isFirstClassType())
766     return ElTy;
767   return 0;
768 }
769
770 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
771   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
772   if (!PTy) return 0;   // Type isn't a pointer type!
773
774   // Check the pointer index.
775   if (!PTy->indexValid(Idx)) return 0;
776
777   return PTy->getElementType();
778 }
779
780 //===----------------------------------------------------------------------===//
781 //                             BinaryOperator Class
782 //===----------------------------------------------------------------------===//
783
784 void BinaryOperator::init(BinaryOps iType)
785 {
786   Value *LHS = getOperand(0), *RHS = getOperand(1);
787   assert(LHS->getType() == RHS->getType() &&
788          "Binary operator operand types must match!");
789 #ifndef NDEBUG
790   switch (iType) {
791   case Add: case Sub:
792   case Mul: case Div:
793   case Rem:
794     assert(getType() == LHS->getType() &&
795            "Arithmetic operation should return same type as operands!");
796     assert((getType()->isInteger() ||
797             getType()->isFloatingPoint() ||
798             isa<PackedType>(getType()) ) &&
799           "Tried to create an arithmetic operation on a non-arithmetic type!");
800     break;
801   case And: case Or:
802   case Xor:
803     assert(getType() == LHS->getType() &&
804            "Logical operation should return same type as operands!");
805     assert(getType()->isIntegral() &&
806            "Tried to create a logical operation on a non-integral type!");
807     break;
808   case SetLT: case SetGT: case SetLE:
809   case SetGE: case SetEQ: case SetNE:
810     assert(getType() == Type::BoolTy && "Setcc must return bool!");
811   default:
812     break;
813   }
814 #endif
815 }
816
817 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
818                                        const std::string &Name,
819                                        Instruction *InsertBefore) {
820   assert(S1->getType() == S2->getType() &&
821          "Cannot create binary operator with two operands of differing type!");
822   switch (Op) {
823   // Binary comparison operators...
824   case SetLT: case SetGT: case SetLE:
825   case SetGE: case SetEQ: case SetNE:
826     return new SetCondInst(Op, S1, S2, Name, InsertBefore);
827
828   default:
829     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
830   }
831 }
832
833 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
834                                        const std::string &Name,
835                                        BasicBlock *InsertAtEnd) {
836   BinaryOperator *Res = create(Op, S1, S2, Name);
837   InsertAtEnd->getInstList().push_back(Res);
838   return Res;
839 }
840
841 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
842                                           Instruction *InsertBefore) {
843   if (!Op->getType()->isFloatingPoint())
844     return new BinaryOperator(Instruction::Sub,
845                               Constant::getNullValue(Op->getType()), Op,
846                               Op->getType(), Name, InsertBefore);
847   else
848     return new BinaryOperator(Instruction::Sub,
849                               ConstantFP::get(Op->getType(), -0.0), Op,
850                               Op->getType(), Name, InsertBefore);
851 }
852
853 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
854                                           BasicBlock *InsertAtEnd) {
855   if (!Op->getType()->isFloatingPoint())
856     return new BinaryOperator(Instruction::Sub,
857                               Constant::getNullValue(Op->getType()), Op,
858                               Op->getType(), Name, InsertAtEnd);
859   else
860     return new BinaryOperator(Instruction::Sub,
861                               ConstantFP::get(Op->getType(), -0.0), Op,
862                               Op->getType(), Name, InsertAtEnd);
863 }
864
865 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
866                                           Instruction *InsertBefore) {
867   return new BinaryOperator(Instruction::Xor, Op,
868                             ConstantIntegral::getAllOnesValue(Op->getType()),
869                             Op->getType(), Name, InsertBefore);
870 }
871
872 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
873                                           BasicBlock *InsertAtEnd) {
874   return new BinaryOperator(Instruction::Xor, Op,
875                             ConstantIntegral::getAllOnesValue(Op->getType()),
876                             Op->getType(), Name, InsertAtEnd);
877 }
878
879
880 // isConstantAllOnes - Helper function for several functions below
881 static inline bool isConstantAllOnes(const Value *V) {
882   return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
883 }
884
885 bool BinaryOperator::isNeg(const Value *V) {
886   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
887     if (Bop->getOpcode() == Instruction::Sub)
888       if (!V->getType()->isFloatingPoint())
889         return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
890       else
891         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
892   return false;
893 }
894
895 bool BinaryOperator::isNot(const Value *V) {
896   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
897     return (Bop->getOpcode() == Instruction::Xor &&
898             (isConstantAllOnes(Bop->getOperand(1)) ||
899              isConstantAllOnes(Bop->getOperand(0))));
900   return false;
901 }
902
903 Value *BinaryOperator::getNegArgument(Value *BinOp) {
904   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
905   return cast<BinaryOperator>(BinOp)->getOperand(1);
906 }
907
908 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
909   return getNegArgument(const_cast<Value*>(BinOp));
910 }
911
912 Value *BinaryOperator::getNotArgument(Value *BinOp) {
913   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
914   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
915   Value *Op0 = BO->getOperand(0);
916   Value *Op1 = BO->getOperand(1);
917   if (isConstantAllOnes(Op0)) return Op1;
918
919   assert(isConstantAllOnes(Op1));
920   return Op0;
921 }
922
923 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
924   return getNotArgument(const_cast<Value*>(BinOp));
925 }
926
927
928 // swapOperands - Exchange the two operands to this instruction.  This
929 // instruction is safe to use on any binary instruction and does not
930 // modify the semantics of the instruction.  If the instruction is
931 // order dependent (SetLT f.e.) the opcode is changed.
932 //
933 bool BinaryOperator::swapOperands() {
934   if (isCommutative())
935     ;  // If the instruction is commutative, it is safe to swap the operands
936   else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
937     /// FIXME: SetCC instructions shouldn't all have different opcodes.
938     setOpcode(SCI->getSwappedCondition());
939   else
940     return true;   // Can't commute operands
941
942   std::swap(Ops[0], Ops[1]);
943   return false;
944 }
945
946
947 //===----------------------------------------------------------------------===//
948 //                             SetCondInst Class
949 //===----------------------------------------------------------------------===//
950
951 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
952                          const std::string &Name, Instruction *InsertBefore)
953   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
954
955   // Make sure it's a valid type... getInverseCondition will assert out if not.
956   assert(getInverseCondition(Opcode));
957 }
958
959 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
960                          const std::string &Name, BasicBlock *InsertAtEnd)
961   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
962
963   // Make sure it's a valid type... getInverseCondition will assert out if not.
964   assert(getInverseCondition(Opcode));
965 }
966
967 // getInverseCondition - Return the inverse of the current condition opcode.
968 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
969 //
970 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
971   switch (Opcode) {
972   default:
973     assert(0 && "Unknown setcc opcode!");
974   case SetEQ: return SetNE;
975   case SetNE: return SetEQ;
976   case SetGT: return SetLE;
977   case SetLT: return SetGE;
978   case SetGE: return SetLT;
979   case SetLE: return SetGT;
980   }
981 }
982
983 // getSwappedCondition - Return the condition opcode that would be the result
984 // of exchanging the two operands of the setcc instruction without changing
985 // the result produced.  Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
986 //
987 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
988   switch (Opcode) {
989   default: assert(0 && "Unknown setcc instruction!");
990   case SetEQ: case SetNE: return Opcode;
991   case SetGT: return SetLT;
992   case SetLT: return SetGT;
993   case SetGE: return SetLE;
994   case SetLE: return SetGE;
995   }
996 }
997
998 //===----------------------------------------------------------------------===//
999 //                        SwitchInst Implementation
1000 //===----------------------------------------------------------------------===//
1001
1002 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1003   assert(Value && Default);
1004   ReservedSpace = 2+NumCases*2;
1005   NumOperands = 2;
1006   OperandList = new Use[ReservedSpace];
1007
1008   OperandList[0].init(Value, this);
1009   OperandList[1].init(Default, this);
1010 }
1011
1012 SwitchInst::SwitchInst(const SwitchInst &SI)
1013   : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1014                    SI.getNumOperands()) {
1015   Use *OL = OperandList, *InOL = SI.OperandList;
1016   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1017     OL[i].init(InOL[i], this);
1018     OL[i+1].init(InOL[i+1], this);
1019   }
1020 }
1021
1022 SwitchInst::~SwitchInst() {
1023   delete [] OperandList;
1024 }
1025
1026
1027 /// addCase - Add an entry to the switch instruction...
1028 ///
1029 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1030   unsigned OpNo = NumOperands;
1031   if (OpNo+2 > ReservedSpace)
1032     resizeOperands(0);  // Get more space!
1033   // Initialize some new operands.
1034   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1035   NumOperands = OpNo+2;
1036   OperandList[OpNo].init(OnVal, this);
1037   OperandList[OpNo+1].init(Dest, this);
1038 }
1039
1040 /// removeCase - This method removes the specified successor from the switch
1041 /// instruction.  Note that this cannot be used to remove the default
1042 /// destination (successor #0).
1043 ///
1044 void SwitchInst::removeCase(unsigned idx) {
1045   assert(idx != 0 && "Cannot remove the default case!");
1046   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1047
1048   unsigned NumOps = getNumOperands();
1049   Use *OL = OperandList;
1050
1051   // Move everything after this operand down.
1052   //
1053   // FIXME: we could just swap with the end of the list, then erase.  However,
1054   // client might not expect this to happen.  The code as it is thrashes the
1055   // use/def lists, which is kinda lame.
1056   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1057     OL[i-2] = OL[i];
1058     OL[i-2+1] = OL[i+1];
1059   }
1060
1061   // Nuke the last value.
1062   OL[NumOps-2].set(0);
1063   OL[NumOps-2+1].set(0);
1064   NumOperands = NumOps-2;
1065 }
1066
1067 /// resizeOperands - resize operands - This adjusts the length of the operands
1068 /// list according to the following behavior:
1069 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
1070 ///      of operation.  This grows the number of ops by 1.5 times.
1071 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
1072 ///   3. If NumOps == NumOperands, trim the reserved space.
1073 ///
1074 void SwitchInst::resizeOperands(unsigned NumOps) {
1075   if (NumOps == 0) {
1076     NumOps = getNumOperands()/2*6;
1077   } else if (NumOps*2 > NumOperands) {
1078     // No resize needed.
1079     if (ReservedSpace >= NumOps) return;
1080   } else if (NumOps == NumOperands) {
1081     if (ReservedSpace == NumOps) return;
1082   } else {
1083     return;
1084   }
1085
1086   ReservedSpace = NumOps;
1087   Use *NewOps = new Use[NumOps];
1088   Use *OldOps = OperandList;
1089   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1090       NewOps[i].init(OldOps[i], this);
1091       OldOps[i].set(0);
1092   }
1093   delete [] OldOps;
1094   OperandList = NewOps;
1095 }
1096
1097
1098 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1099   return getSuccessor(idx);
1100 }
1101 unsigned SwitchInst::getNumSuccessorsV() const {
1102   return getNumSuccessors();
1103 }
1104 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1105   setSuccessor(idx, B);
1106 }
1107
1108
1109 // Define these methods here so vtables don't get emitted into every translation
1110 // unit that uses these classes.
1111
1112 GetElementPtrInst *GetElementPtrInst::clone() const {
1113   return new GetElementPtrInst(*this);
1114 }
1115
1116 BinaryOperator *BinaryOperator::clone() const {
1117   return create(getOpcode(), Ops[0], Ops[1]);
1118 }
1119
1120 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1121 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1122 FreeInst   *FreeInst::clone()   const { return new FreeInst(getOperand(0)); }
1123 LoadInst   *LoadInst::clone()   const { return new LoadInst(*this); }
1124 StoreInst  *StoreInst::clone()  const { return new StoreInst(*this); }
1125 CastInst   *CastInst::clone()   const { return new CastInst(*this); }
1126 CallInst   *CallInst::clone()   const { return new CallInst(*this); }
1127 ShiftInst  *ShiftInst::clone()  const { return new ShiftInst(*this); }
1128 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1129 VAArgInst  *VAArgInst::clone()  const { return new VAArgInst(*this); }
1130 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
1131 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1132 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1133 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1134 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1135 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1136 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}