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