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