Fix dumb bug in alignment adjustment code!
[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/Support/MathExtras.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iOther.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/Method.h"
26 #include "llvm/ConstPoolVals.h"
27 #include <math.h>
28
29 //******************** Internal Data Declarations ************************/
30
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 vector<ConstPoolVal*>& 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  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(TMP_INSTRUCTION_OPCODE, ccType, boolVal, NULL);
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<ConstPoolVal>(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 = ((ConstPoolFP*) 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<ConstPoolVal>(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 = ((ConstPoolFP*) 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   bool needNeg = false;
525
526   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
527   assert(isa<ConstPoolVal>(constOp));
528   
529   // Cases worth optimizing are:
530   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
531   // (2) Multiply by 2^x for integer types: replace with Shift
532   // 
533   const Type* resultType = instrNode->getInstruction()->getType();
534   
535   if (resultType->isIntegral() || resultType->isPointerType())
536     {
537       unsigned pow;
538       bool isValidConst;
539       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
540       if (isValidConst)
541         {
542           bool needNeg = false;
543           if (C < 0)
544             {
545               needNeg = true;
546               C = -C;
547             }
548           
549           if (C == 0 || C == 1)
550             {
551               minstr = new MachineInstr(ADD);
552               
553               if (C == 0)
554                 minstr->SetMachineOperand(0,
555                                           target.getRegInfo().getZeroRegNum());
556               else
557                 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
558                                           instrNode->leftChild()->getValue());
559               minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
560             }
561           else if (IsPowerOf2(C, pow))
562             {
563               minstr = new MachineInstr((resultType == Type::LongTy)
564                                         ? SLLX : SLL);
565               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
566                                            instrNode->leftChild()->getValue());
567               minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
568                                            pow);
569             }
570           
571           if (minstr && needNeg)
572             { // insert <reg = SUB 0, reg> after the instr to flip the sign
573               getMinstr2 = CreateIntNegInstruction(target,
574                                                    instrNode->getValue());
575             }
576         }
577     }
578   else
579     {
580       if (resultType == Type::FloatTy ||
581           resultType == Type::DoubleTy)
582         {
583           double dval = ((ConstPoolFP*) constOp)->getValue();
584           if (fabs(dval) == 1)
585             {
586               bool needNeg = (dval < 0);
587               
588               MachineOpCode opCode = needNeg
589                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
590                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
591               
592               minstr = new MachineInstr(opCode);
593               minstr->SetMachineOperand(0,
594                                         MachineOperand::MO_VirtualRegister,
595                                         instrNode->leftChild()->getValue());
596             } 
597         }
598     }
599   
600   if (minstr != NULL)
601     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
602                               instrNode->getValue());   
603   
604   return minstr;
605 }
606
607
608 // Generate a divide instruction for Div or Rem.
609 // For Rem, this assumes that the operand type will be signed if the result
610 // type is signed.  This is correct because they must have the same sign.
611 // 
612 static inline MachineOpCode 
613 ChooseDivInstruction(TargetMachine &target,
614                      const InstructionNode* instrNode)
615 {
616   MachineOpCode opCode = INVALID_OPCODE;
617   
618   const Type* resultType = instrNode->getInstruction()->getType();
619   
620   if (resultType->isIntegral())
621     opCode = resultType->isSigned()? SDIVX : UDIVX;
622   else
623     switch(resultType->getPrimitiveID())
624       {
625       case Type::FloatTyID:  opCode = FDIVS; break;
626       case Type::DoubleTyID: opCode = FDIVD; break;
627       default: assert(0 && "Invalid type for DIV instruction"); break; 
628       }
629   
630   return opCode;
631 }
632
633
634 static inline MachineInstr* 
635 CreateDivConstInstruction(TargetMachine &target,
636                           const InstructionNode* instrNode,
637                           MachineInstr*& getMinstr2)
638 {
639   MachineInstr* minstr = NULL;
640   getMinstr2 = NULL;
641   
642   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
643   assert(isa<ConstPoolVal>(constOp));
644   
645   // Cases worth optimizing are:
646   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
647   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
648   // 
649   const Type* resultType = instrNode->getInstruction()->getType();
650   
651   if (resultType->isIntegral())
652     {
653       unsigned pow;
654       bool isValidConst;
655       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
656       if (isValidConst)
657         {
658           bool needNeg = false;
659           if (C < 0)
660             {
661               needNeg = true;
662               C = -C;
663             }
664           
665           if (C == 1)
666             {
667               minstr = new MachineInstr(ADD);
668               minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
669                                           instrNode->leftChild()->getValue());
670               minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
671             }
672           else if (IsPowerOf2(C, pow))
673             {
674               MachineOpCode opCode= ((resultType->isSigned())
675                                      ? (resultType==Type::LongTy)? SRAX : SRA
676                                      : (resultType==Type::LongTy)? SRLX : SRL);
677               minstr = new MachineInstr(opCode);
678               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
679                                            instrNode->leftChild()->getValue());
680               minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
681                                            pow);
682             }
683           
684           if (minstr && needNeg)
685             { // insert <reg = SUB 0, reg> after the instr to flip the sign
686               getMinstr2 = CreateIntNegInstruction(target,
687                                                    instrNode->getValue());
688             }
689         }
690     }
691   else
692     {
693       if (resultType == Type::FloatTy ||
694           resultType == Type::DoubleTy)
695         {
696           double dval = ((ConstPoolFP*) constOp)->getValue();
697           if (fabs(dval) == 1)
698             {
699               bool needNeg = (dval < 0);
700               
701               MachineOpCode opCode = needNeg
702                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
703                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
704               
705               minstr = new MachineInstr(opCode);
706               minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
707                                            instrNode->leftChild()->getValue());
708             } 
709         }
710     }
711   
712   if (minstr != NULL)
713     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
714                               instrNode->getValue());   
715   
716   return minstr;
717 }
718
719
720 //------------------------------------------------------------------------ 
721 // Function SetOperandsForMemInstr
722 //
723 // Choose addressing mode for the given load or store instruction.
724 // Use [reg+reg] if it is an indexed reference, and the index offset is
725 //               not a constant or if it cannot fit in the offset field.
726 // Use [reg+offset] in all other cases.
727 // 
728 // This assumes that all array refs are "lowered" to one of these forms:
729 //      %x = load (subarray*) ptr, constant     ; single constant offset
730 //      %x = load (subarray*) ptr, offsetVal    ; single non-constant offset
731 // Generally, this should happen via strength reduction + LICM.
732 // Also, strength reduction should take care of using the same register for
733 // the loop index variable and an array index, when that is profitable.
734 //------------------------------------------------------------------------ 
735
736 static void
737 SetOperandsForMemInstr(MachineInstr* minstr,
738                        const InstructionNode* vmInstrNode,
739                        const TargetMachine& target)
740 {
741   MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
742   
743   // Variables to hold the index vector, ptr value, and offset value.
744   // The major work here is to extract these for all 3 instruction types
745   // and then call the common function SetMemOperands_Internal().
746   // 
747   const vector<ConstPoolVal*>* idxVec = &memInst->getIndices();
748   vector<ConstPoolVal*>* newIdxVec = NULL;
749   Value* ptrVal;
750   Value* arrayOffsetVal = NULL;
751   
752   // Test if a GetElemPtr instruction is being folded into this mem instrn.
753   // If so, it will be in the left child for Load and GetElemPtr,
754   // and in the right child for Store instructions.
755   // 
756   InstrTreeNode* ptrChild = (vmInstrNode->getOpLabel() == Instruction::Store
757                              ? vmInstrNode->rightChild()
758                              : vmInstrNode->leftChild()); 
759   
760   if (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
761       ptrChild->getOpLabel() == GetElemPtrIdx)
762     {
763       // There is a GetElemPtr instruction and there may be a chain of
764       // more than one.  Use the pointer value of the last one in the chain.
765       // Fold the index vectors from the entire chain and from the mem
766       // instruction into one single index vector.
767       // Finally, we never fold for an array instruction so make that NULL.
768       
769       newIdxVec = new vector<ConstPoolVal*>;
770       ptrVal = FoldGetElemChain((InstructionNode*) ptrChild, *newIdxVec);
771       
772       newIdxVec->insert(newIdxVec->end(), idxVec->begin(), idxVec->end());
773       idxVec = newIdxVec;
774       
775       assert(! ((PointerType*)ptrVal->getType())->getValueType()->isArrayType()
776              && "GetElemPtr cannot be folded into array refs in selection");
777     }
778   else
779     {
780       // There is no GetElemPtr instruction.
781       // Use the pointer value and the index vector from the Mem instruction.
782       // If it is an array reference, get the array offset value.
783       // 
784       ptrVal = memInst->getPtrOperand();
785
786       const Type* opType =
787         ((const PointerType*) ptrVal->getType())->getValueType();
788       if (opType->isArrayType())
789         {
790           assert((memInst->getNumOperands()
791                   == (unsigned) 1 + memInst->getFirstOffsetIdx())
792                  && "Array refs must be lowered before Instruction Selection");
793           
794           arrayOffsetVal = memInst->getOperand(memInst->getFirstOffsetIdx());
795         }
796     }
797   
798   SetMemOperands_Internal(minstr, vmInstrNode, ptrVal, arrayOffsetVal,
799                           *idxVec, target);
800   
801   if (newIdxVec != NULL)
802     delete newIdxVec;
803 }
804
805
806 static void
807 SetMemOperands_Internal(MachineInstr* minstr,
808                         const InstructionNode* vmInstrNode,
809                         Value* ptrVal,
810                         Value* arrayOffsetVal,
811                         const vector<ConstPoolVal*>& idxVec,
812                         const TargetMachine& target)
813 {
814   MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
815   
816   // Initialize so we default to storing the offset in a register.
817   int64_t smallConstOffset = 0;
818   Value* valueForRegOffset = NULL;
819   MachineOperand::MachineOperandType offsetOpType =MachineOperand::MO_VirtualRegister;
820
821   // Check if there is an index vector and if so, if it translates to
822   // a small enough constant to fit in the immediate-offset field.
823   // 
824   if (idxVec.size() > 0)
825     {
826       bool isConstantOffset = false;
827       unsigned offset = 0;
828       
829       const PointerType* ptrType = (PointerType*) ptrVal->getType();
830       
831       if (ptrType->getValueType()->isStructType())
832         {
833           // the offset is always constant for structs
834           isConstantOffset = true;
835           
836           // Compute the offset value using the index vector
837           offset = target.DataLayout.getIndexedOffset(ptrType, idxVec);
838         }
839       else
840         {
841           // It must be an array ref.  Check if the offset is a constant,
842           // and that the indexing has been lowered to a single offset.
843           // 
844           assert(ptrType->getValueType()->isArrayType());
845           assert(arrayOffsetVal != NULL
846                  && "Expect to be given Value* for array offsets");
847           
848           if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(arrayOffsetVal))
849             {
850               isConstantOffset = true;  // always constant for structs
851               assert(arrayOffsetVal->getType()->isIntegral());
852               offset = (CPV->getType()->isSigned()
853                         ? ((ConstPoolSInt*)CPV)->getValue()
854                         : (int64_t) ((ConstPoolUInt*)CPV)->getValue());
855             }
856           else
857             {
858               valueForRegOffset = arrayOffsetVal;
859             }
860         }
861       
862       if (isConstantOffset)
863         {
864           // create a virtual register for the constant
865           valueForRegOffset = ConstPoolSInt::get(Type::IntTy, offset);
866         }
867     }
868   else
869     {
870       offsetOpType = MachineOperand::MO_SignExtendedImmed;
871       smallConstOffset = 0;
872     }
873   
874   // Operand 0 is value for STORE, ptr for LOAD or GET_ELEMENT_PTR
875   // It is the left child in the instruction tree in all cases.
876   Value* leftVal = vmInstrNode->leftChild()->getValue();
877   minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister, leftVal);
878   
879   // Operand 1 is ptr for STORE, offset for LOAD or GET_ELEMENT_PTR
880   // Operand 2 is offset for STORE, result reg for LOAD or GET_ELEMENT_PTR
881   //
882   unsigned offsetOpNum = (memInst->getOpcode() == Instruction::Store)? 2 : 1;
883   if (offsetOpType == MachineOperand::MO_VirtualRegister)
884     {
885       assert(valueForRegOffset != NULL);
886       minstr->SetMachineOperand(offsetOpNum, offsetOpType, valueForRegOffset); 
887     }
888   else
889     minstr->SetMachineOperand(offsetOpNum, offsetOpType, smallConstOffset);
890   
891   if (memInst->getOpcode() == Instruction::Store)
892     minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, ptrVal);
893   else
894     minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
895                                  vmInstrNode->getValue());
896 }
897
898
899 // 
900 // Substitute operand `operandNum' of the instruction in node `treeNode'
901 // in place of the use(s) of that instruction in node `parent'.
902 // Check both explicit and implicit operands!
903 // 
904 static void
905 ForwardOperand(InstructionNode* treeNode,
906                InstrTreeNode*   parent,
907                int operandNum)
908 {
909   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
910   
911   Instruction* unusedOp = treeNode->getInstruction();
912   Value* fwdOp = unusedOp->getOperand(operandNum);
913
914   // The parent itself may be a list node, so find the real parent instruction
915   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
916     {
917       parent = parent->parent();
918       assert(parent && "ERROR: Non-instruction node has no parent in tree.");
919     }
920   InstructionNode* parentInstrNode = (InstructionNode*) parent;
921   
922   Instruction* userInstr = parentInstrNode->getInstruction();
923   MachineCodeForVMInstr& mvec = userInstr->getMachineInstrVec();
924   for (unsigned i=0, N=mvec.size(); i < N; i++)
925     {
926       MachineInstr* minstr = mvec[i];
927       
928       for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i)
929         {
930           const MachineOperand& mop = minstr->getOperand(i);
931           if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
932               mop.getVRegValue() == unusedOp)
933             {
934               minstr->SetMachineOperand(i, MachineOperand::MO_VirtualRegister,
935                                            fwdOp);
936             }
937         }
938       
939       for (unsigned i=0, numOps=minstr->getNumImplicitRefs(); i < numOps; ++i)
940         if (minstr->getImplicitRef(i) == unusedOp)
941           minstr->setImplicitRef(i, fwdOp, minstr->implicitRefIsDefined(i));
942     }
943 }
944
945
946 void
947 CreateCopyInstructionsByType(const TargetMachine& target,
948                              Value* src,
949                              Instruction* dest,
950                              vector<MachineInstr*>& minstrVec)
951 {
952   bool loadConstantToReg = false;
953   
954   const Type* resultType = dest->getType();
955   
956   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
957   if (opCode == INVALID_OPCODE)
958     {
959       assert(0 && "Unsupported result type in CreateCopyInstructionsByType()");
960       return;
961     }
962   
963   // if `src' is a constant that doesn't fit in the immed field or if it is
964   // a global variable (i.e., a constant address), generate a load
965   // instruction instead of an add
966   // 
967   if (isa<ConstPoolVal>(src))
968     {
969       unsigned int machineRegNum;
970       int64_t immedValue;
971       MachineOperand::MachineOperandType opType =
972         ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
973                          machineRegNum, immedValue);
974       
975       if (opType == MachineOperand::MO_VirtualRegister)
976         loadConstantToReg = true;
977     }
978   else if (isa<GlobalValue>(src))
979     loadConstantToReg = true;
980   
981   if (loadConstantToReg)
982     { // `src' is constant and cannot fit in immed field for the ADD
983       // Insert instructions to "load" the constant into a register
984       vector<TmpInstruction*> tempVec;
985       target.getInstrInfo().CreateCodeToLoadConst(src,dest,minstrVec,tempVec);
986       for (unsigned i=0; i < tempVec.size(); i++)
987         dest->getMachineInstrVec().addTempValue(tempVec[i]);
988     }
989   else
990     { // Create the appropriate add instruction.
991       // Make `src' the second operand, in case it is a constant
992       // Use (unsigned long) 0 for a NULL pointer value.
993       // 
994       const Type* nullValueType =
995         (resultType->getPrimitiveID() == Type::PointerTyID)? Type::ULongTy
996                                                            : resultType;
997       MachineInstr* minstr = new MachineInstr(opCode);
998       minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
999                                 ConstPoolVal::getNullConstant(nullValueType));
1000       minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, src);
1001       minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, dest);
1002       minstrVec.push_back(minstr);
1003     }
1004 }
1005
1006
1007 //******************* Externally Visible Functions *************************/
1008
1009
1010 //------------------------------------------------------------------------ 
1011 // External Function: GetInstructionsForProlog
1012 // External Function: GetInstructionsForEpilog
1013 //
1014 // Purpose:
1015 //   Create prolog and epilog code for procedure entry and exit
1016 //------------------------------------------------------------------------ 
1017
1018 extern unsigned
1019 GetInstructionsForProlog(BasicBlock* entryBB,
1020                          TargetMachine &target,
1021                          MachineInstr** mvec)
1022 {
1023   int64_t s0=0;                // used to avoid overloading ambiguity below
1024   
1025   const MachineFrameInfo& frameInfo = target.getFrameInfo();
1026   
1027   // The second operand is the stack size. If it does not fit in the
1028   // immediate field, we either have to find an unused register in the
1029   // caller's window or move some elements to the dynamically allocated
1030   // area of the stack frame (just above save area and method args).
1031   Method* method = entryBB->getParent();
1032   MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
1033   unsigned int staticStackSize = mcInfo.getStaticStackSize();
1034   
1035   if (staticStackSize < (unsigned) frameInfo.getMinStackFrameSize())
1036     staticStackSize = (unsigned) frameInfo.getMinStackFrameSize();
1037   
1038   if (unsigned padsz = (staticStackSize %
1039                         (unsigned) frameInfo.getStackFrameSizeAlignment()))
1040     staticStackSize += frameInfo.getStackFrameSizeAlignment() - padsz;
1041   
1042   assert(target.getInstrInfo().constantFitsInImmedField(SAVE, staticStackSize)
1043          && "Stack size too large for immediate field of SAVE instruction. Need additional work as described in the comment above");
1044   
1045   mvec[0] = new MachineInstr(SAVE);
1046   mvec[0]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1047   mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1048                                 - (int) staticStackSize);
1049   mvec[0]->SetMachineOperand(2, target.getRegInfo().getStackPointer());
1050   
1051   return 1;
1052 }
1053
1054
1055 extern unsigned
1056 GetInstructionsForEpilog(BasicBlock* anExitBB,
1057                          TargetMachine &target,
1058                          MachineInstr** mvec)
1059 {
1060   int64_t s0=0;                // used to avoid overloading ambiguity below
1061   
1062   mvec[0] = new MachineInstr(RESTORE);
1063   mvec[0]->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
1064   mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed, s0);
1065   mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
1066   
1067   return 1;
1068 }
1069
1070
1071 //------------------------------------------------------------------------ 
1072 // External Function: ThisIsAChainRule
1073 //
1074 // Purpose:
1075 //   Check if a given BURG rule is a chain rule.
1076 //------------------------------------------------------------------------ 
1077
1078 extern bool
1079 ThisIsAChainRule(int eruleno)
1080 {
1081   switch(eruleno)
1082     {
1083     case 111:   // stmt:  reg
1084     case 113:   // stmt:  bool
1085     case 123:
1086     case 124:
1087     case 125:
1088     case 126:
1089     case 127:
1090     case 128:
1091     case 129:
1092     case 130:
1093     case 131:
1094     case 132:
1095     case 133:
1096     case 155:
1097     case 221:
1098     case 222:
1099     case 241:
1100     case 242:
1101     case 243:
1102     case 244:
1103       return true; break;
1104       
1105     default:
1106       return false; break;
1107     }
1108 }
1109
1110
1111 //------------------------------------------------------------------------ 
1112 // External Function: GetInstructionsByRule
1113 //
1114 // Purpose:
1115 //   Choose machine instructions for the SPARC according to the
1116 //   patterns chosen by the BURG-generated parser.
1117 //------------------------------------------------------------------------ 
1118
1119 unsigned
1120 GetInstructionsByRule(InstructionNode* subtreeRoot,
1121                       int ruleForNode,
1122                       short* nts,
1123                       TargetMachine &target,
1124                       MachineInstr** mvec)
1125 {
1126   int numInstr = 1;                     // initialize for common case
1127   bool checkCast = false;               // initialize here to use fall-through
1128   int nextRule;
1129   int forwardOperandNum = -1;
1130   int64_t s0=0, s8=8;                   // variables holding constants to avoid
1131   uint64_t u0=0;                        // overloading ambiguities below
1132   
1133   for (unsigned i=0; i < MAX_INSTR_PER_VMINSTR; i++)
1134     mvec[i] = NULL;
1135   
1136   // 
1137   // Let's check for chain rules outside the switch so that we don't have
1138   // to duplicate the list of chain rule production numbers here again
1139   // 
1140   if (ThisIsAChainRule(ruleForNode))
1141     {
1142       // Chain rules have a single nonterminal on the RHS.
1143       // Get the rule that matches the RHS non-terminal and use that instead.
1144       // 
1145       assert(nts[0] && ! nts[1]
1146              && "A chain rule should have only one RHS non-terminal!");
1147       nextRule = burm_rule(subtreeRoot->state, nts[0]);
1148       nts = burm_nts[nextRule];
1149       numInstr = GetInstructionsByRule(subtreeRoot, nextRule, nts,target,mvec);
1150     }
1151   else
1152     {
1153       switch(ruleForNode) {
1154       case 1:   // stmt:   Ret
1155       case 2:   // stmt:   RetValue(reg)
1156       {         // NOTE: Prepass of register allocation is responsible
1157                 //       for moving return value to appropriate register.
1158                 // Mark the return-address register as a hidden virtual reg.
1159                 // Mark the return value   register as an implicit ref of
1160                 // the machine instruction.
1161                 // Finally put a NOP in the delay slot.
1162         ReturnInst* returnInstr = (ReturnInst*) subtreeRoot->getInstruction();
1163         assert(returnInstr->getOpcode() == Instruction::Ret);
1164         Method* method = returnInstr->getParent()->getParent();
1165         
1166         Instruction* returnReg = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1167                                                     returnInstr, NULL);
1168         returnInstr->getMachineInstrVec().addTempValue(returnReg);
1169         
1170         mvec[0] = new MachineInstr(JMPLRET);
1171         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1172                                       returnReg);
1173         mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,s8);
1174         mvec[0]->SetMachineOperand(2, target.getRegInfo().getZeroRegNum());
1175         
1176         if (returnInstr->getReturnValue() != NULL)
1177           mvec[0]->addImplicitRef(returnInstr->getReturnValue());
1178         
1179         unsigned n = numInstr++; // delay slot
1180         mvec[n] = new MachineInstr(NOP);
1181         
1182         break;
1183       }  
1184         
1185       case 3:   // stmt:   Store(reg,reg)
1186       case 4:   // stmt:   Store(reg,ptrreg)
1187         mvec[0] = new MachineInstr(
1188                        ChooseStoreInstruction(
1189                             subtreeRoot->leftChild()->getValue()->getType()));
1190         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1191         break;
1192
1193       case 5:   // stmt:   BrUncond
1194         mvec[0] = new MachineInstr(BA);
1195         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1196                                       (Value*)NULL);
1197         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1198               ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1199         
1200         // delay slot
1201         mvec[numInstr++] = new MachineInstr(NOP);
1202         break;
1203
1204       case 206: // stmt:   BrCond(setCCconst)
1205       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1206         // If the constant is ZERO, we can use the branch-on-integer-register
1207         // instructions and avoid the SUBcc instruction entirely.
1208         // Otherwise this is just the same as case 5, so just fall through.
1209         // 
1210         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1211         assert(constNode &&
1212                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1213         ConstPoolVal* constVal = (ConstPoolVal*) constNode->getValue();
1214         bool isValidConst;
1215
1216         if ((constVal->getType()->isIntegral()
1217              || constVal->getType()->isPointerType())
1218             && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1219             && isValidConst)
1220           {
1221             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1222             
1223             // That constant is a zero after all...
1224             // Use the left child of setCC as the first argument!
1225             mvec[0] = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1226             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1227                           subtreeRoot->leftChild()->leftChild()->getValue());
1228             mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1229                                           brInst->getSuccessor(0));
1230
1231             // delay slot
1232             mvec[numInstr++] = new MachineInstr(NOP);
1233
1234             // false branch
1235             int n = numInstr++; 
1236             mvec[n] = new MachineInstr(BA);
1237             mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1238                                           (Value*) NULL);
1239             mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1240                                           brInst->getSuccessor(1));
1241             
1242             // delay slot
1243             mvec[numInstr++] = new MachineInstr(NOP);
1244             
1245             break;
1246           }
1247         // ELSE FALL THROUGH
1248       }
1249
1250       case 6:   // stmt:   BrCond(bool)
1251       { // bool => boolean was computed with some boolean operator
1252         // (SetCC, Not, ...).  We need to check whether the type was a FP,
1253         // signed int or unsigned int, and check the branching condition in
1254         // order to choose the branch to use.
1255         // If it is an integer CC, we also need to find the unique
1256         // TmpInstruction representing that CC.
1257         // 
1258         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1259         bool isFPBranch;
1260         mvec[0] = new MachineInstr(ChooseBccInstruction(subtreeRoot,
1261                                                         isFPBranch));
1262         
1263         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1264                                      brInst->getParent()->getParent(),
1265                                      isFPBranch? Type::FloatTy : Type::IntTy);
1266         
1267         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister, ccValue);
1268         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1269                                       brInst->getSuccessor(0));
1270         
1271         // delay slot
1272         mvec[numInstr++] = new MachineInstr(NOP);
1273         
1274         // false branch
1275         int n = numInstr++;
1276         mvec[n] = new MachineInstr(BA);
1277         mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1278                                       (Value*) NULL);
1279         mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1280                                       brInst->getSuccessor(1));
1281         
1282         // delay slot
1283         mvec[numInstr++] = new MachineInstr(NOP);
1284         break;
1285       }
1286         
1287       case 208: // stmt:   BrCond(boolconst)
1288       {
1289         // boolconst => boolean is a constant; use BA to first or second label
1290         ConstPoolVal* constVal = 
1291           cast<ConstPoolVal>(subtreeRoot->leftChild()->getValue());
1292         unsigned dest = ((ConstPoolBool*) constVal)->getValue()? 0 : 1;
1293         
1294         mvec[0] = new MachineInstr(BA);
1295         mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1296                                       (Value*) NULL);
1297         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1298           ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(dest));
1299         
1300         // delay slot
1301         mvec[numInstr++] = new MachineInstr(NOP);
1302         break;
1303       }
1304         
1305       case   8: // stmt:   BrCond(boolreg)
1306       { // boolreg   => boolean is stored in an existing register.
1307         // Just use the branch-on-integer-register instruction!
1308         // 
1309         mvec[0] = new MachineInstr(BRNZ);
1310         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1311                                       subtreeRoot->leftChild()->getValue());
1312         mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1313               ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1314
1315         // delay slot
1316         mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1317
1318         // false branch
1319         int n = numInstr++;
1320         mvec[n] = new MachineInstr(BA);
1321         mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1322                                       (Value*) NULL);
1323         mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1324               ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1325         
1326         // delay slot
1327         mvec[numInstr++] = new MachineInstr(NOP);
1328         break;
1329       }  
1330       
1331       case 9:   // stmt:   Switch(reg)
1332         assert(0 && "*** SWITCH instruction is not implemented yet.");
1333         numInstr = 0;
1334         break;
1335
1336       case 10:  // reg:   VRegList(reg, reg)
1337         assert(0 && "VRegList should never be the topmost non-chain rule");
1338         break;
1339
1340       case 21:  // bool:  Not(bool):    Both these are implemented as:
1341       case 321: // reg:   BNot(reg) :        reg = reg XOR-NOT 0
1342         mvec[0] = new MachineInstr(XNOR);
1343         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1344                                       subtreeRoot->leftChild()->getValue());
1345         mvec[0]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1346         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1347                                      subtreeRoot->getValue());
1348         break;
1349
1350       case 322: // reg:   ToBoolTy(bool):
1351       case 22:  // reg:   ToBoolTy(reg):
1352       {
1353         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1354         assert(opType->isIntegral() || opType->isPointerType()
1355                || opType == Type::BoolTy);
1356         numInstr = 0;
1357         forwardOperandNum = 0;
1358         break;
1359       }
1360       
1361       case 23:  // reg:   ToUByteTy(reg)
1362       case 25:  // reg:   ToUShortTy(reg)
1363       case 27:  // reg:   ToUIntTy(reg)
1364       case 29:  // reg:   ToULongTy(reg)
1365       {
1366         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1367         assert(opType->isIntegral() ||
1368                opType->isPointerType() ||
1369                opType == Type::BoolTy && "Cast is illegal for other types");
1370         numInstr = 0;
1371         forwardOperandNum = 0;
1372         break;
1373       }
1374       
1375       case 24:  // reg:   ToSByteTy(reg)
1376       case 26:  // reg:   ToShortTy(reg)
1377       case 28:  // reg:   ToIntTy(reg)
1378       case 30:  // reg:   ToLongTy(reg)
1379       {
1380         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1381         if (opType->isIntegral()
1382             || opType->isPointerType()
1383             || opType == Type::BoolTy)
1384           {
1385             numInstr = 0;
1386             forwardOperandNum = 0;
1387           }
1388         else
1389           {
1390             // If the source operand is an FP type, the int result must be
1391             // copied from float to int register via memory!
1392             Instruction *dest = subtreeRoot->getInstruction();
1393             Value* leftVal = subtreeRoot->leftChild()->getValue();
1394             Value* destForCast;
1395             vector<MachineInstr*> minstrVec;
1396             
1397             if (opType == Type::FloatTy || opType == Type::DoubleTy)
1398               {
1399                 // Create a temporary to represent the INT register
1400                 // into which the FP value will be copied via memory.
1401                 // The type of this temporary will determine the FP
1402                 // register used: single-prec for a 32-bit int or smaller,
1403                 // double-prec for a 64-bit int.
1404                 // 
1405                 const Type* destTypeToUse =
1406                   (dest->getType() == Type::LongTy)? Type::DoubleTy
1407                                                    : Type::FloatTy;
1408                 destForCast = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1409                                                  destTypeToUse, leftVal, NULL);
1410                 dest->getMachineInstrVec().addTempValue(destForCast);
1411                 
1412                 vector<TmpInstruction*> tempVec;
1413                 target.getInstrInfo().CreateCodeToCopyFloatToInt(
1414                     dest->getParent()->getParent(),
1415                     (TmpInstruction*) destForCast, dest,
1416                     minstrVec, tempVec, target);
1417                 
1418                 for (unsigned i=0; i < tempVec.size(); ++i)
1419                   dest->getMachineInstrVec().addTempValue(tempVec[i]);
1420               }
1421             else
1422               destForCast = leftVal;
1423             
1424             MachineOpCode opCode=ChooseConvertToIntInstr(subtreeRoot, opType);
1425             assert(opCode != INVALID_OPCODE && "Expected to need conversion!");
1426             
1427             mvec[0] = new MachineInstr(opCode);
1428             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1429                                           leftVal);
1430             mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1431                                           destForCast);
1432
1433             assert(numInstr == 1 && "Should be initialized to 1 at the top");
1434             for (unsigned i=0; i < minstrVec.size(); ++i)
1435               mvec[numInstr++] = minstrVec[i];
1436           }
1437         break;
1438       }  
1439       
1440       case  31: // reg:   ToFloatTy(reg):
1441       case  32: // reg:   ToDoubleTy(reg):
1442       case 232: // reg:   ToDoubleTy(Constant):
1443         
1444         // If this instruction has a parent (a user) in the tree 
1445         // and the user is translated as an FsMULd instruction,
1446         // then the cast is unnecessary.  So check that first.
1447         // In the future, we'll want to do the same for the FdMULq instruction,
1448         // so do the check here instead of only for ToFloatTy(reg).
1449         // 
1450         if (subtreeRoot->parent() != NULL &&
1451             ((InstructionNode*) subtreeRoot->parent())->getInstruction()->getMachineInstrVec()[0]->getOpCode() == FSMULD)
1452           {
1453             numInstr = 0;
1454             forwardOperandNum = 0;
1455           }
1456         else
1457           {
1458             Value* leftVal = subtreeRoot->leftChild()->getValue();
1459             const Type* opType = leftVal->getType();
1460             MachineOpCode opCode=ChooseConvertToFloatInstr(subtreeRoot,opType);
1461             if (opCode == INVALID_OPCODE)       // no conversion needed
1462               {
1463                 numInstr = 0;
1464                 forwardOperandNum = 0;
1465               }
1466             else
1467               {
1468                 // If the source operand is a non-FP type it must be
1469                 // first copied from int to float register via memory!
1470                 Instruction *dest = subtreeRoot->getInstruction();
1471                 Value* srcForCast;
1472                 int n = 0;
1473                 if (opType != Type::FloatTy && opType != Type::DoubleTy)
1474                   {
1475                     // Create a temporary to represent the FP register
1476                     // into which the integer will be copied via memory.
1477                     // The type of this temporary will determine the FP
1478                     // register used: single-prec for a 32-bit int or smaller,
1479                     // double-prec for a 64-bit int.
1480                     // 
1481                     const Type* srcTypeToUse =
1482                       (leftVal->getType() == Type::LongTy)? Type::DoubleTy
1483                                                           : Type::FloatTy;
1484                     
1485                     srcForCast = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1486                                                     srcTypeToUse, dest, NULL);
1487                     dest->getMachineInstrVec().addTempValue(srcForCast);
1488                     
1489                     vector<MachineInstr*> minstrVec;
1490                     vector<TmpInstruction*> tempVec;
1491                     target.getInstrInfo().CreateCodeToCopyIntToFloat(
1492                          dest->getParent()->getParent(),
1493                          leftVal, (TmpInstruction*) srcForCast,
1494                          minstrVec, tempVec, target);
1495                     
1496                     for (unsigned i=0; i < minstrVec.size(); ++i)
1497                       mvec[n++] = minstrVec[i];
1498
1499                     for (unsigned i=0; i < tempVec.size(); ++i)
1500                        dest->getMachineInstrVec().addTempValue(tempVec[i]);
1501                   }
1502                 else
1503                   srcForCast = leftVal;
1504                 
1505                 MachineInstr* castI = new MachineInstr(opCode);
1506                 castI->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1507                                             srcForCast);
1508                 castI->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1509                                             dest);
1510                 mvec[n++] = castI;
1511                 numInstr = n;
1512               }
1513           }
1514         break;
1515
1516       case 19:  // reg:   ToArrayTy(reg):
1517       case 20:  // reg:   ToPointerTy(reg):
1518         numInstr = 0;
1519         forwardOperandNum = 0;
1520         break;
1521
1522       case 233: // reg:   Add(reg, Constant)
1523         mvec[0] = CreateAddConstInstruction(subtreeRoot);
1524         if (mvec[0] != NULL)
1525           break;
1526         // ELSE FALL THROUGH
1527
1528       case 33:  // reg:   Add(reg, reg)
1529         mvec[0] = new MachineInstr(ChooseAddInstruction(subtreeRoot));
1530         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1531         break;
1532
1533       case 234: // reg:   Sub(reg, Constant)
1534         mvec[0] = CreateSubConstInstruction(subtreeRoot);
1535         if (mvec[0] != NULL)
1536           break;
1537         // ELSE FALL THROUGH
1538
1539       case 34:  // reg:   Sub(reg, reg)
1540         mvec[0] = new MachineInstr(ChooseSubInstructionByType(
1541                                    subtreeRoot->getInstruction()->getType()));
1542         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1543         break;
1544
1545       case 135: // reg:   Mul(todouble, todouble)
1546         checkCast = true;
1547         // FALL THROUGH 
1548
1549       case 35:  // reg:   Mul(reg, reg)
1550         mvec[0] =new MachineInstr(ChooseMulInstruction(subtreeRoot,checkCast));
1551         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1552         break;
1553
1554       case 335: // reg:   Mul(todouble, todoubleConst)
1555         checkCast = true;
1556         // FALL THROUGH 
1557
1558       case 235: // reg:   Mul(reg, Constant)
1559         mvec[0] = CreateMulConstInstruction(target, subtreeRoot, mvec[1]);
1560         if (mvec[0] == NULL)
1561           {
1562             mvec[0] = new MachineInstr(ChooseMulInstruction(subtreeRoot,
1563                                                             checkCast));
1564             Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1565           }
1566         else
1567           if (mvec[1] != NULL)
1568             ++numInstr;
1569         break;
1570
1571       case 236: // reg:   Div(reg, Constant)
1572         mvec[0] = CreateDivConstInstruction(target, subtreeRoot, mvec[1]);
1573         if (mvec[0] != NULL)
1574           {
1575             if (mvec[1] != NULL)
1576               ++numInstr;
1577           }
1578         else
1579         // ELSE FALL THROUGH
1580
1581       case 36:  // reg:   Div(reg, reg)
1582         mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1583         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1584         break;
1585
1586       case  37: // reg:   Rem(reg, reg)
1587       case 237: // reg:   Rem(reg, Constant)
1588       {
1589         Instruction* remInstr = subtreeRoot->getInstruction();
1590         
1591         TmpInstruction* quot = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1592                                         subtreeRoot->leftChild()->getValue(),
1593                                         subtreeRoot->rightChild()->getValue());
1594         TmpInstruction* prod = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1595                                         quot,
1596                                         subtreeRoot->rightChild()->getValue());
1597         remInstr->getMachineInstrVec().addTempValue(quot); 
1598         remInstr->getMachineInstrVec().addTempValue(prod); 
1599         
1600         mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1601         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1602         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,quot);
1603         
1604         int n = numInstr++;
1605         mvec[n] = new MachineInstr(ChooseMulInstructionByType(
1606                                    subtreeRoot->getInstruction()->getType()));
1607         mvec[n]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,quot);
1608         mvec[n]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1609                                       subtreeRoot->rightChild()->getValue());
1610         mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,prod);
1611         
1612         n = numInstr++;
1613         mvec[n] = new MachineInstr(ChooseSubInstructionByType(
1614                                    subtreeRoot->getInstruction()->getType()));
1615         Set3OperandsFromInstr(mvec[n], subtreeRoot, target);
1616         mvec[n]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,prod);
1617         
1618         break;
1619       }
1620       
1621       case  38: // bool:   And(bool, bool)
1622       case 238: // bool:   And(bool, boolconst)
1623       case 338: // reg :   BAnd(reg, reg)
1624       case 538: // reg :   BAnd(reg, Constant)
1625         mvec[0] = new MachineInstr(AND);
1626         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1627         break;
1628
1629       case 138: // bool:   And(bool, not)
1630       case 438: // bool:   BAnd(bool, not)
1631         mvec[0] = new MachineInstr(ANDN);
1632         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1633         break;
1634
1635       case  39: // bool:   Or(bool, bool)
1636       case 239: // bool:   Or(bool, boolconst)
1637       case 339: // reg :   BOr(reg, reg)
1638       case 539: // reg :   BOr(reg, Constant)
1639         mvec[0] = new MachineInstr(ORN);
1640         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1641         break;
1642
1643       case 139: // bool:   Or(bool, not)
1644       case 439: // bool:   BOr(bool, not)
1645         mvec[0] = new MachineInstr(ORN);
1646         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1647         break;
1648
1649       case  40: // bool:   Xor(bool, bool)
1650       case 240: // bool:   Xor(bool, boolconst)
1651       case 340: // reg :   BXor(reg, reg)
1652       case 540: // reg :   BXor(reg, Constant)
1653         mvec[0] = new MachineInstr(XOR);
1654         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1655         break;
1656
1657       case 140: // bool:   Xor(bool, not)
1658       case 440: // bool:   BXor(bool, not)
1659         mvec[0] = new MachineInstr(XNOR);
1660         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1661         break;
1662
1663       case 41:  // boolconst:   SetCC(reg, Constant)
1664         // Check if this is an integer comparison, and
1665         // there is a parent, and the parent decided to use
1666         // a branch-on-integer-register instead of branch-on-condition-code.
1667         // If so, the SUBcc instruction is not required.
1668         // (However, we must still check for constants to be loaded from
1669         // the constant pool so that such a load can be associated with
1670         // this instruction.)
1671         // 
1672         // Otherwise this is just the same as case 42, so just fall through.
1673         // 
1674         if ((subtreeRoot->leftChild()->getValue()->getType()->isIntegral() ||
1675              subtreeRoot->leftChild()->getValue()->getType()->isPointerType())
1676             && subtreeRoot->parent() != NULL)
1677           {
1678             InstructionNode* parent = (InstructionNode*) subtreeRoot->parent();
1679             assert(parent->getNodeType() == InstrTreeNode::NTInstructionNode);
1680             const vector<MachineInstr*>&
1681               minstrVec = parent->getInstruction()->getMachineInstrVec();
1682             MachineOpCode parentOpCode;
1683             if (parent->getInstruction()->getOpcode() == Instruction::Br &&
1684                 (parentOpCode = minstrVec[0]->getOpCode()) >= BRZ &&
1685                 parentOpCode <= BRGEZ)
1686               {
1687                 numInstr = 0;           // don't forward the operand!
1688                 break;
1689               }
1690           }
1691         // ELSE FALL THROUGH
1692
1693       case 42:  // bool:   SetCC(reg, reg):
1694       {
1695         // This generates a SUBCC instruction, putting the difference in
1696         // a result register, and setting a condition code.
1697         // 
1698         // If the boolean result of the SetCC is used by anything other
1699         // than a single branch instruction, the boolean must be
1700         // computed and stored in the result register.  Otherwise, discard
1701         // the difference (by using %g0) and keep only the condition code.
1702         // 
1703         // To compute the boolean result in a register we use a conditional
1704         // move, unless the result of the SUBCC instruction can be used as
1705         // the bool!  This assumes that zero is FALSE and any non-zero
1706         // integer is TRUE.
1707         // 
1708         InstructionNode* parentNode = (InstructionNode*) subtreeRoot->parent();
1709         Instruction* setCCInstr = subtreeRoot->getInstruction();
1710         bool keepBoolVal = (parentNode == NULL ||
1711                             parentNode->getInstruction()->getOpcode()
1712                                 != Instruction::Br);
1713         bool subValIsBoolVal = setCCInstr->getOpcode() == Instruction::SetNE;
1714         bool keepSubVal = keepBoolVal && subValIsBoolVal;
1715         bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1716         
1717         bool mustClearReg;
1718         int valueToMove;
1719         MachineOpCode movOpCode = 0;
1720
1721         // Mark the 4th operand as being a CC register, and as a def
1722         // A TmpInstruction is created to represent the CC "result".
1723         // Unlike other instances of TmpInstruction, this one is used
1724         // by machine code of multiple LLVM instructions, viz.,
1725         // the SetCC and the branch.  Make sure to get the same one!
1726         // Note that we do this even for FP CC registers even though they
1727         // are explicit operands, because the type of the operand
1728         // needs to be a floating point condition code, not an integer
1729         // condition code.  Think of this as casting the bool result to
1730         // a FP condition code register.
1731         // 
1732         Value* leftVal = subtreeRoot->leftChild()->getValue();
1733         bool isFPCompare = (leftVal->getType() == Type::FloatTy || 
1734                             leftVal->getType() == Type::DoubleTy);
1735         
1736         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
1737                                      setCCInstr->getParent()->getParent(),
1738                                      isFPCompare? Type::FloatTy : Type::IntTy);
1739         setCCInstr->getMachineInstrVec().addTempValue(tmpForCC);
1740         
1741         if (! isFPCompare)
1742           {
1743             // Integer condition: dest. should be %g0 or an integer register.
1744             // If result must be saved but condition is not SetEQ then we need
1745             // a separate instruction to compute the bool result, so discard
1746             // result of SUBcc instruction anyway.
1747             // 
1748             mvec[0] = new MachineInstr(SUBcc);
1749             Set3OperandsFromInstr(mvec[0], subtreeRoot, target, ! keepSubVal);
1750             
1751             mvec[0]->SetMachineOperand(3, MachineOperand::MO_CCRegister,
1752                                           tmpForCC, /*def*/true);
1753             
1754             if (computeBoolVal)
1755               { // recompute bool using the integer condition codes
1756                 movOpCode =
1757                   ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1758               }
1759           }
1760         else
1761           {
1762             // FP condition: dest of FCMP should be some FCCn register
1763             mvec[0] = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1764             mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1765                                           tmpForCC);
1766             mvec[0]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1767                                          subtreeRoot->leftChild()->getValue());
1768             mvec[0]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1769                                         subtreeRoot->rightChild()->getValue());
1770             
1771             if (computeBoolVal)
1772               {// recompute bool using the FP condition codes
1773                 mustClearReg = true;
1774                 valueToMove = 1;
1775                 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1776               }
1777           }
1778         
1779         if (computeBoolVal)
1780           {
1781             if (mustClearReg)
1782               {// Unconditionally set register to 0
1783                int n = numInstr++;
1784                mvec[n] = new MachineInstr(SETHI);
1785                mvec[n]->SetMachineOperand(0,MachineOperand::MO_UnextendedImmed,
1786                                             s0);
1787                mvec[n]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1788                                             setCCInstr);
1789               }
1790             
1791             // Now conditionally move `valueToMove' (0 or 1) into the register
1792             int n = numInstr++;
1793             mvec[n] = new MachineInstr(movOpCode);
1794             mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1795                                           tmpForCC);
1796             mvec[n]->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
1797                                           valueToMove);
1798             mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1799                                           setCCInstr);
1800           }
1801         break;
1802       }    
1803
1804       case 43:  // boolreg: VReg
1805       case 44:  // boolreg: Constant
1806         numInstr = 0;
1807         break;
1808
1809       case 51:  // reg:   Load(reg)
1810       case 52:  // reg:   Load(ptrreg)
1811       case 53:  // reg:   LoadIdx(reg,reg)
1812       case 54:  // reg:   LoadIdx(ptrreg,reg)
1813         mvec[0] = new MachineInstr(ChooseLoadInstruction(
1814                                      subtreeRoot->getValue()->getType()));
1815         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1816         break;
1817
1818       case 55:  // reg:   GetElemPtr(reg)
1819       case 56:  // reg:   GetElemPtrIdx(reg,reg)
1820         if (subtreeRoot->parent() != NULL)
1821           {
1822             // If the parent was a memory operation and not an array access,
1823             // the parent will fold this instruction in so generate nothing.
1824             // 
1825             Instruction* parent =
1826               cast<Instruction>(subtreeRoot->parent()->getValue());
1827             if (parent->getOpcode() == Instruction::Load ||
1828                 parent->getOpcode() == Instruction::Store ||
1829                 parent->getOpcode() == Instruction::GetElementPtr)
1830               {
1831                 // Check if the parent is an array access,
1832                 // If so, we still need to generate this instruction.
1833                 GetElementPtrInst* getElemInst =
1834                   cast<GetElementPtrInst>(subtreeRoot->getInstruction());
1835                 const PointerType* ptrType =
1836                   (const PointerType*) getElemInst->getPtrOperand()->getType();
1837                 if (! ptrType->getValueType()->isArrayType())
1838                   {// we don't need a separate instr
1839                     numInstr = 0;               // don't forward operand!
1840                     break;
1841                   }
1842               }
1843           }
1844         // else in all other cases we need to a separate ADD instruction
1845         mvec[0] = new MachineInstr(ADD);
1846         SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1847         break;
1848
1849       case 57:  // reg:  Alloca: Implement as 1 instruction:
1850       {         //          add %fp, offsetFromFP -> result
1851         Instruction* instr = subtreeRoot->getInstruction();
1852         const PointerType* instrType = (const PointerType*) instr->getType();
1853         assert(instrType->isPointerType());
1854         int tsize = (int)
1855           target.findOptimalStorageSize(instrType->getValueType());
1856         assert(tsize != 0 && "Just to check when this can happen");
1857         
1858         Method* method = instr->getParent()->getParent();
1859         MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
1860         int offsetFromFP = mcInfo.allocateLocalVar(target, instr);
1861         
1862         // Create a temporary Value to hold the constant offset.
1863         // This is needed because it may not fit in the immediate field.
1864         ConstPoolSInt* offsetVal=ConstPoolSInt::get(Type::IntTy, offsetFromFP);
1865         
1866         // Instruction 1: add %fp, offsetFromFP -> result
1867         mvec[0] = new MachineInstr(ADD);
1868         mvec[0]->SetMachineOperand(0, target.getRegInfo().getFramePointer());
1869         mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1870                                       offsetVal); 
1871         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1872                                       instr);
1873         break;
1874       }
1875         
1876       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
1877                 //      mul num, typeSz -> tmp
1878                 //      sub %sp, tmp    -> %sp
1879       {         //      add %sp, frameSizeBelowDynamicArea -> result
1880         Instruction* instr = subtreeRoot->getInstruction();
1881         const PointerType* instrType = (const PointerType*) instr->getType();
1882         assert(instrType->isPointerType() &&
1883                instrType->getValueType()->isArrayType());
1884         const Type* eltType =
1885           ((ArrayType*) instrType->getValueType())->getElementType();
1886         int tsize = (int) target.findOptimalStorageSize(eltType);
1887         
1888         assert(tsize != 0 && "Just to check when this can happen");
1889         
1890         // Create a temporary Value to hold the constant type-size
1891         ConstPoolSInt* tsizeVal = ConstPoolSInt::get(Type::IntTy, tsize);
1892         
1893         // Create a temporary Value to hold the constant offset from SP
1894         Method* method = instr->getParent()->getParent();
1895         bool ignore;                    // we don't need this 
1896         ConstPoolSInt* dynamicAreaOffset = ConstPoolSInt::get(Type::IntTy,
1897           target.getFrameInfo().getDynamicAreaOffset(MachineCodeForMethod::get(method),
1898                                                      ignore));
1899         
1900         // Create a temporary value to hold `tmp'
1901         Instruction* tmpInstr = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1902                                           subtreeRoot->leftChild()->getValue(),
1903                                           NULL /*could insert tsize here*/);
1904         subtreeRoot->getInstruction()->getMachineInstrVec().addTempValue(tmpInstr);
1905         
1906         // Instruction 1: mul numElements, typeSize -> tmp
1907         mvec[0] = new MachineInstr(MULX);
1908         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1909                                       subtreeRoot->leftChild()->getValue());
1910         mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1911                                       tsizeVal);
1912         mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1913                                       tmpInstr);
1914         
1915         // Instruction 2: sub %sp, tmp -> %sp
1916         numInstr++;
1917         mvec[1] = new MachineInstr(SUB);
1918         mvec[1]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1919         mvec[1]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1920                                       tmpInstr);
1921         mvec[1]->SetMachineOperand(2, target.getRegInfo().getStackPointer());
1922         
1923         // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1924         numInstr++;
1925         mvec[2] = new MachineInstr(ADD);
1926         mvec[2]->SetMachineOperand(0, target.getRegInfo().getStackPointer());
1927         mvec[2]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1928                                       dynamicAreaOffset);
1929         mvec[2]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,instr);
1930         break;
1931       }
1932
1933       case 61:  // reg:   Call
1934       {         // Generate a call-indirect (i.e., jmpl) for now to expose
1935                 // the potential need for registers.  If an absolute address
1936                 // is available, replace this with a CALL instruction.
1937                 // Mark both the indirection register and the return-address
1938                 // register as hidden virtual registers.
1939                 // Also, mark the operands of the Call and return value (if
1940                 // any) as implicit operands of the CALL machine instruction.
1941                 // 
1942         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
1943         Value *callee = callInstr->getCalledValue();
1944         
1945         Instruction* retAddrReg = new TmpInstruction(TMP_INSTRUCTION_OPCODE,
1946                                                      callInstr, NULL);
1947         
1948         // Note temporary values in the machineInstrVec for the VM instr.
1949         //
1950         // WARNING: Operands 0..N-1 must go in slots 0..N-1 of implicitUses.
1951         //          The result value must go in slot N.  This is assumed
1952         //          in register allocation.
1953         // 
1954         callInstr->getMachineInstrVec().addTempValue(retAddrReg);
1955         
1956         
1957         // Generate the machine instruction and its operands.
1958         // Use CALL for direct function calls; this optimistically assumes
1959         // the PC-relative address fits in the CALL address field (22 bits).
1960         // Use JMPL for indirect calls.
1961         // 
1962         if (callee->getValueType() == Value::MethodVal)
1963           { // direct function call
1964             mvec[0] = new MachineInstr(CALL);
1965             mvec[0]->SetMachineOperand(0, MachineOperand::MO_PCRelativeDisp,
1966                                           callee);
1967           } 
1968         else
1969           { // indirect function call
1970             mvec[0] = new MachineInstr(JMPLCALL);
1971             mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1972                                           callee);
1973             mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
1974                                           (int64_t) 0);
1975             mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1976                                           retAddrReg);
1977           }
1978         
1979         // Add the call operands and return value as implicit refs
1980         for (unsigned i=0, N=callInstr->getNumOperands(); i < N; ++i)
1981           if (callInstr->getOperand(i) != callee)
1982             mvec[0]->addImplicitRef(callInstr->getOperand(i));
1983         
1984         if (callInstr->getType() != Type::VoidTy)
1985           mvec[0]->addImplicitRef(callInstr, /*isDef*/ true);
1986         
1987         // For the CALL instruction, the ret. addr. reg. is also implicit
1988         if (callee->getValueType() == Value::MethodVal)
1989           mvec[0]->addImplicitRef(retAddrReg, /*isDef*/ true);
1990         
1991         mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1992         break;
1993       }
1994
1995       case 62:  // reg:   Shl(reg, reg)
1996       { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1997         assert(opType->isIntegral()
1998                || opType == Type::BoolTy
1999                || opType->isPointerType()&& "Shl unsupported for other types");
2000         mvec[0] = new MachineInstr((opType == Type::LongTy)? SLLX : SLL);
2001         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2002         break;
2003       }
2004       
2005       case 63:  // reg:   Shr(reg, reg)
2006       { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2007         assert(opType->isIntegral()
2008                || opType == Type::BoolTy
2009                || opType->isPointerType() &&"Shr unsupported for other types");
2010         mvec[0] = new MachineInstr((opType->isSigned()
2011                                     ? ((opType == Type::LongTy)? SRAX : SRA)
2012                                     : ((opType == Type::LongTy)? SRLX : SRL)));
2013         Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2014         break;
2015       }
2016       
2017       case 64:  // reg:   Phi(reg,reg)
2018       {         // This instruction has variable #operands, so resultPos is 0.
2019         Instruction* phi = subtreeRoot->getInstruction();
2020         mvec[0] = new MachineInstr(PHI, 1 + phi->getNumOperands());
2021         mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2022                                       subtreeRoot->getValue());
2023         for (unsigned i=0, N=phi->getNumOperands(); i < N; i++)
2024           mvec[0]->SetMachineOperand(i+1, MachineOperand::MO_VirtualRegister,
2025                                           phi->getOperand(i));
2026         break;
2027       }  
2028       
2029       case 71:  // reg:     VReg
2030       case 72:  // reg:     Constant
2031         numInstr = 0;                   // don't forward the value
2032         break;
2033
2034       default:
2035         assert(0 && "Unrecognized BURG rule");
2036         numInstr = 0;
2037         break;
2038       }
2039     }
2040   
2041   if (forwardOperandNum >= 0)
2042     { // We did not generate a machine instruction but need to use operand.
2043       // If user is in the same tree, replace Value in its machine operand.
2044       // If not, insert a copy instruction which should get coalesced away
2045       // by register allocation.
2046       if (subtreeRoot->parent() != NULL)
2047         ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2048       else
2049         {
2050           vector<MachineInstr*> minstrVec;
2051           CreateCopyInstructionsByType(target,
2052                 subtreeRoot->getInstruction()->getOperand(forwardOperandNum),
2053                 subtreeRoot->getInstruction(), minstrVec);
2054           assert(minstrVec.size() > 0);
2055           for (unsigned i=0; i < minstrVec.size(); ++i)
2056             mvec[numInstr++] = minstrVec[i];
2057         }
2058     }
2059   
2060   return numInstr;
2061 }
2062
2063