91792a4076229a660c7de93d08eeb13331032554
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9InstrSelection.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      SparcInstrSelection.cpp
5 // 
6 // Purpose:
7 //      BURS instruction selection for SPARC V9 architecture.      
8 //      
9 // History:
10 //      7/02/01  -  Vikram Adve  -  Created
11 //**************************************************************************/
12
13 #include "SparcInternals.h"
14 #include "SparcInstrSelectionSupport.h"
15 #include "llvm/CodeGen/InstrSelectionSupport.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/InstrForest.h"
18 #include "llvm/CodeGen/InstrSelection.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iOther.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Method.h"
25 #include "llvm/ConstantVals.h"
26 #include "Support/MathExtras.h"
27 #include <math.h>
28 using std::vector;
29
30 //************************* Forward Declarations ***************************/
31
32
33 static void SetMemOperands_Internal     (MachineInstr* minstr,
34                                          const InstructionNode* vmInstrNode,
35                                          Value* ptrVal,
36                                          Value* arrayOffsetVal,
37                                          const std::vector<Value*>& idxVec,
38                                          const TargetMachine& target);
39
40
41 //************************ Internal Functions ******************************/
42
43
44 static inline MachineOpCode 
45 ChooseBprInstruction(const InstructionNode* instrNode)
46 {
47   MachineOpCode opCode;
48   
49   Instruction* setCCInstr =
50     ((InstructionNode*) instrNode->leftChild())->getInstruction();
51   
52   switch(setCCInstr->getOpcode())
53     {
54     case Instruction::SetEQ: opCode = BRZ;   break;
55     case Instruction::SetNE: opCode = BRNZ;  break;
56     case Instruction::SetLE: opCode = BRLEZ; break;
57     case Instruction::SetGE: opCode = BRGEZ; break;
58     case Instruction::SetLT: opCode = BRLZ;  break;
59     case Instruction::SetGT: opCode = BRGZ;  break;
60     default:
61       assert(0 && "Unrecognized VM instruction!");
62       opCode = INVALID_OPCODE;
63       break; 
64     }
65   
66   return opCode;
67 }
68
69
70 static inline MachineOpCode 
71 ChooseBpccInstruction(const InstructionNode* instrNode,
72                       const BinaryOperator* setCCInstr)
73 {
74   MachineOpCode opCode = INVALID_OPCODE;
75   
76   bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
77   
78   if (isSigned)
79     {
80       switch(setCCInstr->getOpcode())
81         {
82         case Instruction::SetEQ: opCode = BE;  break;
83         case Instruction::SetNE: opCode = BNE; break;
84         case Instruction::SetLE: opCode = BLE; break;
85         case Instruction::SetGE: opCode = BGE; break;
86         case Instruction::SetLT: opCode = BL;  break;
87         case Instruction::SetGT: opCode = BG;  break;
88         default:
89           assert(0 && "Unrecognized VM instruction!");
90           break; 
91         }
92     }
93   else
94     {
95       switch(setCCInstr->getOpcode())
96         {
97         case Instruction::SetEQ: opCode = BE;   break;
98         case Instruction::SetNE: opCode = BNE;  break;
99         case Instruction::SetLE: opCode = BLEU; break;
100         case Instruction::SetGE: opCode = BCC;  break;
101         case Instruction::SetLT: opCode = BCS;  break;
102         case Instruction::SetGT: opCode = BGU;  break;
103         default:
104           assert(0 && "Unrecognized VM instruction!");
105           break; 
106         }
107     }
108   
109   return opCode;
110 }
111
112 static inline MachineOpCode 
113 ChooseBFpccInstruction(const InstructionNode* instrNode,
114                        const BinaryOperator* setCCInstr)
115 {
116   MachineOpCode opCode = INVALID_OPCODE;
117   
118   switch(setCCInstr->getOpcode())
119     {
120     case Instruction::SetEQ: opCode = FBE;  break;
121     case Instruction::SetNE: opCode = FBNE; break;
122     case Instruction::SetLE: opCode = FBLE; break;
123     case Instruction::SetGE: opCode = FBGE; break;
124     case Instruction::SetLT: opCode = FBL;  break;
125     case Instruction::SetGT: opCode = FBG;  break;
126     default:
127       assert(0 && "Unrecognized VM instruction!");
128       break; 
129     }
130   
131   return opCode;
132 }
133
134
135 // Create a unique TmpInstruction for a boolean value,
136 // representing the CC register used by a branch on that value.
137 // For now, hack this using a little static cache of TmpInstructions.
138 // Eventually the entire BURG instruction selection should be put
139 // into a separate class that can hold such information.
140 // The static cache is not too bad because the memory for these
141 // TmpInstructions will be freed along with the rest of the Method anyway.
142 // 
143 static TmpInstruction*
144 GetTmpForCC(Value* boolVal, const Method* method, const Type* ccType)
145 {
146   typedef std::hash_map<const Value*, TmpInstruction*> BoolTmpCache;
147   static BoolTmpCache boolToTmpCache;     // Map boolVal -> TmpInstruction*
148   static const Method* lastMethod = NULL; // Use to flush cache between methods
149   
150   assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
151   
152   if (lastMethod != method)
153     {
154       lastMethod = method;
155       boolToTmpCache.clear();
156     }
157   
158   // Look for tmpI and create a new one otherwise.  The new value is
159   // directly written to map using the ref returned by operator[].
160   TmpInstruction*& tmpI = boolToTmpCache[boolVal];
161   if (tmpI == NULL)
162     tmpI = new TmpInstruction(TMP_INSTRUCTION_OPCODE, ccType, boolVal, NULL);
163   
164   return tmpI;
165 }
166
167
168 static inline MachineOpCode 
169 ChooseBccInstruction(const InstructionNode* instrNode,
170                      bool& isFPBranch)
171 {
172   InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
173   BinaryOperator* setCCInstr = (BinaryOperator*) setCCNode->getInstruction();
174   const Type* setCCType = setCCInstr->getOperand(0)->getType();
175   
176   isFPBranch = (setCCType == Type::FloatTy || setCCType == Type::DoubleTy); 
177   
178   if (isFPBranch) 
179     return ChooseBFpccInstruction(instrNode, setCCInstr);
180   else
181     return ChooseBpccInstruction(instrNode, setCCInstr);
182 }
183
184
185 static inline MachineOpCode 
186 ChooseMovFpccInstruction(const InstructionNode* instrNode)
187 {
188   MachineOpCode opCode = INVALID_OPCODE;
189   
190   switch(instrNode->getInstruction()->getOpcode())
191     {
192     case Instruction::SetEQ: opCode = MOVFE;  break;
193     case Instruction::SetNE: opCode = MOVFNE; break;
194     case Instruction::SetLE: opCode = MOVFLE; break;
195     case Instruction::SetGE: opCode = MOVFGE; break;
196     case Instruction::SetLT: opCode = MOVFL;  break;
197     case Instruction::SetGT: opCode = MOVFG;  break;
198     default:
199       assert(0 && "Unrecognized VM instruction!");
200       break; 
201     }
202   
203   return opCode;
204 }
205
206
207 // Assumes that SUBcc v1, v2 -> v3 has been executed.
208 // In most cases, we want to clear v3 and then follow it by instruction
209 // MOVcc 1 -> v3.
210 // Set mustClearReg=false if v3 need not be cleared before conditional move.
211 // Set valueToMove=0 if we want to conditionally move 0 instead of 1
212 //                      (i.e., we want to test inverse of a condition)
213 // (The latter two cases do not seem to arise because SetNE needs nothing.)
214 // 
215 static MachineOpCode
216 ChooseMovpccAfterSub(const InstructionNode* instrNode,
217                      bool& mustClearReg,
218                      int& valueToMove)
219 {
220   MachineOpCode opCode = INVALID_OPCODE;
221   mustClearReg = true;
222   valueToMove = 1;
223   
224   switch(instrNode->getInstruction()->getOpcode())
225     {
226     case Instruction::SetEQ: opCode = MOVE;  break;
227     case Instruction::SetLE: opCode = MOVLE; break;
228     case Instruction::SetGE: opCode = MOVGE; break;
229     case Instruction::SetLT: opCode = MOVL;  break;
230     case Instruction::SetGT: opCode = MOVG;  break;
231     case Instruction::SetNE: assert(0 && "No move required!"); break;
232     default:                 assert(0 && "Unrecognized VM instr!"); break; 
233     }
234   
235   return opCode;
236 }
237
238 static inline MachineOpCode
239 ChooseConvertToFloatInstr(const InstructionNode* instrNode,
240                           const Type* opType)
241 {
242   MachineOpCode opCode = INVALID_OPCODE;
243   
244   switch(instrNode->getOpLabel())
245     {
246     case ToFloatTy: 
247       if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
248         opCode = FITOS;
249       else if (opType == Type::LongTy)
250         opCode = FXTOS;
251       else if (opType == Type::DoubleTy)
252         opCode = FDTOS;
253       else if (opType == Type::FloatTy)
254         ;
255       else
256         assert(0 && "Cannot convert this type to FLOAT on SPARC");
257       break;
258       
259     case ToDoubleTy: 
260       // Use FXTOD for all integer-to-double conversions.  This has to be
261       // consistent with the code in CreateCodeToCopyIntToFloat() since
262       // that will be used to load the integer into an FP register.
263       // 
264       if (opType == Type::SByteTy || opType == Type::ShortTy ||
265           opType == Type::IntTy || opType == Type::LongTy)
266         opCode = FXTOD;
267       else if (opType == Type::FloatTy)
268         opCode = FSTOD;
269       else if (opType == Type::DoubleTy)
270         ;
271       else
272         assert(0 && "Cannot convert this type to DOUBLE on SPARC");
273       break;
274       
275     default:
276       break;
277     }
278   
279   return opCode;
280 }
281
282 static inline MachineOpCode 
283 ChooseConvertToIntInstr(const InstructionNode* instrNode,
284                         const Type* opType)
285 {
286   MachineOpCode opCode = INVALID_OPCODE;;
287   
288   int instrType = (int) instrNode->getOpLabel();
289   
290   if (instrType == ToSByteTy || instrType == ToShortTy || instrType == ToIntTy)
291     {
292       switch (opType->getPrimitiveID())
293         {
294         case Type::FloatTyID:   opCode = FSTOI; break;
295         case Type::DoubleTyID:  opCode = FDTOI; break;
296         default:
297           assert(0 && "Non-numeric non-bool type cannot be converted to Int");
298           break;
299         }
300     }
301   else if (instrType == ToLongTy)
302     {
303       switch (opType->getPrimitiveID())
304         {
305         case Type::FloatTyID:   opCode = FSTOX; break;
306         case Type::DoubleTyID:  opCode = FDTOX; break;
307         default:
308           assert(0 && "Non-numeric non-bool type cannot be converted to Long");
309           break;
310         }
311     }
312   else
313       assert(0 && "Should not get here, Mo!");
314   
315   return opCode;
316 }
317
318
319 static inline MachineOpCode 
320 ChooseAddInstructionByType(const Type* resultType)
321 {
322   MachineOpCode opCode = INVALID_OPCODE;
323   
324   if (resultType->isIntegral() ||
325       resultType->isPointerType() ||
326       resultType->isLabelType() ||
327       isa<MethodType>(resultType) ||
328       resultType == Type::BoolTy)
329     {
330       opCode = ADD;
331     }
332   else
333     switch(resultType->getPrimitiveID())
334       {
335       case Type::FloatTyID:  opCode = FADDS; break;
336       case Type::DoubleTyID: opCode = FADDD; break;
337       default: assert(0 && "Invalid type for ADD instruction"); break; 
338       }
339   
340   return opCode;
341 }
342
343
344 static inline MachineOpCode 
345 ChooseAddInstruction(const InstructionNode* instrNode)
346 {
347   return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
348 }
349
350
351 static inline MachineInstr* 
352 CreateMovFloatInstruction(const InstructionNode* instrNode,
353                           const Type* resultType)
354 {
355   MachineInstr* minstr = new MachineInstr((resultType == Type::FloatTy)
356                                           ? FMOVS : FMOVD);
357   minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
358                             instrNode->leftChild()->getValue());
359   minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
360                             instrNode->getValue());
361   return minstr;
362 }
363
364 static inline MachineInstr* 
365 CreateAddConstInstruction(const InstructionNode* instrNode)
366 {
367   MachineInstr* minstr = NULL;
368   
369   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
370   assert(isa<Constant>(constOp));
371   
372   // Cases worth optimizing are:
373   // (1) Add with 0 for float or double: use an FMOV of appropriate type,
374   //     instead of an FADD (1 vs 3 cycles).  There is no integer MOV.
375   // 
376   const Type* resultType = instrNode->getInstruction()->getType();
377   
378   if (resultType == Type::FloatTy ||
379       resultType == Type::DoubleTy)
380     {
381       double dval = cast<ConstantFP>(constOp)->getValue();
382       if (dval == 0.0)
383         minstr = CreateMovFloatInstruction(instrNode, resultType);
384     }
385   
386   return minstr;
387 }
388
389
390 static inline MachineOpCode 
391 ChooseSubInstructionByType(const Type* resultType)
392 {
393   MachineOpCode opCode = INVALID_OPCODE;
394   
395   if (resultType->isIntegral() ||
396       resultType->isPointerType())
397     {
398       opCode = SUB;
399     }
400   else
401     switch(resultType->getPrimitiveID())
402       {
403       case Type::FloatTyID:  opCode = FSUBS; break;
404       case Type::DoubleTyID: opCode = FSUBD; break;
405       default: assert(0 && "Invalid type for SUB instruction"); break; 
406       }
407   
408   return opCode;
409 }
410
411
412 static inline MachineInstr* 
413 CreateSubConstInstruction(const InstructionNode* instrNode)
414 {
415   MachineInstr* minstr = NULL;
416   
417   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
418   assert(isa<Constant>(constOp));
419   
420   // Cases worth optimizing are:
421   // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
422   //     instead of an FSUB (1 vs 3 cycles).  There is no integer MOV.
423   // 
424   const Type* resultType = instrNode->getInstruction()->getType();
425   
426   if (resultType == Type::FloatTy ||
427       resultType == Type::DoubleTy)
428     {
429       double dval = cast<ConstantFP>(constOp)->getValue();
430       if (dval == 0.0)
431         minstr = CreateMovFloatInstruction(instrNode, resultType);
432     }
433   
434   return minstr;
435 }
436
437
438 static inline MachineOpCode 
439 ChooseFcmpInstruction(const InstructionNode* instrNode)
440 {
441   MachineOpCode opCode = INVALID_OPCODE;
442   
443   Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
444   switch(operand->getType()->getPrimitiveID()) {
445   case Type::FloatTyID:  opCode = FCMPS; break;
446   case Type::DoubleTyID: opCode = FCMPD; break;
447   default: assert(0 && "Invalid type for FCMP instruction"); break; 
448   }
449   
450   return opCode;
451 }
452
453
454 // Assumes that leftArg and rightArg are both cast instructions.
455 //
456 static inline bool
457 BothFloatToDouble(const InstructionNode* instrNode)
458 {
459   InstrTreeNode* leftArg = instrNode->leftChild();
460   InstrTreeNode* rightArg = instrNode->rightChild();
461   InstrTreeNode* leftArgArg = leftArg->leftChild();
462   InstrTreeNode* rightArgArg = rightArg->leftChild();
463   assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
464   
465   // Check if both arguments are floats cast to double
466   return (leftArg->getValue()->getType() == Type::DoubleTy &&
467           leftArgArg->getValue()->getType() == Type::FloatTy &&
468           rightArgArg->getValue()->getType() == Type::FloatTy);
469 }
470
471
472 static inline MachineOpCode 
473 ChooseMulInstructionByType(const Type* resultType)
474 {
475   MachineOpCode opCode = INVALID_OPCODE;
476   
477   if (resultType->isIntegral())
478     opCode = MULX;
479   else
480     switch(resultType->getPrimitiveID())
481       {
482       case Type::FloatTyID:  opCode = FMULS; break;
483       case Type::DoubleTyID: opCode = FMULD; break;
484       default: assert(0 && "Invalid type for MUL instruction"); break; 
485       }
486   
487   return opCode;
488 }
489
490
491 static inline MachineOpCode 
492 ChooseMulInstruction(const InstructionNode* instrNode,
493                      bool checkCasts)
494 {
495   if (checkCasts && BothFloatToDouble(instrNode))
496     return FSMULD;
497   
498   // else use the regular multiply instructions
499   return ChooseMulInstructionByType(instrNode->getInstruction()->getType());
500 }
501
502
503 static inline MachineInstr*
504 CreateIntNegInstruction(TargetMachine& target,
505                         Value* vreg)
506 {
507   MachineInstr* minstr = new MachineInstr(SUB);
508   minstr->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
509   minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, vreg);
510   minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, vreg);
511   return minstr;
512 }
513
514
515 static inline MachineInstr* 
516 CreateMulConstInstruction(TargetMachine &target,
517                           const InstructionNode* instrNode,
518                           MachineInstr*& getMinstr2)
519 {
520   MachineInstr* minstr = NULL; // return NULL if we cannot exploit constant
521   getMinstr2 = NULL;           // to create a cheaper instruction
522
523   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
524   assert(isa<Constant>(constOp));
525   
526   // Cases worth optimizing are:
527   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
528   // (2) Multiply by 2^x for integer types: replace with Shift
529   // 
530   const Type* resultType = instrNode->getInstruction()->getType();
531   
532   if (resultType->isIntegral() || resultType->isPointerType())
533     {
534       unsigned pow;
535       bool isValidConst;
536       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
537       if (isValidConst)
538         {
539           bool needNeg = false;
540           if (C < 0)
541             {
542               needNeg = true;
543               C = -C;
544             }
545           
546           if (C == 0 || C == 1)
547             {
548               minstr = new MachineInstr(ADD);
549               
550               if (C == 0)
551                 minstr->SetMachineOperand(0,
552                                           target.getRegInfo().getZeroRegNum());
553               else
554                 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
555                                           instrNode->leftChild()->getValue());
556               minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
557             }
558           else if (IsPowerOf2(C, pow))
559             {
560               minstr = new MachineInstr((resultType == Type::LongTy)
561                                         ? SLLX : SLL);
562               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
563                                            instrNode->leftChild()->getValue());
564               minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
565                                            pow);
566             }
567           
568           if (minstr && needNeg)
569             { // insert <reg = SUB 0, reg> after the instr to flip the sign
570               getMinstr2 = CreateIntNegInstruction(target,
571                                                    instrNode->getValue());
572             }
573         }
574     }
575   else
576     {
577       if (resultType == Type::FloatTy ||
578           resultType == Type::DoubleTy)
579         {
580           double dval = cast<ConstantFP>(constOp)->getValue();
581           if (fabs(dval) == 1)
582             {
583               bool needNeg = (dval < 0);
584               
585               MachineOpCode opCode = needNeg
586                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
587                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
588               
589               minstr = new MachineInstr(opCode);
590               minstr->SetMachineOperand(0,
591                                         MachineOperand::MO_VirtualRegister,
592                                         instrNode->leftChild()->getValue());
593             } 
594         }
595     }
596   
597   if (minstr != NULL)
598     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
599                               instrNode->getValue());   
600   
601   return minstr;
602 }
603
604
605 // Generate a divide instruction for Div or Rem.
606 // For Rem, this assumes that the operand type will be signed if the result
607 // type is signed.  This is correct because they must have the same sign.
608 // 
609 static inline MachineOpCode 
610 ChooseDivInstruction(TargetMachine &target,
611                      const InstructionNode* instrNode)
612 {
613   MachineOpCode opCode = INVALID_OPCODE;
614   
615   const Type* resultType = instrNode->getInstruction()->getType();
616   
617   if (resultType->isIntegral())
618     opCode = resultType->isSigned()? SDIVX : UDIVX;
619   else
620     switch(resultType->getPrimitiveID())
621       {
622       case Type::FloatTyID:  opCode = FDIVS; break;
623       case Type::DoubleTyID: opCode = FDIVD; break;
624       default: assert(0 && "Invalid type for DIV instruction"); break; 
625       }
626   
627   return opCode;
628 }
629
630
631 static inline MachineInstr* 
632 CreateDivConstInstruction(TargetMachine &target,
633                           const InstructionNode* instrNode,
634                           MachineInstr*& getMinstr2)
635 {
636   MachineInstr* minstr = NULL;
637   getMinstr2 = NULL;
638   
639   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
640   assert(isa<Constant>(constOp));
641   
642   // Cases worth optimizing are:
643   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
644   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
645   // 
646   const Type* resultType = instrNode->getInstruction()->getType();
647   
648   if (resultType->isIntegral())
649     {
650       unsigned pow;
651       bool isValidConst;
652       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
653       if (isValidConst)
654         {
655           bool needNeg = false;
656           if (C < 0)
657             {
658               needNeg = true;
659               C = -C;
660             }
661           
662           if (C == 1)
663             {
664               minstr = new MachineInstr(ADD);
665               minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
666                                           instrNode->leftChild()->getValue());
667               minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
668             }
669           else if (IsPowerOf2(C, pow))
670             {
671               MachineOpCode opCode= ((resultType->isSigned())
672                                      ? (resultType==Type::LongTy)? SRAX : SRA
673                                      : (resultType==Type::LongTy)? SRLX : SRL);
674               minstr = new MachineInstr(opCode);
675               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
676                                            instrNode->leftChild()->getValue());
677               minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
678                                            pow);
679             }
680           
681           if (minstr && needNeg)
682             { // insert <reg = SUB 0, reg> after the instr to flip the sign
683               getMinstr2 = CreateIntNegInstruction(target,
684                                                    instrNode->getValue());
685             }
686         }
687     }
688   else
689     {
690       if (resultType == Type::FloatTy ||
691           resultType == Type::DoubleTy)
692         {
693           double dval = cast<ConstantFP>(constOp)->getValue();
694           if (fabs(dval) == 1)
695             {
696               bool needNeg = (dval < 0);
697               
698               MachineOpCode opCode = needNeg
699                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
700                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
701               
702               minstr = new MachineInstr(opCode);
703               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
704                                            instrNode->leftChild()->getValue());
705             } 
706         }
707     }
708   
709   if (minstr != NULL)
710     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
711                               instrNode->getValue());   
712   
713   return minstr;
714 }
715
716
717 //------------------------------------------------------------------------ 
718 // Function SetOperandsForMemInstr
719 //
720 // Choose addressing mode for the given load or store instruction.
721 // Use [reg+reg] if it is an indexed reference, and the index offset is
722 //               not a constant or if it cannot fit in the offset field.
723 // Use [reg+offset] in all other cases.
724 // 
725 // This assumes that all array refs are "lowered" to one of these forms:
726 //      %x = load (subarray*) ptr, constant     ; single constant offset
727 //      %x = load (subarray*) ptr, offsetVal    ; single non-constant offset
728 // Generally, this should happen via strength reduction + LICM.
729 // Also, strength reduction should take care of using the same register for
730 // the loop index variable and an array index, when that is profitable.
731 //------------------------------------------------------------------------ 
732
733 static void
734 SetOperandsForMemInstr(MachineInstr* minstr,
735                        const InstructionNode* vmInstrNode,
736                        const TargetMachine& target)
737 {
738   MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
739   
740   // Variables to hold the index vector, ptr value, and offset value.
741   // The major work here is to extract these for all 3 instruction types
742   // and then call the common function SetMemOperands_Internal().
743   // 
744   vector<Value*> idxVec;
745   Value* ptrVal;
746   Value* arrayOffsetVal = NULL;
747   
748   // Test if a GetElemPtr instruction is being folded into this mem instrn.
749   // If so, it will be in the left child for Load and GetElemPtr,
750   // and in the right child for Store instructions.
751   // 
752   InstrTreeNode* ptrChild = (vmInstrNode->getOpLabel() == Instruction::Store
753                              ? vmInstrNode->rightChild()
754                              : vmInstrNode->leftChild()); 
755   
756   if (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
757       ptrChild->getOpLabel() == GetElemPtrIdx)
758     {
759       // There is a GetElemPtr instruction and there may be a chain of
760       // more than one.  Use the pointer value of the last one in the chain.
761       // Fold the index vectors from the entire chain and from the mem
762       // instruction into one single index vector.
763       // Finally, we never fold for an array instruction so make that NULL.
764       
765       ptrVal = FoldGetElemChain((InstructionNode*) ptrChild, idxVec);
766       idxVec.insert(idxVec.end(), memInst->idx_begin(), memInst->idx_end());
767       assert(!((PointerType*)ptrVal->getType())->getElementType()->isArrayType()
768              && "GetElemPtr cannot be folded into array refs in selection");
769     }
770   else
771     {
772       // There is no GetElemPtr instruction.
773       // Use the pointer value and the index vector from the Mem instruction.
774       // If it is an array reference, check that it has been lowered to
775       // at most a single offset, then get the array offset value.
776       // 
777       ptrVal = memInst->getPointerOperand();
778
779       const Type* opType = cast<PointerType>(ptrVal->getType())->getElementType();
780       if (opType->isArrayType())
781         {
782           assert((memInst->getNumOperands()
783                   == (unsigned) 1 + memInst->getFirstIndexOperandNumber())
784                  && "Array refs must be lowered before Instruction Selection");
785           arrayOffsetVal = * memInst->idx_begin();
786         }
787     }
788   
789   SetMemOperands_Internal(minstr, vmInstrNode, ptrVal, arrayOffsetVal,
790                           idxVec, target);
791 }
792
793
794 static void
795 SetMemOperands_Internal(MachineInstr* minstr,
796                         const InstructionNode* vmInstrNode,
797                         Value* ptrVal,
798                         Value* arrayOffsetVal,
799                         const vector<Value*>& idxVec,
800                         const TargetMachine& target)
801 {
802   MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
803   
804   // Initialize so we default to storing the offset in a register.
805   int64_t smallConstOffset = 0;
806   Value* valueForRegOffset = NULL;
807   MachineOperand::MachineOperandType offsetOpType =MachineOperand::MO_VirtualRegister;
808
809   // Check if there is an index vector and if so, if it translates to
810   // a small enough constant to fit in the immediate-offset field.
811   // 
812   if (idxVec.size() > 0)
813     {
814       bool isConstantOffset = false;
815       unsigned offset = 0;
816       
817       const PointerType* ptrType = (PointerType*) ptrVal->getType();
818       
819       if (ptrType->getElementType()->isStructType())
820         {
821           // the offset is always constant for structs
822           isConstantOffset = true;
823           
824           // Compute the offset value using the index vector
825           offset = target.DataLayout.getIndexedOffset(ptrType, idxVec);
826         }
827       else
828         {
829           // It must be an array ref.  Check if the offset is a constant,
830           // and that the indexing has been lowered to a single offset.
831           // 
832           assert(isa<SequentialType>(ptrType->getElementType()));
833           assert(arrayOffsetVal != NULL
834                  && "Expect to be given Value* for array offsets");
835           
836           if (Constant *CPV = dyn_cast<Constant>(arrayOffsetVal))
837             {
838               isConstantOffset = true;  // always constant for structs
839               assert(arrayOffsetVal->getType()->isIntegral());
840               offset = (CPV->getType()->isSigned()
841                         ? cast<ConstantSInt>(CPV)->getValue()
842                         : (int64_t) cast<ConstantUInt>(CPV)->getValue());
843             }
844           else
845             {
846               valueForRegOffset = arrayOffsetVal;
847             }
848         }
849       
850       if (isConstantOffset)
851         {
852           // create a virtual register for the constant
853           valueForRegOffset = ConstantSInt::get(Type::IntTy, offset);
854         }
855     }
856   else
857     {
858       offsetOpType = MachineOperand::MO_SignExtendedImmed;
859       smallConstOffset = 0;
860     }
861   
862   // Operand 0 is value for STORE, ptr for LOAD or GET_ELEMENT_PTR
863   // It is the left child in the instruction tree in all cases.
864   Value* leftVal = vmInstrNode->leftChild()->getValue();
865   minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister, leftVal);
866   
867   // Operand 1 is ptr for STORE, offset for LOAD or GET_ELEMENT_PTR
868   // Operand 2 is offset for STORE, result reg for LOAD or GET_ELEMENT_PTR
869   //
870   unsigned offsetOpNum = (memInst->getOpcode() == Instruction::Store)? 2 : 1;
871   if (offsetOpType == MachineOperand::MO_VirtualRegister)
872     {
873       assert(valueForRegOffset != NULL);
874       minstr->SetMachineOperand(offsetOpNum, offsetOpType, valueForRegOffset); 
875     }
876   else
877     minstr->SetMachineOperand(offsetOpNum, offsetOpType, smallConstOffset);
878   
879   if (memInst->getOpcode() == Instruction::Store)
880     minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, ptrVal);
881   else
882     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
883                                  vmInstrNode->getValue());
884 }
885
886
887 // 
888 // Substitute operand `operandNum' of the instruction in node `treeNode'
889 // in place of the use(s) of that instruction in node `parent'.
890 // Check both explicit and implicit operands!
891 // 
892 static void
893 ForwardOperand(InstructionNode* treeNode,
894                InstrTreeNode*   parent,
895                int operandNum)
896 {
897   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
898   
899   Instruction* unusedOp = treeNode->getInstruction();
900   Value* fwdOp = unusedOp->getOperand(operandNum);
901
902   // The parent itself may be a list node, so find the real parent instruction
903   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
904     {
905       parent = parent->parent();
906       assert(parent && "ERROR: Non-instruction node has no parent in tree.");
907     }
908   InstructionNode* parentInstrNode = (InstructionNode*) parent;
909   
910   Instruction* userInstr = parentInstrNode->getInstruction();
911   MachineCodeForVMInstr& mvec = userInstr->getMachineInstrVec();
912   for (unsigned i=0, N=mvec.size(); i < N; i++)
913     {
914       MachineInstr* minstr = mvec[i];
915       
916       for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i)
917         {
918           const MachineOperand& mop = minstr->getOperand(i);
919           if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
920               mop.getVRegValue() == unusedOp)
921             {
922               minstr->SetMachineOperand(i, MachineOperand::MO_VirtualRegister,
923                                            fwdOp);
924             }
925         }
926       
927       for (unsigned i=0, numOps=minstr->getNumImplicitRefs(); i < numOps; ++i)
928         if (minstr->getImplicitRef(i) == unusedOp)
929           minstr->setImplicitRef(i, fwdOp, minstr->implicitRefIsDefined(i));
930     }
931 }
932
933
934
935 void UltraSparcInstrInfo::
936 CreateCopyInstructionsByType(const TargetMachine& target,
937                              Value* src,
938                              Instruction* dest,
939                              vector<MachineInstr*>& minstrVec) const
940 {
941   bool loadConstantToReg = false;
942   
943   const Type* resultType = dest->getType();
944   
945   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
946   if (opCode == INVALID_OPCODE)
947     {
948       assert(0 && "Unsupported result type in CreateCopyInstructionsByType()");
949       return;
950     }
951   
952   // if `src' is a constant that doesn't fit in the immed field or if it is
953   // a global variable (i.e., a constant address), generate a load
954   // instruction instead of an add
955   // 
956   if (isa<Constant>(src))
957     {
958       unsigned int machineRegNum;
959       int64_t immedValue;
960       MachineOperand::MachineOperandType opType =
961         ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
962                          machineRegNum, immedValue);
963       
964       if (opType == MachineOperand::MO_VirtualRegister)
965         loadConstantToReg = true;
966     }
967   else if (isa<GlobalValue>(src))
968     loadConstantToReg = true;
969   
970   if (loadConstantToReg)
971     { // `src' is constant and cannot fit in immed field for the ADD
972       // Insert instructions to "load" the constant into a register
973       vector<TmpInstruction*> tempVec;
974       target.getInstrInfo().CreateCodeToLoadConst(src,dest,minstrVec,tempVec);
975       for (unsigned i=0; i < tempVec.size(); i++)
976         dest->getMachineInstrVec().addTempValue(tempVec[i]);
977     }
978   else
979     { // Create the appropriate add instruction.
980       // Make `src' the second operand, in case it is a constant
981       // Use (unsigned long) 0 for a NULL pointer value.
982       // 
983       const Type* nullValueType =
984         (resultType->getPrimitiveID() == Type::PointerTyID)? Type::ULongTy
985                                                            : resultType;
986       MachineInstr* minstr = new MachineInstr(opCode);
987       minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
988                                 Constant::getNullConstant(nullValueType));
989       minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, src);
990       minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, dest);
991       minstrVec.push_back(minstr);
992     }
993 }
994
995
996
997 //******************* Externally Visible Functions *************************/
998
999
1000 //------------------------------------------------------------------------ 
1001 // External Function: GetInstructionsForProlog
1002 // External Function: GetInstructionsForEpilog
1003 //
1004 // Purpose:
1005 //   Create prolog and epilog code for procedure entry and exit
1006 //------------------------------------------------------------------------ 
1007
1008 extern unsigned
1009 GetInstructionsForProlog(BasicBlock* entryBB,
1010                          TargetMachine &target,
1011                          MachineInstr** mvec)
1012 {
1013   const MachineFrameInfo& frameInfo = target.getFrameInfo();
1014   
1015   // The second operand is the stack size. If it does not fit in the
1016   // immediate field, we either have to find an unused register in the
1017   // caller's window or move some elements to the dynamically allocated
1018   // area of the stack frame (just above save area and method args).
1019   Method* method = entryBB->getParent();
1020   MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
1021   unsigned int staticStackSize = mcInfo.getStaticStackSize();
1022   
1023   if (staticStackSize < (unsigned) frameInfo.getMinStackFrameSize())
1024     staticStackSize = (unsigned) frameInfo.getMinStackFrameSize();
1025   
1026   if (unsigned padsz = (staticStackSize %
1027                         (unsigned) frameInfo.getStackFrameSizeAlignment()))
1028     staticStackSize += frameInfo.getStackFrameSizeAlignment() - padsz;
1029   
1030   assert(target.getInstrInfo().constantFitsInImmedField(SAVE, staticStackSize)
1031          && "Stack size too large for immediate field of SAVE instruction. Need additional work as described in the comment above");
1032   
1033   mvec[0] = new MachineInstr(SAVE);
1034   mvec[0]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1035   mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1036                                 - (int) staticStackSize);
1037   mvec[0]->SetMachineOperand(2, target.getRegInfo().getStackPointer());
1038   
1039   return 1;
1040 }
1041
1042
1043 extern unsigned
1044 GetInstructionsForEpilog(BasicBlock* anExitBB,
1045                          TargetMachine &target,
1046                          MachineInstr** mvec)
1047 {
1048   mvec[0] = new MachineInstr(RESTORE);
1049   mvec[0]->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
1050   mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1051                              (int64_t)0);
1052   mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
1053   
1054   return 1;
1055 }
1056
1057
1058 //------------------------------------------------------------------------ 
1059 // External Function: ThisIsAChainRule
1060 //
1061 // Purpose:
1062 //   Check if a given BURG rule is a chain rule.
1063 //------------------------------------------------------------------------ 
1064
1065 extern bool
1066 ThisIsAChainRule(int eruleno)
1067 {
1068   switch(eruleno)
1069     {
1070     case 111:   // stmt:  reg
1071     case 113:   // stmt:  bool
1072     case 123:
1073     case 124:
1074     case 125:
1075     case 126:
1076     case 127:
1077     case 128:
1078     case 129:
1079     case 130:
1080     case 131:
1081     case 132:
1082     case 133:
1083     case 155:
1084     case 221:
1085     case 222:
1086     case 241:
1087     case 242:
1088     case 243:
1089     case 244:
1090       return true; break;
1091       
1092     default:
1093       return false; break;
1094     }
1095 }
1096
1097
1098 //------------------------------------------------------------------------ 
1099 // External Function: GetInstructionsByRule
1100 //
1101 // Purpose:
1102 //   Choose machine instructions for the SPARC according to the
1103 //   patterns chosen by the BURG-generated parser.
1104 //------------------------------------------------------------------------ 
1105
1106 unsigned
1107 GetInstructionsByRule(InstructionNode* subtreeRoot,
1108                       int ruleForNode,
1109                       short* nts,
1110                       TargetMachine &target,
1111                       MachineInstr** mvec)
1112 {
1113   int numInstr = 1;                     // initialize for common case
1114   bool checkCast = false;               // initialize here to use fall-through
1115   int nextRule;
1116   int forwardOperandNum = -1;
1117   
1118   for (unsigned i=0; i < MAX_INSTR_PER_VMINSTR; i++)
1119     mvec[i] = NULL;
1120   
1121   // 
1122   // Let's check for chain rules outside the switch so that we don't have
1123   // to duplicate the list of chain rule production numbers here again
1124   // 
1125   if (ThisIsAChainRule(ruleForNode))
1126     {
1127       // Chain rules have a single nonterminal on the RHS.
1128       // Get the rule that matches the RHS non-terminal and use that instead.
1129       // 
1130       assert(nts[0] && ! nts[1]
1131              && "A chain rule should have only one RHS non-terminal!");
1132       nextRule = burm_rule(subtreeRoot->state, nts[0]);
1133       nts = burm_nts[nextRule];
1134       numInstr = GetInstructionsByRule(subtreeRoot, nextRule, nts,target,mvec);
1135     }
1136   else
1137     {
1138       switch(ruleForNode) {
1139       case 1:   // stmt:   Ret
1140       case 2:   // stmt:   RetValue(reg)
1141       {         // NOTE: Prepass of register allocation is responsible
1142                 //       for moving return value to appropriate register.
1143                 // Mark the return-address register as a hidden virtual reg.
1144                 // Mark the return value   register as an implicit ref of
1145                 // the machine instruction.
1146                 // Finally put a NOP in the delay slot.
1147         ReturnInst *returnInstr =
1148           cast<ReturnInst>(subtreeRoot->getInstruction());
1149         assert(returnInstr->getOpcode() == Instruction::Ret);
1150         
1151         Instruction* returnReg = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1152                                                     returnInstr, NULL);
1153         returnInstr->getMachineInstrVec().addTempValue(returnReg);
1154         
1155         mvec[0] = new MachineInstr(JMPLRET);
1156         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1157                                       returnReg);
1158         mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1159                                    (int64_t)8);
1160         mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
1161         
1162         if (returnInstr->getReturnValue() != NULL)
1163           mvec[0]->addImplicitRef(returnInstr->getReturnValue());
1164         
1165         unsigned n = numInstr++; // delay slot
1166         mvec[n] = new MachineInstr(NOP);
1167         
1168         break;
1169       }  
1170         
1171       case 3:   // stmt:   Store(reg,reg)
1172       case 4:   // stmt:   Store(reg,ptrreg)
1173         mvec[0] = new MachineInstr(
1174                        ChooseStoreInstruction(
1175                             subtreeRoot->leftChild()->getValue()->getType()));
1176         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1177         break;
1178
1179       case 5:   // stmt:   BrUncond
1180         mvec[0] = new MachineInstr(BA);
1181         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1182                                       (Value*)NULL);
1183         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1184              cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(0));
1185         
1186         // delay slot
1187         mvec[numInstr++] = new MachineInstr(NOP);
1188         break;
1189
1190       case 206: // stmt:   BrCond(setCCconst)
1191       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1192         // If the constant is ZERO, we can use the branch-on-integer-register
1193         // instructions and avoid the SUBcc instruction entirely.
1194         // Otherwise this is just the same as case 5, so just fall through.
1195         // 
1196         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1197         assert(constNode &&
1198                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1199         Constant *constVal = cast<Constant>(constNode->getValue());
1200         bool isValidConst;
1201
1202         if ((constVal->getType()->isIntegral()
1203              || constVal->getType()->isPointerType())
1204             && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1205             && isValidConst)
1206           {
1207             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1208             
1209             // That constant is a zero after all...
1210             // Use the left child of setCC as the first argument!
1211             mvec[0] = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1212             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1213                           subtreeRoot->leftChild()->leftChild()->getValue());
1214             mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1215                                           brInst->getSuccessor(0));
1216
1217             // delay slot
1218             mvec[numInstr++] = new MachineInstr(NOP);
1219
1220             // false branch
1221             int n = numInstr++; 
1222             mvec[n] = new MachineInstr(BA);
1223             mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1224                                           (Value*) NULL);
1225             mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1226                                           brInst->getSuccessor(1));
1227             
1228             // delay slot
1229             mvec[numInstr++] = new MachineInstr(NOP);
1230             
1231             break;
1232           }
1233         // ELSE FALL THROUGH
1234       }
1235
1236       case 6:   // stmt:   BrCond(bool)
1237       { // bool => boolean was computed with some boolean operator
1238         // (SetCC, Not, ...).  We need to check whether the type was a FP,
1239         // signed int or unsigned int, and check the branching condition in
1240         // order to choose the branch to use.
1241         // If it is an integer CC, we also need to find the unique
1242         // TmpInstruction representing that CC.
1243         // 
1244         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1245         bool isFPBranch;
1246         mvec[0] = new MachineInstr(ChooseBccInstruction(subtreeRoot,
1247                                                         isFPBranch));
1248         
1249         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1250                                      brInst->getParent()->getParent(),
1251                                      isFPBranch? Type::FloatTy : Type::IntTy);
1252         
1253         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister, ccValue);
1254         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1255                                       brInst->getSuccessor(0));
1256         
1257         // delay slot
1258         mvec[numInstr++] = new MachineInstr(NOP);
1259         
1260         // false branch
1261         int n = numInstr++;
1262         mvec[n] = new MachineInstr(BA);
1263         mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1264                                       (Value*) NULL);
1265         mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1266                                       brInst->getSuccessor(1));
1267         
1268         // delay slot
1269         mvec[numInstr++] = new MachineInstr(NOP);
1270         break;
1271       }
1272         
1273       case 208: // stmt:   BrCond(boolconst)
1274       {
1275         // boolconst => boolean is a constant; use BA to first or second label
1276         Constant* constVal = 
1277           cast<Constant>(subtreeRoot->leftChild()->getValue());
1278         unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1279         
1280         mvec[0] = new MachineInstr(BA);
1281         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1282                                       (Value*) NULL);
1283         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1284           ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(dest));
1285         
1286         // delay slot
1287         mvec[numInstr++] = new MachineInstr(NOP);
1288         break;
1289       }
1290         
1291       case   8: // stmt:   BrCond(boolreg)
1292       { // boolreg   => boolean is stored in an existing register.
1293         // Just use the branch-on-integer-register instruction!
1294         // 
1295         mvec[0] = new MachineInstr(BRNZ);
1296         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1297                                       subtreeRoot->leftChild()->getValue());
1298         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1299               ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1300
1301         // delay slot
1302         mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1303
1304         // false branch
1305         int n = numInstr++;
1306         mvec[n] = new MachineInstr(BA);
1307         mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1308                                       (Value*) NULL);
1309         mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1310               ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1311         
1312         // delay slot
1313         mvec[numInstr++] = new MachineInstr(NOP);
1314         break;
1315       }  
1316       
1317       case 9:   // stmt:   Switch(reg)
1318         assert(0 && "*** SWITCH instruction is not implemented yet.");
1319         numInstr = 0;
1320         break;
1321
1322       case 10:  // reg:   VRegList(reg, reg)
1323         assert(0 && "VRegList should never be the topmost non-chain rule");
1324         break;
1325
1326       case 21:  // bool:  Not(bool):    Both these are implemented as:
1327       case 321: // reg:   BNot(reg) :        reg = reg XOR-NOT 0
1328         mvec[0] = new MachineInstr(XNOR);
1329         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1330                                       subtreeRoot->leftChild()->getValue());
1331         mvec[0]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1332         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1333                                      subtreeRoot->getValue());
1334         break;
1335
1336       case 322: // reg:   ToBoolTy(bool):
1337       case 22:  // reg:   ToBoolTy(reg):
1338       {
1339         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1340         assert(opType->isIntegral() || opType->isPointerType()
1341                || opType == Type::BoolTy);
1342         numInstr = 0;
1343         forwardOperandNum = 0;
1344         break;
1345       }
1346       
1347       case 23:  // reg:   ToUByteTy(reg)
1348       case 25:  // reg:   ToUShortTy(reg)
1349       case 27:  // reg:   ToUIntTy(reg)
1350       case 29:  // reg:   ToULongTy(reg)
1351       {
1352         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1353         assert(opType->isIntegral() ||
1354                opType->isPointerType() ||
1355                opType == Type::BoolTy && "Cast is illegal for other types");
1356         numInstr = 0;
1357         forwardOperandNum = 0;
1358         break;
1359       }
1360       
1361       case 24:  // reg:   ToSByteTy(reg)
1362       case 26:  // reg:   ToShortTy(reg)
1363       case 28:  // reg:   ToIntTy(reg)
1364       case 30:  // reg:   ToLongTy(reg)
1365       {
1366         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1367         if (opType->isIntegral()
1368             || opType->isPointerType()
1369             || opType == Type::BoolTy)
1370           {
1371             numInstr = 0;
1372             forwardOperandNum = 0;
1373           }
1374         else
1375           {
1376             // If the source operand is an FP type, the int result must be
1377             // copied from float to int register via memory!
1378             Instruction *dest = subtreeRoot->getInstruction();
1379             Value* leftVal = subtreeRoot->leftChild()->getValue();
1380             Value* destForCast;
1381             vector<MachineInstr*> minstrVec;
1382             
1383             if (opType == Type::FloatTy || opType == Type::DoubleTy)
1384               {
1385                 // Create a temporary to represent the INT register
1386                 // into which the FP value will be copied via memory.
1387                 // The type of this temporary will determine the FP
1388                 // register used: single-prec for a 32-bit int or smaller,
1389                 // double-prec for a 64-bit int.
1390                 // 
1391                 const Type* destTypeToUse =
1392                   (dest->getType() == Type::LongTy)? Type::DoubleTy
1393                                                    : Type::FloatTy;
1394                 destForCast = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1395                                                  destTypeToUse, leftVal, NULL);
1396                 dest->getMachineInstrVec().addTempValue(destForCast);
1397                 
1398                 vector<TmpInstruction*> tempVec;
1399                 target.getInstrInfo().CreateCodeToCopyFloatToInt(
1400                     dest->getParent()->getParent(),
1401                     (TmpInstruction*) destForCast, dest,
1402                     minstrVec, tempVec, target);
1403                 
1404                 for (unsigned i=0; i < tempVec.size(); ++i)
1405                   dest->getMachineInstrVec().addTempValue(tempVec[i]);
1406               }
1407             else
1408               destForCast = leftVal;
1409             
1410             MachineOpCode opCode=ChooseConvertToIntInstr(subtreeRoot, opType);
1411             assert(opCode != INVALID_OPCODE && "Expected to need conversion!");
1412             
1413             mvec[0] = new MachineInstr(opCode);
1414             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1415                                           leftVal);
1416             mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1417                                           destForCast);
1418
1419             assert(numInstr == 1 && "Should be initialized to 1 at the top");
1420             for (unsigned i=0; i < minstrVec.size(); ++i)
1421               mvec[numInstr++] = minstrVec[i];
1422           }
1423         break;
1424       }  
1425       
1426       case  31: // reg:   ToFloatTy(reg):
1427       case  32: // reg:   ToDoubleTy(reg):
1428       case 232: // reg:   ToDoubleTy(Constant):
1429         
1430         // If this instruction has a parent (a user) in the tree 
1431         // and the user is translated as an FsMULd instruction,
1432         // then the cast is unnecessary.  So check that first.
1433         // In the future, we'll want to do the same for the FdMULq instruction,
1434         // so do the check here instead of only for ToFloatTy(reg).
1435         // 
1436         if (subtreeRoot->parent() != NULL &&
1437             ((InstructionNode*) subtreeRoot->parent())->getInstruction()->getMachineInstrVec()[0]->getOpCode() == FSMULD)
1438           {
1439             numInstr = 0;
1440             forwardOperandNum = 0;
1441           }
1442         else
1443           {
1444             Value* leftVal = subtreeRoot->leftChild()->getValue();
1445             const Type* opType = leftVal->getType();
1446             MachineOpCode opCode=ChooseConvertToFloatInstr(subtreeRoot,opType);
1447             if (opCode == INVALID_OPCODE)       // no conversion needed
1448               {
1449                 numInstr = 0;
1450                 forwardOperandNum = 0;
1451               }
1452             else
1453               {
1454                 // If the source operand is a non-FP type it must be
1455                 // first copied from int to float register via memory!
1456                 Instruction *dest = subtreeRoot->getInstruction();
1457                 Value* srcForCast;
1458                 int n = 0;
1459                 if (opType != Type::FloatTy && opType != Type::DoubleTy)
1460                   {
1461                     // Create a temporary to represent the FP register
1462                     // into which the integer will be copied via memory.
1463                     // The type of this temporary will determine the FP
1464                     // register used: single-prec for a 32-bit int or smaller,
1465                     // double-prec for a 64-bit int.
1466                     // 
1467                     const Type* srcTypeToUse =
1468                       (leftVal->getType() == Type::LongTy)? Type::DoubleTy
1469                                                           : Type::FloatTy;
1470                     
1471                     srcForCast = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1472                                                     srcTypeToUse, dest, NULL);
1473                     dest->getMachineInstrVec().addTempValue(srcForCast);
1474                     
1475                     vector<MachineInstr*> minstrVec;
1476                     vector<TmpInstruction*> tempVec;
1477                     target.getInstrInfo().CreateCodeToCopyIntToFloat(
1478                          dest->getParent()->getParent(),
1479                          leftVal, (TmpInstruction*) srcForCast,
1480                          minstrVec, tempVec, target);
1481                     
1482                     for (unsigned i=0; i < minstrVec.size(); ++i)
1483                       mvec[n++] = minstrVec[i];
1484
1485                     for (unsigned i=0; i < tempVec.size(); ++i)
1486                        dest->getMachineInstrVec().addTempValue(tempVec[i]);
1487                   }
1488                 else
1489                   srcForCast = leftVal;
1490                 
1491                 MachineInstr* castI = new MachineInstr(opCode);
1492                 castI->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1493                                             srcForCast);
1494                 castI->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1495                                             dest);
1496                 mvec[n++] = castI;
1497                 numInstr = n;
1498               }
1499           }
1500         break;
1501
1502       case 19:  // reg:   ToArrayTy(reg):
1503       case 20:  // reg:   ToPointerTy(reg):
1504         numInstr = 0;
1505         forwardOperandNum = 0;
1506         break;
1507
1508       case 233: // reg:   Add(reg, Constant)
1509         mvec[0] = CreateAddConstInstruction(subtreeRoot);
1510         if (mvec[0] != NULL)
1511           break;
1512         // ELSE FALL THROUGH
1513
1514       case 33:  // reg:   Add(reg, reg)
1515         mvec[0] = new MachineInstr(ChooseAddInstruction(subtreeRoot));
1516         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1517         break;
1518
1519       case 234: // reg:   Sub(reg, Constant)
1520         mvec[0] = CreateSubConstInstruction(subtreeRoot);
1521         if (mvec[0] != NULL)
1522           break;
1523         // ELSE FALL THROUGH
1524
1525       case 34:  // reg:   Sub(reg, reg)
1526         mvec[0] = new MachineInstr(ChooseSubInstructionByType(
1527                                    subtreeRoot->getInstruction()->getType()));
1528         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1529         break;
1530
1531       case 135: // reg:   Mul(todouble, todouble)
1532         checkCast = true;
1533         // FALL THROUGH 
1534
1535       case 35:  // reg:   Mul(reg, reg)
1536         mvec[0] =new MachineInstr(ChooseMulInstruction(subtreeRoot,checkCast));
1537         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1538         break;
1539
1540       case 335: // reg:   Mul(todouble, todoubleConst)
1541         checkCast = true;
1542         // FALL THROUGH 
1543
1544       case 235: // reg:   Mul(reg, Constant)
1545         mvec[0] = CreateMulConstInstruction(target, subtreeRoot, mvec[1]);
1546         if (mvec[0] == NULL)
1547           {
1548             mvec[0] = new MachineInstr(ChooseMulInstruction(subtreeRoot,
1549                                                             checkCast));
1550             Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1551           }
1552         else
1553           if (mvec[1] != NULL)
1554             ++numInstr;
1555         break;
1556
1557       case 236: // reg:   Div(reg, Constant)
1558         mvec[0] = CreateDivConstInstruction(target, subtreeRoot, mvec[1]);
1559         if (mvec[0] != NULL)
1560           {
1561             if (mvec[1] != NULL)
1562               ++numInstr;
1563           }
1564         else
1565         // ELSE FALL THROUGH
1566
1567       case 36:  // reg:   Div(reg, reg)
1568         mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1569         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1570         break;
1571
1572       case  37: // reg:   Rem(reg, reg)
1573       case 237: // reg:   Rem(reg, Constant)
1574       {
1575         Instruction* remInstr = subtreeRoot->getInstruction();
1576         
1577         TmpInstruction* quot = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1578                                         subtreeRoot->leftChild()->getValue(),
1579                                         subtreeRoot->rightChild()->getValue());
1580         TmpInstruction* prod = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1581                                         quot,
1582                                         subtreeRoot->rightChild()->getValue());
1583         remInstr->getMachineInstrVec().addTempValue(quot); 
1584         remInstr->getMachineInstrVec().addTempValue(prod); 
1585         
1586         mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1587         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1588         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,quot);
1589         
1590         int n = numInstr++;
1591         mvec[n] = new MachineInstr(ChooseMulInstructionByType(
1592                                    subtreeRoot->getInstruction()->getType()));
1593         mvec[n]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,quot);
1594         mvec[n]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1595                                       subtreeRoot->rightChild()->getValue());
1596         mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,prod);
1597         
1598         n = numInstr++;
1599         mvec[n] = new MachineInstr(ChooseSubInstructionByType(
1600                                    subtreeRoot->getInstruction()->getType()));
1601         Set3OperandsFromInstr(mvec[n], subtreeRoot, target);
1602         mvec[n]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,prod);
1603         
1604         break;
1605       }
1606       
1607       case  38: // bool:   And(bool, bool)
1608       case 238: // bool:   And(bool, boolconst)
1609       case 338: // reg :   BAnd(reg, reg)
1610       case 538: // reg :   BAnd(reg, Constant)
1611         mvec[0] = new MachineInstr(AND);
1612         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1613         break;
1614
1615       case 138: // bool:   And(bool, not)
1616       case 438: // bool:   BAnd(bool, not)
1617         mvec[0] = new MachineInstr(ANDN);
1618         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1619         break;
1620
1621       case  39: // bool:   Or(bool, bool)
1622       case 239: // bool:   Or(bool, boolconst)
1623       case 339: // reg :   BOr(reg, reg)
1624       case 539: // reg :   BOr(reg, Constant)
1625         mvec[0] = new MachineInstr(ORN);
1626         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1627         break;
1628
1629       case 139: // bool:   Or(bool, not)
1630       case 439: // bool:   BOr(bool, not)
1631         mvec[0] = new MachineInstr(ORN);
1632         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1633         break;
1634
1635       case  40: // bool:   Xor(bool, bool)
1636       case 240: // bool:   Xor(bool, boolconst)
1637       case 340: // reg :   BXor(reg, reg)
1638       case 540: // reg :   BXor(reg, Constant)
1639         mvec[0] = new MachineInstr(XOR);
1640         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1641         break;
1642
1643       case 140: // bool:   Xor(bool, not)
1644       case 440: // bool:   BXor(bool, not)
1645         mvec[0] = new MachineInstr(XNOR);
1646         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1647         break;
1648
1649       case 41:  // boolconst:   SetCC(reg, Constant)
1650         // Check if this is an integer comparison, and
1651         // there is a parent, and the parent decided to use
1652         // a branch-on-integer-register instead of branch-on-condition-code.
1653         // If so, the SUBcc instruction is not required.
1654         // (However, we must still check for constants to be loaded from
1655         // the constant pool so that such a load can be associated with
1656         // this instruction.)
1657         // 
1658         // Otherwise this is just the same as case 42, so just fall through.
1659         // 
1660         if ((subtreeRoot->leftChild()->getValue()->getType()->isIntegral() ||
1661              subtreeRoot->leftChild()->getValue()->getType()->isPointerType())
1662             && subtreeRoot->parent() != NULL)
1663           {
1664             InstructionNode* parent = (InstructionNode*) subtreeRoot->parent();
1665             assert(parent->getNodeType() == InstrTreeNode::NTInstructionNode);
1666             const vector<MachineInstr*>&
1667               minstrVec = parent->getInstruction()->getMachineInstrVec();
1668             MachineOpCode parentOpCode;
1669             if (parent->getInstruction()->getOpcode() == Instruction::Br &&
1670                 (parentOpCode = minstrVec[0]->getOpCode()) >= BRZ &&
1671                 parentOpCode <= BRGEZ)
1672               {
1673                 numInstr = 0;           // don't forward the operand!
1674                 break;
1675               }
1676           }
1677         // ELSE FALL THROUGH
1678
1679       case 42:  // bool:   SetCC(reg, reg):
1680       {
1681         // This generates a SUBCC instruction, putting the difference in
1682         // a result register, and setting a condition code.
1683         // 
1684         // If the boolean result of the SetCC is used by anything other
1685         // than a single branch instruction, the boolean must be
1686         // computed and stored in the result register.  Otherwise, discard
1687         // the difference (by using %g0) and keep only the condition code.
1688         // 
1689         // To compute the boolean result in a register we use a conditional
1690         // move, unless the result of the SUBCC instruction can be used as
1691         // the bool!  This assumes that zero is FALSE and any non-zero
1692         // integer is TRUE.
1693         // 
1694         InstructionNode* parentNode = (InstructionNode*) subtreeRoot->parent();
1695         Instruction* setCCInstr = subtreeRoot->getInstruction();
1696         bool keepBoolVal = (parentNode == NULL ||
1697                             parentNode->getInstruction()->getOpcode()
1698                                 != Instruction::Br);
1699         bool subValIsBoolVal = setCCInstr->getOpcode() == Instruction::SetNE;
1700         bool keepSubVal = keepBoolVal && subValIsBoolVal;
1701         bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1702         
1703         bool mustClearReg;
1704         int valueToMove;
1705         MachineOpCode movOpCode = 0;
1706
1707         // Mark the 4th operand as being a CC register, and as a def
1708         // A TmpInstruction is created to represent the CC "result".
1709         // Unlike other instances of TmpInstruction, this one is used
1710         // by machine code of multiple LLVM instructions, viz.,
1711         // the SetCC and the branch.  Make sure to get the same one!
1712         // Note that we do this even for FP CC registers even though they
1713         // are explicit operands, because the type of the operand
1714         // needs to be a floating point condition code, not an integer
1715         // condition code.  Think of this as casting the bool result to
1716         // a FP condition code register.
1717         // 
1718         Value* leftVal = subtreeRoot->leftChild()->getValue();
1719         bool isFPCompare = (leftVal->getType() == Type::FloatTy || 
1720                             leftVal->getType() == Type::DoubleTy);
1721         
1722         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
1723                                      setCCInstr->getParent()->getParent(),
1724                                      isFPCompare? Type::FloatTy : Type::IntTy);
1725         setCCInstr->getMachineInstrVec().addTempValue(tmpForCC);
1726         
1727         if (! isFPCompare)
1728           {
1729             // Integer condition: dest. should be %g0 or an integer register.
1730             // If result must be saved but condition is not SetEQ then we need
1731             // a separate instruction to compute the bool result, so discard
1732             // result of SUBcc instruction anyway.
1733             // 
1734             mvec[0] = new MachineInstr(SUBcc);
1735             Set3OperandsFromInstr(mvec[0], subtreeRoot, target, ! keepSubVal);
1736             
1737             mvec[0]->SetMachineOperand(3, MachineOperand::MO_CCRegister,
1738                                           tmpForCC, /*def*/true);
1739             
1740             if (computeBoolVal)
1741               { // recompute bool using the integer condition codes
1742                 movOpCode =
1743                   ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1744               }
1745           }
1746         else
1747           {
1748             // FP condition: dest of FCMP should be some FCCn register
1749             mvec[0] = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1750             mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1751                                           tmpForCC);
1752             mvec[0]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1753                                          subtreeRoot->leftChild()->getValue());
1754             mvec[0]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1755                                         subtreeRoot->rightChild()->getValue());
1756             
1757             if (computeBoolVal)
1758               {// recompute bool using the FP condition codes
1759                 mustClearReg = true;
1760                 valueToMove = 1;
1761                 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1762               }
1763           }
1764         
1765         if (computeBoolVal)
1766           {
1767             if (mustClearReg)
1768               {// Unconditionally set register to 0
1769                int n = numInstr++;
1770                mvec[n] = new MachineInstr(SETHI);
1771                mvec[n]->SetMachineOperand(0,MachineOperand::MO_UnextendedImmed,
1772                                             (int64_t)0);
1773                mvec[n]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1774                                             setCCInstr);
1775               }
1776             
1777             // Now conditionally move `valueToMove' (0 or 1) into the register
1778             int n = numInstr++;
1779             mvec[n] = new MachineInstr(movOpCode);
1780             mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1781                                           tmpForCC);
1782             mvec[n]->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
1783                                           valueToMove);
1784             mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1785                                           setCCInstr);
1786           }
1787         break;
1788       }    
1789
1790       case 43:  // boolreg: VReg
1791       case 44:  // boolreg: Constant
1792         numInstr = 0;
1793         break;
1794
1795       case 51:  // reg:   Load(reg)
1796       case 52:  // reg:   Load(ptrreg)
1797       case 53:  // reg:   LoadIdx(reg,reg)
1798       case 54:  // reg:   LoadIdx(ptrreg,reg)
1799         mvec[0] = new MachineInstr(ChooseLoadInstruction(
1800                                      subtreeRoot->getValue()->getType()));
1801         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1802         break;
1803
1804       case 55:  // reg:   GetElemPtr(reg)
1805       case 56:  // reg:   GetElemPtrIdx(reg,reg)
1806         if (subtreeRoot->parent() != NULL)
1807           {
1808             // If the parent was a memory operation and not an array access,
1809             // the parent will fold this instruction in so generate nothing.
1810             // 
1811             Instruction* parent =
1812               cast<Instruction>(subtreeRoot->parent()->getValue());
1813             if (parent->getOpcode() == Instruction::Load ||
1814                 parent->getOpcode() == Instruction::Store ||
1815                 parent->getOpcode() == Instruction::GetElementPtr)
1816               {
1817                 // Check if the parent is an array access,
1818                 // If so, we still need to generate this instruction.
1819                 GetElementPtrInst* getElemInst =
1820                   cast<GetElementPtrInst>(subtreeRoot->getInstruction());
1821                 const PointerType* ptrType =
1822                   cast<PointerType>(getElemInst->getPointerOperand()->getType());
1823                 if (! ptrType->getElementType()->isArrayType())
1824                   {// we don't need a separate instr
1825                     numInstr = 0;               // don't forward operand!
1826                     break;
1827                   }
1828               }
1829           }
1830         // else in all other cases we need to a separate ADD instruction
1831         mvec[0] = new MachineInstr(ADD);
1832         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1833         break;
1834
1835       case 57:  // reg:  Alloca: Implement as 1 instruction:
1836       {         //          add %fp, offsetFromFP -> result
1837         Instruction* instr = subtreeRoot->getInstruction();
1838         const PointerType* instrType = (const PointerType*) instr->getType();
1839         assert(instrType->isPointerType());
1840         int tsize = (int)
1841           target.findOptimalStorageSize(instrType->getElementType());
1842         assert(tsize != 0 && "Just to check when this can happen");
1843         
1844         Method* method = instr->getParent()->getParent();
1845         MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
1846         int offsetFromFP = mcInfo.allocateLocalVar(target, instr, (unsigned int) tsize);
1847         
1848         // Create a temporary Value to hold the constant offset.
1849         // This is needed because it may not fit in the immediate field.
1850         ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1851         
1852         // Instruction 1: add %fp, offsetFromFP -> result
1853         mvec[0] = new MachineInstr(ADD);
1854         mvec[0]->SetMachineOperand(0, target.getRegInfo().getFramePointer());
1855         mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1856                                       offsetVal); 
1857         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1858                                       instr);
1859         break;
1860       }
1861         
1862       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
1863                 //      mul num, typeSz -> tmp
1864                 //      sub %sp, tmp    -> %sp
1865       {         //      add %sp, frameSizeBelowDynamicArea -> result
1866         Instruction* instr = subtreeRoot->getInstruction();
1867         const PointerType* instrType = (const PointerType*) instr->getType();
1868         assert(instrType->isPointerType() &&
1869                instrType->getElementType()->isArrayType());
1870         const Type* eltType =
1871           ((ArrayType*) instrType->getElementType())->getElementType();
1872         int tsize = (int) target.findOptimalStorageSize(eltType);
1873         
1874         assert(tsize != 0 && "Just to check when this can happen");
1875         
1876         // Create a temporary Value to hold the constant type-size
1877         ConstantSInt* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1878         
1879         // Create a temporary Value to hold the constant offset from SP
1880         Method* method = instr->getParent()->getParent();
1881         bool ignore;                    // we don't need this 
1882         ConstantSInt* dynamicAreaOffset = ConstantSInt::get(Type::IntTy,
1883           target.getFrameInfo().getDynamicAreaOffset(MachineCodeForMethod::get(method),
1884                                                      ignore));
1885         
1886         // Create a temporary value to hold `tmp'
1887         Instruction* tmpInstr = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1888                                           subtreeRoot->leftChild()->getValue(),
1889                                           NULL /*could insert tsize here*/);
1890         subtreeRoot->getInstruction()->getMachineInstrVec().addTempValue(tmpInstr);
1891         
1892         // Instruction 1: mul numElements, typeSize -> tmp
1893         mvec[0] = new MachineInstr(MULX);
1894         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1895                                       subtreeRoot->leftChild()->getValue());
1896         mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1897                                       tsizeVal);
1898         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1899                                       tmpInstr);
1900         
1901         // Instruction 2: sub %sp, tmp -> %sp
1902         numInstr++;
1903         mvec[1] = new MachineInstr(SUB);
1904         mvec[1]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1905         mvec[1]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1906                                       tmpInstr);
1907         mvec[1]->SetMachineOperand(2, target.getRegInfo().getStackPointer());
1908         
1909         // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1910         numInstr++;
1911         mvec[2] = new MachineInstr(ADD);
1912         mvec[2]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1913         mvec[2]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1914                                       dynamicAreaOffset);
1915         mvec[2]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,instr);
1916         break;
1917       }
1918
1919       case 61:  // reg:   Call
1920       {         // Generate a call-indirect (i.e., jmpl) for now to expose
1921                 // the potential need for registers.  If an absolute address
1922                 // is available, replace this with a CALL instruction.
1923                 // Mark both the indirection register and the return-address
1924                 // register as hidden virtual registers.
1925                 // Also, mark the operands of the Call and return value (if
1926                 // any) as implicit operands of the CALL machine instruction.
1927                 // 
1928         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
1929         Value *callee = callInstr->getCalledValue();
1930         
1931         Instruction* retAddrReg = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1932                                                      callInstr, NULL);
1933         
1934         // Note temporary values in the machineInstrVec for the VM instr.
1935         //
1936         // WARNING: Operands 0..N-1 must go in slots 0..N-1 of implicitUses.
1937         //          The result value must go in slot N.  This is assumed
1938         //          in register allocation.
1939         // 
1940         callInstr->getMachineInstrVec().addTempValue(retAddrReg);
1941         
1942         
1943         // Generate the machine instruction and its operands.
1944         // Use CALL for direct function calls; this optimistically assumes
1945         // the PC-relative address fits in the CALL address field (22 bits).
1946         // Use JMPL for indirect calls.
1947         // 
1948         if (callee->getValueType() == Value::MethodVal)
1949           { // direct function call
1950             mvec[0] = new MachineInstr(CALL);
1951             mvec[0]->SetMachineOperand(0, MachineOperand::MO_PCRelativeDisp,
1952                                           callee);
1953           } 
1954         else
1955           { // indirect function call
1956             mvec[0] = new MachineInstr(JMPLCALL);
1957             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1958                                           callee);
1959             mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1960                                           (int64_t) 0);
1961             mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1962                                           retAddrReg);
1963           }
1964         
1965         // Add the call operands and return value as implicit refs
1966         for (unsigned i=0, N=callInstr->getNumOperands(); i < N; ++i)
1967           if (callInstr->getOperand(i) != callee)
1968             mvec[0]->addImplicitRef(callInstr->getOperand(i));
1969         
1970         if (callInstr->getType() != Type::VoidTy)
1971           mvec[0]->addImplicitRef(callInstr, /*isDef*/ true);
1972         
1973         // For the CALL instruction, the ret. addr. reg. is also implicit
1974         if (callee->getValueType() == Value::MethodVal)
1975           mvec[0]->addImplicitRef(retAddrReg, /*isDef*/ true);
1976         
1977         mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1978         break;
1979       }
1980
1981       case 62:  // reg:   Shl(reg, reg)
1982       { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1983         assert(opType->isIntegral()
1984                || opType == Type::BoolTy
1985                || opType->isPointerType()&& "Shl unsupported for other types");
1986         mvec[0] = new MachineInstr((opType == Type::LongTy)? SLLX : SLL);
1987         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1988         break;
1989       }
1990       
1991       case 63:  // reg:   Shr(reg, reg)
1992       { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1993         assert(opType->isIntegral()
1994                || opType == Type::BoolTy
1995                || opType->isPointerType() &&"Shr unsupported for other types");
1996         mvec[0] = new MachineInstr((opType->isSigned()
1997                                     ? ((opType == Type::LongTy)? SRAX : SRA)
1998                                     : ((opType == Type::LongTy)? SRLX : SRL)));
1999         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2000         break;
2001       }
2002       
2003       case 64:  // reg:   Phi(reg,reg)
2004         numInstr = 0;                   // don't forward the value
2005         break;
2006 #undef NEED_PHI_MACHINE_INSTRS
2007 #ifdef NEED_PHI_MACHINE_INSTRS
2008       {         // This instruction has variable #operands, so resultPos is 0.
2009         Instruction* phi = subtreeRoot->getInstruction();
2010         mvec[0] = new MachineInstr(PHI, 1 + phi->getNumOperands());
2011         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2012                                       subtreeRoot->getValue());
2013         for (unsigned i=0, N=phi->getNumOperands(); i < N; i++)
2014           mvec[0]->SetMachineOperand(i+1, MachineOperand::MO_VirtualRegister,
2015                                           phi->getOperand(i));
2016         break;
2017       }  
2018 #endif // NEED_PHI_MACHINE_INSTRS
2019       
2020       case 71:  // reg:     VReg
2021       case 72:  // reg:     Constant
2022         numInstr = 0;                   // don't forward the value
2023         break;
2024
2025       default:
2026         assert(0 && "Unrecognized BURG rule");
2027         numInstr = 0;
2028         break;
2029       }
2030     }
2031   
2032   if (forwardOperandNum >= 0)
2033     { // We did not generate a machine instruction but need to use operand.
2034       // If user is in the same tree, replace Value in its machine operand.
2035       // If not, insert a copy instruction which should get coalesced away
2036       // by register allocation.
2037       if (subtreeRoot->parent() != NULL)
2038         ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2039       else
2040         {
2041           vector<MachineInstr*> minstrVec;
2042           target.getInstrInfo().CreateCopyInstructionsByType(target,
2043                 subtreeRoot->getInstruction()->getOperand(forwardOperandNum),
2044                 subtreeRoot->getInstruction(), minstrVec);
2045           assert(minstrVec.size() > 0);
2046           for (unsigned i=0; i < minstrVec.size(); ++i)
2047             mvec[numInstr++] = minstrVec[i];
2048         }
2049     }
2050   
2051   return numInstr;
2052 }
2053
2054