Move MachineCodeForInstruction.h and MachineFunctionInfo.h into lib/Target/SparcV9
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9BurgISel.cpp
1 //===- SparcV9BurgISel.cpp - SparcV9 BURG-based Instruction Selector ------===//
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 // SparcV9 BURG-based instruction selector. It uses the SSA graph to
11 // construct a forest of BURG instruction trees (class InstrForest) and then
12 // uses the BURG-generated tree grammar (BURM) to find the optimal instruction
13 // sequences for the SparcV9.
14 //      
15 //===----------------------------------------------------------------------===//
16
17 #include "MachineInstrAnnot.h"
18 #include "SparcV9BurgISel.h"
19 #include "SparcV9InstrForest.h"
20 #include "SparcV9Internals.h"
21 #include "SparcV9TmpInstr.h"
22 #include "SparcV9FrameInfo.h"
23 #include "SparcV9RegisterInfo.h"
24 #include "MachineFunctionInfo.h"
25 #include "llvm/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Type.h"
40 #include "Config/alloca.h"
41 #include "Support/CommandLine.h"
42 #include "Support/LeakDetector.h"
43 #include "Support/MathExtras.h"
44 #include "Support/STLExtras.h"
45 #include "Support/hash_map"
46 #include <algorithm>
47 #include <cmath>
48 #include <iostream>
49 using namespace llvm;
50
51 //==------------------------------------------------------------------------==//
52 //          InstrForest (V9ISel BURG instruction trees) implementation
53 //==------------------------------------------------------------------------==//
54
55 namespace llvm {
56
57 class InstructionNode : public InstrTreeNode {
58   bool codeIsFoldedIntoParent;
59   
60 public:
61   InstructionNode(Instruction *_instr);
62
63   Instruction *getInstruction() const {
64     assert(treeNodeType == NTInstructionNode);
65     return cast<Instruction>(val);
66   }
67
68   void markFoldedIntoParent() { codeIsFoldedIntoParent = true; }
69   bool isFoldedIntoParent()   { return codeIsFoldedIntoParent; }
70
71   // Methods to support type inquiry through isa, cast, and dyn_cast:
72   static inline bool classof(const InstructionNode *N) { return true; }
73   static inline bool classof(const InstrTreeNode *N) {
74     return N->getNodeType() == InstrTreeNode::NTInstructionNode;
75   }
76   
77 protected:
78   virtual void dumpNode(int indent) const;
79 };
80
81 class VRegListNode : public InstrTreeNode {
82 public:
83   VRegListNode() : InstrTreeNode(NTVRegListNode, 0) { opLabel = VRegListOp; }
84   // Methods to support type inquiry through isa, cast, and dyn_cast:
85   static inline bool classof(const VRegListNode  *N) { return true; }
86   static inline bool classof(const InstrTreeNode *N) {
87     return N->getNodeType() == InstrTreeNode::NTVRegListNode;
88   }
89 protected:
90   virtual void dumpNode(int indent) const;
91 };
92
93 class VRegNode : public InstrTreeNode {
94 public:
95   VRegNode(Value* _val) : InstrTreeNode(NTVRegNode, _val) {
96     opLabel = VRegNodeOp;
97   }
98   // Methods to support type inquiry through isa, cast, and dyn_cast:
99   static inline bool classof(const VRegNode  *N) { return true; }
100   static inline bool classof(const InstrTreeNode *N) {
101     return N->getNodeType() == InstrTreeNode::NTVRegNode;
102   }
103 protected:
104   virtual void dumpNode(int indent) const;
105 };
106
107 class ConstantNode : public InstrTreeNode {
108 public:
109   ConstantNode(Constant *constVal) 
110     : InstrTreeNode(NTConstNode, (Value*)constVal) {
111     opLabel = ConstantNodeOp;    
112   }
113   Constant *getConstVal() const { return (Constant*) val;}
114   // Methods to support type inquiry through isa, cast, and dyn_cast:
115   static inline bool classof(const ConstantNode  *N) { return true; }
116   static inline bool classof(const InstrTreeNode *N) {
117     return N->getNodeType() == InstrTreeNode::NTConstNode;
118   }
119 protected:
120   virtual void dumpNode(int indent) const;
121 };
122
123 class LabelNode : public InstrTreeNode {
124 public:
125   LabelNode(BasicBlock* BB) : InstrTreeNode(NTLabelNode, (Value*)BB) {
126     opLabel = LabelNodeOp;
127   }
128   BasicBlock *getBasicBlock() const { return (BasicBlock*)val;}
129   // Methods to support type inquiry through isa, cast, and dyn_cast:
130   static inline bool classof(const LabelNode     *N) { return true; }
131   static inline bool classof(const InstrTreeNode *N) {
132     return N->getNodeType() == InstrTreeNode::NTLabelNode;
133   }
134 protected:
135   virtual void dumpNode(int indent) const;
136 };
137
138 /// InstrForest -  A forest of instruction trees for a single function.
139 /// The goal of InstrForest is to group instructions into a single
140 /// tree if one or more of them might be potentially combined into a
141 /// single complex instruction in the target machine. We group two
142 /// instructions O and I if: (1) Instruction O computes an operand used
143 /// by instruction I, and (2) O and I are part of the same basic block,
144 /// and (3) O has only a single use, viz., I.
145 /// 
146 class InstrForest : private hash_map<const Instruction *, InstructionNode*> {
147 public:
148   // Use a vector for the root set to get a deterministic iterator
149   // for stable code generation.  Even though we need to erase nodes
150   // during forest construction, a vector should still be efficient
151   // because the elements to erase are nearly always near the end.
152   typedef std::vector<InstructionNode*> RootSet;
153   typedef RootSet::      iterator       root_iterator;
154   typedef RootSet::const_iterator const_root_iterator;
155   
156 private:
157   RootSet treeRoots;
158   
159 public:
160   /*ctor*/      InstrForest     (Function *F);
161   /*dtor*/      ~InstrForest    ();
162   
163   /// getTreeNodeForInstr - Returns the tree node for an Instruction.
164   ///
165   inline InstructionNode *getTreeNodeForInstr(Instruction* instr) {
166     return (*this)[instr];
167   }
168   
169   /// Iterators for the root nodes for all the trees.
170   ///
171   const_root_iterator roots_begin() const     { return treeRoots.begin(); }
172         root_iterator roots_begin()           { return treeRoots.begin(); }
173   const_root_iterator roots_end  () const     { return treeRoots.end();   }
174         root_iterator roots_end  ()           { return treeRoots.end();   }
175   
176   void dump() const;
177   
178 private:
179   // Methods used to build the instruction forest.
180   void eraseRoot    (InstructionNode* node);
181   void setLeftChild (InstrTreeNode* parent, InstrTreeNode* child);
182   void setRightChild(InstrTreeNode* parent, InstrTreeNode* child);
183   void setParent    (InstrTreeNode* child,  InstrTreeNode* parent);
184   void noteTreeNodeForInstr(Instruction* instr, InstructionNode* treeNode);
185   InstructionNode* buildTreeForInstruction(Instruction* instr);
186 };
187
188 void InstrTreeNode::dump(int dumpChildren, int indent) const {
189   dumpNode(indent);
190   
191   if (dumpChildren) {
192     if (LeftChild)
193       LeftChild->dump(dumpChildren, indent+1);
194     if (RightChild)
195       RightChild->dump(dumpChildren, indent+1);
196   }
197 }
198
199 InstructionNode::InstructionNode(Instruction* I)
200   : InstrTreeNode(NTInstructionNode, I), codeIsFoldedIntoParent(false) {
201   opLabel = I->getOpcode();
202
203   // Distinguish special cases of some instructions such as Ret and Br
204   // 
205   if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue()) {
206     opLabel = RetValueOp;                // ret(value) operation
207   }
208   else if (opLabel ==Instruction::Br && !cast<BranchInst>(I)->isUnconditional())
209   {
210     opLabel = BrCondOp;         // br(cond) operation
211   } else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT) {
212     opLabel = SetCCOp;          // common label for all SetCC ops
213   } else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0) {
214     opLabel = AllocaN;           // Alloca(ptr, N) operation
215   } else if (opLabel == Instruction::GetElementPtr &&
216              cast<GetElementPtrInst>(I)->hasIndices()) {
217     opLabel = opLabel + 100;             // getElem with index vector
218   } else if (opLabel == Instruction::Xor &&
219              BinaryOperator::isNot(I)) {
220     opLabel = (I->getType() == Type::BoolTy)?  NotOp  // boolean Not operator
221       : BNotOp; // bitwise Not operator
222   } else if (opLabel == Instruction::And || opLabel == Instruction::Or ||
223              opLabel == Instruction::Xor) {
224     // Distinguish bitwise operators from logical operators!
225     if (I->getType() != Type::BoolTy)
226       opLabel = opLabel + 100;   // bitwise operator
227   } else if (opLabel == Instruction::Cast) {
228     const Type *ITy = I->getType();
229     switch(ITy->getTypeID())
230     {
231     case Type::BoolTyID:    opLabel = ToBoolTy;    break;
232     case Type::UByteTyID:   opLabel = ToUByteTy;   break;
233     case Type::SByteTyID:   opLabel = ToSByteTy;   break;
234     case Type::UShortTyID:  opLabel = ToUShortTy;  break;
235     case Type::ShortTyID:   opLabel = ToShortTy;   break;
236     case Type::UIntTyID:    opLabel = ToUIntTy;    break;
237     case Type::IntTyID:     opLabel = ToIntTy;     break;
238     case Type::ULongTyID:   opLabel = ToULongTy;   break;
239     case Type::LongTyID:    opLabel = ToLongTy;    break;
240     case Type::FloatTyID:   opLabel = ToFloatTy;   break;
241     case Type::DoubleTyID:  opLabel = ToDoubleTy;  break;
242     case Type::ArrayTyID:   opLabel = ToArrayTy;   break;
243     case Type::PointerTyID: opLabel = ToPointerTy; break;
244     default:
245       // Just use `Cast' opcode otherwise. It's probably ignored.
246       break;
247     }
248   }
249 }
250
251 void InstructionNode::dumpNode(int indent) const {
252   for (int i=0; i < indent; i++)
253     std::cerr << "    ";
254   std::cerr << getInstruction()->getOpcodeName()
255             << " [label " << getOpLabel() << "]" << "\n";
256 }
257
258 void VRegListNode::dumpNode(int indent) const {
259   for (int i=0; i < indent; i++)
260     std::cerr << "    ";
261   
262   std::cerr << "List" << "\n";
263 }
264
265 void VRegNode::dumpNode(int indent) const {
266   for (int i=0; i < indent; i++)
267     std::cerr << "    ";
268     std::cerr << "VReg " << *getValue() << "\n";
269 }
270
271 void ConstantNode::dumpNode(int indent) const {
272   for (int i=0; i < indent; i++)
273     std::cerr << "    ";
274   std::cerr << "Constant " << *getValue() << "\n";
275 }
276
277 void LabelNode::dumpNode(int indent) const {
278   for (int i=0; i < indent; i++)
279     std::cerr << "    ";
280   
281   std::cerr << "Label " << *getValue() << "\n";
282 }
283
284 /// InstrForest ctor - Create a forest of instruction trees for a
285 /// single function.
286 ///
287 InstrForest::InstrForest(Function *F) {
288   for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
289     for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
290       buildTreeForInstruction(I);
291   }
292 }
293
294 InstrForest::~InstrForest() {
295   for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
296 }
297
298 void InstrForest::dump() const {
299   for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
300     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
301 }
302
303 inline void InstrForest::eraseRoot(InstructionNode* node) {
304   for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
305        RI != RE; ++RI)
306     if (*RI == node)
307       treeRoots.erase(RI.base()-1);
308 }
309
310 inline void InstrForest::noteTreeNodeForInstr(Instruction *instr,
311                                               InstructionNode *treeNode) {
312   (*this)[instr] = treeNode;
313   treeRoots.push_back(treeNode);        // mark node as root of a new tree
314 }
315
316 inline void InstrForest::setLeftChild(InstrTreeNode *parent,
317                                       InstrTreeNode *child) {
318   parent->LeftChild = child;
319   child->Parent = parent;
320   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
321     eraseRoot(instrNode); // no longer a tree root
322 }
323
324 inline void InstrForest::setRightChild(InstrTreeNode *parent,
325                                        InstrTreeNode *child) {
326   parent->RightChild = child;
327   child->Parent = parent;
328   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
329     eraseRoot(instrNode); // no longer a tree root
330 }
331
332 InstructionNode* InstrForest::buildTreeForInstruction(Instruction *instr) {
333   InstructionNode *treeNode = getTreeNodeForInstr(instr);
334   if (treeNode) {
335     // treeNode has already been constructed for this instruction
336     assert(treeNode->getInstruction() == instr);
337     return treeNode;
338   }
339   
340   // Otherwise, create a new tree node for this instruction.
341   treeNode = new InstructionNode(instr);
342   noteTreeNodeForInstr(instr, treeNode);
343   
344   if (instr->getOpcode() == Instruction::Call) {
345     // Operands of call instruction
346     return treeNode;
347   }
348   
349   // If the instruction has more than 2 instruction operands,
350   // then we need to create artificial list nodes to hold them.
351   // (Note that we only count operands that get tree nodes, and not
352   // others such as branch labels for a branch or switch instruction.)
353   // To do this efficiently, we'll walk all operands, build treeNodes
354   // for all appropriate operands and save them in an array.  We then
355   // insert children at the end, creating list nodes where needed.
356   // As a performance optimization, allocate a child array only
357   // if a fixed array is too small.
358   int numChildren = 0;
359   InstrTreeNode** childArray = new InstrTreeNode*[instr->getNumOperands()];
360   
361   // Walk the operands of the instruction
362   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end();
363        ++O) {
364       Value* operand = *O;
365       
366       // Check if the operand is a data value, not an branch label, type,
367       // method or module.  If the operand is an address type (i.e., label
368       // or method) that is used in an non-branching operation, e.g., `add'.
369       // that should be considered a data value.
370       // Check latter condition here just to simplify the next IF.
371       bool includeAddressOperand =
372         (isa<BasicBlock>(operand) || isa<Function>(operand))
373         && !instr->isTerminator();
374     
375       if (includeAddressOperand || isa<Instruction>(operand) ||
376           isa<Constant>(operand) || isa<Argument>(operand)) {
377         // This operand is a data value.
378         // An instruction that computes the incoming value is added as a
379         // child of the current instruction if:
380         //   the value has only a single use
381         //   AND both instructions are in the same basic block.
382         //   AND the current instruction is not a PHI (because the incoming
383         //              value is conceptually in a predecessor block,
384         //              even though it may be in the same static block)
385         // (Note that if the value has only a single use (viz., `instr'),
386         //  the def of the value can be safely moved just before instr
387         //  and therefore it is safe to combine these two instructions.)
388         // In all other cases, the virtual register holding the value
389         // is used directly, i.e., made a child of the instruction node.
390         InstrTreeNode* opTreeNode;
391         if (isa<Instruction>(operand) && operand->hasOneUse() &&
392             cast<Instruction>(operand)->getParent() == instr->getParent() &&
393             instr->getOpcode() != Instruction::PHI &&
394             instr->getOpcode() != Instruction::Call) {
395           // Recursively create a treeNode for it.
396           opTreeNode = buildTreeForInstruction((Instruction*)operand);
397         } else if (Constant *CPV = dyn_cast<Constant>(operand)) {
398           if (isa<GlobalValue>(CPV))
399             opTreeNode = new VRegNode(operand);
400           else
401             // Create a leaf node for a constant
402             opTreeNode = new ConstantNode(CPV);
403         } else {
404           // Create a leaf node for the virtual register
405           opTreeNode = new VRegNode(operand);
406         }
407
408         childArray[numChildren++] = opTreeNode;
409       }
410     }
411   
412   // Add any selected operands as children in the tree.
413   // Certain instructions can have more than 2 in some instances (viz.,
414   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
415   // array or struct). Make the operands of every such instruction into
416   // a right-leaning binary tree with the operand nodes at the leaves
417   // and VRegList nodes as internal nodes.
418   InstrTreeNode *parent = treeNode;
419   
420   if (numChildren > 2) {
421     unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
422     assert(instrOpcode == Instruction::PHI ||
423            instrOpcode == Instruction::Call ||
424            instrOpcode == Instruction::Load ||
425            instrOpcode == Instruction::Store ||
426            instrOpcode == Instruction::GetElementPtr);
427   }
428   
429   // Insert the first child as a direct child
430   if (numChildren >= 1)
431     setLeftChild(parent, childArray[0]);
432
433   int n;
434   
435   // Create a list node for children 2 .. N-1, if any
436   for (n = numChildren-1; n >= 2; n--) {
437     // We have more than two children
438     InstrTreeNode *listNode = new VRegListNode();
439     setRightChild(parent, listNode);
440     setLeftChild(listNode, childArray[numChildren - n]);
441     parent = listNode;
442   }
443   
444   // Now insert the last remaining child (if any).
445   if (numChildren >= 2) {
446     assert(n == 1);
447     setRightChild(parent, childArray[numChildren - 1]);
448   }
449
450   delete [] childArray;
451   return treeNode;
452 }
453 //==------------------------------------------------------------------------==//
454 //                V9ISel Command-line options and declarations
455 //==------------------------------------------------------------------------==//
456
457 namespace {
458   /// Allow the user to select the amount of debugging information printed
459   /// out by V9ISel.
460   ///
461   enum SelectDebugLevel_t {
462     Select_NoDebugInfo,
463     Select_PrintMachineCode, 
464     Select_DebugInstTrees, 
465     Select_DebugBurgTrees,
466   };
467   cl::opt<SelectDebugLevel_t>
468   SelectDebugLevel("dselect", cl::Hidden,
469                    cl::desc("enable instruction selection debug information"),
470                    cl::values(
471      clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
472      clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
473      clEnumValN(Select_DebugInstTrees,   "i",
474                 "print debugging info for instruction selection"),
475      clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
476                               clEnumValEnd));
477
478
479   /// V9ISel - This is the FunctionPass that drives the instruction selection
480   /// process on the SparcV9 target.
481   ///
482   class V9ISel : public FunctionPass {
483     TargetMachine &Target;
484     void InsertCodeForPhis(Function &F);
485     void InsertPhiElimInstructions(BasicBlock *BB,
486                                    const std::vector<MachineInstr*>& CpVec);
487     void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
488     void PostprocessMachineCodeForTree(InstructionNode* instrNode,
489                                        int ruleForNode, short* nts);
490   public:
491     V9ISel(TargetMachine &TM) : Target(TM) {}
492
493     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
494       AU.setPreservesCFG();
495     }
496     
497     bool runOnFunction(Function &F);
498     virtual const char *getPassName() const {
499       return "SparcV9 BURG Instruction Selector";
500     }
501   };
502 }
503
504
505 //==------------------------------------------------------------------------==//
506 //                     Various V9ISel helper functions
507 //==------------------------------------------------------------------------==//
508
509 static const uint32_t MAXLO   = (1 << 10) - 1; // set bits set by %lo(*)
510 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
511
512 /// ConvertConstantToIntType - Function to get the value of an integral
513 /// constant in the form that must be put into the machine register.  The
514 /// specified constant is interpreted as (i.e., converted if necessary to) the
515 /// specified destination type.  The result is always returned as an uint64_t,
516 /// since the representation of int64_t and uint64_t are identical.  The
517 /// argument can be any known const.  isValidConstant is set to true if a valid
518 /// constant was found.
519 /// 
520 uint64_t ConvertConstantToIntType(const TargetMachine &target, const Value *V,
521                                   const Type *destType, bool &isValidConstant) {
522   isValidConstant = false;
523   uint64_t C = 0;
524
525   if (! destType->isIntegral() && ! isa<PointerType>(destType))
526     return C;
527
528   if (! isa<Constant>(V) || isa<GlobalValue>(V))
529     return C;
530
531   // GlobalValue: no conversions needed: get value and return it
532   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
533     isValidConstant = true;             // may be overwritten by recursive call
534     return ConvertConstantToIntType(target, GV, destType, isValidConstant);
535   }
536
537   // ConstantBool: no conversions needed: get value and return it
538   if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
539     isValidConstant = true;
540     return (uint64_t) CB->getValue();
541   }
542
543   // ConstantPointerNull: it's really just a big, shiny version of zero.
544   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(V)) {
545     isValidConstant = true;
546     return 0;
547   }
548
549   // For other types of constants, some conversion may be needed.
550   // First, extract the constant operand according to its own type
551   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
552     switch(CE->getOpcode()) {
553     case Instruction::Cast:             // recursively get the value as cast
554       C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
555                                    isValidConstant);
556       break;
557     default:                            // not simplifying other ConstantExprs
558       break;
559     }
560   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
561     isValidConstant = true;
562     C = CI->getRawValue();
563   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
564     isValidConstant = true;
565     double fC = CFP->getValue();
566     C = (destType->isSigned()? (uint64_t) (int64_t) fC
567                              : (uint64_t)           fC);
568   }
569
570   // Now if a valid value was found, convert it to destType.
571   if (isValidConstant) {
572     unsigned opSize   = target.getTargetData().getTypeSize(V->getType());
573     unsigned destSize = target.getTargetData().getTypeSize(destType);
574     uint64_t maskHi   = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
575     assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
576     
577     if (destType->isSigned()) {
578       if (opSize > destSize)            // operand is larger than dest:
579         C = C & maskHi;                 // mask high bits
580
581       if (opSize > destSize ||
582           (opSize == destSize && ! V->getType()->isSigned()))
583         if (C & (1U << (8*destSize - 1)))
584           C =  C | ~maskHi;             // sign-extend from destSize to 64 bits
585     }
586     else {
587       if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
588         // operand is larger than dest,
589         //    OR both are equal but smaller than the full register size
590         //       AND operand is signed, so it may have extra sign bits:
591         // mask high bits
592         C = C & maskHi;
593       }
594     }
595   }
596
597   return C;
598 }
599
600 /// CreateSETUWConst - Copy a 32-bit unsigned constant into the register
601 /// `dest', using SETHI, OR in the worst case.  This function correctly emulates
602 /// the SETUW pseudo-op for SPARC v9 (if argument isSigned == false). The
603 /// isSigned=true case is used to implement SETSW without duplicating code. It
604 /// optimizes some common cases:
605 /// (1) Small value that fits in simm13 field of OR: don't need SETHI.
606 /// (2) isSigned = true and C is a small negative signed value, i.e.,
607 ///     high bits are 1, and the remaining bits fit in simm13(OR).
608 static inline void
609 CreateSETUWConst(const TargetMachine& target, uint32_t C,
610                  Instruction* dest, std::vector<MachineInstr*>& mvec,
611                  bool isSigned = false) {
612   MachineInstr *miSETHI = NULL, *miOR = NULL;
613
614   // In order to get efficient code, we should not generate the SETHI if
615   // all high bits are 1 (i.e., this is a small signed value that fits in
616   // the simm13 field of OR).  So we check for and handle that case specially.
617   // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
618   //       In fact, sC == -sC, so we have to check for this explicitly.
619   int32_t sC = (int32_t) C;
620   bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
621
622   // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
623   if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
624     miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(dest);
625     miSETHI->getOperand(0).markHi32();
626     mvec.push_back(miSETHI);
627   }
628   
629   // Set the low 10 or 12 bits in dest.  This is necessary if no SETHI
630   // was generated, or if the low 10 bits are non-zero.
631   if (miSETHI==NULL || C & MAXLO) {
632     if (miSETHI) {
633       // unsigned value with high-order bits set using SETHI
634       miOR = BuildMI(V9::ORi,3).addReg(dest).addZImm(C).addRegDef(dest);
635       miOR->getOperand(1).markLo32();
636     } else {
637       // unsigned or small signed value that fits in simm13 field of OR
638       assert(smallNegValue || (C & ~MAXSIMM) == 0);
639       miOR = BuildMI(V9::ORi, 3).addMReg(target.getRegInfo()->getZeroRegNum())
640         .addSImm(sC).addRegDef(dest);
641     }
642     mvec.push_back(miOR);
643   }
644   
645   assert((miSETHI || miOR) && "Oops, no code was generated!");
646 }
647
648 /// CreateSETSWConst - Set a 32-bit signed constant in the register `dest',
649 /// with sign-extension to 64 bits.  This uses SETHI, OR, SRA in the worst case.
650 /// This function correctly emulates the SETSW pseudo-op for SPARC v9.  It
651 /// optimizes the same cases as SETUWConst, plus:
652 /// (1) SRA is not needed for positive or small negative values.
653 /// 
654 static inline void
655 CreateSETSWConst(const TargetMachine& target, int32_t C,
656                  Instruction* dest, std::vector<MachineInstr*>& mvec) {
657   // Set the low 32 bits of dest
658   CreateSETUWConst(target, (uint32_t) C,  dest, mvec, /*isSigned*/true);
659
660   // Sign-extend to the high 32 bits if needed.
661   // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
662   if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
663     mvec.push_back(BuildMI(V9::SRAi5,3).addReg(dest).addZImm(0).addRegDef(dest));
664 }
665
666 /// CreateSETXConst - Set a 64-bit signed or unsigned constant in the
667 /// register `dest'.  Use SETUWConst for each 32 bit word, plus a
668 /// left-shift-by-32 in between.  This function correctly emulates the SETX
669 /// pseudo-op for SPARC v9.  It optimizes the same cases as SETUWConst for each
670 /// 32 bit word.
671 /// 
672 static inline void
673 CreateSETXConst(const TargetMachine& target, uint64_t C,
674                 Instruction* tmpReg, Instruction* dest,
675                 std::vector<MachineInstr*>& mvec) {
676   assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
677   
678   MachineInstr* MI;
679   
680   // Code to set the upper 32 bits of the value in register `tmpReg'
681   CreateSETUWConst(target, (C >> 32), tmpReg, mvec);
682   
683   // Shift tmpReg left by 32 bits
684   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
685                  .addRegDef(tmpReg));
686   
687   // Code to set the low 32 bits of the value in register `dest'
688   CreateSETUWConst(target, C, dest, mvec);
689   
690   // dest = OR(tmpReg, dest)
691   mvec.push_back(BuildMI(V9::ORr,3).addReg(dest).addReg(tmpReg).addRegDef(dest));
692 }
693
694 /// CreateSETUWLabel - Set a 32-bit constant (given by a symbolic label) in
695 /// the register `dest'.
696 /// 
697 static inline void
698 CreateSETUWLabel(const TargetMachine& target, Value* val,
699                  Instruction* dest, std::vector<MachineInstr*>& mvec) {
700   MachineInstr* MI;
701   
702   // Set the high 22 bits in dest
703   MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(dest);
704   MI->getOperand(0).markHi32();
705   mvec.push_back(MI);
706   
707   // Set the low 10 bits in dest
708   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(val).addRegDef(dest);
709   MI->getOperand(1).markLo32();
710   mvec.push_back(MI);
711 }
712
713 /// CreateSETXLabel - Set a 64-bit constant (given by a symbolic label) in the
714 /// register `dest'.
715 /// 
716 static inline void
717 CreateSETXLabel(const TargetMachine& target, Value* val, Instruction* tmpReg,
718                 Instruction* dest, std::vector<MachineInstr*>& mvec) {
719   assert(isa<Constant>(val) && 
720          "I only know about constant values and global addresses");
721   
722   MachineInstr* MI;
723   
724   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
725   MI->getOperand(0).markHi64();
726   mvec.push_back(MI);
727   
728   MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg);
729   MI->getOperand(1).markLo64();
730   mvec.push_back(MI);
731   
732   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
733                  .addRegDef(tmpReg));
734   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(dest);
735   MI->getOperand(0).markHi32();
736   mvec.push_back(MI);
737   
738   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(tmpReg).addRegDef(dest);
739   mvec.push_back(MI);
740   
741   MI = BuildMI(V9::ORi, 3).addReg(dest).addPCDisp(val).addRegDef(dest);
742   MI->getOperand(1).markLo32();
743   mvec.push_back(MI);
744 }
745
746 /// CreateUIntSetInstruction - Create code to Set an unsigned constant in the
747 /// register `dest'.  Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst
748 /// as needed.  CreateSETSWConst is an optimization for the case that the
749 /// unsigned value has all ones in the 33 high bits (so that sign-extension sets
750 /// them all).
751 /// 
752 static inline void
753 CreateUIntSetInstruction(const TargetMachine& target,
754                          uint64_t C, Instruction* dest,
755                          std::vector<MachineInstr*>& mvec,
756                          MachineCodeForInstruction& mcfi) {
757   static const uint64_t lo32 = (uint32_t) ~0;
758   if (C <= lo32)                        // High 32 bits are 0.  Set low 32 bits.
759     CreateSETUWConst(target, (uint32_t) C, dest, mvec);
760   else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
761     // All high 33 (not 32) bits are 1s: sign-extension will take care
762     // of high 32 bits, so use the sequence for signed int
763     CreateSETSWConst(target, (int32_t) C, dest, mvec);
764   } else if (C > lo32) {
765     // C does not fit in 32 bits
766     TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
767     CreateSETXConst(target, C, tmpReg, dest, mvec);
768   }
769 }
770
771 /// CreateIntSetInstruction - Create code to Set a signed constant in the
772 /// register `dest'.  Really the same as CreateUIntSetInstruction.
773 /// 
774 static inline void
775 CreateIntSetInstruction(const TargetMachine& target,
776                         int64_t C, Instruction* dest,
777                         std::vector<MachineInstr*>& mvec,
778                         MachineCodeForInstruction& mcfi) {
779   CreateUIntSetInstruction(target, (uint64_t) C, dest, mvec, mcfi);
780 }
781
782 /// MaxConstantsTableTy - Table mapping LLVM opcodes to the max. immediate
783 /// constant usable for that operation in the SparcV9 backend. Used by
784 /// ConstantMayNotFitInImmedField().
785 /// 
786 struct MaxConstantsTableTy {
787   // Entry == 0 ==> no immediate constant field exists at all.
788   // Entry >  0 ==> abs(immediate constant) <= Entry
789   std::vector<int> tbl;
790
791   int getMaxConstantForInstr (unsigned llvmOpCode);
792   MaxConstantsTableTy ();
793   unsigned size() const            { return tbl.size (); }
794   int &operator[] (unsigned index) { return tbl[index];  }
795 };
796
797 int MaxConstantsTableTy::getMaxConstantForInstr(unsigned llvmOpCode) {
798   int modelOpCode = -1;
799
800   if (llvmOpCode >= Instruction::BinaryOpsBegin &&
801       llvmOpCode <  Instruction::BinaryOpsEnd)
802     modelOpCode = V9::ADDi;
803   else
804     switch(llvmOpCode) {
805     case Instruction::Ret:   modelOpCode = V9::JMPLCALLi; break;
806
807     case Instruction::Malloc:         
808     case Instruction::Alloca:         
809     case Instruction::GetElementPtr:  
810     case Instruction::PHI:       
811     case Instruction::Cast:
812     case Instruction::Call:  modelOpCode = V9::ADDi; break;
813
814     case Instruction::Shl:
815     case Instruction::Shr:   modelOpCode = V9::SLLXi6; break;
816
817     default: break;
818     };
819
820   return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
821 }
822
823 MaxConstantsTableTy::MaxConstantsTableTy () : tbl (Instruction::OtherOpsEnd) {
824   unsigned op;
825   assert(tbl.size() == Instruction::OtherOpsEnd &&
826          "assignments below will be illegal!");
827   for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
828     tbl[op] = getMaxConstantForInstr(op);
829   for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
830     tbl[op] = getMaxConstantForInstr(op);
831   for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
832     tbl[op] = getMaxConstantForInstr(op);
833   for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
834     tbl[op] = getMaxConstantForInstr(op);
835 }
836
837 bool ConstantMayNotFitInImmedField(const Constant* CV, const Instruction* I) {
838   // The one and only MaxConstantsTable, used only by this function.
839   static MaxConstantsTableTy MaxConstantsTable;
840
841   if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
842     return true;
843
844   if (isa<ConstantPointerNull>(CV))               // can always use %g0
845     return false;
846
847   if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
848     return false;
849
850   if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
851     return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
852
853   if (isa<ConstantBool>(CV))
854     return 1 > MaxConstantsTable[I->getOpcode()];
855
856   return true;
857 }
858
859 /// ChooseLoadInstruction - Return the appropriate load instruction opcode
860 /// based on the given LLVM value type.
861 /// 
862 static inline MachineOpCode ChooseLoadInstruction(const Type *DestTy) {
863   switch (DestTy->getTypeID()) {
864   case Type::BoolTyID:
865   case Type::UByteTyID:   return V9::LDUBr;
866   case Type::SByteTyID:   return V9::LDSBr;
867   case Type::UShortTyID:  return V9::LDUHr;
868   case Type::ShortTyID:   return V9::LDSHr;
869   case Type::UIntTyID:    return V9::LDUWr;
870   case Type::IntTyID:     return V9::LDSWr;
871   case Type::PointerTyID:
872   case Type::ULongTyID:
873   case Type::LongTyID:    return V9::LDXr;
874   case Type::FloatTyID:   return V9::LDFr;
875   case Type::DoubleTyID:  return V9::LDDFr;
876   default: assert(0 && "Invalid type for Load instruction");
877   }
878   return 0;
879 }
880
881 /// ChooseStoreInstruction - Return the appropriate store instruction opcode
882 /// based on the given LLVM value type.
883 /// 
884 static inline MachineOpCode ChooseStoreInstruction(const Type *DestTy) {
885   switch (DestTy->getTypeID()) {
886   case Type::BoolTyID:
887   case Type::UByteTyID:
888   case Type::SByteTyID:   return V9::STBr;
889   case Type::UShortTyID:
890   case Type::ShortTyID:   return V9::STHr;
891   case Type::UIntTyID:
892   case Type::IntTyID:     return V9::STWr;
893   case Type::PointerTyID:
894   case Type::ULongTyID:
895   case Type::LongTyID:    return V9::STXr;
896   case Type::FloatTyID:   return V9::STFr;
897   case Type::DoubleTyID:  return V9::STDFr;
898   default: assert(0 && "Invalid type for Store instruction");
899   }
900   return 0;
901 }
902
903 static inline MachineOpCode ChooseAddInstructionByType(const Type* resultType) {
904   MachineOpCode opCode = V9::INVALID_OPCODE;
905   if (resultType->isIntegral() || isa<PointerType>(resultType)
906       || isa<FunctionType>(resultType) || resultType == Type::LabelTy) {
907     opCode = V9::ADDr;
908   } else
909     switch(resultType->getTypeID()) {
910     case Type::FloatTyID:  opCode = V9::FADDS; break;
911     case Type::DoubleTyID: opCode = V9::FADDD; break;
912     default: assert(0 && "Invalid type for ADD instruction"); break; 
913     }
914   
915   return opCode;
916 }
917
918 /// convertOpcodeFromRegToImm - Because the SparcV9 instruction selector likes
919 /// to re-write operands to instructions, making them change from a Value*
920 /// (virtual register) to a Constant* (making an immediate field), we need to
921 /// change the opcode from a register-based instruction to an immediate-based
922 /// instruction, hence this mapping.
923 /// 
924 static unsigned convertOpcodeFromRegToImm(unsigned Opcode) {
925   switch (Opcode) {
926     /* arithmetic */
927   case V9::ADDr:     return V9::ADDi;
928   case V9::ADDccr:   return V9::ADDcci;
929   case V9::ADDCr:    return V9::ADDCi;
930   case V9::ADDCccr:  return V9::ADDCcci;
931   case V9::SUBr:     return V9::SUBi;
932   case V9::SUBccr:   return V9::SUBcci;
933   case V9::SUBCr:    return V9::SUBCi;
934   case V9::SUBCccr:  return V9::SUBCcci;
935   case V9::MULXr:    return V9::MULXi;
936   case V9::SDIVXr:   return V9::SDIVXi;
937   case V9::UDIVXr:   return V9::UDIVXi;
938
939     /* logical */
940   case V9::ANDr:    return V9::ANDi;
941   case V9::ANDccr:  return V9::ANDcci;
942   case V9::ANDNr:   return V9::ANDNi;
943   case V9::ANDNccr: return V9::ANDNcci;
944   case V9::ORr:     return V9::ORi;
945   case V9::ORccr:   return V9::ORcci;
946   case V9::ORNr:    return V9::ORNi;
947   case V9::ORNccr:  return V9::ORNcci;
948   case V9::XORr:    return V9::XORi;
949   case V9::XORccr:  return V9::XORcci;
950   case V9::XNORr:   return V9::XNORi;
951   case V9::XNORccr: return V9::XNORcci;
952
953     /* shift */
954   case V9::SLLr5:   return V9::SLLi5;
955   case V9::SRLr5:   return V9::SRLi5;
956   case V9::SRAr5:   return V9::SRAi5;
957   case V9::SLLXr6:  return V9::SLLXi6;
958   case V9::SRLXr6:  return V9::SRLXi6;
959   case V9::SRAXr6:  return V9::SRAXi6;
960
961     /* Conditional move on int comparison with zero */
962   case V9::MOVRZr:   return V9::MOVRZi;
963   case V9::MOVRLEZr: return V9::MOVRLEZi;
964   case V9::MOVRLZr:  return V9::MOVRLZi;
965   case V9::MOVRNZr:  return V9::MOVRNZi;
966   case V9::MOVRGZr:  return V9::MOVRGZi;
967   case V9::MOVRGEZr: return V9::MOVRGEZi;
968
969
970     /* Conditional move on int condition code */
971   case V9::MOVAr:   return V9::MOVAi;
972   case V9::MOVNr:   return V9::MOVNi;
973   case V9::MOVNEr:  return V9::MOVNEi;
974   case V9::MOVEr:   return V9::MOVEi;
975   case V9::MOVGr:   return V9::MOVGi;
976   case V9::MOVLEr:  return V9::MOVLEi;
977   case V9::MOVGEr:  return V9::MOVGEi;
978   case V9::MOVLr:   return V9::MOVLi;
979   case V9::MOVGUr:  return V9::MOVGUi;
980   case V9::MOVLEUr: return V9::MOVLEUi;
981   case V9::MOVCCr:  return V9::MOVCCi;
982   case V9::MOVCSr:  return V9::MOVCSi;
983   case V9::MOVPOSr: return V9::MOVPOSi;
984   case V9::MOVNEGr: return V9::MOVNEGi;
985   case V9::MOVVCr:  return V9::MOVVCi;
986   case V9::MOVVSr:  return V9::MOVVSi;
987
988     /* Conditional move of int reg on fp condition code */
989   case V9::MOVFAr:   return V9::MOVFAi;
990   case V9::MOVFNr:   return V9::MOVFNi;
991   case V9::MOVFUr:   return V9::MOVFUi;
992   case V9::MOVFGr:   return V9::MOVFGi;
993   case V9::MOVFUGr:  return V9::MOVFUGi;
994   case V9::MOVFLr:   return V9::MOVFLi;
995   case V9::MOVFULr:  return V9::MOVFULi;
996   case V9::MOVFLGr:  return V9::MOVFLGi;
997   case V9::MOVFNEr:  return V9::MOVFNEi;
998   case V9::MOVFEr:   return V9::MOVFEi;
999   case V9::MOVFUEr:  return V9::MOVFUEi;
1000   case V9::MOVFGEr:  return V9::MOVFGEi;
1001   case V9::MOVFUGEr: return V9::MOVFUGEi;
1002   case V9::MOVFLEr:  return V9::MOVFLEi;
1003   case V9::MOVFULEr: return V9::MOVFULEi;
1004   case V9::MOVFOr:   return V9::MOVFOi;
1005
1006     /* load */
1007   case V9::LDSBr:   return V9::LDSBi;
1008   case V9::LDSHr:   return V9::LDSHi;
1009   case V9::LDSWr:   return V9::LDSWi;
1010   case V9::LDUBr:   return V9::LDUBi;
1011   case V9::LDUHr:   return V9::LDUHi;
1012   case V9::LDUWr:   return V9::LDUWi;
1013   case V9::LDXr:    return V9::LDXi;
1014   case V9::LDFr:    return V9::LDFi;
1015   case V9::LDDFr:   return V9::LDDFi;
1016   case V9::LDQFr:   return V9::LDQFi;
1017   case V9::LDFSRr:  return V9::LDFSRi;
1018   case V9::LDXFSRr: return V9::LDXFSRi;
1019
1020     /* store */
1021   case V9::STBr:    return V9::STBi;
1022   case V9::STHr:    return V9::STHi;
1023   case V9::STWr:    return V9::STWi;
1024   case V9::STXr:    return V9::STXi;
1025   case V9::STFr:    return V9::STFi;
1026   case V9::STDFr:   return V9::STDFi;
1027   case V9::STFSRr:  return V9::STFSRi;
1028   case V9::STXFSRr: return V9::STXFSRi;
1029
1030     /* jump & return */
1031   case V9::JMPLCALLr: return V9::JMPLCALLi;
1032   case V9::JMPLRETr:  return V9::JMPLRETi;
1033
1034   /* save and restore */
1035   case V9::SAVEr:     return V9::SAVEi;
1036   case V9::RESTOREr:  return V9::RESTOREi;
1037
1038   default:
1039     // It's already in correct format
1040     // Or, it's just not handled yet, but an assert() would break LLC
1041 #if 0
1042     std::cerr << "Unhandled opcode in convertOpcodeFromRegToImm(): " << Opcode 
1043               << "\n";
1044 #endif
1045     return Opcode;
1046   }
1047 }
1048
1049 /// CreateCodeToLoadConst - Create an instruction sequence to put the
1050 /// constant `val' into the virtual register `dest'.  `val' may be a Constant or
1051 /// a GlobalValue, viz., the constant address of a global variable or function.
1052 /// The generated instructions are returned in `mvec'. Any temp. registers
1053 /// (TmpInstruction) created are recorded in mcfi. Any stack space required is
1054 /// allocated via MachineFunction.
1055 /// 
1056 void CreateCodeToLoadConst(const TargetMachine& target, Function* F,
1057                            Value* val, Instruction* dest,
1058                            std::vector<MachineInstr*>& mvec,
1059                            MachineCodeForInstruction& mcfi) {
1060   assert(isa<Constant>(val) &&
1061          "I only know about constant values and global addresses");
1062   
1063   // Use a "set" instruction for known constants or symbolic constants (labels)
1064   // that can go in an integer reg.
1065   // We have to use a "load" instruction for all other constants,
1066   // in particular, floating point constants.
1067   const Type* valType = val->getType();
1068   
1069   if (isa<GlobalValue>(val)) {
1070       TmpInstruction* tmpReg =
1071         new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
1072       CreateSETXLabel(target, val, tmpReg, dest, mvec);
1073       return;
1074   }
1075
1076   bool isValid;
1077   uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
1078   if (isValid) {
1079     if (dest->getType()->isSigned())
1080       CreateUIntSetInstruction(target, C, dest, mvec, mcfi);
1081     else
1082       CreateIntSetInstruction(target, (int64_t) C, dest, mvec, mcfi);
1083
1084   } else {
1085     // Make an instruction sequence to load the constant, viz:
1086     //            SETX <addr-of-constant>, tmpReg, addrReg
1087     //            LOAD  /*addr*/ addrReg, /*offset*/ 0, dest
1088     // First, create a tmp register to be used by the SETX sequence.
1089     TmpInstruction* tmpReg =
1090       new TmpInstruction(mcfi, PointerType::get(val->getType()));
1091       
1092     // Create another TmpInstruction for the address register
1093     TmpInstruction* addrReg =
1094       new TmpInstruction(mcfi, PointerType::get(val->getType()));
1095     
1096     // Get the constant pool index for this constant
1097     MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
1098     Constant *C = cast<Constant>(val);
1099     unsigned CPI = CP->getConstantPoolIndex(C);
1100
1101     // Put the address of the constant into a register
1102     MachineInstr* MI;
1103   
1104     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
1105     MI->getOperand(0).markHi64();
1106     mvec.push_back(MI);
1107   
1108     MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
1109       .addRegDef(tmpReg);
1110     MI->getOperand(1).markLo64();
1111     mvec.push_back(MI);
1112   
1113     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
1114                    .addRegDef(tmpReg));
1115     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
1116     MI->getOperand(0).markHi32();
1117     mvec.push_back(MI);
1118   
1119     MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg).addRegDef(addrReg);
1120     mvec.push_back(MI);
1121   
1122     MI = BuildMI(V9::ORi, 3).addReg(addrReg).addConstantPoolIndex(CPI)
1123       .addRegDef(addrReg);
1124     MI->getOperand(1).markLo32();
1125     mvec.push_back(MI);
1126
1127     // Now load the constant from out ConstantPool label
1128     unsigned Opcode = ChooseLoadInstruction(val->getType());
1129     Opcode = convertOpcodeFromRegToImm(Opcode);
1130     mvec.push_back(BuildMI(Opcode, 3)
1131                    .addReg(addrReg).addSImm((int64_t)0).addRegDef(dest));
1132   }
1133 }
1134
1135 /// CreateCodeToCopyFloatToInt - Similarly, create an instruction sequence
1136 /// to copy an FP register `val' to an integer register `dest' by copying to
1137 /// memory and back.  The generated instructions are returned in `mvec'.  Any
1138 /// temp. virtual registers (TmpInstruction) created are recorded in mcfi.
1139 /// Temporary stack space required is allocated via MachineFunction.
1140 /// 
1141 void CreateCodeToCopyFloatToInt(const TargetMachine& target, Function* F,
1142                                 Value* val, Instruction* dest,
1143                                 std::vector<MachineInstr*>& mvec,
1144                                 MachineCodeForInstruction& mcfi) {
1145   const Type* opTy   = val->getType();
1146   const Type* destTy = dest->getType();
1147   assert(opTy->isFloatingPoint() && "Source type must be float/double");
1148   assert((destTy->isIntegral() || isa<PointerType>(destTy))
1149          && "Dest type must be integer, bool or pointer");
1150
1151   // FIXME: For now, we allocate permanent space because the stack frame
1152   // manager does not allow locals to be allocated (e.g., for alloca) after
1153   // a temp is allocated!
1154   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val); 
1155
1156   unsigned FPReg = target.getRegInfo()->getFramePointer();
1157
1158   // Store instruction stores `val' to [%fp+offset].
1159   // The store opCode is based only the source value being copied.
1160   unsigned StoreOpcode = ChooseStoreInstruction(opTy);
1161   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);  
1162   mvec.push_back(BuildMI(StoreOpcode, 3)
1163                  .addReg(val).addMReg(FPReg).addSImm(offset));
1164
1165   // Load instruction loads [%fp+offset] to `dest'.
1166   // The type of the load opCode is the integer type that matches the
1167   // source type in size:
1168   // On SparcV9: int for float, long for double.
1169   // Note that we *must* use signed loads even for unsigned dest types, to
1170   // ensure correct sign-extension for UByte, UShort or UInt:
1171   const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
1172   unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
1173   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1174   mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
1175                  .addSImm(offset).addRegDef(dest));
1176 }
1177
1178 /// CreateBitExtensionInstructions - Helper function for sign-extension and
1179 /// zero-extension. For SPARC v9, we sign-extend the given operand using SLL;
1180 /// SRA/SRL.
1181 /// 
1182 inline void
1183 CreateBitExtensionInstructions(bool signExtend, const TargetMachine& target,
1184                                Function* F, Value* srcVal, Value* destVal,
1185                                unsigned int numLowBits,
1186                                std::vector<MachineInstr*>& mvec,
1187                                MachineCodeForInstruction& mcfi) {
1188   MachineInstr* M;
1189
1190   assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
1191
1192   if (numLowBits < 32) {
1193     // SLL is needed since operand size is < 32 bits.
1194     TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
1195                                               srcVal, destVal, "make32");
1196     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
1197                    .addZImm(32-numLowBits).addRegDef(tmpI));
1198     srcVal = tmpI;
1199   }
1200
1201   mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
1202                  .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
1203 }
1204
1205 /// CreateSignExtensionInstructions - Create instruction sequence to produce
1206 /// a sign-extended register value from an arbitrary-sized integer value (sized
1207 /// in bits, not bytes). The generated instructions are returned in `mvec'. Any
1208 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1209 /// space required is allocated via MachineFunction.
1210 /// 
1211 void CreateSignExtensionInstructions(const TargetMachine& target,
1212                                      Function* F, Value* srcVal, Value* destVal,
1213                                      unsigned int numLowBits,
1214                                      std::vector<MachineInstr*>& mvec,
1215                                      MachineCodeForInstruction& mcfi) {
1216   CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
1217                                  destVal, numLowBits, mvec, mcfi);
1218 }
1219
1220 /// CreateZeroExtensionInstructions - Create instruction sequence to produce
1221 /// a zero-extended register value from an arbitrary-sized integer value (sized
1222 /// in bits, not bytes).  For SPARC v9, we sign-extend the given operand using
1223 /// SLL; SRL.  The generated instructions are returned in `mvec'.  Any temp.
1224 /// registers (TmpInstruction) created are recorded in mcfi.  Any stack space
1225 /// required is allocated via MachineFunction.
1226 /// 
1227 void CreateZeroExtensionInstructions(const TargetMachine& target,
1228                                      Function* F, Value* srcVal, Value* destVal,
1229                                      unsigned int numLowBits,
1230                                      std::vector<MachineInstr*>& mvec,
1231                                      MachineCodeForInstruction& mcfi) {
1232   CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
1233                                  destVal, numLowBits, mvec, mcfi);
1234 }
1235
1236 /// CreateCodeToCopyIntToFloat - Create an instruction sequence to copy an
1237 /// integer register `val' to a floating point register `dest' by copying to
1238 /// memory and back. val must be an integral type.  dest must be a Float or
1239 /// Double. The generated instructions are returned in `mvec'. Any temp.
1240 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1241 /// required is allocated via MachineFunction.
1242 ///
1243 void CreateCodeToCopyIntToFloat(const TargetMachine& target,
1244                                 Function* F, Value* val, Instruction* dest,
1245                                 std::vector<MachineInstr*>& mvec,
1246                                 MachineCodeForInstruction& mcfi) {
1247   assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
1248          && "Source type must be integral (integer or bool) or pointer");
1249   assert(dest->getType()->isFloatingPoint()
1250          && "Dest type must be float/double");
1251
1252   // Get a stack slot to use for the copy
1253   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val);
1254
1255   // Get the size of the source value being copied. 
1256   size_t srcSize = target.getTargetData().getTypeSize(val->getType());
1257
1258   // Store instruction stores `val' to [%fp+offset].
1259   // The store and load opCodes are based on the size of the source value.
1260   // If the value is smaller than 32 bits, we must sign- or zero-extend it
1261   // to 32 bits since the load-float will load 32 bits.
1262   // Note that the store instruction is the same for signed and unsigned ints.
1263   const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
1264   Value* storeVal = val;
1265   if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
1266     // sign- or zero-extend respectively
1267     storeVal = new TmpInstruction(mcfi, storeType, val);
1268     if (val->getType()->isSigned())
1269       CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1270                                       mvec, mcfi);
1271     else
1272       CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1273                                       mvec, mcfi);
1274   }
1275
1276   unsigned FPReg = target.getRegInfo()->getFramePointer();
1277   unsigned StoreOpcode = ChooseStoreInstruction(storeType);
1278   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1279   mvec.push_back(BuildMI(StoreOpcode, 3)
1280                  .addReg(storeVal).addMReg(FPReg).addSImm(offset));
1281
1282   // Load instruction loads [%fp+offset] to `dest'.
1283   // The type of the load opCode is the floating point type that matches the
1284   // stored type in size:
1285   // On SparcV9: float for int or smaller, double for long.
1286   const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1287   unsigned LoadOpcode = ChooseLoadInstruction(loadType);
1288   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1289   mvec.push_back(BuildMI(LoadOpcode, 3)
1290                  .addMReg(FPReg).addSImm(offset).addRegDef(dest));
1291 }
1292
1293 /// InsertCodeToLoadConstant - Generates code to load the constant
1294 /// into a TmpInstruction (virtual reg) and returns the virtual register.
1295 /// 
1296 static TmpInstruction*
1297 InsertCodeToLoadConstant(Function *F, Value* opValue, Instruction* vmInstr,
1298                          std::vector<MachineInstr*>& loadConstVec,
1299                          TargetMachine& target) {
1300   // Create a tmp virtual register to hold the constant.
1301   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
1302   TmpInstruction* tmpReg = new TmpInstruction(mcfi, opValue);
1303   
1304   CreateCodeToLoadConst(target, F, opValue, tmpReg, loadConstVec, mcfi);
1305   
1306   // Record the mapping from the tmp VM instruction to machine instruction.
1307   // Do this for all machine instructions that were not mapped to any
1308   // other temp values created by 
1309   // tmpReg->addMachineInstruction(loadConstVec.back());
1310   return tmpReg;
1311 }
1312
1313 MachineOperand::MachineOperandType
1314 ChooseRegOrImmed(int64_t intValue, bool isSigned,
1315                  MachineOpCode opCode, const TargetMachine& target,
1316                  bool canUseImmed, unsigned int& getMachineRegNum,
1317                  int64_t& getImmedValue) {
1318   MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
1319   getMachineRegNum = 0;
1320   getImmedValue = 0;
1321
1322   if (canUseImmed &&
1323       target.getInstrInfo()->constantFitsInImmedField(opCode, intValue)) {
1324       opType = isSigned? MachineOperand::MO_SignExtendedImmed
1325                        : MachineOperand::MO_UnextendedImmed;
1326       getImmedValue = intValue;
1327   } else if (intValue == 0 &&
1328              target.getRegInfo()->getZeroRegNum() != (unsigned)-1) {
1329     opType = MachineOperand::MO_MachineRegister;
1330     getMachineRegNum = target.getRegInfo()->getZeroRegNum();
1331   }
1332
1333   return opType;
1334 }
1335
1336 MachineOperand::MachineOperandType
1337 ChooseRegOrImmed(Value* val,
1338                  MachineOpCode opCode, const TargetMachine& target,
1339                  bool canUseImmed, unsigned int& getMachineRegNum,
1340                  int64_t& getImmedValue) {
1341   getMachineRegNum = 0;
1342   getImmedValue = 0;
1343
1344   // To use reg or immed, constant needs to be integer, bool, or a NULL pointer.
1345   // ConvertConstantToIntType() does the right conversions.
1346   bool isValidConstant;
1347   uint64_t valueToUse =
1348     ConvertConstantToIntType(target, val, val->getType(), isValidConstant);
1349   if (! isValidConstant)
1350     return MachineOperand::MO_VirtualRegister;
1351
1352   // Now check if the constant value fits in the IMMED field.
1353   return ChooseRegOrImmed((int64_t) valueToUse, val->getType()->isSigned(),
1354                           opCode, target, canUseImmed,
1355                           getMachineRegNum, getImmedValue);
1356 }
1357
1358 /// CreateCopyInstructionsByType - Create instruction(s) to copy src to dest,
1359 /// for arbitrary types. The generated instructions are returned in `mvec'. Any
1360 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1361 /// space required is allocated via MachineFunction.
1362 /// 
1363 void CreateCopyInstructionsByType(const TargetMachine& target,
1364                                   Function *F, Value* src, Instruction* dest,
1365                                   std::vector<MachineInstr*>& mvec,
1366                                   MachineCodeForInstruction& mcfi) {
1367   bool loadConstantToReg = false;
1368   const Type* resultType = dest->getType();
1369   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1370   assert (opCode != V9::INVALID_OPCODE
1371           && "Unsupported result type in CreateCopyInstructionsByType()");
1372
1373   // If `src' is a constant that doesn't fit in the immed field or if it is
1374   // a global variable (i.e., a constant address), generate a load
1375   // instruction instead of an add.
1376   if (isa<GlobalValue>(src))
1377     loadConstantToReg = true;
1378   else if (isa<Constant>(src)) {
1379     unsigned int machineRegNum;
1380     int64_t immedValue;
1381     MachineOperand::MachineOperandType opType =
1382       ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1383                        machineRegNum, immedValue);
1384       
1385     if (opType == MachineOperand::MO_VirtualRegister)
1386       loadConstantToReg = true;
1387   }
1388   
1389   if (loadConstantToReg) { 
1390     // `src' is constant and cannot fit in immed field for the ADD.
1391     // Insert instructions to "load" the constant into a register.
1392     CreateCodeToLoadConst(target, F, src, dest, mvec, mcfi);
1393   } else { 
1394     // Create a reg-to-reg copy instruction for the given type:
1395     // -- For FP values, create a FMOVS or FMOVD instruction
1396     // -- For non-FP values, create an add-with-0 instruction (opCode as above)
1397     // Make `src' the second operand, in case it is a small constant!
1398     MachineInstr* MI;
1399     if (resultType->isFloatingPoint())
1400       MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1401             .addReg(src).addRegDef(dest));
1402     else {
1403         const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
1404         MI = (BuildMI(opCode, 3)
1405               .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
1406     }
1407     mvec.push_back(MI);
1408   }
1409 }
1410
1411 /// FixConstantOperandsForInstr - Make a machine instruction use its constant
1412 /// operands more efficiently.  If the constant is 0, then use the hardwired 0
1413 /// register, if any.  Else, if the constant fits in the IMMEDIATE field, then
1414 /// use that field.  Otherwise, else create instructions to put the constant
1415 /// into a register, either directly or by loading explicitly from the constant
1416 /// pool.  In the first 2 cases, the operand of `minstr' is modified in place.
1417 /// Returns a vector of machine instructions generated for operands that fall
1418 /// under case 3; these must be inserted before `minstr'.
1419 /// 
1420 std::vector<MachineInstr*>
1421 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
1422                             TargetMachine& target) {
1423   std::vector<MachineInstr*> MVec;
1424   
1425   MachineOpCode opCode = minstr->getOpcode();
1426   const TargetInstrInfo& instrInfo = *target.getInstrInfo();
1427   int resultPos = instrInfo.get(opCode).resultPos;
1428   int immedPos = instrInfo.getImmedConstantPos(opCode);
1429
1430   Function *F = vmInstr->getParent()->getParent();
1431
1432   for (unsigned op=0; op < minstr->getNumOperands(); op++) {
1433       const MachineOperand& mop = minstr->getOperand(op);
1434           
1435       // Skip the result position, preallocated machine registers, or operands
1436       // that cannot be constants (CC regs or PC-relative displacements)
1437       if (resultPos == (int)op ||
1438           mop.getType() == MachineOperand::MO_MachineRegister ||
1439           mop.getType() == MachineOperand::MO_CCRegister ||
1440           mop.getType() == MachineOperand::MO_PCRelativeDisp)
1441         continue;
1442
1443       bool constantThatMustBeLoaded = false;
1444       unsigned int machineRegNum = 0;
1445       int64_t immedValue = 0;
1446       Value* opValue = NULL;
1447       MachineOperand::MachineOperandType opType =
1448         MachineOperand::MO_VirtualRegister;
1449
1450       // Operand may be a virtual register or a compile-time constant
1451       if (mop.getType() == MachineOperand::MO_VirtualRegister) {
1452         assert(mop.getVRegValue() != NULL);
1453         opValue = mop.getVRegValue();
1454         if (Constant *opConst = dyn_cast<Constant>(opValue)) 
1455           if (!isa<GlobalValue>(opConst)) {
1456             opType = ChooseRegOrImmed(opConst, opCode, target,
1457                                       (immedPos == (int)op), machineRegNum,
1458                                       immedValue);
1459             if (opType == MachineOperand::MO_VirtualRegister)
1460               constantThatMustBeLoaded = true;
1461           }
1462       } else {
1463         // If the operand is from the constant pool, don't try to change it.
1464         if (mop.getType() == MachineOperand::MO_ConstantPoolIndex) {
1465           continue;
1466         }
1467         assert(mop.isImmediate());
1468         bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
1469
1470         // Bit-selection flags indicate an instruction that is extracting
1471         // bits from its operand so ignore this even if it is a big constant.
1472         if (mop.isHiBits32() || mop.isLoBits32() ||
1473             mop.isHiBits64() || mop.isLoBits64())
1474           continue;
1475
1476         opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
1477                                   opCode, target, (immedPos == (int)op), 
1478                                   machineRegNum, immedValue);
1479
1480         if (opType == MachineOperand::MO_SignExtendedImmed ||
1481             opType == MachineOperand::MO_UnextendedImmed) {
1482           // The optype is an immediate value
1483           // This means we need to change the opcode, e.g. ADDr -> ADDi
1484           unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1485           minstr->setOpcode(newOpcode);
1486         }
1487
1488         if (opType == mop.getType()) 
1489           continue;           // no change: this is the most common case
1490
1491         if (opType == MachineOperand::MO_VirtualRegister) {
1492           constantThatMustBeLoaded = true;
1493           opValue = isSigned
1494             ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
1495             : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
1496         }
1497       }
1498
1499       if (opType == MachineOperand::MO_MachineRegister)
1500         minstr->SetMachineOperandReg(op, machineRegNum);
1501       else if (opType == MachineOperand::MO_SignExtendedImmed ||
1502                opType == MachineOperand::MO_UnextendedImmed) {
1503         minstr->SetMachineOperandConst(op, opType, immedValue);
1504         // The optype is or has become an immediate
1505         // This means we need to change the opcode, e.g. ADDr -> ADDi
1506         unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1507         minstr->setOpcode(newOpcode);
1508       } else if (constantThatMustBeLoaded ||
1509                (opValue && isa<GlobalValue>(opValue)))
1510         { // opValue is a constant that must be explicitly loaded into a reg
1511           assert(opValue);
1512           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
1513                                                             MVec, target);
1514           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
1515                                        tmpReg);
1516         }
1517     }
1518   
1519   // Also, check for implicit operands used by the machine instruction
1520   // (no need to check those defined since they cannot be constants).
1521   // These include:
1522   // -- arguments to a Call
1523   // -- return value of a Return
1524   // Any such operand that is a constant value needs to be fixed also.
1525   // The current instructions with implicit refs (viz., Call and Return)
1526   // have no immediate fields, so the constant always needs to be loaded
1527   // into a register.
1528   bool isCall = instrInfo.isCall(opCode);
1529   unsigned lastCallArgNum = 0;          // unused if not a call
1530   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
1531   if (isCall)
1532     argDesc = CallArgsDescriptor::get(minstr);
1533   
1534   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
1535     if (isa<Constant>(minstr->getImplicitRef(i))) {
1536         Value* oldVal = minstr->getImplicitRef(i);
1537         TmpInstruction* tmpReg =
1538           InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
1539         minstr->setImplicitRef(i, tmpReg);
1540         
1541         if (isCall) {
1542           // find and replace the argument in the CallArgsDescriptor
1543           unsigned i=lastCallArgNum;
1544           while (argDesc->getArgInfo(i).getArgVal() != oldVal)
1545             ++i;
1546           assert(i < argDesc->getNumArgs() &&
1547                  "Constant operands to a call *must* be in the arg list");
1548           lastCallArgNum = i;
1549           argDesc->getArgInfo(i).replaceArgVal(tmpReg);
1550         }
1551       }
1552   
1553   return MVec;
1554 }
1555
1556 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
1557                                     std::vector<MachineInstr*>& mvec) {
1558   mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
1559                                    .addReg(Node->rightChild()->getValue())
1560                                    .addRegDef(Node->getValue()));
1561 }
1562
1563 /// IsZero - Check for a constant 0.
1564 ///
1565 static inline bool IsZero(Value* idx) {
1566   return (idx == ConstantSInt::getNullValue(idx->getType()));
1567 }
1568
1569 /// FoldGetElemChain - Fold a chain of GetElementPtr instructions containing
1570 /// only constant offsets into an equivalent (Pointer, IndexVector) pair.
1571 /// Returns the pointer Value, and stores the resulting IndexVector in argument
1572 /// chainIdxVec. This is a helper function for FoldConstantIndices that does the
1573 /// actual folding.
1574 //
1575 static Value*
1576 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
1577                  bool lastInstHasLeadingNonZero) {
1578   InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
1579   GetElementPtrInst* gepInst =
1580     dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
1581
1582   // ptr value is not computed in this tree or ptr value does not come from GEP
1583   // instruction
1584   if (gepInst == NULL)
1585     return NULL;
1586
1587   // Return NULL if we don't fold any instructions in.
1588   Value* ptrVal = NULL;
1589
1590   // Now chase the chain of getElementInstr instructions, if any.
1591   // Check for any non-constant indices and stop there.
1592   // Also, stop if the first index of child is a non-zero array index
1593   // and the last index of the current node is a non-array index:
1594   // in that case, a non-array declared type is being accessed as an array
1595   // which is not type-safe, but could be legal.
1596   InstructionNode* ptrChild = gepNode;
1597   while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
1598                       ptrChild->getOpLabel() == GetElemPtrIdx)) {
1599     // Child is a GetElemPtr instruction
1600     gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
1601     User::op_iterator OI, firstIdx = gepInst->idx_begin();
1602     User::op_iterator lastIdx = gepInst->idx_end();
1603     bool allConstantOffsets = true;
1604
1605     // The first index of every GEP must be an array index.
1606     assert((*firstIdx)->getType() == Type::LongTy &&
1607            "INTERNAL ERROR: Structure index for a pointer type!");
1608
1609     // If the last instruction had a leading non-zero index, check if the
1610     // current one references a sequential (i.e., indexable) type.
1611     // If not, the code is not type-safe and we would create an illegal GEP
1612     // by folding them, so don't fold any more instructions.
1613     if (lastInstHasLeadingNonZero)
1614       if (! isa<SequentialType>(gepInst->getType()->getElementType()))
1615         break;   // cannot fold in any preceding getElementPtr instrs.
1616
1617     // Check that all offsets are constant for this instruction
1618     for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
1619       allConstantOffsets = isa<ConstantInt>(*OI);
1620
1621     if (allConstantOffsets) {
1622       // Get pointer value out of ptrChild.
1623       ptrVal = gepInst->getPointerOperand();
1624
1625       // Insert its index vector at the start, skipping any leading [0]
1626       // Remember the old size to check if anything was inserted.
1627       unsigned oldSize = chainIdxVec.size();
1628       int firstIsZero = IsZero(*firstIdx);
1629       chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
1630
1631       // Remember if it has leading zero index: it will be discarded later.
1632       if (oldSize < chainIdxVec.size())
1633         lastInstHasLeadingNonZero = !firstIsZero;
1634
1635       // Mark the folded node so no code is generated for it.
1636       ((InstructionNode*) ptrChild)->markFoldedIntoParent();
1637
1638       // Get the previous GEP instruction and continue trying to fold
1639       ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
1640     } else // cannot fold this getElementPtr instr. or any preceding ones
1641       break;
1642   }
1643
1644   // If the first getElementPtr instruction had a leading [0], add it back.
1645   // Note that this instruction is the *last* one that was successfully
1646   // folded *and* contributed any indices, in the loop above.
1647   if (ptrVal && ! lastInstHasLeadingNonZero) 
1648     chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
1649
1650   return ptrVal;
1651 }
1652
1653 /// GetGEPInstArgs - Helper function for GetMemInstArgs that handles the
1654 /// final getElementPtr instruction used by (or same as) the memory operation.
1655 /// Extracts the indices of the current instruction and tries to fold in
1656 /// preceding ones if all indices of the current one are constant.
1657 ///
1658 static Value *GetGEPInstArgs(InstructionNode *gepNode,
1659                              std::vector<Value *> &idxVec,
1660                              bool &allConstantIndices) {
1661   allConstantIndices = true;
1662   GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
1663
1664   // Default pointer is the one from the current instruction.
1665   Value* ptrVal = gepI->getPointerOperand();
1666   InstrTreeNode* ptrChild = gepNode->leftChild(); 
1667
1668   // Extract the index vector of the GEP instruction.
1669   // If all indices are constant and first index is zero, try to fold
1670   // in preceding GEPs with all constant indices.
1671   for (User::op_iterator OI=gepI->idx_begin(),  OE=gepI->idx_end();
1672        allConstantIndices && OI != OE; ++OI)
1673     if (! isa<Constant>(*OI))
1674       allConstantIndices = false;     // note: this also terminates loop!
1675
1676   // If we have only constant indices, fold chains of constant indices
1677   // in this and any preceding GetElemPtr instructions.
1678   bool foldedGEPs = false;
1679   bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
1680   if (allConstantIndices)
1681     if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
1682       ptrVal = newPtr;
1683       foldedGEPs = true;
1684     }
1685
1686   // Append the index vector of the current instruction.
1687   // Skip the leading [0] index if preceding GEPs were folded into this.
1688   idxVec.insert(idxVec.end(),
1689                 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
1690                 gepI->idx_end());
1691
1692   return ptrVal;
1693 }
1694
1695 /// GetMemInstArgs - Get the pointer value and the index vector for a memory
1696 /// operation (GetElementPtr, Load, or Store).  If all indices of the given
1697 /// memory operation are constant, fold in constant indices in a chain of
1698 /// preceding GetElementPtr instructions (if any), and return the pointer value
1699 /// of the first instruction in the chain. All folded instructions are marked so
1700 /// no code is generated for them. Returns the pointer Value to use, and
1701 /// returns the resulting IndexVector in idxVec. Sets allConstantIndices
1702 /// to true/false if all indices are/aren't const.
1703 /// 
1704 static Value *GetMemInstArgs(InstructionNode *memInstrNode,
1705                              std::vector<Value*> &idxVec,
1706                              bool& allConstantIndices) {
1707   allConstantIndices = false;
1708   Instruction* memInst = memInstrNode->getInstruction();
1709   assert(idxVec.size() == 0 && "Need empty vector to return indices");
1710
1711   // If there is a GetElemPtr instruction to fold in to this instr,
1712   // it must be in the left child for Load and GetElemPtr, and in the
1713   // right child for Store instructions.
1714   InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
1715                              ? memInstrNode->rightChild()
1716                              : memInstrNode->leftChild()); 
1717   
1718   // Default pointer is the one from the current instruction.
1719   Value* ptrVal = ptrChild->getValue(); 
1720
1721   // Find the "last" GetElemPtr instruction: this one or the immediate child.
1722   // There will be none if this is a load or a store from a scalar pointer.
1723   InstructionNode* gepNode = NULL;
1724   if (isa<GetElementPtrInst>(memInst))
1725     gepNode = memInstrNode;
1726   else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
1727     // Child of load/store is a GEP and memInst is its only use.
1728     // Use its indices and mark it as folded.
1729     gepNode = cast<InstructionNode>(ptrChild);
1730     gepNode->markFoldedIntoParent();
1731   }
1732
1733   // If there are no indices, return the current pointer.
1734   // Else extract the pointer from the GEP and fold the indices.
1735   return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
1736                  : ptrVal;
1737 }
1738
1739 static inline MachineOpCode 
1740 ChooseBprInstruction(const InstructionNode* instrNode) {
1741   MachineOpCode opCode;
1742   
1743   Instruction* setCCInstr =
1744     ((InstructionNode*) instrNode->leftChild())->getInstruction();
1745   
1746   switch(setCCInstr->getOpcode()) {
1747   case Instruction::SetEQ: opCode = V9::BRZ;   break;
1748   case Instruction::SetNE: opCode = V9::BRNZ;  break;
1749   case Instruction::SetLE: opCode = V9::BRLEZ; break;
1750   case Instruction::SetGE: opCode = V9::BRGEZ; break;
1751   case Instruction::SetLT: opCode = V9::BRLZ;  break;
1752   case Instruction::SetGT: opCode = V9::BRGZ;  break;
1753   default:
1754     assert(0 && "Unrecognized VM instruction!");
1755     opCode = V9::INVALID_OPCODE;
1756     break; 
1757   }
1758   
1759   return opCode;
1760 }
1761
1762 static inline MachineOpCode 
1763 ChooseBpccInstruction(const InstructionNode* instrNode,
1764                       const BinaryOperator* setCCInstr) {
1765   MachineOpCode opCode = V9::INVALID_OPCODE;
1766   
1767   bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
1768   
1769   if (isSigned) {
1770     switch(setCCInstr->getOpcode()) {
1771     case Instruction::SetEQ: opCode = V9::BE;  break;
1772     case Instruction::SetNE: opCode = V9::BNE; break;
1773     case Instruction::SetLE: opCode = V9::BLE; break;
1774     case Instruction::SetGE: opCode = V9::BGE; break;
1775     case Instruction::SetLT: opCode = V9::BL;  break;
1776     case Instruction::SetGT: opCode = V9::BG;  break;
1777     default:
1778       assert(0 && "Unrecognized VM instruction!");
1779       break; 
1780     }
1781   } else {
1782     switch(setCCInstr->getOpcode()) {
1783     case Instruction::SetEQ: opCode = V9::BE;   break;
1784     case Instruction::SetNE: opCode = V9::BNE;  break;
1785     case Instruction::SetLE: opCode = V9::BLEU; break;
1786     case Instruction::SetGE: opCode = V9::BCC;  break;
1787     case Instruction::SetLT: opCode = V9::BCS;  break;
1788     case Instruction::SetGT: opCode = V9::BGU;  break;
1789     default:
1790       assert(0 && "Unrecognized VM instruction!");
1791       break; 
1792     }
1793   }
1794   
1795   return opCode;
1796 }
1797
1798 static inline MachineOpCode 
1799 ChooseBFpccInstruction(const InstructionNode* instrNode,
1800                        const BinaryOperator* setCCInstr) {
1801   MachineOpCode opCode = V9::INVALID_OPCODE;
1802   
1803   switch(setCCInstr->getOpcode()) {
1804   case Instruction::SetEQ: opCode = V9::FBE;  break;
1805   case Instruction::SetNE: opCode = V9::FBNE; break;
1806   case Instruction::SetLE: opCode = V9::FBLE; break;
1807   case Instruction::SetGE: opCode = V9::FBGE; break;
1808   case Instruction::SetLT: opCode = V9::FBL;  break;
1809   case Instruction::SetGT: opCode = V9::FBG;  break;
1810   default:
1811     assert(0 && "Unrecognized VM instruction!");
1812     break; 
1813   }
1814   
1815   return opCode;
1816 }
1817
1818 // GetTmpForCC - Create a unique TmpInstruction for a boolean value,
1819 // representing the CC register used by a branch on that value.
1820 // For now, hack this using a little static cache of TmpInstructions.
1821 // Eventually the entire BURG instruction selection should be put
1822 // into a separate class that can hold such information.
1823 // The static cache is not too bad because the memory for these
1824 // TmpInstructions will be freed along with the rest of the Function anyway.
1825 // 
1826 static TmpInstruction *GetTmpForCC (Value* boolVal, const Function *F,
1827                                     const Type* ccType,
1828                                     MachineCodeForInstruction& mcfi) {
1829   typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
1830   static BoolTmpCache boolToTmpCache;     // Map boolVal -> TmpInstruction*
1831   static const Function *lastFunction = 0;// Use to flush cache between funcs
1832   
1833   assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
1834   
1835   if (lastFunction != F) {
1836     lastFunction = F;
1837     boolToTmpCache.clear();
1838   }
1839   
1840   // Look for tmpI and create a new one otherwise.  The new value is
1841   // directly written to map using the ref returned by operator[].
1842   TmpInstruction*& tmpI = boolToTmpCache[boolVal];
1843   if (tmpI == NULL)
1844     tmpI = new TmpInstruction(mcfi, ccType, boolVal);
1845   
1846   return tmpI;
1847 }
1848
1849 static inline MachineOpCode 
1850 ChooseBccInstruction(const InstructionNode* instrNode, const Type*& setCCType) {
1851   InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
1852   assert(setCCNode->getOpLabel() == SetCCOp);
1853   BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
1854   setCCType = setCCInstr->getOperand(0)->getType();
1855   
1856   if (setCCType->isFloatingPoint())
1857     return ChooseBFpccInstruction(instrNode, setCCInstr);
1858   else
1859     return ChooseBpccInstruction(instrNode, setCCInstr);
1860 }
1861
1862 /// ChooseMovFpcciInstruction - WARNING: since this function has only one
1863 /// caller, it always returns the opcode that expects an immediate and a
1864 /// register. If this function is ever used in cases where an opcode that takes
1865 /// two registers is required, then modify this function and use
1866 /// convertOpcodeFromRegToImm() where required. It will be necessary to expand
1867 /// convertOpcodeFromRegToImm() to handle the new cases of opcodes.
1868 /// 
1869 static inline MachineOpCode 
1870 ChooseMovFpcciInstruction(const InstructionNode* instrNode) {
1871   MachineOpCode opCode = V9::INVALID_OPCODE;
1872   
1873   switch(instrNode->getInstruction()->getOpcode()) {
1874   case Instruction::SetEQ: opCode = V9::MOVFEi;  break;
1875   case Instruction::SetNE: opCode = V9::MOVFNEi; break;
1876   case Instruction::SetLE: opCode = V9::MOVFLEi; break;
1877   case Instruction::SetGE: opCode = V9::MOVFGEi; break;
1878   case Instruction::SetLT: opCode = V9::MOVFLi;  break;
1879   case Instruction::SetGT: opCode = V9::MOVFGi;  break;
1880   default:
1881     assert(0 && "Unrecognized VM instruction!");
1882     break; 
1883   }
1884   
1885   return opCode;
1886 }
1887
1888 /// ChooseMovpcciForSetCC -- Choose a conditional-move instruction
1889 /// based on the type of SetCC operation.
1890 /// 
1891 /// WARNING: like the previous function, this function always returns
1892 /// the opcode that expects an immediate and a register.  See above.
1893 /// 
1894 static MachineOpCode ChooseMovpcciForSetCC(const InstructionNode* instrNode) {
1895   MachineOpCode opCode = V9::INVALID_OPCODE;
1896
1897   const Type* opType = instrNode->leftChild()->getValue()->getType();
1898   assert(opType->isIntegral() || isa<PointerType>(opType));
1899   bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
1900   
1901   switch(instrNode->getInstruction()->getOpcode()) {
1902   case Instruction::SetEQ: opCode = V9::MOVEi;                        break;
1903   case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
1904   case Instruction::SetGE: opCode = noSign? V9::MOVCCi  : V9::MOVGEi; break;
1905   case Instruction::SetLT: opCode = noSign? V9::MOVCSi  : V9::MOVLi;  break;
1906   case Instruction::SetGT: opCode = noSign? V9::MOVGUi  : V9::MOVGi;  break;
1907   case Instruction::SetNE: opCode = V9::MOVNEi;                       break;
1908   default: assert(0 && "Unrecognized LLVM instr!"); break; 
1909   }
1910   
1911   return opCode;
1912 }
1913
1914 /// ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
1915 /// instruction based on the type of SetCC operation.  These instructions
1916 /// compare a register with 0 and perform the move is the comparison is true.
1917 /// 
1918 /// WARNING: like the previous function, this function it always returns
1919 /// the opcode that expects an immediate and a register.  See above.
1920 /// 
1921 static MachineOpCode ChooseMovpregiForSetCC(const InstructionNode* instrNode) {
1922   MachineOpCode opCode = V9::INVALID_OPCODE;
1923   
1924   switch(instrNode->getInstruction()->getOpcode()) {
1925   case Instruction::SetEQ: opCode = V9::MOVRZi;  break;
1926   case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
1927   case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
1928   case Instruction::SetLT: opCode = V9::MOVRLZi;  break;
1929   case Instruction::SetGT: opCode = V9::MOVRGZi;  break;
1930   case Instruction::SetNE: opCode = V9::MOVRNZi; break;
1931   default: assert(0 && "Unrecognized VM instr!"); break; 
1932   }
1933   
1934   return opCode;
1935 }
1936
1937 static inline MachineOpCode
1938 ChooseConvertToFloatInstr(const TargetMachine& target,
1939                           OpLabel vopCode, const Type* opType) {
1940   assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
1941          "Unrecognized convert-to-float opcode!");
1942   assert((opType->isIntegral() || opType->isFloatingPoint() ||
1943           isa<PointerType>(opType))
1944          && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
1945
1946   MachineOpCode opCode = V9::INVALID_OPCODE;
1947
1948   unsigned opSize = target.getTargetData().getTypeSize(opType);
1949
1950   if (opType == Type::FloatTy)
1951     opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
1952   else if (opType == Type::DoubleTy)
1953     opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
1954   else if (opSize <= 4)
1955     opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
1956   else {
1957     assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
1958     opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
1959   }
1960   
1961   return opCode;
1962 }
1963
1964 static inline MachineOpCode 
1965 ChooseConvertFPToIntInstr(const TargetMachine& target,
1966                           const Type* destType, const Type* opType) {
1967   assert((opType == Type::FloatTy || opType == Type::DoubleTy)
1968          && "This function should only be called for FLOAT or DOUBLE");
1969   assert((destType->isIntegral() || isa<PointerType>(destType))
1970          && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
1971
1972   MachineOpCode opCode = V9::INVALID_OPCODE;
1973
1974   unsigned destSize = target.getTargetData().getTypeSize(destType);
1975
1976   if (destType == Type::UIntTy)
1977     assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
1978   else if (destSize <= 4)
1979     opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
1980   else {
1981     assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
1982     opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
1983   }
1984
1985   return opCode;
1986 }
1987
1988 static MachineInstr*
1989 CreateConvertFPToIntInstr(const TargetMachine& target, Value* srcVal,
1990                           Value* destVal, const Type* destType) {
1991   MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
1992                                                    srcVal->getType());
1993   assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
1994   return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
1995 }
1996
1997 /// CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned
1998 /// integer.  The FP value must be converted to the dest type in an FP register,
1999 /// and the result is then copied from FP to int register via memory.  SPARC
2000 /// does not have a float-to-uint conversion, only a float-to-int (fdtoi).
2001 /// Since fdtoi converts to signed integers, any FP value V between MAXINT+1 and
2002 /// MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
2003 /// Therefore, for converting an FP value to uint32_t, we first need to convert
2004 /// to uint64_t and then to uint32_t.
2005 /// 
2006 static void
2007 CreateCodeToConvertFloatToInt(const TargetMachine& target,
2008                               Value* opVal, Instruction* destI,
2009                               std::vector<MachineInstr*>& mvec,
2010                               MachineCodeForInstruction& mcfi) {
2011   Function* F = destI->getParent()->getParent();
2012
2013   // Create a temporary to represent the FP register into which the
2014   // int value will placed after conversion.  The type of this temporary
2015   // depends on the type of FP register to use: single-prec for a 32-bit
2016   // int or smaller; double-prec for a 64-bit int.
2017   size_t destSize = target.getTargetData().getTypeSize(destI->getType());
2018
2019   const Type* castDestType = destI->getType(); // type for the cast instr result
2020   const Type* castDestRegType;          // type for cast instruction result reg
2021   TmpInstruction* destForCast;          // dest for cast instruction
2022   Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
2023
2024   // For converting an FP value to uint32_t, we first need to convert to
2025   // uint64_t and then to uint32_t, as explained above.
2026   if (destI->getType() == Type::UIntTy) {
2027     castDestType    = Type::ULongTy;       // use this instead of type of destI
2028     castDestRegType = Type::DoubleTy;      // uint64_t needs 64-bit FP register.
2029     destForCast     = new TmpInstruction(mcfi, castDestRegType, opVal);
2030     fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
2031   } else {
2032     castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
2033     destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2034   }
2035
2036   // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
2037   mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
2038                                            castDestType));
2039
2040   // Create the fpreg-to-intreg copy code
2041   CreateCodeToCopyFloatToInt(target, F, destForCast, fpToIntCopyDest, mvec,
2042                              mcfi);
2043
2044   // Create the uint64_t to uint32_t conversion, if needed
2045   if (destI->getType() == Type::UIntTy)
2046     CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
2047                                     /*numLowBits*/ 32, mvec, mcfi);
2048 }
2049
2050 static inline MachineOpCode 
2051 ChooseAddInstruction(const InstructionNode* instrNode) {
2052   return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
2053 }
2054
2055 static inline MachineInstr* 
2056 CreateMovFloatInstruction(const InstructionNode* instrNode,
2057                           const Type* resultType) {
2058   return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
2059                    .addReg(instrNode->leftChild()->getValue())
2060                    .addRegDef(instrNode->getValue());
2061 }
2062
2063 static inline MachineInstr* 
2064 CreateAddConstInstruction(const InstructionNode* instrNode) {
2065   MachineInstr* minstr = NULL;
2066   
2067   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2068   assert(isa<Constant>(constOp));
2069   
2070   // Cases worth optimizing are:
2071   // (1) Add with 0 for float or double: use an FMOV of appropriate type,
2072   //     instead of an FADD (1 vs 3 cycles).  There is no integer MOV.
2073   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2074     double dval = FPC->getValue();
2075     if (dval == 0.0)
2076       minstr = CreateMovFloatInstruction(instrNode,
2077                                         instrNode->getInstruction()->getType());
2078   }
2079   
2080   return minstr;
2081 }
2082
2083 static inline MachineOpCode ChooseSubInstructionByType(const Type* resultType) {
2084   MachineOpCode opCode = V9::INVALID_OPCODE;
2085   
2086   if (resultType->isInteger() || isa<PointerType>(resultType)) {
2087       opCode = V9::SUBr;
2088   } else {
2089     switch(resultType->getTypeID()) {
2090     case Type::FloatTyID:  opCode = V9::FSUBS; break;
2091     case Type::DoubleTyID: opCode = V9::FSUBD; break;
2092     default: assert(0 && "Invalid type for SUB instruction"); break; 
2093     }
2094   }
2095
2096   return opCode;
2097 }
2098
2099 static inline MachineInstr* 
2100 CreateSubConstInstruction(const InstructionNode* instrNode) {
2101   MachineInstr* minstr = NULL;
2102   
2103   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2104   assert(isa<Constant>(constOp));
2105   
2106   // Cases worth optimizing are:
2107   // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
2108   //     instead of an FSUB (1 vs 3 cycles).  There is no integer MOV.
2109   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2110     double dval = FPC->getValue();
2111     if (dval == 0.0)
2112       minstr = CreateMovFloatInstruction(instrNode,
2113                                         instrNode->getInstruction()->getType());
2114   }
2115   
2116   return minstr;
2117 }
2118
2119 static inline MachineOpCode 
2120 ChooseFcmpInstruction(const InstructionNode* instrNode) {
2121   MachineOpCode opCode = V9::INVALID_OPCODE;
2122   
2123   Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
2124   switch(operand->getType()->getTypeID()) {
2125   case Type::FloatTyID:  opCode = V9::FCMPS; break;
2126   case Type::DoubleTyID: opCode = V9::FCMPD; break;
2127   default: assert(0 && "Invalid type for FCMP instruction"); break; 
2128   }
2129   
2130   return opCode;
2131 }
2132
2133 /// BothFloatToDouble - Assumes that leftArg and rightArg of instrNode are both
2134 /// cast instructions. Returns true if both are floats cast to double.
2135 /// 
2136 static inline bool BothFloatToDouble(const InstructionNode* instrNode) {
2137   InstrTreeNode* leftArg = instrNode->leftChild();
2138   InstrTreeNode* rightArg = instrNode->rightChild();
2139   InstrTreeNode* leftArgArg = leftArg->leftChild();
2140   InstrTreeNode* rightArgArg = rightArg->leftChild();
2141   assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
2142   return (leftArg->getValue()->getType() == Type::DoubleTy &&
2143           leftArgArg->getValue()->getType() == Type::FloatTy &&
2144           rightArgArg->getValue()->getType() == Type::FloatTy);
2145 }
2146
2147 static inline MachineOpCode ChooseMulInstructionByType(const Type* resultType) {
2148   MachineOpCode opCode = V9::INVALID_OPCODE;
2149   
2150   if (resultType->isInteger())
2151     opCode = V9::MULXr;
2152   else
2153     switch(resultType->getTypeID()) {
2154     case Type::FloatTyID:  opCode = V9::FMULS; break;
2155     case Type::DoubleTyID: opCode = V9::FMULD; break;
2156     default: assert(0 && "Invalid type for MUL instruction"); break; 
2157     }
2158   
2159   return opCode;
2160 }
2161
2162 static inline MachineInstr*
2163 CreateIntNegInstruction(const TargetMachine& target, Value* vreg) {
2164   return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
2165     .addReg(vreg).addRegDef(vreg);
2166 }
2167
2168 /// CreateShiftInstructions - Create instruction sequence for any shift
2169 /// operation. SLL or SLLX on an operand smaller than the integer reg. size
2170 /// (64bits) requires a second instruction for explicit sign-extension. Note
2171 /// that we only have to worry about a sign-bit appearing in the most
2172 /// significant bit of the operand after shifting (e.g., bit 32 of Int or bit 16
2173 /// of Short), so we do not have to worry about results that are as large as a
2174 /// normal integer register.
2175 /// 
2176 static inline void
2177 CreateShiftInstructions(const TargetMachine& target, Function* F,
2178                         MachineOpCode shiftOpCode, Value* argVal1,
2179                         Value* optArgVal2, /* Use optArgVal2 if not NULL */
2180                         unsigned optShiftNum, /* else use optShiftNum */
2181                         Instruction* destVal, std::vector<MachineInstr*>& mvec,
2182                         MachineCodeForInstruction& mcfi) {
2183   assert((optArgVal2 != NULL || optShiftNum <= 64) &&
2184          "Large shift sizes unexpected, but can be handled below: "
2185          "You need to check whether or not it fits in immed field below");
2186   
2187   // If this is a logical left shift of a type smaller than the standard
2188   // integer reg. size, we have to extend the sign-bit into upper bits
2189   // of dest, so we need to put the result of the SLL into a temporary.
2190   Value* shiftDest = destVal;
2191   unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
2192
2193   if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
2194     // put SLL result into a temporary
2195     shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
2196   }
2197   
2198   MachineInstr* M = (optArgVal2 != NULL)
2199     ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
2200                              .addReg(shiftDest, MachineOperand::Def)
2201     : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
2202                              .addReg(shiftDest, MachineOperand::Def);
2203   mvec.push_back(M);
2204   
2205   if (shiftDest != destVal) {
2206     // extend the sign-bit of the result into all upper bits of dest
2207     assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
2208     CreateSignExtensionInstructions(target, F, shiftDest, destVal, 8*opSize,
2209                                     mvec, mcfi);
2210   }
2211 }
2212
2213 /// CreateMulConstInstruction - Does not create any instructions if we
2214 /// cannot exploit constant to create a cheaper instruction. This returns the
2215 /// approximate cost of the instructions generated, which is used to pick the
2216 /// cheapest when both operands are constant.
2217 /// 
2218 static unsigned
2219 CreateMulConstInstruction(const TargetMachine &target, Function* F,
2220                           Value* lval, Value* rval, Instruction* destVal,
2221                           std::vector<MachineInstr*>& mvec,
2222                           MachineCodeForInstruction& mcfi) {
2223   // Use max. multiply cost, viz., cost of MULX
2224   unsigned cost = target.getInstrInfo()->minLatency(V9::MULXr);
2225   unsigned firstNewInstr = mvec.size();
2226   
2227   Value* constOp = rval;
2228   if (! isa<Constant>(constOp))
2229     return cost;
2230   
2231   // Cases worth optimizing are:
2232   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
2233   // (2) Multiply by 2^x for integer types: replace with Shift
2234   const Type* resultType = destVal->getType();
2235   
2236   if (resultType->isInteger() || isa<PointerType>(resultType)) {
2237     bool isValidConst;
2238     int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2239                                                    constOp->getType(),
2240                                                    isValidConst);
2241     if (isValidConst) {
2242       unsigned pow;
2243       bool needNeg = false;
2244       if (C < 0) {
2245         needNeg = true;
2246         C = -C;
2247       }
2248           
2249       if (C == 0 || C == 1) {
2250         cost = target.getInstrInfo()->minLatency(V9::ADDr);
2251         unsigned Zero = target.getRegInfo()->getZeroRegNum();
2252         MachineInstr* M;
2253         if (C == 0)
2254           M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
2255         else
2256           M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
2257         mvec.push_back(M);
2258       } else if (isPowerOf2(C, pow)) {
2259         unsigned opSize = target.getTargetData().getTypeSize(resultType);
2260         MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
2261         CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
2262                                 destVal, mvec, mcfi);
2263       }
2264           
2265       if (mvec.size() > 0 && needNeg) {
2266         // insert <reg = SUB 0, reg> after the instr to flip the sign
2267         MachineInstr* M = CreateIntNegInstruction(target, destVal);
2268         mvec.push_back(M);
2269       }
2270     }
2271   } else {
2272     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2273       double dval = FPC->getValue();
2274       if (fabs(dval) == 1) {
2275         MachineOpCode opCode =  (dval < 0)
2276           ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2277           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2278         mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
2279       } 
2280     }
2281   }
2282   
2283   if (firstNewInstr < mvec.size()) {
2284     cost = 0;
2285     for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
2286       cost += target.getInstrInfo()->minLatency(mvec[i]->getOpcode());
2287   }
2288   
2289   return cost;
2290 }
2291
2292 /// CreateCheapestMulConstInstruction - Does not create any instructions
2293 /// if we cannot exploit constant to create a cheaper instruction.
2294 ///
2295 static inline void
2296 CreateCheapestMulConstInstruction(const TargetMachine &target, Function* F,
2297                                   Value* lval, Value* rval,
2298                                   Instruction* destVal,
2299                                   std::vector<MachineInstr*>& mvec,
2300                                   MachineCodeForInstruction& mcfi) {
2301   Value* constOp;
2302   if (isa<Constant>(lval) && isa<Constant>(rval)) {
2303     // both operands are constant: evaluate and "set" in dest
2304     Constant* P = ConstantExpr::get(Instruction::Mul,
2305                                     cast<Constant>(lval),
2306                                     cast<Constant>(rval));
2307     CreateCodeToLoadConst (target, F, P, destVal, mvec, mcfi);
2308   }
2309   else if (isa<Constant>(rval))         // rval is constant, but not lval
2310     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2311   else if (isa<Constant>(lval))         // lval is constant, but not rval
2312     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2313   
2314   // else neither is constant
2315   return;
2316 }
2317
2318 /// CreateMulInstruction - Returns NULL if we cannot exploit constant
2319 /// to create a cheaper instruction.
2320 /// 
2321 static inline void
2322 CreateMulInstruction(const TargetMachine &target, Function* F,
2323                      Value* lval, Value* rval, Instruction* destVal,
2324                      std::vector<MachineInstr*>& mvec,
2325                      MachineCodeForInstruction& mcfi,
2326                      MachineOpCode forceMulOp = -1) {
2327   unsigned L = mvec.size();
2328   CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
2329   if (mvec.size() == L) {
2330     // no instructions were added so create MUL reg, reg, reg.
2331     // Use FSMULD if both operands are actually floats cast to doubles.
2332     // Otherwise, use the default opcode for the appropriate type.
2333     MachineOpCode mulOp = ((forceMulOp != -1)
2334                            ? forceMulOp 
2335                            : ChooseMulInstructionByType(destVal->getType()));
2336     mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
2337                    .addRegDef(destVal));
2338   }
2339 }
2340
2341 /// ChooseDivInstruction - Generate a divide instruction for Div or Rem.
2342 /// For Rem, this assumes that the operand type will be signed if the result
2343 /// type is signed.  This is correct because they must have the same sign.
2344 /// 
2345 static inline MachineOpCode 
2346 ChooseDivInstruction(TargetMachine &target, const InstructionNode* instrNode) {
2347   MachineOpCode opCode = V9::INVALID_OPCODE;
2348   
2349   const Type* resultType = instrNode->getInstruction()->getType();
2350   
2351   if (resultType->isInteger())
2352     opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
2353   else
2354     switch(resultType->getTypeID()) {
2355       case Type::FloatTyID:  opCode = V9::FDIVS; break;
2356       case Type::DoubleTyID: opCode = V9::FDIVD; break;
2357       default: assert(0 && "Invalid type for DIV instruction"); break; 
2358       }
2359   
2360   return opCode;
2361 }
2362
2363 /// CreateDivConstInstruction - Return if we cannot exploit constant to create
2364 /// a cheaper instruction.
2365 /// 
2366 static void CreateDivConstInstruction(TargetMachine &target,
2367                                       const InstructionNode* instrNode,
2368                                       std::vector<MachineInstr*>& mvec) {
2369   Value* LHS  = instrNode->leftChild()->getValue();
2370   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2371   if (!isa<Constant>(constOp))
2372     return;
2373
2374   Instruction* destVal = instrNode->getInstruction();
2375   unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
2376   
2377   // Cases worth optimizing are:
2378   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
2379   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
2380   const Type* resultType = instrNode->getInstruction()->getType();
2381  
2382   if (resultType->isInteger()) {
2383     unsigned pow;
2384     bool isValidConst;
2385     int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2386                                                    constOp->getType(),
2387                                                    isValidConst);
2388     if (isValidConst) {
2389       bool needNeg = false;
2390       if (C < 0) {
2391         needNeg = true;
2392         C = -C;
2393       }
2394       
2395       if (C == 1) {
2396         mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
2397                        .addRegDef(destVal));
2398       } else if (isPowerOf2(C, pow)) {
2399         unsigned opCode;
2400         Value* shiftOperand;
2401         unsigned opSize = target.getTargetData().getTypeSize(resultType);
2402
2403         if (resultType->isSigned()) {
2404           // For N / 2^k, if the operand N is negative,
2405           // we need to add (2^k - 1) before right-shifting by k, i.e.,
2406           // 
2407           //    (N / 2^k) = N >> k,               if N >= 0;
2408           //                (N + 2^k - 1) >> k,   if N < 0
2409           // 
2410           // If N is <= 32 bits, use:
2411           //    sra N, 31, t1           // t1 = ~0,         if N < 0,  0 else
2412           //    srl t1, 32-k, t2        // t2 = 2^k - 1,    if N < 0,  0 else
2413           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
2414           //    sra t3, k, result       // result = N / 2^k
2415           // 
2416           // If N is 64 bits, use:
2417           //    srax N,  k-1,  t1       // t1 = sign bit in high k positions
2418           //    srlx t1, 64-k, t2       // t2 = 2^k - 1,    if N < 0,  0 else
2419           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
2420           //    sra t3, k, result       // result = N / 2^k
2421           TmpInstruction *sraTmp, *srlTmp, *addTmp;
2422           MachineCodeForInstruction& mcfi
2423             = MachineCodeForInstruction::get(destVal);
2424           sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
2425           srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
2426           addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
2427
2428           // Create the SRA or SRAX instruction to get the sign bit
2429           mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
2430                          .addReg(LHS)
2431                          .addSImm((resultType==Type::LongTy)? pow-1 : 31)
2432                          .addRegDef(sraTmp));
2433
2434           // Create the SRL or SRLX instruction to get the sign bit
2435           mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
2436                          .addReg(sraTmp)
2437                          .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
2438                          .addRegDef(srlTmp));
2439
2440           // Create the ADD instruction to add 2^pow-1 for negative values
2441           mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
2442                          .addRegDef(addTmp));
2443
2444           // Get the shift operand and "right-shift" opcode to do the divide
2445           shiftOperand = addTmp;
2446           opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
2447         } else {
2448           // Get the shift operand and "right-shift" opcode to do the divide
2449           shiftOperand = LHS;
2450           opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
2451         }
2452
2453         // Now do the actual shift!
2454         mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
2455                        .addRegDef(destVal));
2456       }
2457           
2458       if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
2459         // insert <reg = SUB 0, reg> after the instr to flip the sign
2460         mvec.push_back(CreateIntNegInstruction(target, destVal));
2461       }
2462     }
2463   } else {
2464     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2465       double dval = FPC->getValue();
2466       if (fabs(dval) == 1) {
2467         unsigned opCode = 
2468           (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2469           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2470               
2471         mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
2472       } 
2473     }
2474   }
2475 }
2476
2477 static void CreateCodeForVariableSizeAlloca(const TargetMachine& target,
2478                                             Instruction* result, unsigned tsize,
2479                                             Value* numElementsVal,
2480                                             std::vector<MachineInstr*>& getMvec)
2481 {
2482   Value* totalSizeVal;
2483   MachineInstr* M;
2484   MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
2485   Function *F = result->getParent()->getParent();
2486
2487   // Enforce the alignment constraints on the stack pointer at
2488   // compile time if the total size is a known constant.
2489   if (isa<Constant>(numElementsVal)) {
2490     bool isValid;
2491     int64_t numElem = (int64_t)
2492       ConvertConstantToIntType(target, numElementsVal,
2493                                numElementsVal->getType(), isValid);
2494     assert(isValid && "Unexpectedly large array dimension in alloca!");
2495     int64_t total = numElem * tsize;
2496     if (int extra= total % SparcV9FrameInfo::StackFrameSizeAlignment)
2497       total += SparcV9FrameInfo::StackFrameSizeAlignment - extra;
2498     totalSizeVal = ConstantSInt::get(Type::IntTy, total);
2499   } else {
2500     // The size is not a constant.  Generate code to compute it and
2501     // code to pad the size for stack alignment.
2502     // Create a Value to hold the (constant) element size
2503     Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
2504
2505     // Create temporary values to hold the result of MUL, SLL, SRL
2506     // To pad `size' to next smallest multiple of 16:
2507     //          size = (size + 15) & (-16 = 0xfffffffffffffff0)
2508     TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
2509     TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
2510     TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
2511
2512     // Instruction 1: mul numElements, typeSize -> tmpProd
2513     // This will optimize the MUL as far as possible.
2514     CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
2515                          mcfi, -1);
2516
2517     // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
2518     getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
2519                       .addReg(tmpAdd15, MachineOperand::Def));
2520
2521     // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
2522     getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
2523                       .addReg(tmpAndf0, MachineOperand::Def));
2524
2525     totalSizeVal = tmpAndf0;
2526   }
2527
2528   // Get the constant offset from SP for dynamically allocated storage
2529   // and create a temporary Value to hold it.
2530   MachineFunction& mcInfo = MachineFunction::get(F);
2531   bool growUp;
2532   ConstantSInt* dynamicAreaOffset =
2533     ConstantSInt::get(Type::IntTy,
2534                     target.getFrameInfo()->getDynamicAreaOffset(mcInfo,growUp));
2535   assert(! growUp && "Has SPARC v9 stack frame convention changed?");
2536
2537   unsigned SPReg = target.getRegInfo()->getStackPointer();
2538
2539   // Instruction 2: sub %sp, totalSizeVal -> %sp
2540   getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
2541                     .addMReg(SPReg,MachineOperand::Def));
2542
2543   // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
2544   getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
2545                     .addRegDef(result));
2546 }        
2547
2548 static void
2549 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
2550                              Instruction* result, unsigned tsize,
2551                              unsigned numElements,
2552                              std::vector<MachineInstr*>& getMvec) {
2553   assert(result && result->getParent() &&
2554          "Result value is not part of a function?");
2555   Function *F = result->getParent()->getParent();
2556   MachineFunction &mcInfo = MachineFunction::get(F);
2557
2558   // If the alloca is of zero bytes (which is perfectly legal) we bump it up to
2559   // one byte.  This is unnecessary, but I really don't want to break any
2560   // fragile logic in this code.  FIXME.
2561   if (tsize == 0)
2562     tsize = 1;
2563
2564   // Put the variable in the dynamically sized area of the frame if either:
2565   // (a) The offset is too large to use as an immediate in load/stores
2566   //     (check LDX because all load/stores have the same-size immed. field).
2567   // (b) The object is "large", so it could cause many other locals,
2568   //     spills, and temporaries to have large offsets.
2569   //     NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
2570   // You've gotta love having only 13 bits for constant offset values :-|.
2571   // 
2572   unsigned paddedSize;
2573   int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
2574                                                                 paddedSize,
2575                                                          tsize * numElements);
2576
2577   if (((int)paddedSize) > 8 * SparcV9FrameInfo::SizeOfEachArgOnStack ||
2578       !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
2579     CreateCodeForVariableSizeAlloca(target, result, tsize, 
2580                                     ConstantSInt::get(Type::IntTy,numElements),
2581                                     getMvec);
2582     return;
2583   }
2584   
2585   // else offset fits in immediate field so go ahead and allocate it.
2586   offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
2587   
2588   // Create a temporary Value to hold the constant offset.
2589   // This is needed because it may not fit in the immediate field.
2590   ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
2591   
2592   // Instruction 1: add %fp, offsetFromFP -> result
2593   unsigned FPReg = target.getRegInfo()->getFramePointer();
2594   getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
2595                     .addRegDef(result));
2596 }
2597
2598 /// SetOperandsForMemInstr - Choose addressing mode for the given load or store
2599 /// instruction.  Use [reg+reg] if it is an indexed reference, and the index
2600 /// offset is not a constant or if it cannot fit in the offset field.  Use
2601 /// [reg+offset] in all other cases.  This assumes that all array refs are
2602 /// "lowered" to one of these forms:
2603 ///    %x = load (subarray*) ptr, constant      ; single constant offset
2604 ///    %x = load (subarray*) ptr, offsetVal     ; single non-constant offset
2605 /// Generally, this should happen via strength reduction + LICM.  Also, strength
2606 /// reduction should take care of using the same register for the loop index
2607 /// variable and an array index, when that is profitable.
2608 ///
2609 static void SetOperandsForMemInstr(unsigned Opcode,
2610                                    std::vector<MachineInstr*>& mvec,
2611                                    InstructionNode* vmInstrNode,
2612                                    const TargetMachine& target) {
2613   Instruction* memInst = vmInstrNode->getInstruction();
2614   // Index vector, ptr value, and flag if all indices are const.
2615   std::vector<Value*> idxVec;
2616   bool allConstantIndices;
2617   Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
2618
2619   // Now create the appropriate operands for the machine instruction.
2620   // First, initialize so we default to storing the offset in a register.
2621   int64_t smallConstOffset = 0;
2622   Value* valueForRegOffset = NULL;
2623   MachineOperand::MachineOperandType offsetOpType =
2624     MachineOperand::MO_VirtualRegister;
2625
2626   // Check if there is an index vector and if so, compute the
2627   // right offset for structures and for arrays 
2628   if (!idxVec.empty()) {
2629     const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
2630       
2631     // If all indices are constant, compute the combined offset directly.
2632     if (allConstantIndices) {
2633       // Compute the offset value using the index vector. Create a
2634       // virtual reg. for it since it may not fit in the immed field.
2635       uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
2636       valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
2637     } else {
2638       // There is at least one non-constant offset.  Therefore, this must
2639       // be an array ref, and must have been lowered to a single non-zero
2640       // offset.  (An extra leading zero offset, if any, can be ignored.)
2641       // Generate code sequence to compute address from index.
2642       bool firstIdxIsZero = IsZero(idxVec[0]);
2643       assert(idxVec.size() == 1U + firstIdxIsZero 
2644              && "Array refs must be lowered before Instruction Selection");
2645
2646       Value* idxVal = idxVec[firstIdxIsZero];
2647
2648       std::vector<MachineInstr*> mulVec;
2649       Instruction* addr =
2650         new TmpInstruction(MachineCodeForInstruction::get(memInst),
2651                            Type::ULongTy, memInst);
2652
2653       // Get the array type indexed by idxVal, and compute its element size.
2654       // The call to getTypeSize() will fail if size is not constant.
2655       const Type* vecType = (firstIdxIsZero
2656                              ? GetElementPtrInst::getIndexedType(ptrType,
2657                                            std::vector<Value*>(1U, idxVec[0]),
2658                                            /*AllowCompositeLeaf*/ true)
2659                                  : ptrType);
2660       const Type* eltType = cast<SequentialType>(vecType)->getElementType();
2661       ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
2662                                    target.getTargetData().getTypeSize(eltType));
2663
2664       // CreateMulInstruction() folds constants intelligently enough.
2665       CreateMulInstruction(target, memInst->getParent()->getParent(),
2666                            idxVal,         /* lval, not likely to be const*/
2667                            eltSizeVal,     /* rval, likely to be constant */
2668                            addr,           /* result */
2669                            mulVec, MachineCodeForInstruction::get(memInst),
2670                            -1);
2671
2672       assert(mulVec.size() > 0 && "No multiply code created?");
2673       mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
2674       
2675       valueForRegOffset = addr;
2676     }
2677   } else {
2678     offsetOpType = MachineOperand::MO_SignExtendedImmed;
2679     smallConstOffset = 0;
2680   }
2681
2682   // For STORE:
2683   //   Operand 0 is value, operand 1 is ptr, operand 2 is offset
2684   // For LOAD or GET_ELEMENT_PTR,
2685   //   Operand 0 is ptr, operand 1 is offset, operand 2 is result.
2686   unsigned offsetOpNum, ptrOpNum;
2687   MachineInstr *MI;
2688   if (memInst->getOpcode() == Instruction::Store) {
2689     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2690       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2691                              .addReg(ptrVal).addReg(valueForRegOffset);
2692     } else {
2693       Opcode = convertOpcodeFromRegToImm(Opcode);
2694       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2695                              .addReg(ptrVal).addSImm(smallConstOffset);
2696     }
2697   } else {
2698     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2699       MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
2700                              .addRegDef(memInst);
2701     } else {
2702       Opcode = convertOpcodeFromRegToImm(Opcode);
2703       MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
2704                              .addRegDef(memInst);
2705     }
2706   }
2707   mvec.push_back(MI);
2708 }
2709
2710 /// ForwardOperand - Substitute operand `operandNum' of the instruction in
2711 /// node `treeNode' in place of the use(s) of that instruction in node `parent'.
2712 /// Check both explicit and implicit operands!  Also make sure to skip over a
2713 /// parent who: (1) is a list node in the Burg tree, or (2) itself had its
2714 /// results forwarded to its parent.
2715 /// 
2716 static void ForwardOperand (InstructionNode *treeNode, InstrTreeNode *parent,
2717                             int operandNum) {
2718   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
2719   
2720   Instruction* unusedOp = treeNode->getInstruction();
2721   Value* fwdOp = unusedOp->getOperand(operandNum);
2722
2723   // The parent itself may be a list node, so find the real parent instruction
2724   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode) {
2725     parent = parent->parent();
2726     assert(parent && "ERROR: Non-instruction node has no parent in tree.");
2727   }
2728   InstructionNode* parentInstrNode = (InstructionNode*) parent;
2729   
2730   Instruction* userInstr = parentInstrNode->getInstruction();
2731   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
2732
2733   // The parent's mvec would be empty if it was itself forwarded.
2734   // Recursively call ForwardOperand in that case...
2735   //
2736   if (mvec.size() == 0) {
2737     assert(parent->parent() != NULL &&
2738            "Parent could not have been forwarded, yet has no instructions?");
2739     ForwardOperand(treeNode, parent->parent(), operandNum);
2740   } else {
2741     for (unsigned i=0, N=mvec.size(); i < N; i++) {
2742       MachineInstr* minstr = mvec[i];
2743       for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
2744         const MachineOperand& mop = minstr->getOperand(i);
2745         if (mop.getType() == MachineOperand::MO_VirtualRegister &&
2746             mop.getVRegValue() == unusedOp) {
2747           minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
2748                                        fwdOp);
2749         }
2750       }
2751           
2752       for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
2753         if (minstr->getImplicitRef(i) == unusedOp)
2754           minstr->setImplicitRef(i, fwdOp);
2755     }
2756   }
2757 }
2758
2759 /// AllUsesAreBranches - Returns true if all the uses of I are
2760 /// Branch instructions, false otherwise.
2761 /// 
2762 inline bool AllUsesAreBranches(const Instruction* I) {
2763   for (Value::use_const_iterator UI=I->use_begin(), UE=I->use_end();
2764        UI != UE; ++UI)
2765     if (! isa<TmpInstruction>(*UI)     // ignore tmp instructions here
2766         && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
2767       return false;
2768   return true;
2769 }
2770
2771 /// CodeGenIntrinsic - Generate code for any intrinsic that needs a special
2772 /// code sequence instead of a regular call.  If not that kind of intrinsic, do
2773 /// nothing. Returns true if code was generated, otherwise false.
2774 /// 
2775 static bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
2776                              TargetMachine &target,
2777                              std::vector<MachineInstr*>& mvec) {
2778   switch (iid) {
2779   default:
2780     assert(0 && "Unknown intrinsic function call should have been lowered!");
2781   case Intrinsic::vastart: {
2782     // Get the address of the first incoming vararg argument on the stack
2783     Function* func = cast<Function>(callInstr.getParent()->getParent());
2784     int numFixedArgs   = func->getFunctionType()->getNumParams();
2785     int fpReg          = SparcV9::i6;
2786     int firstVarArgOff = numFixedArgs * 8 + 
2787                          SparcV9FrameInfo::FirstIncomingArgOffsetFromFP;
2788     mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
2789                    addRegDef(&callInstr));
2790     return true;
2791   }
2792
2793   case Intrinsic::vaend:
2794     return true;                        // no-op on SparcV9
2795
2796   case Intrinsic::vacopy:
2797     // Simple copy of current va_list (arg1) to new va_list (result)
2798     mvec.push_back(BuildMI(V9::ORr, 3).
2799                    addMReg(target.getRegInfo()->getZeroRegNum()).
2800                    addReg(callInstr.getOperand(1)).
2801                    addRegDef(&callInstr));
2802     return true;
2803   }
2804 }
2805
2806 /// ThisIsAChainRule - returns true if the given  BURG rule is a chain rule.
2807 /// 
2808 extern bool ThisIsAChainRule(int eruleno) {
2809   switch(eruleno) {
2810     case 111:   // stmt:  reg
2811     case 123:
2812     case 124:
2813     case 125:
2814     case 126:
2815     case 127:
2816     case 128:
2817     case 129:
2818     case 130:
2819     case 131:
2820     case 132:
2821     case 133:
2822     case 155:
2823     case 221:
2824     case 222:
2825     case 241:
2826     case 242:
2827     case 243:
2828     case 244:
2829     case 245:
2830     case 321:
2831       return true; break;
2832
2833     default:
2834       return false; break;
2835     }
2836 }
2837
2838 /// GetInstructionsByRule - Choose machine instructions for the
2839 /// SPARC V9 according to the patterns chosen by the BURG-generated parser.
2840 /// This is where most of the work in the V9 instruction selector gets done.
2841 /// 
2842 void GetInstructionsByRule(InstructionNode* subtreeRoot, int ruleForNode,
2843                            short* nts, TargetMachine &target,
2844                            std::vector<MachineInstr*>& mvec) {
2845   bool checkCast = false;               // initialize here to use fall-through
2846   bool maskUnsignedResult = false;
2847   int nextRule;
2848   int forwardOperandNum = -1;
2849   unsigned allocaSize = 0;
2850   MachineInstr* M, *M2;
2851   unsigned L;
2852   bool foldCase = false;
2853
2854   mvec.clear(); 
2855   
2856   // If the code for this instruction was folded into the parent (user),
2857   // then do nothing!
2858   if (subtreeRoot->isFoldedIntoParent())
2859     return;
2860   
2861   // Let's check for chain rules outside the switch so that we don't have
2862   // to duplicate the list of chain rule production numbers here again
2863   if (ThisIsAChainRule(ruleForNode)) {
2864     // Chain rules have a single nonterminal on the RHS.
2865     // Get the rule that matches the RHS non-terminal and use that instead.
2866     assert(nts[0] && ! nts[1]
2867            && "A chain rule should have only one RHS non-terminal!");
2868     nextRule = burm_rule(subtreeRoot->state, nts[0]);
2869     nts = burm_nts[nextRule];
2870     GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
2871   } else {
2872     switch(ruleForNode) {
2873       case 1:   // stmt:   Ret
2874       case 2:   // stmt:   RetValue(reg)
2875       {         // NOTE: Prepass of register allocation is responsible
2876                 //       for moving return value to appropriate register.
2877                 // Copy the return value to the required return register.
2878                 // Mark the return Value as an implicit ref of the RET instr..
2879                 // Mark the return-address register as a hidden virtual reg.
2880                 // Finally put a NOP in the delay slot.
2881         ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
2882         Value* retVal = returnInstr->getReturnValue();
2883         MachineCodeForInstruction& mcfi =
2884           MachineCodeForInstruction::get(returnInstr);
2885
2886         // Create a hidden virtual reg to represent the return address register
2887         // used by the machine instruction but not represented in LLVM.
2888         Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
2889
2890         MachineInstr* retMI = 
2891           BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
2892           .addMReg(target.getRegInfo()->getZeroRegNum(), MachineOperand::Def);
2893       
2894         // If there is a value to return, we need to:
2895         // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
2896         // (b) Insert a copy to copy the return value to the appropriate reg.
2897         //     -- For FP values, create a FMOVS or FMOVD instruction
2898         //     -- For non-FP values, create an add-with-0 instruction
2899         if (retVal != NULL) {
2900           const SparcV9RegInfo& regInfo =
2901             (SparcV9RegInfo&) *target.getRegInfo();
2902           const Type* retType = retVal->getType();
2903           unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2904           unsigned retRegNum = (retType->isFloatingPoint()
2905                                 ? (unsigned) SparcV9FloatRegClass::f0
2906                                 : (unsigned) SparcV9IntRegClass::i0);
2907           retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
2908
2909           // Insert sign-extension instructions for small signed values.
2910           Value* retValToUse = retVal;
2911           if (retType->isIntegral() && retType->isSigned()) {
2912             unsigned retSize = target.getTargetData().getTypeSize(retType);
2913             if (retSize <= 4) {
2914               // Create a temporary virtual reg. to hold the sign-extension.
2915               retValToUse = new TmpInstruction(mcfi, retVal);
2916
2917               // Sign-extend retVal and put the result in the temporary reg.
2918               CreateSignExtensionInstructions
2919                 (target, returnInstr->getParent()->getParent(),
2920                  retVal, retValToUse, 8*retSize, mvec, mcfi);
2921             }
2922           }
2923
2924           // (b) Now, insert a copy to to the appropriate register:
2925           //     -- For FP values, create a FMOVS or FMOVD instruction
2926           //     -- For non-FP values, create an add-with-0 instruction
2927           // First, create a virtual register to represent the register and
2928           // mark this vreg as being an implicit operand of the ret MI.
2929           TmpInstruction* retVReg = 
2930             new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
2931           
2932           retMI->addImplicitRef(retVReg);
2933           
2934           if (retType->isFloatingPoint())
2935             M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2936                  .addReg(retValToUse).addReg(retVReg, MachineOperand::Def));
2937           else
2938             M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2939                  .addReg(retValToUse).addSImm((int64_t) 0)
2940                  .addReg(retVReg, MachineOperand::Def));
2941
2942           // Mark the operand with the register it should be assigned
2943           M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
2944           retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
2945
2946           mvec.push_back(M);
2947         }
2948         
2949         // Now insert the RET instruction and a NOP for the delay slot
2950         mvec.push_back(retMI);
2951         mvec.push_back(BuildMI(V9::NOP, 0));
2952         
2953         break;
2954       }  
2955         
2956       case 3:   // stmt:   Store(reg,reg)
2957       case 4:   // stmt:   Store(reg,ptrreg)
2958         SetOperandsForMemInstr(ChooseStoreInstruction(
2959                         subtreeRoot->leftChild()->getValue()->getType()),
2960                                mvec, subtreeRoot, target);
2961         break;
2962
2963       case 5:   // stmt:   BrUncond
2964         {
2965           BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
2966           mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
2967         
2968           // delay slot
2969           mvec.push_back(BuildMI(V9::NOP, 0));
2970           break;
2971         }
2972
2973       case 206: // stmt:   BrCond(setCCconst)
2974       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
2975         // If the constant is ZERO, we can use the branch-on-integer-register
2976         // instructions and avoid the SUBcc instruction entirely.
2977         // Otherwise this is just the same as case 5, so just fall through.
2978         // 
2979         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
2980         assert(constNode &&
2981                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2982         Constant *constVal = cast<Constant>(constNode->getValue());
2983         bool isValidConst;
2984         
2985         if ((constVal->getType()->isInteger()
2986              || isa<PointerType>(constVal->getType()))
2987             && ConvertConstantToIntType(target,
2988                              constVal, constVal->getType(), isValidConst) == 0
2989             && isValidConst)
2990           {
2991             // That constant is a zero after all...
2992             // Use the left child of setCC as the first argument!
2993             // Mark the setCC node so that no code is generated for it.
2994             InstructionNode* setCCNode = (InstructionNode*)
2995                                          subtreeRoot->leftChild();
2996             assert(setCCNode->getOpLabel() == SetCCOp);
2997             setCCNode->markFoldedIntoParent();
2998             
2999             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
3000             
3001             M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
3002                                 .addReg(setCCNode->leftChild()->getValue())
3003                                 .addPCDisp(brInst->getSuccessor(0));
3004             mvec.push_back(M);
3005             
3006             // delay slot
3007             mvec.push_back(BuildMI(V9::NOP, 0));
3008
3009             // false branch
3010             mvec.push_back(BuildMI(V9::BA, 1)
3011                            .addPCDisp(brInst->getSuccessor(1)));
3012             
3013             // delay slot
3014             mvec.push_back(BuildMI(V9::NOP, 0));
3015             break;
3016           }
3017         // ELSE FALL THROUGH
3018       }
3019
3020       case 6:   // stmt:   BrCond(setCC)
3021       { // bool => boolean was computed with SetCC.
3022         // The branch to use depends on whether it is FP, signed, or unsigned.
3023         // If it is an integer CC, we also need to find the unique
3024         // TmpInstruction representing that CC.
3025         // 
3026         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
3027         const Type* setCCType;
3028         unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
3029         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
3030                                      brInst->getParent()->getParent(),
3031                                      setCCType,
3032                                      MachineCodeForInstruction::get(brInst));
3033         M = BuildMI(Opcode, 2).addCCReg(ccValue)
3034                               .addPCDisp(brInst->getSuccessor(0));
3035         mvec.push_back(M);
3036
3037         // delay slot
3038         mvec.push_back(BuildMI(V9::NOP, 0));
3039
3040         // false branch
3041         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
3042
3043         // delay slot
3044         mvec.push_back(BuildMI(V9::NOP, 0));
3045         break;
3046       }
3047         
3048       case 208: // stmt:   BrCond(boolconst)
3049       {
3050         // boolconst => boolean is a constant; use BA to first or second label
3051         Constant* constVal = 
3052           cast<Constant>(subtreeRoot->leftChild()->getValue());
3053         unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
3054         
3055         M = BuildMI(V9::BA, 1).addPCDisp(
3056           cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
3057         mvec.push_back(M);
3058         
3059         // delay slot
3060         mvec.push_back(BuildMI(V9::NOP, 0));
3061         break;
3062       }
3063         
3064       case   8: // stmt:   BrCond(boolreg)
3065       { // boolreg   => boolean is recorded in an integer register.
3066         //              Use branch-on-integer-register instruction.
3067         // 
3068         BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3069         M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
3070           .addPCDisp(BI->getSuccessor(0));
3071         mvec.push_back(M);
3072
3073         // delay slot
3074         mvec.push_back(BuildMI(V9::NOP, 0));
3075
3076         // false branch
3077         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
3078         
3079         // delay slot
3080         mvec.push_back(BuildMI(V9::NOP, 0));
3081         break;
3082       }  
3083       
3084       case 9:   // stmt:   Switch(reg)
3085         assert(0 && "*** SWITCH instruction is not implemented yet.");
3086         break;
3087
3088       case 10:  // reg:   VRegList(reg, reg)
3089         assert(0 && "VRegList should never be the topmost non-chain rule");
3090         break;
3091
3092       case 21:  // bool:  Not(bool,reg): Compute with a conditional-move-on-reg
3093       { // First find the unary operand. It may be left or right, usually right.
3094         Instruction* notI = subtreeRoot->getInstruction();
3095         Value* notArg = BinaryOperator::getNotArgument(
3096                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
3097         unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3098
3099         // Unconditionally set register to 0
3100         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
3101
3102         // Now conditionally move 1 into the register.
3103         // Mark the register as a use (as well as a def) because the old
3104         // value will be retained if the condition is false.
3105         mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
3106                        .addReg(notI, MachineOperand::UseAndDef));
3107
3108         break;
3109       }
3110
3111       case 421: // reg:   BNot(reg,reg): Compute as reg = reg XOR-NOT 0
3112       { // First find the unary operand. It may be left or right, usually right.
3113         Value* notArg = BinaryOperator::getNotArgument(
3114                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
3115         unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3116         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
3117                                        .addRegDef(subtreeRoot->getValue()));
3118         break;
3119       }
3120
3121       case 322: // reg:   Not(tobool, reg):
3122         // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
3123         foldCase = true;
3124         // Just fall through!
3125
3126       case 22:  // reg:   ToBoolTy(reg):
3127       {
3128         Instruction* castI = subtreeRoot->getInstruction();
3129         Value* opVal = subtreeRoot->leftChild()->getValue();
3130         assert(opVal->getType()->isIntegral() ||
3131                isa<PointerType>(opVal->getType()));
3132
3133         // Unconditionally set register to 0
3134         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
3135
3136         // Now conditionally move 1 into the register.
3137         // Mark the register as a use (as well as a def) because the old
3138         // value will be retained if the condition is false.
3139         MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
3140         mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
3141                        .addReg(castI, MachineOperand::UseAndDef));
3142
3143         break;
3144       }
3145       
3146       case 23:  // reg:   ToUByteTy(reg)
3147       case 24:  // reg:   ToSByteTy(reg)
3148       case 25:  // reg:   ToUShortTy(reg)
3149       case 26:  // reg:   ToShortTy(reg)
3150       case 27:  // reg:   ToUIntTy(reg)
3151       case 28:  // reg:   ToIntTy(reg)
3152       case 29:  // reg:   ToULongTy(reg)
3153       case 30:  // reg:   ToLongTy(reg)
3154       {
3155         //======================================================================
3156         // Rules for integer conversions:
3157         // 
3158         //--------
3159         // From ISO 1998 C++ Standard, Sec. 4.7:
3160         //
3161         // 2. If the destination type is unsigned, the resulting value is
3162         // the least unsigned integer congruent to the source integer
3163         // (modulo 2n where n is the number of bits used to represent the
3164         // unsigned type). [Note: In a two s complement representation,
3165         // this conversion is conceptual and there is no change in the
3166         // bit pattern (if there is no truncation). ]
3167         // 
3168         // 3. If the destination type is signed, the value is unchanged if
3169         // it can be represented in the destination type (and bitfield width);
3170         // otherwise, the value is implementation-defined.
3171         //--------
3172         // 
3173         // Since we assume 2s complement representations, this implies:
3174         // 
3175         // -- If operand is smaller than destination, zero-extend or sign-extend
3176         //    according to the signedness of the *operand*: source decides:
3177         //    (1) If operand is signed, sign-extend it.
3178         //        If dest is unsigned, zero-ext the result!
3179         //    (2) If operand is unsigned, our current invariant is that
3180         //        it's high bits are correct, so zero-extension is not needed.
3181         // 
3182         // -- If operand is same size as or larger than destination,
3183         //    zero-extend or sign-extend according to the signedness of
3184         //    the *destination*: destination decides:
3185         //    (1) If destination is signed, sign-extend (truncating if needed)
3186         //        This choice is implementation defined.  We sign-extend the
3187         //        operand, which matches both Sun's cc and gcc3.2.
3188         //    (2) If destination is unsigned, zero-extend (truncating if needed)
3189         //======================================================================
3190
3191         Instruction* destI =  subtreeRoot->getInstruction();
3192         Function* currentFunc = destI->getParent()->getParent();
3193         MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
3194
3195         Value* opVal = subtreeRoot->leftChild()->getValue();
3196         const Type* opType = opVal->getType();
3197         const Type* destType = destI->getType();
3198         unsigned opSize   = target.getTargetData().getTypeSize(opType);
3199         unsigned destSize = target.getTargetData().getTypeSize(destType);
3200         
3201         bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
3202
3203         if (opType == Type::BoolTy ||
3204             opType == destType ||
3205             isIntegral && opSize == destSize && opSize == 8) {
3206           // nothing to do in all these cases
3207           forwardOperandNum = 0;          // forward first operand to user
3208
3209         } else if (opType->isFloatingPoint()) {
3210
3211           CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
3212           if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
3213             maskUnsignedResult = true; // not handled by fp->int code
3214
3215         } else if (isIntegral) {
3216
3217           bool opSigned     = opType->isSigned();
3218           bool destSigned   = destType->isSigned();
3219           unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
3220
3221           assert(! (opSize == destSize && opSigned == destSigned) &&
3222                  "How can different int types have same size and signedness?");
3223
3224           bool signExtend = (opSize <  destSize && opSigned ||
3225                              opSize >= destSize && destSigned);
3226
3227           bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
3228                                     opSigned && !destSigned);
3229           assert(!signAndZeroExtend || signExtend);
3230
3231           bool zeroExtendOnly = opSize >= destSize && !destSigned;
3232           assert(!zeroExtendOnly || !signExtend);
3233
3234           if (signExtend) {
3235             Value* signExtDest = (signAndZeroExtend
3236                                   ? new TmpInstruction(mcfi, destType, opVal)
3237                                   : destI);
3238
3239             CreateSignExtensionInstructions
3240               (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
3241
3242             if (signAndZeroExtend)
3243               CreateZeroExtensionInstructions
3244               (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
3245           }
3246           else if (zeroExtendOnly) {
3247             CreateZeroExtensionInstructions
3248               (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
3249           }
3250           else
3251             forwardOperandNum = 0;          // forward first operand to user
3252
3253         } else
3254           assert(0 && "Unrecognized operand type for convert-to-integer");
3255
3256         break;
3257       }
3258       
3259       case  31: // reg:   ToFloatTy(reg):
3260       case  32: // reg:   ToDoubleTy(reg):
3261       case 232: // reg:   ToDoubleTy(Constant):
3262       
3263         // If this instruction has a parent (a user) in the tree 
3264         // and the user is translated as an FsMULd instruction,
3265         // then the cast is unnecessary.  So check that first.
3266         // In the future, we'll want to do the same for the FdMULq instruction,
3267         // so do the check here instead of only for ToFloatTy(reg).
3268         // 
3269         if (subtreeRoot->parent() != NULL) {
3270           const MachineCodeForInstruction& mcfi =
3271             MachineCodeForInstruction::get(
3272                 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
3273           if (mcfi.size() == 0 || mcfi.front()->getOpcode() == V9::FSMULD)
3274             forwardOperandNum = 0;    // forward first operand to user
3275         }
3276
3277         if (forwardOperandNum != 0) {    // we do need the cast
3278           Value* leftVal = subtreeRoot->leftChild()->getValue();
3279           const Type* opType = leftVal->getType();
3280           MachineOpCode opCode=ChooseConvertToFloatInstr(target,
3281                                        subtreeRoot->getOpLabel(), opType);
3282           if (opCode == V9::NOP) {      // no conversion needed
3283             forwardOperandNum = 0;      // forward first operand to user
3284           } else {
3285             // If the source operand is a non-FP type it must be
3286             // first copied from int to float register via memory!
3287             Instruction *dest = subtreeRoot->getInstruction();
3288             Value* srcForCast;
3289             int n = 0;
3290             if (! opType->isFloatingPoint()) {
3291               // Create a temporary to represent the FP register
3292               // into which the integer will be copied via memory.
3293               // The type of this temporary will determine the FP
3294               // register used: single-prec for a 32-bit int or smaller,
3295               // double-prec for a 64-bit int.
3296               // 
3297               uint64_t srcSize =
3298                 target.getTargetData().getTypeSize(leftVal->getType());
3299               Type* tmpTypeToUse =
3300                 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
3301               MachineCodeForInstruction &destMCFI = 
3302                 MachineCodeForInstruction::get(dest);
3303               srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
3304
3305               CreateCodeToCopyIntToFloat(target,
3306                          dest->getParent()->getParent(),
3307                          leftVal, cast<Instruction>(srcForCast),
3308                          mvec, destMCFI);
3309             } else
3310               srcForCast = leftVal;
3311
3312             M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
3313             mvec.push_back(M);
3314           }
3315         }
3316         break;
3317
3318       case 19:  // reg:   ToArrayTy(reg):
3319       case 20:  // reg:   ToPointerTy(reg):
3320         forwardOperandNum = 0;          // forward first operand to user
3321         break;
3322
3323       case 233: // reg:   Add(reg, Constant)
3324         maskUnsignedResult = true;
3325         M = CreateAddConstInstruction(subtreeRoot);
3326         if (M != NULL) {
3327           mvec.push_back(M);
3328           break;
3329         }
3330         // ELSE FALL THROUGH
3331         
3332       case 33:  // reg:   Add(reg, reg)
3333         maskUnsignedResult = true;
3334         Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
3335         break;
3336
3337       case 234: // reg:   Sub(reg, Constant)
3338         maskUnsignedResult = true;
3339         M = CreateSubConstInstruction(subtreeRoot);
3340         if (M != NULL) {
3341           mvec.push_back(M);
3342           break;
3343         }
3344         // ELSE FALL THROUGH
3345         
3346       case 34:  // reg:   Sub(reg, reg)
3347         maskUnsignedResult = true;
3348         Add3OperandInstr(ChooseSubInstructionByType(
3349                                    subtreeRoot->getInstruction()->getType()),
3350                          subtreeRoot, mvec);
3351         break;
3352
3353       case 135: // reg:   Mul(todouble, todouble)
3354         checkCast = true;
3355         // FALL THROUGH 
3356
3357       case 35:  // reg:   Mul(reg, reg)
3358       {
3359         maskUnsignedResult = true;
3360         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3361                                  ? (MachineOpCode)V9::FSMULD
3362                                  : -1);
3363         Instruction* mulInstr = subtreeRoot->getInstruction();
3364         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3365                              subtreeRoot->leftChild()->getValue(),
3366                              subtreeRoot->rightChild()->getValue(),
3367                              mulInstr, mvec,
3368                              MachineCodeForInstruction::get(mulInstr),forceOp);
3369         break;
3370       }
3371       case 335: // reg:   Mul(todouble, todoubleConst)
3372         checkCast = true;
3373         // FALL THROUGH 
3374
3375       case 235: // reg:   Mul(reg, Constant)
3376       {
3377         maskUnsignedResult = true;
3378         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3379                                  ? (MachineOpCode)V9::FSMULD
3380                                  : -1);
3381         Instruction* mulInstr = subtreeRoot->getInstruction();
3382         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3383                              subtreeRoot->leftChild()->getValue(),
3384                              subtreeRoot->rightChild()->getValue(),
3385                              mulInstr, mvec,
3386                              MachineCodeForInstruction::get(mulInstr),
3387                              forceOp);
3388         break;
3389       }
3390       case 236: // reg:   Div(reg, Constant)
3391         maskUnsignedResult = true;
3392         L = mvec.size();
3393         CreateDivConstInstruction(target, subtreeRoot, mvec);
3394         if (mvec.size() > L)
3395           break;
3396         // ELSE FALL THROUGH
3397       
3398       case 36:  // reg:   Div(reg, reg)
3399       {
3400         maskUnsignedResult = true;
3401
3402         // If either operand of divide is smaller than 64 bits, we have
3403         // to make sure the unused top bits are correct because they affect
3404         // the result.  These bits are already correct for unsigned values.
3405         // They may be incorrect for signed values, so sign extend to fill in.
3406         Instruction* divI = subtreeRoot->getInstruction();
3407         Value* divOp1 = subtreeRoot->leftChild()->getValue();
3408         Value* divOp2 = subtreeRoot->rightChild()->getValue();
3409         Value* divOp1ToUse = divOp1;
3410         Value* divOp2ToUse = divOp2;
3411         if (divI->getType()->isSigned()) {
3412           unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
3413           if (opSize < 8) {
3414             MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
3415             divOp1ToUse = new TmpInstruction(mcfi, divOp1);
3416             divOp2ToUse = new TmpInstruction(mcfi, divOp2);
3417             CreateSignExtensionInstructions(target,
3418                                               divI->getParent()->getParent(),
3419                                               divOp1, divOp1ToUse,
3420                                               8*opSize, mvec, mcfi);
3421             CreateSignExtensionInstructions(target,
3422                                               divI->getParent()->getParent(),
3423                                               divOp2, divOp2ToUse,
3424                                               8*opSize, mvec, mcfi);
3425           }
3426         }
3427
3428         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3429                        .addReg(divOp1ToUse)
3430                        .addReg(divOp2ToUse)
3431                        .addRegDef(divI));
3432
3433         break;
3434       }
3435
3436       case  37: // reg:   Rem(reg, reg)
3437       case 237: // reg:   Rem(reg, Constant)
3438       {
3439         maskUnsignedResult = true;
3440
3441         Instruction* remI   = subtreeRoot->getInstruction();
3442         Value* divOp1 = subtreeRoot->leftChild()->getValue();
3443         Value* divOp2 = subtreeRoot->rightChild()->getValue();
3444
3445         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
3446         
3447         // If second operand of divide is smaller than 64 bits, we have
3448         // to make sure the unused top bits are correct because they affect
3449         // the result.  These bits are already correct for unsigned values.
3450         // They may be incorrect for signed values, so sign extend to fill in.
3451         // 
3452         Value* divOpToUse = divOp2;
3453         if (divOp2->getType()->isSigned()) {
3454           unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
3455           if (opSize < 8) {
3456             divOpToUse = new TmpInstruction(mcfi, divOp2);
3457             CreateSignExtensionInstructions(target,
3458                                               remI->getParent()->getParent(),
3459                                               divOp2, divOpToUse,
3460                                               8*opSize, mvec, mcfi);
3461           }
3462         }
3463
3464         // Now compute: result = rem V1, V2 as:
3465         //      result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
3466         // 
3467         TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
3468         TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
3469
3470         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3471                        .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
3472         
3473         mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
3474                        .addReg(quot).addReg(divOpToUse).addRegDef(prod));
3475         
3476         mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
3477                        .addReg(divOp1).addReg(prod).addRegDef(remI));
3478         
3479         break;
3480       }
3481       
3482       case  38: // bool:   And(bool, bool)
3483       case 138: // bool:   And(bool, not)
3484       case 238: // bool:   And(bool, boolconst)
3485       case 338: // reg :   BAnd(reg, reg)
3486       case 538: // reg :   BAnd(reg, Constant)
3487         Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
3488         break;
3489
3490       case 438: // bool:   BAnd(bool, bnot)
3491       { // Use the argument of NOT as the second argument!
3492         // Mark the NOT node so that no code is generated for it.
3493         // If the type is boolean, set 1 or 0 in the result register.
3494         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3495         Value* notArg = BinaryOperator::getNotArgument(
3496                            cast<BinaryOperator>(notNode->getInstruction()));
3497         notNode->markFoldedIntoParent();
3498         Value *lhs = subtreeRoot->leftChild()->getValue();
3499         Value *dest = subtreeRoot->getValue();
3500         mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
3501                                        .addReg(dest, MachineOperand::Def));
3502
3503         if (notArg->getType() == Type::BoolTy) {
3504           // set 1 in result register if result of above is non-zero
3505           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3506                          .addReg(dest, MachineOperand::UseAndDef));
3507         }
3508
3509         break;
3510       }
3511
3512       case  39: // bool:   Or(bool, bool)
3513       case 139: // bool:   Or(bool, not)
3514       case 239: // bool:   Or(bool, boolconst)
3515       case 339: // reg :   BOr(reg, reg)
3516       case 539: // reg :   BOr(reg, Constant)
3517         Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
3518         break;
3519
3520       case 439: // bool:   BOr(bool, bnot)
3521       { // Use the argument of NOT as the second argument!
3522         // Mark the NOT node so that no code is generated for it.
3523         // If the type is boolean, set 1 or 0 in the result register.
3524         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3525         Value* notArg = BinaryOperator::getNotArgument(
3526                            cast<BinaryOperator>(notNode->getInstruction()));
3527         notNode->markFoldedIntoParent();
3528         Value *lhs = subtreeRoot->leftChild()->getValue();
3529         Value *dest = subtreeRoot->getValue();
3530
3531         mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
3532                        .addReg(dest, MachineOperand::Def));
3533
3534         if (notArg->getType() == Type::BoolTy) {
3535           // set 1 in result register if result of above is non-zero
3536           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3537                          .addReg(dest, MachineOperand::UseAndDef));
3538         }
3539
3540         break;
3541       }
3542
3543       case  40: // bool:   Xor(bool, bool)
3544       case 140: // bool:   Xor(bool, not)
3545       case 240: // bool:   Xor(bool, boolconst)
3546       case 340: // reg :   BXor(reg, reg)
3547       case 540: // reg :   BXor(reg, Constant)
3548         Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
3549         break;
3550
3551       case 440: // bool:   BXor(bool, bnot)
3552       { // Use the argument of NOT as the second argument!
3553         // Mark the NOT node so that no code is generated for it.
3554         // If the type is boolean, set 1 or 0 in the result register.
3555         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3556         Value* notArg = BinaryOperator::getNotArgument(
3557                            cast<BinaryOperator>(notNode->getInstruction()));
3558         notNode->markFoldedIntoParent();
3559         Value *lhs = subtreeRoot->leftChild()->getValue();
3560         Value *dest = subtreeRoot->getValue();
3561         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
3562                        .addReg(dest, MachineOperand::Def));
3563
3564         if (notArg->getType() == Type::BoolTy) {
3565           // set 1 in result register if result of above is non-zero
3566           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3567                          .addReg(dest, MachineOperand::UseAndDef));
3568         }
3569         break;
3570       }
3571
3572       case 41:  // setCCconst:   SetCC(reg, Constant)
3573       { // Comparison is with a constant:
3574         // 
3575         // If the bool result must be computed into a register (see below),
3576         // and the constant is int ZERO, we can use the MOVR[op] instructions
3577         // and avoid the SUBcc instruction entirely.
3578         // Otherwise this is just the same as case 42, so just fall through.
3579         // 
3580         // The result of the SetCC must be computed and stored in a register if
3581         // it is used outside the current basic block (so it must be computed
3582         // as a boolreg) or it is used by anything other than a branch.
3583         // We will use a conditional move to do this.
3584         // 
3585         Instruction* setCCInstr = subtreeRoot->getInstruction();
3586         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3587                                ! AllUsesAreBranches(setCCInstr));
3588
3589         if (computeBoolVal) {
3590           InstrTreeNode* constNode = subtreeRoot->rightChild();
3591           assert(constNode &&
3592                  constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3593           Constant *constVal = cast<Constant>(constNode->getValue());
3594           bool isValidConst;
3595           
3596           if ((constVal->getType()->isInteger()
3597                || isa<PointerType>(constVal->getType()))
3598               && ConvertConstantToIntType(target,
3599                              constVal, constVal->getType(), isValidConst) == 0
3600               && isValidConst)
3601           {
3602             // That constant is an integer zero after all...
3603             // Use a MOVR[op] to compute the boolean result
3604             // Unconditionally set register to 0
3605             mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
3606                            .addRegDef(setCCInstr));
3607                 
3608             // Now conditionally move 1 into the register.
3609             // Mark the register as a use (as well as a def) because the old
3610             // value will be retained if the condition is false.
3611             MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
3612             mvec.push_back(BuildMI(movOpCode, 3)
3613                            .addReg(subtreeRoot->leftChild()->getValue())
3614                            .addZImm(1)
3615                            .addReg(setCCInstr, MachineOperand::UseAndDef));
3616                 
3617             break;
3618           }
3619         }
3620         // ELSE FALL THROUGH
3621       }
3622
3623       case 42:  // bool:   SetCC(reg, reg):
3624       {
3625         // This generates a SUBCC instruction, putting the difference in a
3626         // result reg. if needed, and/or setting a condition code if needed.
3627         // 
3628         Instruction* setCCInstr = subtreeRoot->getInstruction();
3629         Value* leftVal  = subtreeRoot->leftChild()->getValue();
3630         Value* rightVal = subtreeRoot->rightChild()->getValue();
3631         const Type* opType = leftVal->getType();
3632         bool isFPCompare = opType->isFloatingPoint();
3633         
3634         // If the boolean result of the SetCC is used outside the current basic
3635         // block (so it must be computed as a boolreg) or is used by anything
3636         // other than a branch, the boolean must be computed and stored
3637         // in a result register.  We will use a conditional move to do this.
3638         // 
3639         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3640                                ! AllUsesAreBranches(setCCInstr));
3641         
3642         // A TmpInstruction is created to represent the CC "result".
3643         // Unlike other instances of TmpInstruction, this one is used
3644         // by machine code of multiple LLVM instructions, viz.,
3645         // the SetCC and the branch.  Make sure to get the same one!
3646         // Note that we do this even for FP CC registers even though they
3647         // are explicit operands, because the type of the operand
3648         // needs to be a floating point condition code, not an integer
3649         // condition code.  Think of this as casting the bool result to
3650         // a FP condition code register.
3651         // Later, we mark the 4th operand as being a CC register, and as a def.
3652         // 
3653         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
3654                                     setCCInstr->getParent()->getParent(),
3655                                     leftVal->getType(),
3656                                     MachineCodeForInstruction::get(setCCInstr));
3657
3658         // If the operands are signed values smaller than 4 bytes, then they
3659         // must be sign-extended in order to do a valid 32-bit comparison
3660         // and get the right result in the 32-bit CC register (%icc).
3661         // 
3662         Value* leftOpToUse  = leftVal;
3663         Value* rightOpToUse = rightVal;
3664         if (opType->isIntegral() && opType->isSigned()) {
3665           unsigned opSize = target.getTargetData().getTypeSize(opType);
3666           if (opSize < 4) {
3667             MachineCodeForInstruction& mcfi =
3668               MachineCodeForInstruction::get(setCCInstr); 
3669
3670             // create temporary virtual regs. to hold the sign-extensions
3671             leftOpToUse  = new TmpInstruction(mcfi, leftVal);
3672             rightOpToUse = new TmpInstruction(mcfi, rightVal);
3673             
3674             // sign-extend each operand and put the result in the temporary reg.
3675             CreateSignExtensionInstructions
3676               (target, setCCInstr->getParent()->getParent(),
3677                leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
3678             CreateSignExtensionInstructions
3679               (target, setCCInstr->getParent()->getParent(),
3680                rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
3681           }
3682         }
3683
3684         if (! isFPCompare) {
3685           // Integer condition: set CC and discard result.
3686           mvec.push_back(BuildMI(V9::SUBccr, 4)
3687                          .addReg(leftOpToUse)
3688                          .addReg(rightOpToUse)
3689                          .addMReg(target.getRegInfo()->
3690                                    getZeroRegNum(), MachineOperand::Def)
3691                          .addCCReg(tmpForCC, MachineOperand::Def));
3692         } else {
3693           // FP condition: dest of FCMP should be some FCCn register
3694           mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
3695                          .addCCReg(tmpForCC, MachineOperand::Def)
3696                          .addReg(leftOpToUse)
3697                          .addReg(rightOpToUse));
3698         }
3699         
3700         if (computeBoolVal) {
3701           MachineOpCode movOpCode = (isFPCompare
3702                                      ? ChooseMovFpcciInstruction(subtreeRoot)
3703                                      : ChooseMovpcciForSetCC(subtreeRoot));
3704
3705           // Unconditionally set register to 0
3706           M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
3707           mvec.push_back(M);
3708           
3709           // Now conditionally move 1 into the register.
3710           // Mark the register as a use (as well as a def) because the old
3711           // value will be retained if the condition is false.
3712           M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
3713                .addReg(setCCInstr, MachineOperand::UseAndDef));
3714           mvec.push_back(M);
3715         }
3716         break;
3717       }    
3718       
3719       case 51:  // reg:   Load(reg)
3720       case 52:  // reg:   Load(ptrreg)
3721         SetOperandsForMemInstr(ChooseLoadInstruction(
3722                                    subtreeRoot->getValue()->getType()),
3723                                mvec, subtreeRoot, target);
3724         break;
3725
3726       case 55:  // reg:   GetElemPtr(reg)
3727       case 56:  // reg:   GetElemPtrIdx(reg,reg)
3728         // If the GetElemPtr was folded into the user (parent), it will be
3729         // caught above.  For other cases, we have to compute the address.
3730         SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
3731         break;
3732
3733       case 57:  // reg:  Alloca: Implement as 1 instruction:
3734       {         //          add %fp, offsetFromFP -> result
3735         AllocationInst* instr =
3736           cast<AllocationInst>(subtreeRoot->getInstruction());
3737         unsigned tsize =
3738           target.getTargetData().getTypeSize(instr->getAllocatedType());
3739         assert(tsize != 0);
3740         CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
3741         break;
3742       }
3743
3744       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
3745                 //      mul num, typeSz -> tmp
3746                 //      sub %sp, tmp    -> %sp
3747       {         //      add %sp, frameSizeBelowDynamicArea -> result
3748         AllocationInst* instr =
3749           cast<AllocationInst>(subtreeRoot->getInstruction());
3750         const Type* eltType = instr->getAllocatedType();
3751         
3752         // If #elements is constant, use simpler code for fixed-size allocas
3753         int tsize = (int) target.getTargetData().getTypeSize(eltType);
3754         Value* numElementsVal = NULL;
3755         bool isArray = instr->isArrayAllocation();
3756         
3757         if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
3758           // total size is constant: generate code for fixed-size alloca
3759           unsigned numElements = isArray? 
3760             cast<ConstantUInt>(numElementsVal)->getValue() : 1;
3761           CreateCodeForFixedSizeAlloca(target, instr, tsize,
3762                                        numElements, mvec);
3763         } else {
3764           // total size is not constant.
3765           CreateCodeForVariableSizeAlloca(target, instr, tsize,
3766                                           numElementsVal, mvec);
3767         }
3768         break;
3769       }
3770
3771       case 61:  // reg:   Call
3772       {         // Generate a direct (CALL) or indirect (JMPL) call.
3773                 // Mark the return-address register, the indirection
3774                 // register (for indirect calls), the operands of the Call,
3775                 // and the return value (if any) as implicit operands
3776                 // of the machine instruction.
3777                 // 
3778                 // If this is a varargs function, floating point arguments
3779                 // have to passed in integer registers so insert
3780                 // copy-float-to-int instructions for each float operand.
3781                 // 
3782         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
3783         Value *callee = callInstr->getCalledValue();
3784         Function* calledFunc = dyn_cast<Function>(callee);
3785
3786         // Check if this is an intrinsic function that needs a special code
3787         // sequence (e.g., va_start).  Indirect calls cannot be special.
3788         // 
3789         bool specialIntrinsic = false;
3790         Intrinsic::ID iid;
3791         if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
3792           specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
3793
3794         // If not, generate the normal call sequence for the function.
3795         // This can also handle any intrinsics that are just function calls.
3796         // 
3797         if (! specialIntrinsic) {
3798           Function* currentFunc = callInstr->getParent()->getParent();
3799           MachineFunction& MF = MachineFunction::get(currentFunc);
3800           MachineCodeForInstruction& mcfi =
3801             MachineCodeForInstruction::get(callInstr); 
3802           const SparcV9RegInfo& regInfo =
3803             (SparcV9RegInfo&) *target.getRegInfo();
3804           const TargetFrameInfo& frameInfo = *target.getFrameInfo();
3805
3806           // Create hidden virtual register for return address with type void*
3807           TmpInstruction* retAddrReg =
3808             new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
3809
3810           // Generate the machine instruction and its operands.
3811           // Use CALL for direct function calls; this optimistically assumes
3812           // the PC-relative address fits in the CALL address field (22 bits).
3813           // Use JMPL for indirect calls.
3814           // This will be added to mvec later, after operand copies.
3815           // 
3816           MachineInstr* callMI;
3817           if (calledFunc)             // direct function call
3818             callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
3819           else                        // indirect function call
3820             callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
3821                       .addSImm((int64_t)0).addRegDef(retAddrReg));
3822
3823           const FunctionType* funcType =
3824             cast<FunctionType>(cast<PointerType>(callee->getType())
3825                                ->getElementType());
3826           bool isVarArgs = funcType->isVarArg();
3827           bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
3828         
3829           // Use a descriptor to pass information about call arguments
3830           // to the register allocator.  This descriptor will be "owned"
3831           // and freed automatically when the MachineCodeForInstruction
3832           // object for the callInstr goes away.
3833           CallArgsDescriptor* argDesc =
3834             new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
3835           assert(callInstr->getOperand(0) == callee
3836                  && "This is assumed in the loop below!");
3837
3838           // Insert sign-extension instructions for small signed values,
3839           // if this is an unknown function (i.e., called via a funcptr)
3840           // or an external one (i.e., which may not be compiled by llc).
3841           // 
3842           if (calledFunc == NULL || calledFunc->isExternal()) {
3843             for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3844               Value* argVal = callInstr->getOperand(i);
3845               const Type* argType = argVal->getType();
3846               if (argType->isIntegral() && argType->isSigned()) {
3847                 unsigned argSize = target.getTargetData().getTypeSize(argType);
3848                 if (argSize <= 4) {
3849                   // create a temporary virtual reg. to hold the sign-extension
3850                   TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
3851
3852                   // sign-extend argVal and put the result in the temporary reg.
3853                   CreateSignExtensionInstructions
3854                     (target, currentFunc, argVal, argExtend,
3855                      8*argSize, mvec, mcfi);
3856
3857                   // replace argVal with argExtend in CallArgsDescriptor
3858                   argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
3859                 }
3860               }
3861             }
3862           }
3863
3864           // Insert copy instructions to get all the arguments into
3865           // all the places that they need to be.
3866           // 
3867           for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3868             int argNo = i-1;
3869             CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
3870             Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
3871             const Type* argType = argVal->getType();
3872             unsigned regType = regInfo.getRegTypeForDataType(argType);
3873             unsigned argSize = target.getTargetData().getTypeSize(argType);
3874             int regNumForArg = SparcV9RegInfo::getInvalidRegNum();
3875             unsigned regClassIDOfArgReg;
3876
3877             // Check for FP arguments to varargs functions.
3878             // Any such argument in the first $K$ args must be passed in an
3879             // integer register.  If there is no prototype, it must also
3880             // be passed as an FP register.
3881             // K = #integer argument registers.
3882             bool isFPArg = argVal->getType()->isFloatingPoint();
3883             if (isVarArgs && isFPArg) {
3884
3885               if (noPrototype) {
3886                 // It is a function with no prototype: pass value
3887                 // as an FP value as well as a varargs value.  The FP value
3888                 // may go in a register or on the stack.  The copy instruction
3889                 // to the outgoing reg/stack is created by the normal argument
3890                 // handling code since this is the "normal" passing mode.
3891                 // 
3892                 regNumForArg = regInfo.regNumForFPArg(regType,
3893                                                       false, false, argNo,
3894                                                       regClassIDOfArgReg);
3895                 if (regNumForArg == regInfo.getInvalidRegNum())
3896                   argInfo.setUseStackSlot();
3897                 else
3898                   argInfo.setUseFPArgReg();
3899               }
3900               
3901               // If this arg. is in the first $K$ regs, add special copy-
3902               // float-to-int instructions to pass the value as an int.
3903               // To check if it is in the first $K$, get the register
3904               // number for the arg #i.  These copy instructions are
3905               // generated here because they are extra cases and not needed
3906               // for the normal argument handling (some code reuse is
3907               // possible though -- later).
3908               // 
3909               int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
3910                                                        regClassIDOfArgReg);
3911               if (copyRegNum != regInfo.getInvalidRegNum()) {
3912                 // Create a virtual register to represent copyReg. Mark
3913                 // this vreg as being an implicit operand of the call MI
3914                 const Type* loadTy = (argType == Type::FloatTy
3915                                       ? Type::IntTy : Type::LongTy);
3916                 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
3917                                                              argVal, NULL,
3918                                                              "argRegCopy");
3919                 callMI->addImplicitRef(argVReg);
3920                 
3921                 // Get a temp stack location to use to copy
3922                 // float-to-int via the stack.
3923                 // 
3924                 // FIXME: For now, we allocate permanent space because
3925                 // the stack frame manager does not allow locals to be
3926                 // allocated (e.g., for alloca) after a temp is
3927                 // allocated!
3928                 // 
3929                 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
3930                 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
3931                     
3932                 // Generate the store from FP reg to stack
3933                 unsigned StoreOpcode = ChooseStoreInstruction(argType);
3934                 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
3935                   .addReg(argVal).addMReg(regInfo.getFramePointer())
3936                   .addSImm(tmpOffset);
3937                 mvec.push_back(M);
3938                         
3939                 // Generate the load from stack to int arg reg
3940                 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
3941                 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
3942                   .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
3943                   .addReg(argVReg, MachineOperand::Def);
3944
3945                 // Mark operand with register it should be assigned
3946                 // both for copy and for the callMI
3947                 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
3948                 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
3949                                              copyRegNum);
3950                 mvec.push_back(M);
3951
3952                 // Add info about the argument to the CallArgsDescriptor
3953                 argInfo.setUseIntArgReg();
3954                 argInfo.setArgCopy(copyRegNum);
3955               } else {
3956                 // Cannot fit in first $K$ regs so pass arg on stack
3957                 argInfo.setUseStackSlot();
3958               }
3959             } else if (isFPArg) {
3960               // Get the outgoing arg reg to see if there is one.
3961               regNumForArg = regInfo.regNumForFPArg(regType, false, false,
3962                                                     argNo, regClassIDOfArgReg);
3963               if (regNumForArg == regInfo.getInvalidRegNum())
3964                 argInfo.setUseStackSlot();
3965               else {
3966                 argInfo.setUseFPArgReg();
3967                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
3968                                                        regNumForArg);
3969               }
3970             } else {
3971               // Get the outgoing arg reg to see if there is one.
3972               regNumForArg = regInfo.regNumForIntArg(false,false,
3973                                                      argNo, regClassIDOfArgReg);
3974               if (regNumForArg == regInfo.getInvalidRegNum())
3975                 argInfo.setUseStackSlot();
3976               else {
3977                 argInfo.setUseIntArgReg();
3978                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
3979                                                        regNumForArg);
3980               }
3981             }                
3982
3983             // 
3984             // Now insert copy instructions to stack slot or arg. register
3985             // 
3986             if (argInfo.usesStackSlot()) {
3987               // Get the stack offset for this argument slot.
3988               // FP args on stack are right justified so adjust offset!
3989               // int arguments are also right justified but they are
3990               // always loaded as a full double-word so the offset does
3991               // not need to be adjusted.
3992               int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
3993               if (argType->isFloatingPoint()) {
3994                 unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
3995                 assert(argSize <= slotSize && "Insufficient slot size!");
3996                 argOffset += slotSize - argSize;
3997               }
3998
3999               // Now generate instruction to copy argument to stack
4000               MachineOpCode storeOpCode =
4001                 (argType->isFloatingPoint()
4002                  ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
4003
4004               M = BuildMI(storeOpCode, 3).addReg(argVal)
4005                 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
4006               mvec.push_back(M);
4007             }
4008             else if (regNumForArg != regInfo.getInvalidRegNum()) {
4009
4010               // Create a virtual register to represent the arg reg. Mark
4011               // this vreg as being an implicit operand of the call MI.
4012               TmpInstruction* argVReg = 
4013                 new TmpInstruction(mcfi, argVal, NULL, "argReg");
4014
4015               callMI->addImplicitRef(argVReg);
4016               
4017               // Generate the reg-to-reg copy into the outgoing arg reg.
4018               // -- For FP values, create a FMOVS or FMOVD instruction
4019               // -- For non-FP values, create an add-with-0 instruction
4020               if (argType->isFloatingPoint())
4021                 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
4022                    .addReg(argVal).addReg(argVReg, MachineOperand::Def));
4023               else
4024                 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
4025                      .addReg(argVal).addSImm((int64_t) 0)
4026                      .addReg(argVReg, MachineOperand::Def));
4027               
4028               // Mark the operand with the register it should be assigned
4029               M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
4030               callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4031                                            regNumForArg);
4032
4033               mvec.push_back(M);
4034             }
4035             else
4036               assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
4037                      "Arg. not in stack slot, primary or secondary register?");
4038           }
4039
4040           // add call instruction and delay slot before copying return value
4041           mvec.push_back(callMI);
4042           mvec.push_back(BuildMI(V9::NOP, 0));
4043
4044           // Add the return value as an implicit ref.  The call operands
4045           // were added above.  Also, add code to copy out the return value.
4046           // This is always register-to-register for int or FP return values.
4047           // 
4048           if (callInstr->getType() != Type::VoidTy) { 
4049             // Get the return value reg.
4050             const Type* retType = callInstr->getType();
4051
4052             int regNum = (retType->isFloatingPoint()
4053                           ? (unsigned) SparcV9FloatRegClass::f0 
4054                           : (unsigned) SparcV9IntRegClass::o0);
4055             unsigned regClassID = regInfo.getRegClassIDOfType(retType);
4056             regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
4057
4058             // Create a virtual register to represent it and mark
4059             // this vreg as being an implicit operand of the call MI
4060             TmpInstruction* retVReg = 
4061               new TmpInstruction(mcfi, callInstr, NULL, "argReg");
4062
4063             callMI->addImplicitRef(retVReg, /*isDef*/ true);
4064
4065             // Generate the reg-to-reg copy from the return value reg.
4066             // -- For FP values, create a FMOVS or FMOVD instruction
4067             // -- For non-FP values, create an add-with-0 instruction
4068             if (retType->isFloatingPoint())
4069               M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
4070                    .addReg(retVReg).addReg(callInstr, MachineOperand::Def));
4071             else
4072               M = (BuildMI(ChooseAddInstructionByType(retType), 3)
4073                    .addReg(retVReg).addSImm((int64_t) 0)
4074                    .addReg(callInstr, MachineOperand::Def));
4075
4076             // Mark the operand with the register it should be assigned
4077             // Also mark the implicit ref of the call defining this operand
4078             M->SetRegForOperand(0, regNum);
4079             callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
4080
4081             mvec.push_back(M);
4082           }
4083
4084           // For the CALL instruction, the ret. addr. reg. is also implicit
4085           if (isa<Function>(callee))
4086             callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
4087
4088           MF.getInfo()->popAllTempValues();  // free temps used for this inst
4089         }
4090
4091         break;
4092       }
4093       
4094       case 62:  // reg:   Shl(reg, reg)
4095       {
4096         Value* argVal1 = subtreeRoot->leftChild()->getValue();
4097         Value* argVal2 = subtreeRoot->rightChild()->getValue();
4098         Instruction* shlInstr = subtreeRoot->getInstruction();
4099         
4100         const Type* opType = argVal1->getType();
4101         assert((opType->isInteger() || isa<PointerType>(opType)) &&
4102                "Shl unsupported for other types");
4103         unsigned opSize = target.getTargetData().getTypeSize(opType);
4104         
4105         CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
4106                                 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
4107                                 argVal1, argVal2, 0, shlInstr, mvec,
4108                                 MachineCodeForInstruction::get(shlInstr));
4109         break;
4110       }
4111       
4112       case 63:  // reg:   Shr(reg, reg)
4113       { 
4114         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
4115         assert((opType->isInteger() || isa<PointerType>(opType)) &&
4116                "Shr unsupported for other types");
4117         unsigned opSize = target.getTargetData().getTypeSize(opType);
4118         Add3OperandInstr(opType->isSigned()
4119                          ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
4120                          : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
4121                          subtreeRoot, mvec);
4122         break;
4123       }
4124       
4125       case 64:  // reg:   Phi(reg,reg)
4126         break;                          // don't forward the value
4127
4128       case 65:  // reg:   VANext(reg):  the va_next(va_list, type) instruction
4129       { // Increment the va_list pointer register according to the type.
4130         // All LLVM argument types are <= 64 bits, so use one doubleword.
4131         Instruction* vaNextI = subtreeRoot->getInstruction();
4132         assert(target.getTargetData().getTypeSize(vaNextI->getType()) <= 8 &&
4133                "We assumed that all LLVM parameter types <= 8 bytes!");
4134         unsigned argSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4135         mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaNextI->getOperand(0)).
4136                        addSImm(argSize).addRegDef(vaNextI));
4137         break;
4138       }
4139
4140       case 66:  // reg:   VAArg (reg): the va_arg instruction
4141       { // Load argument from stack using current va_list pointer value.
4142         // Use 64-bit load for all non-FP args, and LDDF or double for FP.
4143         Instruction* vaArgI = subtreeRoot->getInstruction();
4144         MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
4145                                 ? (vaArgI->getType() == Type::FloatTy
4146                                    ? V9::LDFi : V9::LDDFi)
4147                                 : V9::LDXi);
4148         mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
4149                        addSImm(0).addRegDef(vaArgI));
4150         break;
4151       }
4152       
4153       case 71:  // reg:     VReg
4154       case 72:  // reg:     Constant
4155         break;                          // don't forward the value
4156
4157       default:
4158         assert(0 && "Unrecognized BURG rule");
4159         break;
4160       }
4161     }
4162
4163   if (forwardOperandNum >= 0) {
4164     // We did not generate a machine instruction but need to use operand.
4165     // If user is in the same tree, replace Value in its machine operand.
4166     // If not, insert a copy instruction which should get coalesced away
4167     // by register allocation.
4168     if (subtreeRoot->parent() != NULL)
4169       ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
4170     else {
4171       std::vector<MachineInstr*> minstrVec;
4172       Instruction* instr = subtreeRoot->getInstruction();
4173       CreateCopyInstructionsByType(target,
4174                                      instr->getParent()->getParent(),
4175                                      instr->getOperand(forwardOperandNum),
4176                                      instr, minstrVec,
4177                                      MachineCodeForInstruction::get(instr));
4178       assert(minstrVec.size() > 0);
4179       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4180     }
4181   }
4182
4183   if (maskUnsignedResult) {
4184     // If result is unsigned and smaller than int reg size,
4185     // we need to clear high bits of result value.
4186     assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
4187     Instruction* dest = subtreeRoot->getInstruction();
4188     if (dest->getType()->isUnsigned()) {
4189       unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
4190       if (destSize <= 4) {
4191         // Mask high 64 - N bits, where N = 4*destSize.
4192         
4193         // Use a TmpInstruction to represent the
4194         // intermediate result before masking.  Since those instructions
4195         // have already been generated, go back and substitute tmpI
4196         // for dest in the result position of each one of them.
4197         // 
4198         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
4199         TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
4200                                                   dest, NULL, "maskHi");
4201         Value* srlArgToUse = tmpI;
4202
4203         unsigned numSubst = 0;
4204         for (unsigned i=0, N=mvec.size(); i < N; ++i) {
4205
4206           // Make sure we substitute all occurrences of dest in these instrs.
4207           // Otherwise, we will have bogus code.
4208           bool someArgsWereIgnored = false;
4209
4210           // Make sure not to substitute an upwards-exposed use -- that would
4211           // introduce a use of `tmpI' with no preceding def.  Therefore,
4212           // substitute a use or def-and-use operand only if a previous def
4213           // operand has already been substituted (i.e., numSubst > 0).
4214           // 
4215           numSubst += mvec[i]->substituteValue(dest, tmpI,
4216                                                /*defsOnly*/ numSubst == 0,
4217                                                /*notDefsAndUses*/ numSubst > 0,
4218                                                someArgsWereIgnored);
4219           assert(!someArgsWereIgnored &&
4220                  "Operand `dest' exists but not replaced: probably bogus!");
4221         }
4222         assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
4223
4224         // Left shift 32-N if size (N) is less than 32 bits.
4225         // Use another tmp. virtual register to represent this result.
4226         if (destSize < 4) {
4227           srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
4228                                            tmpI, NULL, "maskHi2");
4229           mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
4230                          .addZImm(8*(4-destSize))
4231                          .addReg(srlArgToUse, MachineOperand::Def));
4232         }
4233
4234         // Logical right shift 32-N to get zero extension in top 64-N bits.
4235         mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
4236                          .addZImm(8*(4-destSize))
4237                          .addReg(dest, MachineOperand::Def));
4238
4239       } else if (destSize < 8) {
4240         assert(0 && "Unsupported type size: 32 < size < 64 bits");
4241       }
4242     }
4243   }
4244 }
4245
4246 } // End llvm namespace
4247
4248 //==------------------------------------------------------------------------==//
4249 //                     Class V9ISel Implementation
4250 //==------------------------------------------------------------------------==//
4251
4252 bool V9ISel::runOnFunction(Function &F) {
4253   // First pass - Walk the function, lowering any calls to intrinsic functions
4254   // which the instruction selector cannot handle.
4255   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4256     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
4257       if (CallInst *CI = dyn_cast<CallInst>(I++))
4258         if (Function *F = CI->getCalledFunction())
4259           switch (F->getIntrinsicID()) {
4260           case Intrinsic::not_intrinsic:
4261           case Intrinsic::vastart:
4262           case Intrinsic::vacopy:
4263           case Intrinsic::vaend:
4264             // We directly implement these intrinsics.  Note that this knowledge
4265             // is incestuously entangled with the code in
4266             // SparcInstrSelection.cpp and must be updated when it is updated.
4267             // Since ALL of the code in this library is incestuously intertwined
4268             // with it already and sparc specific, we will live with this.
4269             break;
4270           default:
4271             // All other intrinsic calls we must lower.
4272             Instruction *Before = CI->getPrev();
4273             Target.getIntrinsicLowering().LowerIntrinsicCall(CI);
4274             if (Before) {        // Move iterator to instruction after call
4275               I = Before;  ++I;
4276             } else {
4277               I = BB->begin();
4278             }
4279           }
4280
4281   // Build the instruction trees to be given as inputs to BURG.
4282   InstrForest instrForest(&F);
4283   if (SelectDebugLevel >= Select_DebugInstTrees) {
4284     std::cerr << "\n\n*** Input to instruction selection for function "
4285               << F.getName() << "\n\n" << F
4286               << "\n\n*** Instruction trees for function "
4287               << F.getName() << "\n\n";
4288     instrForest.dump();
4289   }
4290   
4291   // Invoke BURG instruction selection for each tree
4292   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
4293        RI != instrForest.roots_end(); ++RI) {
4294     InstructionNode* basicNode = *RI;
4295     assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
4296       
4297     // Invoke BURM to label each tree node with a state
4298     burm_label(basicNode);
4299     if (SelectDebugLevel >= Select_DebugBurgTrees) {
4300       printcover(basicNode, 1, 0);
4301       std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
4302       printMatches(basicNode);
4303     }
4304       
4305     // Then recursively walk the tree to select instructions
4306     SelectInstructionsForTree(basicNode, /*goalnt*/1);
4307   }
4308   
4309   // Create the MachineBasicBlocks and add all of the MachineInstrs
4310   // defined in the MachineCodeForInstruction objects to the MachineBasicBlocks.
4311   MachineFunction &MF = MachineFunction::get(&F);
4312   std::map<const BasicBlock *, MachineBasicBlock *> MBBMap;
4313   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
4314     MachineBasicBlock *MBB = new MachineBasicBlock(BI);
4315     MF.getBasicBlockList().push_back(MBB);
4316     MBBMap[BI] = MBB;
4317
4318     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
4319       MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
4320       MBB->insert(MBB->end(), mvec.begin(), mvec.end());
4321     }
4322   }
4323
4324   // Initialize Machine-CFG for the function.
4325   for (MachineFunction::iterator i = MF.begin (), e = MF.end (); i != e; ++i) {
4326     MachineBasicBlock &MBB = *i;
4327     const BasicBlock *BB = MBB.getBasicBlock ();
4328     // for each successor S of BB, add MBBMap[S] as a successor of MBB.
4329     for (succ_const_iterator si = succ_begin(BB), se = succ_end(BB); si != se;
4330          ++si) {
4331       MachineBasicBlock *succMBB = MBBMap[*si];
4332       assert (succMBB && "Can't find MachineBasicBlock for this successor");
4333       MBB.addSuccessor (succMBB);
4334     }
4335   }
4336
4337   // Insert phi elimination code
4338   InsertCodeForPhis(F);
4339   
4340   if (SelectDebugLevel >= Select_PrintMachineCode) {
4341     std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
4342     MachineFunction::get(&F).dump();
4343   }
4344   
4345   return true;
4346 }
4347
4348 /// InsertCodeForPhis - This method inserts Phi elimination code for
4349 /// all Phi nodes in the given function.  After this method is called,
4350 /// the Phi nodes still exist in the LLVM code, but copies are added to the
4351 /// machine code.
4352 ///
4353 void V9ISel::InsertCodeForPhis(Function &F) {
4354   // Iterate over every Phi node PN in F:
4355   MachineFunction &MF = MachineFunction::get(&F);
4356   for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
4357     for (BasicBlock::const_iterator IIt = BB->getBasicBlock()->begin();
4358          const PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
4359       // Create a new temporary register to hold the result of the Phi copy.
4360       // The leak detector shouldn't track these nodes.  They are not garbage,
4361       // even though their parent field is never filled in.
4362       Value *PhiCpRes = new PHINode(PN->getType(), PN->getName() + ":PhiCp");
4363       LeakDetector::removeGarbageObject(PhiCpRes);
4364
4365       // For each of PN's incoming values, insert a copy in the corresponding
4366       // predecessor block.
4367       MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get (PN);
4368       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
4369         std::vector<MachineInstr*> mvec, CpVec;
4370         Target.getRegInfo()->cpValue2Value(PN->getIncomingValue(i), 
4371                                            PhiCpRes, mvec);
4372         for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
4373              MI != mvec.end(); ++MI) {
4374           std::vector<MachineInstr*> CpVec2 =
4375             FixConstantOperandsForInstr(const_cast<PHINode*>(PN), *MI, Target);
4376           CpVec2.push_back(*MI);
4377           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
4378         }
4379         // Insert the copy instructions into the predecessor BB.        
4380         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
4381         MCforPN.insert (MCforPN.end (), CpVec.begin (), CpVec.end ());
4382       }
4383       // Insert a copy instruction from PhiCpRes to PN.
4384       std::vector<MachineInstr*> mvec;
4385       Target.getRegInfo()->cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
4386                                         mvec);
4387       BB->insert(BB->begin(), mvec.begin(), mvec.end());
4388       MCforPN.insert (MCforPN.end (), mvec.begin (), mvec.end ());
4389     }  // for each Phi Instr in BB
4390   } // for all BBs in function
4391 }
4392
4393 /// InsertPhiElimInstructions - Inserts the instructions in CpVec into the
4394 /// MachineBasicBlock corresponding to BB, just before its terminator
4395 /// instruction. This is used by InsertCodeForPhis() to insert copies, above.
4396 ///
4397 void V9ISel::InsertPhiElimInstructions(BasicBlock *BB,
4398                                        const std::vector<MachineInstr*>& CpVec)
4399
4400   Instruction *TermInst = (Instruction*)BB->getTerminator();
4401   MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
4402   MachineInstr *FirstMIOfTerm = MC4Term.front();
4403   assert (FirstMIOfTerm && "No Machine Instrs for terminator");
4404
4405   MachineBasicBlock *MBB = FirstMIOfTerm->getParent();
4406   assert(MBB && "Machine BB for predecessor's terminator not found");
4407   MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
4408   assert(MCIt != MBB->end() && "Start inst of terminator not found");
4409   
4410   // Insert the copy instructions just before the first machine instruction
4411   // generated for the terminator.
4412   MBB->insert(MCIt, CpVec.begin(), CpVec.end());
4413 }
4414
4415 /// SelectInstructionsForTree - Recursively walk the tree to select
4416 /// instructions. Do this top-down so that child instructions can exploit
4417 /// decisions made at the child instructions.
4418 /// 
4419 /// E.g., if br(setle(reg,const)) decides the constant is 0 and uses
4420 /// a branch-on-integer-register instruction, then the setle node
4421 /// can use that information to avoid generating the SUBcc instruction.
4422 ///
4423 /// Note that this cannot be done bottom-up because setle must do this
4424 /// only if it is a child of the branch (otherwise, the result of setle
4425 /// may be used by multiple instructions).
4426 ///
4427 void V9ISel::SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt) {
4428   // Get the rule that matches this node.
4429   int ruleForNode = burm_rule(treeRoot->state, goalnt);
4430   
4431   if (ruleForNode == 0) {
4432     std::cerr << "Could not match instruction tree for instr selection\n";
4433     abort();
4434   }
4435   
4436   // Get this rule's non-terminals and the corresponding child nodes (if any)
4437   short *nts = burm_nts[ruleForNode];
4438   
4439   // First, select instructions for the current node and rule.
4440   // (If this is a list node, not an instruction, then skip this step).
4441   // This function is specific to the target architecture.
4442   if (treeRoot->opLabel != VRegListOp) {
4443     std::vector<MachineInstr*> minstrVec;
4444     InstructionNode* instrNode = (InstructionNode*)treeRoot;
4445     assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
4446     GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
4447     MachineCodeForInstruction &mvec = 
4448       MachineCodeForInstruction::get(instrNode->getInstruction());
4449     mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4450   }
4451   
4452   // Then, recursively compile the child nodes, if any.
4453   // 
4454   if (nts[0]) {
4455     // i.e., there is at least one kid
4456     InstrTreeNode* kids[2];
4457     int currentRule = ruleForNode;
4458     burm_kids(treeRoot, currentRule, kids);
4459     
4460     // First skip over any chain rules so that we don't visit
4461     // the current node again.
4462     while (ThisIsAChainRule(currentRule)) {
4463       currentRule = burm_rule(treeRoot->state, nts[0]);
4464       nts = burm_nts[currentRule];
4465       burm_kids(treeRoot, currentRule, kids);
4466     }
4467       
4468     // Now we have the first non-chain rule so we have found
4469     // the actual child nodes.  Recursively compile them.
4470     for (unsigned i = 0; nts[i]; i++) {
4471       assert(i < 2);
4472       InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
4473       if (nodeType == InstrTreeNode::NTVRegListNode ||
4474           nodeType == InstrTreeNode::NTInstructionNode)
4475         SelectInstructionsForTree(kids[i], nts[i]);
4476     }
4477   }
4478   
4479   // Finally, do any post-processing on this node after its children
4480   // have been translated.
4481   if (treeRoot->opLabel != VRegListOp)
4482     PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
4483 }
4484
4485 /// PostprocessMachineCodeForTree - Apply any final cleanups to
4486 /// machine code for the root of a subtree after selection for all its
4487 /// children has been completed.
4488 ///
4489 void V9ISel::PostprocessMachineCodeForTree(InstructionNode *instrNode,
4490                                            int ruleForNode, short *nts) {
4491   // Fix up any constant operands in the machine instructions to either
4492   // use an immediate field or to load the constant into a register.
4493   // Walk backwards and use direct indexes to allow insertion before current.
4494   Instruction* vmInstr = instrNode->getInstruction();
4495   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
4496   for (unsigned i = mvec.size(); i != 0; --i) {
4497     std::vector<MachineInstr*> loadConstVec =
4498       FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
4499     mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
4500   }
4501 }
4502
4503 /// createSparcV9BurgInstSelector - Creates and returns a new SparcV9
4504 /// BURG-based instruction selection pass.
4505 ///
4506 FunctionPass *llvm::createSparcV9BurgInstSelector(TargetMachine &TM) {
4507   return new V9ISel(TM);
4508 }