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