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