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