1. Bug fix: was using SLL instead of SLLX for ULongTy. Chump.
[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 #include <algorithm>
29
30 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
31                                     std::vector<MachineInstr*>& mvec) {
32   mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
33                                    .addReg(Node->rightChild()->getValue())
34                                    .addRegDef(Node->getValue()));
35 }
36
37
38
39 //---------------------------------------------------------------------------
40 // Function: GetMemInstArgs
41 // 
42 // Purpose:
43 //   Get the pointer value and the index vector for a memory operation
44 //   (GetElementPtr, Load, or Store).  If all indices of the given memory
45 //   operation are constant, fold in constant indices in a chain of
46 //   preceding GetElementPtr instructions (if any), and return the
47 //   pointer value of the first instruction in the chain.
48 //   All folded instructions are marked so no code is generated for them.
49 //
50 // Return values:
51 //   Returns the pointer Value to use.
52 //   Returns the resulting IndexVector in idxVec.
53 //   Returns true/false in allConstantIndices if all indices are/aren't const.
54 //---------------------------------------------------------------------------
55
56
57 //---------------------------------------------------------------------------
58 // Function: FoldGetElemChain
59 // 
60 // Purpose:
61 //   Fold a chain of GetElementPtr instructions containing only
62 //   constant offsets into an equivalent (Pointer, IndexVector) pair.
63 //   Returns the pointer Value, and stores the resulting IndexVector
64 //   in argument chainIdxVec. This is a helper function for
65 //   FoldConstantIndices that does the actual folding. 
66 //---------------------------------------------------------------------------
67
68
69 // Check for a constant 0.
70 inline bool
71 IsZero(Value* idx)
72 {
73   return (idx == ConstantSInt::getNullValue(idx->getType()));
74 }
75
76 static Value*
77 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
78                  bool lastInstHasLeadingNonZero)
79 {
80   InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
81   GetElementPtrInst* gepInst =
82     dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
83
84   // ptr value is not computed in this tree or ptr value does not come from GEP
85   // instruction
86   if (gepInst == NULL)
87     return NULL;
88
89   // Return NULL if we don't fold any instructions in.
90   Value* ptrVal = NULL;
91
92   // Now chase the chain of getElementInstr instructions, if any.
93   // Check for any non-constant indices and stop there.
94   // Also, stop if the first index of child is a non-zero array index
95   // and the last index of the current node is a non-array index:
96   // in that case, a non-array declared type is being accessed as an array
97   // which is not type-safe, but could be legal.
98   // 
99   InstructionNode* ptrChild = gepNode;
100   while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
101                       ptrChild->getOpLabel() == GetElemPtrIdx))
102   {
103     // Child is a GetElemPtr instruction
104     gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
105     User::op_iterator OI, firstIdx = gepInst->idx_begin();
106     User::op_iterator lastIdx = gepInst->idx_end();
107     bool allConstantOffsets = true;
108
109     // The first index of every GEP must be an array index.
110     assert((*firstIdx)->getType() == Type::LongTy &&
111            "INTERNAL ERROR: Structure index for a pointer type!");
112
113     // If the last instruction had a leading non-zero index, check if the
114     // current one references a sequential (i.e., indexable) type.
115     // If not, the code is not type-safe and we would create an illegal GEP
116     // by folding them, so don't fold any more instructions.
117     // 
118     if (lastInstHasLeadingNonZero)
119       if (! isa<SequentialType>(gepInst->getType()->getElementType()))
120         break;   // cannot fold in any preceding getElementPtr instrs.
121
122     // Check that all offsets are constant for this instruction
123     for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
124       allConstantOffsets = isa<ConstantInt>(*OI);
125
126     if (allConstantOffsets) {
127       // Get pointer value out of ptrChild.
128       ptrVal = gepInst->getPointerOperand();
129
130       // Insert its index vector at the start, skipping any leading [0]
131       // Remember the old size to check if anything was inserted.
132       unsigned oldSize = chainIdxVec.size();
133       int firstIsZero = IsZero(*firstIdx);
134       chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
135
136       // Remember if it has leading zero index: it will be discarded later.
137       if (oldSize < chainIdxVec.size())
138         lastInstHasLeadingNonZero = !firstIsZero;
139
140       // Mark the folded node so no code is generated for it.
141       ((InstructionNode*) ptrChild)->markFoldedIntoParent();
142
143       // Get the previous GEP instruction and continue trying to fold
144       ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
145     } else // cannot fold this getElementPtr instr. or any preceding ones
146       break;
147   }
148
149   // If the first getElementPtr instruction had a leading [0], add it back.
150   // Note that this instruction is the *last* one that was successfully
151   // folded *and* contributed any indices, in the loop above.
152   // 
153   if (ptrVal && ! lastInstHasLeadingNonZero) 
154     chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
155
156   return ptrVal;
157 }
158
159
160 //---------------------------------------------------------------------------
161 // Function: GetGEPInstArgs
162 // 
163 // Purpose:
164 //   Helper function for GetMemInstArgs that handles the final getElementPtr
165 //   instruction used by (or same as) the memory operation.
166 //   Extracts the indices of the current instruction and tries to fold in
167 //   preceding ones if all indices of the current one are constant.
168 //---------------------------------------------------------------------------
169
170 static Value *
171 GetGEPInstArgs(InstructionNode* gepNode,
172                std::vector<Value*>& idxVec,
173                bool& allConstantIndices)
174 {
175   allConstantIndices = true;
176   GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
177
178   // Default pointer is the one from the current instruction.
179   Value* ptrVal = gepI->getPointerOperand();
180   InstrTreeNode* ptrChild = gepNode->leftChild(); 
181
182   // Extract the index vector of the GEP instructin.
183   // If all indices are constant and first index is zero, try to fold
184   // in preceding GEPs with all constant indices.
185   for (User::op_iterator OI=gepI->idx_begin(),  OE=gepI->idx_end();
186        allConstantIndices && OI != OE; ++OI)
187     if (! isa<Constant>(*OI))
188       allConstantIndices = false;     // note: this also terminates loop!
189
190   // If we have only constant indices, fold chains of constant indices
191   // in this and any preceding GetElemPtr instructions.
192   bool foldedGEPs = false;
193   bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
194   if (allConstantIndices)
195     if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
196       ptrVal = newPtr;
197       foldedGEPs = true;
198     }
199
200   // Append the index vector of the current instruction.
201   // Skip the leading [0] index if preceding GEPs were folded into this.
202   idxVec.insert(idxVec.end(),
203                 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
204                 gepI->idx_end());
205
206   return ptrVal;
207 }
208
209 //---------------------------------------------------------------------------
210 // Function: GetMemInstArgs
211 // 
212 // Purpose:
213 //   Get the pointer value and the index vector for a memory operation
214 //   (GetElementPtr, Load, or Store).  If all indices of the given memory
215 //   operation are constant, fold in constant indices in a chain of
216 //   preceding GetElementPtr instructions (if any), and return the
217 //   pointer value of the first instruction in the chain.
218 //   All folded instructions are marked so no code is generated for them.
219 //
220 // Return values:
221 //   Returns the pointer Value to use.
222 //   Returns the resulting IndexVector in idxVec.
223 //   Returns true/false in allConstantIndices if all indices are/aren't const.
224 //---------------------------------------------------------------------------
225
226 static Value*
227 GetMemInstArgs(InstructionNode* memInstrNode,
228                std::vector<Value*>& idxVec,
229                bool& allConstantIndices)
230 {
231   allConstantIndices = false;
232   Instruction* memInst = memInstrNode->getInstruction();
233   assert(idxVec.size() == 0 && "Need empty vector to return indices");
234
235   // If there is a GetElemPtr instruction to fold in to this instr,
236   // it must be in the left child for Load and GetElemPtr, and in the
237   // right child for Store instructions.
238   InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
239                              ? memInstrNode->rightChild()
240                              : memInstrNode->leftChild()); 
241   
242   // Default pointer is the one from the current instruction.
243   Value* ptrVal = ptrChild->getValue(); 
244
245   // Find the "last" GetElemPtr instruction: this one or the immediate child.
246   // There will be none if this is a load or a store from a scalar pointer.
247   InstructionNode* gepNode = NULL;
248   if (isa<GetElementPtrInst>(memInst))
249     gepNode = memInstrNode;
250   else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
251     // Child of load/store is a GEP and memInst is its only use.
252     // Use its indices and mark it as folded.
253     gepNode = cast<InstructionNode>(ptrChild);
254     gepNode->markFoldedIntoParent();
255   }
256
257   // If there are no indices, return the current pointer.
258   // Else extract the pointer from the GEP and fold the indices.
259   return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
260                  : ptrVal;
261 }
262
263
264 //************************ Internal Functions ******************************/
265
266
267 static inline MachineOpCode 
268 ChooseBprInstruction(const InstructionNode* instrNode)
269 {
270   MachineOpCode opCode;
271   
272   Instruction* setCCInstr =
273     ((InstructionNode*) instrNode->leftChild())->getInstruction();
274   
275   switch(setCCInstr->getOpcode())
276   {
277   case Instruction::SetEQ: opCode = V9::BRZ;   break;
278   case Instruction::SetNE: opCode = V9::BRNZ;  break;
279   case Instruction::SetLE: opCode = V9::BRLEZ; break;
280   case Instruction::SetGE: opCode = V9::BRGEZ; break;
281   case Instruction::SetLT: opCode = V9::BRLZ;  break;
282   case Instruction::SetGT: opCode = V9::BRGZ;  break;
283   default:
284     assert(0 && "Unrecognized VM instruction!");
285     opCode = V9::INVALID_OPCODE;
286     break; 
287   }
288   
289   return opCode;
290 }
291
292
293 static inline MachineOpCode 
294 ChooseBpccInstruction(const InstructionNode* instrNode,
295                       const BinaryOperator* setCCInstr)
296 {
297   MachineOpCode opCode = V9::INVALID_OPCODE;
298   
299   bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
300   
301   if (isSigned) {
302     switch(setCCInstr->getOpcode())
303     {
304     case Instruction::SetEQ: opCode = V9::BE;  break;
305     case Instruction::SetNE: opCode = V9::BNE; break;
306     case Instruction::SetLE: opCode = V9::BLE; break;
307     case Instruction::SetGE: opCode = V9::BGE; break;
308     case Instruction::SetLT: opCode = V9::BL;  break;
309     case Instruction::SetGT: opCode = V9::BG;  break;
310     default:
311       assert(0 && "Unrecognized VM instruction!");
312       break; 
313     }
314   } else {
315     switch(setCCInstr->getOpcode())
316     {
317     case Instruction::SetEQ: opCode = V9::BE;   break;
318     case Instruction::SetNE: opCode = V9::BNE;  break;
319     case Instruction::SetLE: opCode = V9::BLEU; break;
320     case Instruction::SetGE: opCode = V9::BCC;  break;
321     case Instruction::SetLT: opCode = V9::BCS;  break;
322     case Instruction::SetGT: opCode = V9::BGU;  break;
323     default:
324       assert(0 && "Unrecognized VM instruction!");
325       break; 
326     }
327   }
328   
329   return opCode;
330 }
331
332 static inline MachineOpCode 
333 ChooseBFpccInstruction(const InstructionNode* instrNode,
334                        const BinaryOperator* setCCInstr)
335 {
336   MachineOpCode opCode = V9::INVALID_OPCODE;
337   
338   switch(setCCInstr->getOpcode())
339   {
340   case Instruction::SetEQ: opCode = V9::FBE;  break;
341   case Instruction::SetNE: opCode = V9::FBNE; break;
342   case Instruction::SetLE: opCode = V9::FBLE; break;
343   case Instruction::SetGE: opCode = V9::FBGE; break;
344   case Instruction::SetLT: opCode = V9::FBL;  break;
345   case Instruction::SetGT: opCode = V9::FBG;  break;
346   default:
347     assert(0 && "Unrecognized VM instruction!");
348     break; 
349   }
350   
351   return opCode;
352 }
353
354
355 // Create a unique TmpInstruction for a boolean value,
356 // representing the CC register used by a branch on that value.
357 // For now, hack this using a little static cache of TmpInstructions.
358 // Eventually the entire BURG instruction selection should be put
359 // into a separate class that can hold such information.
360 // The static cache is not too bad because the memory for these
361 // TmpInstructions will be freed along with the rest of the Function anyway.
362 // 
363 static TmpInstruction*
364 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType,
365             MachineCodeForInstruction& mcfi)
366 {
367   typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
368   static BoolTmpCache boolToTmpCache;     // Map boolVal -> TmpInstruction*
369   static const Function *lastFunction = 0;// Use to flush cache between funcs
370   
371   assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
372   
373   if (lastFunction != F) {
374     lastFunction = F;
375     boolToTmpCache.clear();
376   }
377   
378   // Look for tmpI and create a new one otherwise.  The new value is
379   // directly written to map using the ref returned by operator[].
380   TmpInstruction*& tmpI = boolToTmpCache[boolVal];
381   if (tmpI == NULL)
382     tmpI = new TmpInstruction(mcfi, ccType, boolVal);
383   
384   return tmpI;
385 }
386
387
388 static inline MachineOpCode 
389 ChooseBccInstruction(const InstructionNode* instrNode,
390                      const Type*& setCCType)
391 {
392   InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
393   assert(setCCNode->getOpLabel() == SetCCOp);
394   BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
395   setCCType = setCCInstr->getOperand(0)->getType();
396   
397   if (setCCType->isFloatingPoint())
398     return ChooseBFpccInstruction(instrNode, setCCInstr);
399   else
400     return ChooseBpccInstruction(instrNode, setCCInstr);
401 }
402
403
404 // WARNING: since this function has only one caller, it always returns
405 // the opcode that expects an immediate and a register. If this function
406 // is ever used in cases where an opcode that takes two registers is required,
407 // then modify this function and use convertOpcodeFromRegToImm() where required.
408 //
409 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
410 // new cases of opcodes.
411 static inline MachineOpCode 
412 ChooseMovFpcciInstruction(const InstructionNode* instrNode)
413 {
414   MachineOpCode opCode = V9::INVALID_OPCODE;
415   
416   switch(instrNode->getInstruction()->getOpcode())
417   {
418   case Instruction::SetEQ: opCode = V9::MOVFEi;  break;
419   case Instruction::SetNE: opCode = V9::MOVFNEi; break;
420   case Instruction::SetLE: opCode = V9::MOVFLEi; break;
421   case Instruction::SetGE: opCode = V9::MOVFGEi; break;
422   case Instruction::SetLT: opCode = V9::MOVFLi;  break;
423   case Instruction::SetGT: opCode = V9::MOVFGi;  break;
424   default:
425     assert(0 && "Unrecognized VM instruction!");
426     break; 
427   }
428   
429   return opCode;
430 }
431
432
433 // ChooseMovpcciForSetCC -- Choose a conditional-move instruction
434 // based on the type of SetCC operation.
435 // 
436 // WARNING: since this function has only one caller, it always returns
437 // the opcode that expects an immediate and a register. If this function
438 // is ever used in cases where an opcode that takes two registers is required,
439 // then modify this function and use convertOpcodeFromRegToImm() where required.
440 //
441 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
442 // new cases of opcodes.
443 // 
444 static MachineOpCode
445 ChooseMovpcciForSetCC(const InstructionNode* instrNode)
446 {
447   MachineOpCode opCode = V9::INVALID_OPCODE;
448
449   const Type* opType = instrNode->leftChild()->getValue()->getType();
450   assert(opType->isIntegral() || isa<PointerType>(opType));
451   bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
452   
453   switch(instrNode->getInstruction()->getOpcode())
454   {
455   case Instruction::SetEQ: opCode = V9::MOVEi;                        break;
456   case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
457   case Instruction::SetGE: opCode = noSign? V9::MOVCCi  : V9::MOVGEi; break;
458   case Instruction::SetLT: opCode = noSign? V9::MOVCSi  : V9::MOVLi;  break;
459   case Instruction::SetGT: opCode = noSign? V9::MOVGUi  : V9::MOVGi;  break;
460   case Instruction::SetNE: opCode = V9::MOVNEi;                       break;
461   default: assert(0 && "Unrecognized LLVM instr!"); break; 
462   }
463   
464   return opCode;
465 }
466
467
468 // ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
469 // instruction based on the type of SetCC operation.  These instructions
470 // compare a register with 0 and perform the move is the comparison is true.
471 // 
472 // WARNING: like the previous function, this function it always returns
473 // the opcode that expects an immediate and a register.  See above.
474 // 
475 static MachineOpCode
476 ChooseMovpregiForSetCC(const InstructionNode* instrNode)
477 {
478   MachineOpCode opCode = V9::INVALID_OPCODE;
479   
480   switch(instrNode->getInstruction()->getOpcode())
481   {
482   case Instruction::SetEQ: opCode = V9::MOVRZi;  break;
483   case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
484   case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
485   case Instruction::SetLT: opCode = V9::MOVRLZi;  break;
486   case Instruction::SetGT: opCode = V9::MOVRGZi;  break;
487   case Instruction::SetNE: opCode = V9::MOVRNZi; break;
488   default: assert(0 && "Unrecognized VM instr!"); break; 
489   }
490   
491   return opCode;
492 }
493
494
495 static inline MachineOpCode
496 ChooseConvertToFloatInstr(const TargetMachine& target,
497                           OpLabel vopCode, const Type* opType)
498 {
499   assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
500          "Unrecognized convert-to-float opcode!");
501   assert((opType->isIntegral() || opType->isFloatingPoint() ||
502           isa<PointerType>(opType))
503          && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
504
505   MachineOpCode opCode = V9::INVALID_OPCODE;
506
507   unsigned opSize = target.getTargetData().getTypeSize(opType);
508
509   if (opType == Type::FloatTy)
510     opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
511   else if (opType == Type::DoubleTy)
512     opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
513   else if (opSize <= 4)
514     opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
515   else {
516     assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
517     opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
518   }
519   
520   return opCode;
521 }
522
523 static inline MachineOpCode 
524 ChooseConvertFPToIntInstr(const TargetMachine& target,
525                           const Type* destType, const Type* opType)
526 {
527   assert((opType == Type::FloatTy || opType == Type::DoubleTy)
528          && "This function should only be called for FLOAT or DOUBLE");
529   assert((destType->isIntegral() || isa<PointerType>(destType))
530          && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
531
532   MachineOpCode opCode = V9::INVALID_OPCODE;
533
534   unsigned destSize = target.getTargetData().getTypeSize(destType);
535
536   if (destType == Type::UIntTy)
537     assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
538   else if (destSize <= 4)
539     opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
540   else {
541     assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
542     opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
543   }
544
545   return opCode;
546 }
547
548 static MachineInstr*
549 CreateConvertFPToIntInstr(const TargetMachine& target,
550                           Value* srcVal,
551                           Value* destVal,
552                           const Type* destType)
553 {
554   MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
555                                                    srcVal->getType());
556   assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
557   return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
558 }
559
560 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
561 // The FP value must be converted to the dest type in an FP register,
562 // and the result is then copied from FP to int register via memory.
563 // SPARC does not have a float-to-uint conversion, only a float-to-int (fdtoi).
564 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
565 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
566 // Therefore, for converting an FP value to uint32_t, we first need to convert
567 // to uint64_t and then to uint32_t.
568 // 
569 static void
570 CreateCodeToConvertFloatToInt(const TargetMachine& target,
571                               Value* opVal,
572                               Instruction* destI,
573                               std::vector<MachineInstr*>& mvec,
574                               MachineCodeForInstruction& mcfi)
575 {
576   Function* F = destI->getParent()->getParent();
577
578   // Create a temporary to represent the FP register into which the
579   // int value will placed after conversion.  The type of this temporary
580   // depends on the type of FP register to use: single-prec for a 32-bit
581   // int or smaller; double-prec for a 64-bit int.
582   // 
583   size_t destSize = target.getTargetData().getTypeSize(destI->getType());
584
585   const Type* castDestType = destI->getType(); // type for the cast instr result
586   const Type* castDestRegType;          // type for cast instruction result reg
587   TmpInstruction* destForCast;          // dest for cast instruction
588   Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
589
590   // For converting an FP value to uint32_t, we first need to convert to
591   // uint64_t and then to uint32_t, as explained above.
592   if (destI->getType() == Type::UIntTy) {
593     castDestType    = Type::ULongTy;       // use this instead of type of destI
594     castDestRegType = Type::DoubleTy;      // uint64_t needs 64-bit FP register.
595     destForCast     = new TmpInstruction(mcfi, castDestRegType, opVal);
596     fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
597   }
598   else {
599     castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
600     destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
601   }
602
603   // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
604   mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
605                                            castDestType));
606
607   // Create the fpreg-to-intreg copy code
608   target.getInstrInfo().CreateCodeToCopyFloatToInt(target, F, destForCast,
609                                                    fpToIntCopyDest, mvec, mcfi);
610
611   // Create the uint64_t to uint32_t conversion, if needed
612   if (destI->getType() == Type::UIntTy)
613     target.getInstrInfo().
614       CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
615                                       /*numLowBits*/ 32, mvec, mcfi);
616 }
617
618
619 static inline MachineOpCode 
620 ChooseAddInstruction(const InstructionNode* instrNode)
621 {
622   return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
623 }
624
625
626 static inline MachineInstr* 
627 CreateMovFloatInstruction(const InstructionNode* instrNode,
628                           const Type* resultType)
629 {
630   return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
631                    .addReg(instrNode->leftChild()->getValue())
632                    .addRegDef(instrNode->getValue());
633 }
634
635 static inline MachineInstr* 
636 CreateAddConstInstruction(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) Add with 0 for float or double: use an FMOV of appropriate type,
645   //     instead of an FADD (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 ChooseSubInstructionByType(const Type* resultType)
660 {
661   MachineOpCode opCode = V9::INVALID_OPCODE;
662   
663   if (resultType->isInteger() || isa<PointerType>(resultType)) {
664       opCode = V9::SUBr;
665   } else {
666     switch(resultType->getPrimitiveID())
667     {
668     case Type::FloatTyID:  opCode = V9::FSUBS; break;
669     case Type::DoubleTyID: opCode = V9::FSUBD; break;
670     default: assert(0 && "Invalid type for SUB instruction"); break; 
671     }
672   }
673
674   return opCode;
675 }
676
677
678 static inline MachineInstr* 
679 CreateSubConstInstruction(const InstructionNode* instrNode)
680 {
681   MachineInstr* minstr = NULL;
682   
683   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
684   assert(isa<Constant>(constOp));
685   
686   // Cases worth optimizing are:
687   // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
688   //     instead of an FSUB (1 vs 3 cycles).  There is no integer MOV.
689   // 
690   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
691     double dval = FPC->getValue();
692     if (dval == 0.0)
693       minstr = CreateMovFloatInstruction(instrNode,
694                                         instrNode->getInstruction()->getType());
695   }
696   
697   return minstr;
698 }
699
700
701 static inline MachineOpCode 
702 ChooseFcmpInstruction(const InstructionNode* instrNode)
703 {
704   MachineOpCode opCode = V9::INVALID_OPCODE;
705   
706   Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
707   switch(operand->getType()->getPrimitiveID()) {
708   case Type::FloatTyID:  opCode = V9::FCMPS; break;
709   case Type::DoubleTyID: opCode = V9::FCMPD; break;
710   default: assert(0 && "Invalid type for FCMP instruction"); break; 
711   }
712   
713   return opCode;
714 }
715
716
717 // Assumes that leftArg and rightArg are both cast instructions.
718 //
719 static inline bool
720 BothFloatToDouble(const InstructionNode* instrNode)
721 {
722   InstrTreeNode* leftArg = instrNode->leftChild();
723   InstrTreeNode* rightArg = instrNode->rightChild();
724   InstrTreeNode* leftArgArg = leftArg->leftChild();
725   InstrTreeNode* rightArgArg = rightArg->leftChild();
726   assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
727   
728   // Check if both arguments are floats cast to double
729   return (leftArg->getValue()->getType() == Type::DoubleTy &&
730           leftArgArg->getValue()->getType() == Type::FloatTy &&
731           rightArgArg->getValue()->getType() == Type::FloatTy);
732 }
733
734
735 static inline MachineOpCode 
736 ChooseMulInstructionByType(const Type* resultType)
737 {
738   MachineOpCode opCode = V9::INVALID_OPCODE;
739   
740   if (resultType->isInteger())
741     opCode = V9::MULXr;
742   else
743     switch(resultType->getPrimitiveID())
744     {
745     case Type::FloatTyID:  opCode = V9::FMULS; break;
746     case Type::DoubleTyID: opCode = V9::FMULD; break;
747     default: assert(0 && "Invalid type for MUL instruction"); break; 
748     }
749   
750   return opCode;
751 }
752
753
754
755 static inline MachineInstr*
756 CreateIntNegInstruction(const TargetMachine& target,
757                         Value* vreg)
758 {
759   return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo().getZeroRegNum())
760     .addReg(vreg).addRegDef(vreg);
761 }
762
763
764 // Create instruction sequence for any shift operation.
765 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
766 // requires a second instruction for explicit sign-extension.
767 // Note that we only have to worry about a sign-bit appearing in the
768 // most significant bit of the operand after shifting (e.g., bit 32 of
769 // Int or bit 16 of Short), so we do not have to worry about results
770 // that are as large as a normal integer register.
771 // 
772 static inline void
773 CreateShiftInstructions(const TargetMachine& target,
774                         Function* F,
775                         MachineOpCode shiftOpCode,
776                         Value* argVal1,
777                         Value* optArgVal2, /* Use optArgVal2 if not NULL */
778                         unsigned optShiftNum, /* else use optShiftNum */
779                         Instruction* destVal,
780                         std::vector<MachineInstr*>& mvec,
781                         MachineCodeForInstruction& mcfi)
782 {
783   assert((optArgVal2 != NULL || optShiftNum <= 64) &&
784          "Large shift sizes unexpected, but can be handled below: "
785          "You need to check whether or not it fits in immed field below");
786   
787   // If this is a logical left shift of a type smaller than the standard
788   // integer reg. size, we have to extend the sign-bit into upper bits
789   // of dest, so we need to put the result of the SLL into a temporary.
790   // 
791   Value* shiftDest = destVal;
792   unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
793
794   if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
795     // put SLL result into a temporary
796     shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
797   }
798   
799   MachineInstr* M = (optArgVal2 != NULL)
800     ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
801                              .addReg(shiftDest, MOTy::Def)
802     : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
803                              .addReg(shiftDest, MOTy::Def);
804   mvec.push_back(M);
805   
806   if (shiftDest != destVal) {
807     // extend the sign-bit of the result into all upper bits of dest
808     assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
809     target.getInstrInfo().
810       CreateSignExtensionInstructions(target, F, shiftDest, destVal,
811                                       8*opSize, mvec, mcfi);
812   }
813 }
814
815
816 // Does not create any instructions if we cannot exploit constant to
817 // create a cheaper instruction.
818 // This returns the approximate cost of the instructions generated,
819 // which is used to pick the cheapest when both operands are constant.
820 static unsigned
821 CreateMulConstInstruction(const TargetMachine &target, Function* F,
822                           Value* lval, Value* rval, Instruction* destVal,
823                           std::vector<MachineInstr*>& mvec,
824                           MachineCodeForInstruction& mcfi)
825 {
826   /* Use max. multiply cost, viz., cost of MULX */
827   unsigned cost = target.getInstrInfo().minLatency(V9::MULXr);
828   unsigned firstNewInstr = mvec.size();
829   
830   Value* constOp = rval;
831   if (! isa<Constant>(constOp))
832     return cost;
833   
834   // Cases worth optimizing are:
835   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
836   // (2) Multiply by 2^x for integer types: replace with Shift
837   // 
838   const Type* resultType = destVal->getType();
839   
840   if (resultType->isInteger() || isa<PointerType>(resultType)) {
841     bool isValidConst;
842     int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
843                                      constOp, constOp->getType(), isValidConst);
844     if (isValidConst) {
845       unsigned pow;
846       bool needNeg = false;
847       if (C < 0) {
848         needNeg = true;
849         C = -C;
850       }
851           
852       if (C == 0 || C == 1) {
853         cost = target.getInstrInfo().minLatency(V9::ADDr);
854         unsigned Zero = target.getRegInfo().getZeroRegNum();
855         MachineInstr* M;
856         if (C == 0)
857           M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
858         else
859           M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
860         mvec.push_back(M);
861       } else if (isPowerOf2(C, pow)) {
862         unsigned opSize = target.getTargetData().getTypeSize(resultType);
863         MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
864         CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
865                                 destVal, mvec, mcfi);
866       }
867           
868       if (mvec.size() > 0 && needNeg) {
869         // insert <reg = SUB 0, reg> after the instr to flip the sign
870         MachineInstr* M = CreateIntNegInstruction(target, destVal);
871         mvec.push_back(M);
872       }
873     }
874   } else {
875     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
876       double dval = FPC->getValue();
877       if (fabs(dval) == 1) {
878         MachineOpCode opCode =  (dval < 0)
879           ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
880           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
881         mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
882       } 
883     }
884   }
885   
886   if (firstNewInstr < mvec.size()) {
887     cost = 0;
888     for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
889       cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
890   }
891   
892   return cost;
893 }
894
895
896 // Does not create any instructions if we cannot exploit constant to
897 // create a cheaper instruction.
898 // 
899 static inline void
900 CreateCheapestMulConstInstruction(const TargetMachine &target,
901                                   Function* F,
902                                   Value* lval, Value* rval,
903                                   Instruction* destVal,
904                                   std::vector<MachineInstr*>& mvec,
905                                   MachineCodeForInstruction& mcfi)
906 {
907   Value* constOp;
908   if (isa<Constant>(lval) && isa<Constant>(rval)) {
909     // both operands are constant: evaluate and "set" in dest
910     Constant* P = ConstantFoldBinaryInstruction(Instruction::Mul,
911                                                 cast<Constant>(lval),
912                                                 cast<Constant>(rval));
913     target.getInstrInfo().CreateCodeToLoadConst(target,F,P,destVal,mvec,mcfi);
914   }
915   else if (isa<Constant>(rval))         // rval is constant, but not lval
916     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
917   else if (isa<Constant>(lval))         // lval is constant, but not rval
918     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
919   
920   // else neither is constant
921   return;
922 }
923
924 // Return NULL if we cannot exploit constant to create a cheaper instruction
925 static inline void
926 CreateMulInstruction(const TargetMachine &target, Function* F,
927                      Value* lval, Value* rval, Instruction* destVal,
928                      std::vector<MachineInstr*>& mvec,
929                      MachineCodeForInstruction& mcfi,
930                      MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
931 {
932   unsigned L = mvec.size();
933   CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
934   if (mvec.size() == L) {
935     // no instructions were added so create MUL reg, reg, reg.
936     // Use FSMULD if both operands are actually floats cast to doubles.
937     // Otherwise, use the default opcode for the appropriate type.
938     MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
939                            ? forceMulOp 
940                            : ChooseMulInstructionByType(destVal->getType()));
941     mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
942                    .addRegDef(destVal));
943   }
944 }
945
946
947 // Generate a divide instruction for Div or Rem.
948 // For Rem, this assumes that the operand type will be signed if the result
949 // type is signed.  This is correct because they must have the same sign.
950 // 
951 static inline MachineOpCode 
952 ChooseDivInstruction(TargetMachine &target,
953                      const InstructionNode* instrNode)
954 {
955   MachineOpCode opCode = V9::INVALID_OPCODE;
956   
957   const Type* resultType = instrNode->getInstruction()->getType();
958   
959   if (resultType->isInteger())
960     opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
961   else
962     switch(resultType->getPrimitiveID())
963       {
964       case Type::FloatTyID:  opCode = V9::FDIVS; break;
965       case Type::DoubleTyID: opCode = V9::FDIVD; break;
966       default: assert(0 && "Invalid type for DIV instruction"); break; 
967       }
968   
969   return opCode;
970 }
971
972
973 // Return if we cannot exploit constant to create a cheaper instruction
974 static void
975 CreateDivConstInstruction(TargetMachine &target,
976                           const InstructionNode* instrNode,
977                           std::vector<MachineInstr*>& mvec)
978 {
979   Value* LHS  = instrNode->leftChild()->getValue();
980   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
981   if (!isa<Constant>(constOp))
982     return;
983
984   Instruction* destVal = instrNode->getInstruction();
985   unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
986   
987   // Cases worth optimizing are:
988   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
989   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
990   // 
991   const Type* resultType = instrNode->getInstruction()->getType();
992  
993   if (resultType->isInteger()) {
994     unsigned pow;
995     bool isValidConst;
996     int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
997                                      constOp, constOp->getType(), isValidConst);
998     if (isValidConst) {
999       bool needNeg = false;
1000       if (C < 0) {
1001         needNeg = true;
1002         C = -C;
1003       }
1004       
1005       if (C == 1) {
1006         mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
1007                        .addRegDef(destVal));
1008       } else if (isPowerOf2(C, pow)) {
1009         unsigned opCode;
1010         Value* shiftOperand;
1011         unsigned opSize = target.getTargetData().getTypeSize(resultType);
1012
1013         if (resultType->isSigned()) {
1014           // For N / 2^k, if the operand N is negative,
1015           // we need to add (2^k - 1) before right-shifting by k, i.e.,
1016           // 
1017           //    (N / 2^k) = N >> k,               if N >= 0;
1018           //                (N + 2^k - 1) >> k,   if N < 0
1019           // 
1020           // If N is <= 32 bits, use:
1021           //    sra N, 31, t1           // t1 = ~0,         if N < 0,  0 else
1022           //    srl t1, 32-k, t2        // t2 = 2^k - 1,    if N < 0,  0 else
1023           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
1024           //    sra t3, k, result       // result = N / 2^k
1025           // 
1026           // If N is 64 bits, use:
1027           //    srax N,  k-1,  t1       // t1 = sign bit in high k positions
1028           //    srlx t1, 64-k, t2       // t2 = 2^k - 1,    if N < 0,  0 else
1029           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
1030           //    sra t3, k, result       // result = N / 2^k
1031           //
1032           TmpInstruction *sraTmp, *srlTmp, *addTmp;
1033           MachineCodeForInstruction& mcfi
1034             = MachineCodeForInstruction::get(destVal);
1035           sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
1036           srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
1037           addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
1038
1039           // Create the SRA or SRAX instruction to get the sign bit
1040           mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
1041                          .addReg(LHS)
1042                          .addSImm((resultType==Type::LongTy)? pow-1 : 31)
1043                          .addRegDef(sraTmp));
1044
1045           // Create the SRL or SRLX instruction to get the sign bit
1046           mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
1047                          .addReg(sraTmp)
1048                          .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
1049                          .addRegDef(srlTmp));
1050
1051           // Create the ADD instruction to add 2^pow-1 for negative values
1052           mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
1053                          .addRegDef(addTmp));
1054
1055           // Get the shift operand and "right-shift" opcode to do the divide
1056           shiftOperand = addTmp;
1057           opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
1058         } else {
1059           // Get the shift operand and "right-shift" opcode to do the divide
1060           shiftOperand = LHS;
1061           opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
1062         }
1063
1064         // Now do the actual shift!
1065         mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
1066                        .addRegDef(destVal));
1067       }
1068           
1069       if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
1070         // insert <reg = SUB 0, reg> after the instr to flip the sign
1071         mvec.push_back(CreateIntNegInstruction(target, destVal));
1072       }
1073     }
1074   } else {
1075     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
1076       double dval = FPC->getValue();
1077       if (fabs(dval) == 1) {
1078         unsigned opCode = 
1079           (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
1080           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
1081               
1082         mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
1083       } 
1084     }
1085   }
1086 }
1087
1088
1089 static void
1090 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
1091                                 Instruction* result,
1092                                 unsigned tsize,
1093                                 Value* numElementsVal,
1094                                 std::vector<MachineInstr*>& getMvec)
1095 {
1096   Value* totalSizeVal;
1097   MachineInstr* M;
1098   MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
1099   Function *F = result->getParent()->getParent();
1100
1101   // Enforce the alignment constraints on the stack pointer at
1102   // compile time if the total size is a known constant.
1103   if (isa<Constant>(numElementsVal)) {
1104     bool isValid;
1105     int64_t numElem = (int64_t) target.getInstrInfo().
1106       ConvertConstantToIntType(target, numElementsVal,
1107                                numElementsVal->getType(), isValid);
1108     assert(isValid && "Unexpectedly large array dimension in alloca!");
1109     int64_t total = numElem * tsize;
1110     if (int extra= total % target.getFrameInfo().getStackFrameSizeAlignment())
1111       total += target.getFrameInfo().getStackFrameSizeAlignment() - extra;
1112     totalSizeVal = ConstantSInt::get(Type::IntTy, total);
1113   } else {
1114     // The size is not a constant.  Generate code to compute it and
1115     // code to pad the size for stack alignment.
1116     // Create a Value to hold the (constant) element size
1117     Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1118
1119     // Create temporary values to hold the result of MUL, SLL, SRL
1120     // To pad `size' to next smallest multiple of 16:
1121     //          size = (size + 15) & (-16 = 0xfffffffffffffff0)
1122     // 
1123     TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
1124     TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
1125     TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
1126
1127     // Instruction 1: mul numElements, typeSize -> tmpProd
1128     // This will optimize the MUL as far as possible.
1129     CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
1130                          mcfi, INVALID_MACHINE_OPCODE);
1131
1132     // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
1133     getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
1134                       .addReg(tmpAdd15, MOTy::Def));
1135
1136     // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
1137     getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
1138                       .addReg(tmpAndf0, MOTy::Def));
1139
1140     totalSizeVal = tmpAndf0;
1141   }
1142
1143   // Get the constant offset from SP for dynamically allocated storage
1144   // and create a temporary Value to hold it.
1145   MachineFunction& mcInfo = MachineFunction::get(F);
1146   bool growUp;
1147   ConstantSInt* dynamicAreaOffset =
1148     ConstantSInt::get(Type::IntTy,
1149                      target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
1150   assert(! growUp && "Has SPARC v9 stack frame convention changed?");
1151
1152   unsigned SPReg = target.getRegInfo().getStackPointer();
1153
1154   // Instruction 2: sub %sp, totalSizeVal -> %sp
1155   getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
1156                     .addMReg(SPReg,MOTy::Def));
1157
1158   // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1159   getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
1160                     .addRegDef(result));
1161 }        
1162
1163
1164 static void
1165 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
1166                              Instruction* result,
1167                              unsigned tsize,
1168                              unsigned numElements,
1169                              std::vector<MachineInstr*>& getMvec)
1170 {
1171   assert(tsize > 0 && "Illegal (zero) type size for alloca");
1172   assert(result && result->getParent() &&
1173          "Result value is not part of a function?");
1174   Function *F = result->getParent()->getParent();
1175   MachineFunction &mcInfo = MachineFunction::get(F);
1176
1177   // Put the variable in the dynamically sized area of the frame if either:
1178   // (a) The offset is too large to use as an immediate in load/stores
1179   //     (check LDX because all load/stores have the same-size immed. field).
1180   // (b) The object is "large", so it could cause many other locals,
1181   //     spills, and temporaries to have large offsets.
1182   //     NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
1183   // You've gotta love having only 13 bits for constant offset values :-|.
1184   // 
1185   unsigned paddedSize;
1186   int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
1187                                                                 paddedSize,
1188                                                          tsize * numElements);
1189
1190   if (((int)paddedSize) > 8 * target.getFrameInfo().getSizeOfEachArgOnStack() ||
1191       ! target.getInstrInfo().constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
1192     CreateCodeForVariableSizeAlloca(target, result, tsize, 
1193                                     ConstantSInt::get(Type::IntTy,numElements),
1194                                     getMvec);
1195     return;
1196   }
1197   
1198   // else offset fits in immediate field so go ahead and allocate it.
1199   offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
1200   
1201   // Create a temporary Value to hold the constant offset.
1202   // This is needed because it may not fit in the immediate field.
1203   ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1204   
1205   // Instruction 1: add %fp, offsetFromFP -> result
1206   unsigned FPReg = target.getRegInfo().getFramePointer();
1207   getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
1208                     .addRegDef(result));
1209 }
1210
1211
1212 //------------------------------------------------------------------------ 
1213 // Function SetOperandsForMemInstr
1214 //
1215 // Choose addressing mode for the given load or store instruction.
1216 // Use [reg+reg] if it is an indexed reference, and the index offset is
1217 //               not a constant or if it cannot fit in the offset field.
1218 // Use [reg+offset] in all other cases.
1219 // 
1220 // This assumes that all array refs are "lowered" to one of these forms:
1221 //      %x = load (subarray*) ptr, constant     ; single constant offset
1222 //      %x = load (subarray*) ptr, offsetVal    ; single non-constant offset
1223 // Generally, this should happen via strength reduction + LICM.
1224 // Also, strength reduction should take care of using the same register for
1225 // the loop index variable and an array index, when that is profitable.
1226 //------------------------------------------------------------------------ 
1227
1228 static void
1229 SetOperandsForMemInstr(unsigned Opcode,
1230                        std::vector<MachineInstr*>& mvec,
1231                        InstructionNode* vmInstrNode,
1232                        const TargetMachine& target)
1233 {
1234   Instruction* memInst = vmInstrNode->getInstruction();
1235   // Index vector, ptr value, and flag if all indices are const.
1236   std::vector<Value*> idxVec;
1237   bool allConstantIndices;
1238   Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
1239
1240   // Now create the appropriate operands for the machine instruction.
1241   // First, initialize so we default to storing the offset in a register.
1242   int64_t smallConstOffset = 0;
1243   Value* valueForRegOffset = NULL;
1244   MachineOperand::MachineOperandType offsetOpType =
1245     MachineOperand::MO_VirtualRegister;
1246
1247   // Check if there is an index vector and if so, compute the
1248   // right offset for structures and for arrays 
1249   // 
1250   if (!idxVec.empty()) {
1251     const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1252       
1253     // If all indices are constant, compute the combined offset directly.
1254     if (allConstantIndices) {
1255       // Compute the offset value using the index vector. Create a
1256       // virtual reg. for it since it may not fit in the immed field.
1257       uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
1258       valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1259     } else {
1260       // There is at least one non-constant offset.  Therefore, this must
1261       // be an array ref, and must have been lowered to a single non-zero
1262       // offset.  (An extra leading zero offset, if any, can be ignored.)
1263       // Generate code sequence to compute address from index.
1264       // 
1265       bool firstIdxIsZero = IsZero(idxVec[0]);
1266       assert(idxVec.size() == 1U + firstIdxIsZero 
1267              && "Array refs must be lowered before Instruction Selection");
1268
1269       Value* idxVal = idxVec[firstIdxIsZero];
1270
1271       std::vector<MachineInstr*> mulVec;
1272       Instruction* addr =
1273         new TmpInstruction(MachineCodeForInstruction::get(memInst),
1274                            Type::ULongTy, memInst);
1275
1276       // Get the array type indexed by idxVal, and compute its element size.
1277       // The call to getTypeSize() will fail if size is not constant.
1278       const Type* vecType = (firstIdxIsZero
1279                              ? GetElementPtrInst::getIndexedType(ptrType,
1280                                            std::vector<Value*>(1U, idxVec[0]),
1281                                            /*AllowCompositeLeaf*/ true)
1282                                  : ptrType);
1283       const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1284       ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
1285                                    target.getTargetData().getTypeSize(eltType));
1286
1287       // CreateMulInstruction() folds constants intelligently enough.
1288       CreateMulInstruction(target, memInst->getParent()->getParent(),
1289                            idxVal,         /* lval, not likely to be const*/
1290                            eltSizeVal,     /* rval, likely to be constant */
1291                            addr,           /* result */
1292                            mulVec, MachineCodeForInstruction::get(memInst),
1293                            INVALID_MACHINE_OPCODE);
1294
1295       assert(mulVec.size() > 0 && "No multiply code created?");
1296       mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
1297       
1298       valueForRegOffset = addr;
1299     }
1300   } else {
1301     offsetOpType = MachineOperand::MO_SignExtendedImmed;
1302     smallConstOffset = 0;
1303   }
1304
1305   // For STORE:
1306   //   Operand 0 is value, operand 1 is ptr, operand 2 is offset
1307   // For LOAD or GET_ELEMENT_PTR,
1308   //   Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1309   // 
1310   unsigned offsetOpNum, ptrOpNum;
1311   MachineInstr *MI;
1312   if (memInst->getOpcode() == Instruction::Store) {
1313     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1314       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1315                              .addReg(ptrVal).addReg(valueForRegOffset);
1316     } else {
1317       Opcode = convertOpcodeFromRegToImm(Opcode);
1318       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1319                              .addReg(ptrVal).addSImm(smallConstOffset);
1320     }
1321   } else {
1322     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1323       MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
1324                              .addRegDef(memInst);
1325     } else {
1326       Opcode = convertOpcodeFromRegToImm(Opcode);
1327       MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
1328                              .addRegDef(memInst);
1329     }
1330   }
1331   mvec.push_back(MI);
1332 }
1333
1334
1335 // 
1336 // Substitute operand `operandNum' of the instruction in node `treeNode'
1337 // in place of the use(s) of that instruction in node `parent'.
1338 // Check both explicit and implicit operands!
1339 // Also make sure to skip over a parent who:
1340 // (1) is a list node in the Burg tree, or
1341 // (2) itself had its results forwarded to its parent
1342 // 
1343 static void
1344 ForwardOperand(InstructionNode* treeNode,
1345                InstrTreeNode*   parent,
1346                int operandNum)
1347 {
1348   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1349   
1350   Instruction* unusedOp = treeNode->getInstruction();
1351   Value* fwdOp = unusedOp->getOperand(operandNum);
1352
1353   // The parent itself may be a list node, so find the real parent instruction
1354   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1355     {
1356       parent = parent->parent();
1357       assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1358     }
1359   InstructionNode* parentInstrNode = (InstructionNode*) parent;
1360   
1361   Instruction* userInstr = parentInstrNode->getInstruction();
1362   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1363
1364   // The parent's mvec would be empty if it was itself forwarded.
1365   // Recursively call ForwardOperand in that case...
1366   //
1367   if (mvec.size() == 0) {
1368     assert(parent->parent() != NULL &&
1369            "Parent could not have been forwarded, yet has no instructions?");
1370     ForwardOperand(treeNode, parent->parent(), operandNum);
1371   } else {
1372     for (unsigned i=0, N=mvec.size(); i < N; i++) {
1373       MachineInstr* minstr = mvec[i];
1374       for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
1375         const MachineOperand& mop = minstr->getOperand(i);
1376         if (mop.getType() == MachineOperand::MO_VirtualRegister &&
1377             mop.getVRegValue() == unusedOp)
1378         {
1379           minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
1380                                        fwdOp);
1381         }
1382       }
1383           
1384       for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1385         if (minstr->getImplicitRef(i) == unusedOp)
1386           minstr->setImplicitRef(i, fwdOp);
1387     }
1388   }
1389 }
1390
1391
1392 inline bool
1393 AllUsesAreBranches(const Instruction* setccI)
1394 {
1395   for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1396        UI != UE; ++UI)
1397     if (! isa<TmpInstruction>(*UI)     // ignore tmp instructions here
1398         && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1399       return false;
1400   return true;
1401 }
1402
1403 // Generate code for any intrinsic that needs a special code sequence
1404 // instead of a regular call.  If not that kind of intrinsic, do nothing.
1405 // Returns true if code was generated, otherwise false.
1406 // 
1407 bool CodeGenIntrinsic(LLVMIntrinsic::ID iid, CallInst &callInstr,
1408                       TargetMachine &target,
1409                       std::vector<MachineInstr*>& mvec)
1410 {
1411   switch (iid) {
1412   case LLVMIntrinsic::va_start: {
1413     // Get the address of the first vararg value on stack and copy it to
1414     // the argument of va_start(va_list* ap).
1415     bool ignore;
1416     Function* func = cast<Function>(callInstr.getParent()->getParent());
1417     int numFixedArgs   = func->getFunctionType()->getNumParams();
1418     int fpReg          = target.getFrameInfo().getIncomingArgBaseRegNum();
1419     int argSize        = target.getFrameInfo().getSizeOfEachArgOnStack();
1420     int firstVarArgOff = numFixedArgs * argSize + target.getFrameInfo().
1421       getFirstIncomingArgOffset(MachineFunction::get(func), ignore);
1422     mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
1423                    addReg(callInstr.getOperand(1)));
1424     return true;
1425   }
1426
1427   case LLVMIntrinsic::va_end:
1428     return true;                        // no-op on Sparc
1429
1430   case LLVMIntrinsic::va_copy:
1431     // Simple copy of current va_list (arg2) to new va_list (arg1)
1432     mvec.push_back(BuildMI(V9::ORr, 3).
1433                    addMReg(target.getRegInfo().getZeroRegNum()).
1434                    addReg(callInstr.getOperand(2)).
1435                    addReg(callInstr.getOperand(1)));
1436     return true;
1437
1438   default:
1439     return false;
1440   }
1441 }
1442
1443 //******************* Externally Visible Functions *************************/
1444
1445 //------------------------------------------------------------------------ 
1446 // External Function: ThisIsAChainRule
1447 //
1448 // Purpose:
1449 //   Check if a given BURG rule is a chain rule.
1450 //------------------------------------------------------------------------ 
1451
1452 extern bool
1453 ThisIsAChainRule(int eruleno)
1454 {
1455   switch(eruleno)
1456     {
1457     case 111:   // stmt:  reg
1458     case 123:
1459     case 124:
1460     case 125:
1461     case 126:
1462     case 127:
1463     case 128:
1464     case 129:
1465     case 130:
1466     case 131:
1467     case 132:
1468     case 133:
1469     case 155:
1470     case 221:
1471     case 222:
1472     case 241:
1473     case 242:
1474     case 243:
1475     case 244:
1476     case 245:
1477     case 321:
1478       return true; break;
1479
1480     default:
1481       return false; break;
1482     }
1483 }
1484
1485
1486 //------------------------------------------------------------------------ 
1487 // External Function: GetInstructionsByRule
1488 //
1489 // Purpose:
1490 //   Choose machine instructions for the SPARC according to the
1491 //   patterns chosen by the BURG-generated parser.
1492 //------------------------------------------------------------------------ 
1493
1494 void
1495 GetInstructionsByRule(InstructionNode* subtreeRoot,
1496                       int ruleForNode,
1497                       short* nts,
1498                       TargetMachine &target,
1499                       std::vector<MachineInstr*>& mvec)
1500 {
1501   bool checkCast = false;               // initialize here to use fall-through
1502   bool maskUnsignedResult = false;
1503   int nextRule;
1504   int forwardOperandNum = -1;
1505   unsigned allocaSize = 0;
1506   MachineInstr* M, *M2;
1507   unsigned L;
1508   bool foldCase = false;
1509
1510   mvec.clear(); 
1511   
1512   // If the code for this instruction was folded into the parent (user),
1513   // then do nothing!
1514   if (subtreeRoot->isFoldedIntoParent())
1515     return;
1516   
1517   // 
1518   // Let's check for chain rules outside the switch so that we don't have
1519   // to duplicate the list of chain rule production numbers here again
1520   // 
1521   if (ThisIsAChainRule(ruleForNode))
1522     {
1523       // Chain rules have a single nonterminal on the RHS.
1524       // Get the rule that matches the RHS non-terminal and use that instead.
1525       // 
1526       assert(nts[0] && ! nts[1]
1527              && "A chain rule should have only one RHS non-terminal!");
1528       nextRule = burm_rule(subtreeRoot->state, nts[0]);
1529       nts = burm_nts[nextRule];
1530       GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1531     }
1532   else
1533     {
1534       switch(ruleForNode) {
1535       case 1:   // stmt:   Ret
1536       case 2:   // stmt:   RetValue(reg)
1537       {         // NOTE: Prepass of register allocation is responsible
1538                 //       for moving return value to appropriate register.
1539                 // Copy the return value to the required return register.
1540                 // Mark the return Value as an implicit ref of the RET instr..
1541                 // Mark the return-address register as a hidden virtual reg.
1542                 // Finally put a NOP in the delay slot.
1543         ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
1544         Value* retVal = returnInstr->getReturnValue();
1545         MachineCodeForInstruction& mcfi =
1546           MachineCodeForInstruction::get(returnInstr);
1547
1548         // Create a hidden virtual reg to represent the return address register
1549         // used by the machine instruction but not represented in LLVM.
1550         // 
1551         Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
1552
1553         MachineInstr* retMI = 
1554           BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
1555           .addMReg(target.getRegInfo().getZeroRegNum(), MOTy::Def);
1556       
1557         // If there is a value to return, we need to:
1558         // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
1559         // (b) Insert a copy to copy the return value to the appropriate reg.
1560         //     -- For FP values, create a FMOVS or FMOVD instruction
1561         //     -- For non-FP values, create an add-with-0 instruction
1562         // 
1563         if (retVal != NULL) {
1564           const UltraSparcRegInfo& regInfo =
1565             (UltraSparcRegInfo&) target.getRegInfo();
1566           const Type* retType = retVal->getType();
1567           unsigned regClassID = regInfo.getRegClassIDOfType(retType);
1568           unsigned retRegNum = (retType->isFloatingPoint()
1569                                 ? (unsigned) SparcFloatRegClass::f0
1570                                 : (unsigned) SparcIntRegClass::i0);
1571           retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
1572
1573           // () Insert sign-extension instructions for small signed values.
1574           // 
1575           Value* retValToUse = retVal;
1576           if (retType->isIntegral() && retType->isSigned()) {
1577             unsigned retSize = target.getTargetData().getTypeSize(retType);
1578             if (retSize <= 4) {
1579               // create a temporary virtual reg. to hold the sign-extension
1580               retValToUse = new TmpInstruction(mcfi, retVal);
1581
1582               // sign-extend retVal and put the result in the temporary reg.
1583               target.getInstrInfo().CreateSignExtensionInstructions
1584                 (target, returnInstr->getParent()->getParent(),
1585                  retVal, retValToUse, 8*retSize, mvec, mcfi);
1586             }
1587           }
1588
1589           // (b) Now, insert a copy to to the appropriate register:
1590           //     -- For FP values, create a FMOVS or FMOVD instruction
1591           //     -- For non-FP values, create an add-with-0 instruction
1592           // 
1593           // First, create a virtual register to represent the register and
1594           // mark this vreg as being an implicit operand of the ret MI.
1595           TmpInstruction* retVReg = 
1596             new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
1597           
1598           retMI->addImplicitRef(retVReg);
1599           
1600           if (retType->isFloatingPoint())
1601             M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1602                  .addReg(retValToUse).addReg(retVReg, MOTy::Def));
1603           else
1604             M = (BuildMI(ChooseAddInstructionByType(retType), 3)
1605                  .addReg(retValToUse).addSImm((int64_t) 0)
1606                  .addReg(retVReg, MOTy::Def));
1607
1608           // Mark the operand with the register it should be assigned
1609           M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
1610           retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
1611
1612           mvec.push_back(M);
1613         }
1614         
1615         // Now insert the RET instruction and a NOP for the delay slot
1616         mvec.push_back(retMI);
1617         mvec.push_back(BuildMI(V9::NOP, 0));
1618         
1619         break;
1620       }  
1621         
1622       case 3:   // stmt:   Store(reg,reg)
1623       case 4:   // stmt:   Store(reg,ptrreg)
1624         SetOperandsForMemInstr(ChooseStoreInstruction(
1625                         subtreeRoot->leftChild()->getValue()->getType()),
1626                                mvec, subtreeRoot, target);
1627         break;
1628
1629       case 5:   // stmt:   BrUncond
1630         {
1631           BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1632           mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
1633         
1634           // delay slot
1635           mvec.push_back(BuildMI(V9::NOP, 0));
1636           break;
1637         }
1638
1639       case 206: // stmt:   BrCond(setCCconst)
1640       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1641         // If the constant is ZERO, we can use the branch-on-integer-register
1642         // instructions and avoid the SUBcc instruction entirely.
1643         // Otherwise this is just the same as case 5, so just fall through.
1644         // 
1645         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1646         assert(constNode &&
1647                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1648         Constant *constVal = cast<Constant>(constNode->getValue());
1649         bool isValidConst;
1650         
1651         if ((constVal->getType()->isInteger()
1652              || isa<PointerType>(constVal->getType()))
1653             && target.getInstrInfo().ConvertConstantToIntType(target,
1654                              constVal, constVal->getType(), isValidConst) == 0
1655             && isValidConst)
1656           {
1657             // That constant is a zero after all...
1658             // Use the left child of setCC as the first argument!
1659             // Mark the setCC node so that no code is generated for it.
1660             InstructionNode* setCCNode = (InstructionNode*)
1661                                          subtreeRoot->leftChild();
1662             assert(setCCNode->getOpLabel() == SetCCOp);
1663             setCCNode->markFoldedIntoParent();
1664             
1665             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1666             
1667             M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
1668                                 .addReg(setCCNode->leftChild()->getValue())
1669                                 .addPCDisp(brInst->getSuccessor(0));
1670             mvec.push_back(M);
1671             
1672             // delay slot
1673             mvec.push_back(BuildMI(V9::NOP, 0));
1674
1675             // false branch
1676             mvec.push_back(BuildMI(V9::BA, 1)
1677                            .addPCDisp(brInst->getSuccessor(1)));
1678             
1679             // delay slot
1680             mvec.push_back(BuildMI(V9::NOP, 0));
1681             break;
1682           }
1683         // ELSE FALL THROUGH
1684       }
1685
1686       case 6:   // stmt:   BrCond(setCC)
1687       { // bool => boolean was computed with SetCC.
1688         // The branch to use depends on whether it is FP, signed, or unsigned.
1689         // If it is an integer CC, we also need to find the unique
1690         // TmpInstruction representing that CC.
1691         // 
1692         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1693         const Type* setCCType;
1694         unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
1695         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1696                                      brInst->getParent()->getParent(),
1697                                      setCCType,
1698                                      MachineCodeForInstruction::get(brInst));
1699         M = BuildMI(Opcode, 2).addCCReg(ccValue)
1700                               .addPCDisp(brInst->getSuccessor(0));
1701         mvec.push_back(M);
1702
1703         // delay slot
1704         mvec.push_back(BuildMI(V9::NOP, 0));
1705
1706         // false branch
1707         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
1708
1709         // delay slot
1710         mvec.push_back(BuildMI(V9::NOP, 0));
1711         break;
1712       }
1713         
1714       case 208: // stmt:   BrCond(boolconst)
1715       {
1716         // boolconst => boolean is a constant; use BA to first or second label
1717         Constant* constVal = 
1718           cast<Constant>(subtreeRoot->leftChild()->getValue());
1719         unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1720         
1721         M = BuildMI(V9::BA, 1).addPCDisp(
1722           cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1723         mvec.push_back(M);
1724         
1725         // delay slot
1726         mvec.push_back(BuildMI(V9::NOP, 0));
1727         break;
1728       }
1729         
1730       case   8: // stmt:   BrCond(boolreg)
1731       { // boolreg   => boolean is recorded in an integer register.
1732         //              Use branch-on-integer-register instruction.
1733         // 
1734         BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1735         M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
1736           .addPCDisp(BI->getSuccessor(0));
1737         mvec.push_back(M);
1738
1739         // delay slot
1740         mvec.push_back(BuildMI(V9::NOP, 0));
1741
1742         // false branch
1743         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
1744         
1745         // delay slot
1746         mvec.push_back(BuildMI(V9::NOP, 0));
1747         break;
1748       }  
1749       
1750       case 9:   // stmt:   Switch(reg)
1751         assert(0 && "*** SWITCH instruction is not implemented yet.");
1752         break;
1753
1754       case 10:  // reg:   VRegList(reg, reg)
1755         assert(0 && "VRegList should never be the topmost non-chain rule");
1756         break;
1757
1758       case 21:  // bool:  Not(bool,reg): Compute with a conditional-move-on-reg
1759       { // First find the unary operand. It may be left or right, usually right.
1760         Instruction* notI = subtreeRoot->getInstruction();
1761         Value* notArg = BinaryOperator::getNotArgument(
1762                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
1763         unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1764
1765         // Unconditionally set register to 0
1766         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
1767
1768         // Now conditionally move 1 into the register.
1769         // Mark the register as a use (as well as a def) because the old
1770         // value will be retained if the condition is false.
1771         mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
1772                        .addReg(notI, MOTy::UseAndDef));
1773
1774         break;
1775       }
1776
1777       case 421: // reg:   BNot(reg,reg): Compute as reg = reg XOR-NOT 0
1778       { // First find the unary operand. It may be left or right, usually right.
1779         Value* notArg = BinaryOperator::getNotArgument(
1780                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
1781         unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1782         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
1783                                        .addRegDef(subtreeRoot->getValue()));
1784         break;
1785       }
1786
1787       case 322: // reg:   Not(tobool, reg):
1788         // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
1789         foldCase = true;
1790         // Just fall through!
1791
1792       case 22:  // reg:   ToBoolTy(reg):
1793       {
1794         Instruction* castI = subtreeRoot->getInstruction();
1795         Value* opVal = subtreeRoot->leftChild()->getValue();
1796         assert(opVal->getType()->isIntegral() ||
1797                isa<PointerType>(opVal->getType()));
1798
1799         // Unconditionally set register to 0
1800         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
1801
1802         // Now conditionally move 1 into the register.
1803         // Mark the register as a use (as well as a def) because the old
1804         // value will be retained if the condition is false.
1805         MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
1806         mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
1807                        .addReg(castI, MOTy::UseAndDef));
1808
1809         break;
1810       }
1811       
1812       case 23:  // reg:   ToUByteTy(reg)
1813       case 24:  // reg:   ToSByteTy(reg)
1814       case 25:  // reg:   ToUShortTy(reg)
1815       case 26:  // reg:   ToShortTy(reg)
1816       case 27:  // reg:   ToUIntTy(reg)
1817       case 28:  // reg:   ToIntTy(reg)
1818       case 29:  // reg:   ToULongTy(reg)
1819       case 30:  // reg:   ToLongTy(reg)
1820       {
1821         //======================================================================
1822         // Rules for integer conversions:
1823         // 
1824         //--------
1825         // From ISO 1998 C++ Standard, Sec. 4.7:
1826         //
1827         // 2. If the destination type is unsigned, the resulting value is
1828         // the least unsigned integer congruent to the source integer
1829         // (modulo 2n where n is the number of bits used to represent the
1830         // unsigned type). [Note: In a two s complement representation,
1831         // this conversion is conceptual and there is no change in the
1832         // bit pattern (if there is no truncation). ]
1833         // 
1834         // 3. If the destination type is signed, the value is unchanged if
1835         // it can be represented in the destination type (and bitfield width);
1836         // otherwise, the value is implementation-defined.
1837         //--------
1838         // 
1839         // Since we assume 2s complement representations, this implies:
1840         // 
1841         // -- If operand is smaller than destination, zero-extend or sign-extend
1842         //    according to the signedness of the *operand*: source decides:
1843         //    (1) If operand is signed, sign-extend it.
1844         //        If dest is unsigned, zero-ext the result!
1845         //    (2) If operand is unsigned, our current invariant is that
1846         //        it's high bits are correct, so zero-extension is not needed.
1847         // 
1848         // -- If operand is same size as or larger than destination,
1849         //    zero-extend or sign-extend according to the signedness of
1850         //    the *destination*: destination decides:
1851         //    (1) If destination is signed, sign-extend (truncating if needed)
1852         //        This choice is implementation defined.  We sign-extend the
1853         //        operand, which matches both Sun's cc and gcc3.2.
1854         //    (2) If destination is unsigned, zero-extend (truncating if needed)
1855         //======================================================================
1856
1857         Instruction* destI =  subtreeRoot->getInstruction();
1858         Function* currentFunc = destI->getParent()->getParent();
1859         MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
1860
1861         Value* opVal = subtreeRoot->leftChild()->getValue();
1862         const Type* opType = opVal->getType();
1863         const Type* destType = destI->getType();
1864         unsigned opSize   = target.getTargetData().getTypeSize(opType);
1865         unsigned destSize = target.getTargetData().getTypeSize(destType);
1866         
1867         bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
1868
1869         if (opType == Type::BoolTy ||
1870             opType == destType ||
1871             isIntegral && opSize == destSize && opSize == 8) {
1872           // nothing to do in all these cases
1873           forwardOperandNum = 0;          // forward first operand to user
1874
1875         } else if (opType->isFloatingPoint()) {
1876
1877           CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1878           if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
1879             maskUnsignedResult = true; // not handled by fp->int code
1880
1881         } else if (isIntegral) {
1882
1883           bool opSigned     = opType->isSigned();
1884           bool destSigned   = destType->isSigned();
1885           unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
1886
1887           assert(! (opSize == destSize && opSigned == destSigned) &&
1888                  "How can different int types have same size and signedness?");
1889
1890           bool signExtend = (opSize <  destSize && opSigned ||
1891                              opSize >= destSize && destSigned);
1892
1893           bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
1894                                     opSigned && !destSigned);
1895           assert(!signAndZeroExtend || signExtend);
1896
1897           bool zeroExtendOnly = opSize >= destSize && !destSigned;
1898           assert(!zeroExtendOnly || !signExtend);
1899
1900           if (signExtend) {
1901             Value* signExtDest = (signAndZeroExtend
1902                                   ? new TmpInstruction(mcfi, destType, opVal)
1903                                   : destI);
1904
1905             target.getInstrInfo().CreateSignExtensionInstructions
1906               (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
1907
1908             if (signAndZeroExtend)
1909               target.getInstrInfo().CreateZeroExtensionInstructions
1910               (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
1911           }
1912           else if (zeroExtendOnly) {
1913             target.getInstrInfo().CreateZeroExtensionInstructions
1914               (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
1915           }
1916           else
1917             forwardOperandNum = 0;          // forward first operand to user
1918
1919         } else
1920           assert(0 && "Unrecognized operand type for convert-to-integer");
1921
1922         break;
1923       }
1924       
1925       case  31: // reg:   ToFloatTy(reg):
1926       case  32: // reg:   ToDoubleTy(reg):
1927       case 232: // reg:   ToDoubleTy(Constant):
1928       
1929         // If this instruction has a parent (a user) in the tree 
1930         // and the user is translated as an FsMULd instruction,
1931         // then the cast is unnecessary.  So check that first.
1932         // In the future, we'll want to do the same for the FdMULq instruction,
1933         // so do the check here instead of only for ToFloatTy(reg).
1934         // 
1935         if (subtreeRoot->parent() != NULL) {
1936           const MachineCodeForInstruction& mcfi =
1937             MachineCodeForInstruction::get(
1938                 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1939           if (mcfi.size() == 0 || mcfi.front()->getOpCode() == V9::FSMULD)
1940             forwardOperandNum = 0;    // forward first operand to user
1941         }
1942
1943         if (forwardOperandNum != 0) {    // we do need the cast
1944           Value* leftVal = subtreeRoot->leftChild()->getValue();
1945           const Type* opType = leftVal->getType();
1946           MachineOpCode opCode=ChooseConvertToFloatInstr(target,
1947                                        subtreeRoot->getOpLabel(), opType);
1948           if (opCode == V9::NOP) {      // no conversion needed
1949             forwardOperandNum = 0;      // forward first operand to user
1950           } else {
1951             // If the source operand is a non-FP type it must be
1952             // first copied from int to float register via memory!
1953             Instruction *dest = subtreeRoot->getInstruction();
1954             Value* srcForCast;
1955             int n = 0;
1956             if (! opType->isFloatingPoint()) {
1957               // Create a temporary to represent the FP register
1958               // into which the integer will be copied via memory.
1959               // The type of this temporary will determine the FP
1960               // register used: single-prec for a 32-bit int or smaller,
1961               // double-prec for a 64-bit int.
1962               // 
1963               uint64_t srcSize =
1964                 target.getTargetData().getTypeSize(leftVal->getType());
1965               Type* tmpTypeToUse =
1966                 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1967               MachineCodeForInstruction &destMCFI = 
1968                 MachineCodeForInstruction::get(dest);
1969               srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
1970
1971               target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
1972                          dest->getParent()->getParent(),
1973                          leftVal, cast<Instruction>(srcForCast),
1974                          mvec, destMCFI);
1975             } else
1976               srcForCast = leftVal;
1977
1978             M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
1979             mvec.push_back(M);
1980           }
1981         }
1982         break;
1983
1984       case 19:  // reg:   ToArrayTy(reg):
1985       case 20:  // reg:   ToPointerTy(reg):
1986         forwardOperandNum = 0;          // forward first operand to user
1987         break;
1988
1989       case 233: // reg:   Add(reg, Constant)
1990         maskUnsignedResult = true;
1991         M = CreateAddConstInstruction(subtreeRoot);
1992         if (M != NULL) {
1993           mvec.push_back(M);
1994           break;
1995         }
1996         // ELSE FALL THROUGH
1997         
1998       case 33:  // reg:   Add(reg, reg)
1999         maskUnsignedResult = true;
2000         Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
2001         break;
2002
2003       case 234: // reg:   Sub(reg, Constant)
2004         maskUnsignedResult = true;
2005         M = CreateSubConstInstruction(subtreeRoot);
2006         if (M != NULL) {
2007           mvec.push_back(M);
2008           break;
2009         }
2010         // ELSE FALL THROUGH
2011         
2012       case 34:  // reg:   Sub(reg, reg)
2013         maskUnsignedResult = true;
2014         Add3OperandInstr(ChooseSubInstructionByType(
2015                                    subtreeRoot->getInstruction()->getType()),
2016                          subtreeRoot, mvec);
2017         break;
2018
2019       case 135: // reg:   Mul(todouble, todouble)
2020         checkCast = true;
2021         // FALL THROUGH 
2022
2023       case 35:  // reg:   Mul(reg, reg)
2024       {
2025         maskUnsignedResult = true;
2026         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2027                                  ? V9::FSMULD
2028                                  : INVALID_MACHINE_OPCODE);
2029         Instruction* mulInstr = subtreeRoot->getInstruction();
2030         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2031                              subtreeRoot->leftChild()->getValue(),
2032                              subtreeRoot->rightChild()->getValue(),
2033                              mulInstr, mvec,
2034                              MachineCodeForInstruction::get(mulInstr),forceOp);
2035         break;
2036       }
2037       case 335: // reg:   Mul(todouble, todoubleConst)
2038         checkCast = true;
2039         // FALL THROUGH 
2040
2041       case 235: // reg:   Mul(reg, Constant)
2042       {
2043         maskUnsignedResult = true;
2044         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2045                                  ? V9::FSMULD
2046                                  : INVALID_MACHINE_OPCODE);
2047         Instruction* mulInstr = subtreeRoot->getInstruction();
2048         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2049                              subtreeRoot->leftChild()->getValue(),
2050                              subtreeRoot->rightChild()->getValue(),
2051                              mulInstr, mvec,
2052                              MachineCodeForInstruction::get(mulInstr),
2053                              forceOp);
2054         break;
2055       }
2056       case 236: // reg:   Div(reg, Constant)
2057         maskUnsignedResult = true;
2058         L = mvec.size();
2059         CreateDivConstInstruction(target, subtreeRoot, mvec);
2060         if (mvec.size() > L)
2061           break;
2062         // ELSE FALL THROUGH
2063       
2064       case 36:  // reg:   Div(reg, reg)
2065       {
2066         maskUnsignedResult = true;
2067
2068         // If either operand of divide is smaller than 64 bits, we have
2069         // to make sure the unused top bits are correct because they affect
2070         // the result.  These bits are already correct for unsigned values.
2071         // They may be incorrect for signed values, so sign extend to fill in.
2072         Instruction* divI = subtreeRoot->getInstruction();
2073         Value* divOp1 = subtreeRoot->leftChild()->getValue();
2074         Value* divOp2 = subtreeRoot->rightChild()->getValue();
2075         Value* divOp1ToUse = divOp1;
2076         Value* divOp2ToUse = divOp2;
2077         if (divI->getType()->isSigned()) {
2078           unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
2079           if (opSize < 8) {
2080             MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
2081             divOp1ToUse = new TmpInstruction(mcfi, divOp1);
2082             divOp2ToUse = new TmpInstruction(mcfi, divOp2);
2083             target.getInstrInfo().
2084               CreateSignExtensionInstructions(target,
2085                                               divI->getParent()->getParent(),
2086                                               divOp1, divOp1ToUse,
2087                                               8*opSize, mvec, mcfi);
2088             target.getInstrInfo().
2089               CreateSignExtensionInstructions(target,
2090                                               divI->getParent()->getParent(),
2091                                               divOp2, divOp2ToUse,
2092                                               8*opSize, mvec, mcfi);
2093           }
2094         }
2095
2096         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2097                        .addReg(divOp1ToUse)
2098                        .addReg(divOp2ToUse)
2099                        .addRegDef(divI));
2100
2101         break;
2102       }
2103
2104       case  37: // reg:   Rem(reg, reg)
2105       case 237: // reg:   Rem(reg, Constant)
2106       {
2107         maskUnsignedResult = true;
2108
2109         Instruction* remI   = subtreeRoot->getInstruction();
2110         Value* divOp1 = subtreeRoot->leftChild()->getValue();
2111         Value* divOp2 = subtreeRoot->rightChild()->getValue();
2112
2113         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
2114         
2115         // If second operand of divide is smaller than 64 bits, we have
2116         // to make sure the unused top bits are correct because they affect
2117         // the result.  These bits are already correct for unsigned values.
2118         // They may be incorrect for signed values, so sign extend to fill in.
2119         // 
2120         Value* divOpToUse = divOp2;
2121         if (divOp2->getType()->isSigned()) {
2122           unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
2123           if (opSize < 8) {
2124             divOpToUse = new TmpInstruction(mcfi, divOp2);
2125             target.getInstrInfo().
2126               CreateSignExtensionInstructions(target,
2127                                               remI->getParent()->getParent(),
2128                                               divOp2, divOpToUse,
2129                                               8*opSize, mvec, mcfi);
2130           }
2131         }
2132
2133         // Now compute: result = rem V1, V2 as:
2134         //      result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
2135         // 
2136         TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
2137         TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
2138
2139         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2140                        .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
2141         
2142         mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
2143                        .addReg(quot).addReg(divOpToUse).addRegDef(prod));
2144         
2145         mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
2146                        .addReg(divOp1).addReg(prod).addRegDef(remI));
2147         
2148         break;
2149       }
2150       
2151       case  38: // bool:   And(bool, bool)
2152       case 138: // bool:   And(bool, not)
2153       case 238: // bool:   And(bool, boolconst)
2154       case 338: // reg :   BAnd(reg, reg)
2155       case 538: // reg :   BAnd(reg, Constant)
2156         Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
2157         break;
2158
2159       case 438: // bool:   BAnd(bool, bnot)
2160       { // Use the argument of NOT as the second argument!
2161         // Mark the NOT node so that no code is generated for it.
2162         // If the type is boolean, set 1 or 0 in the result register.
2163         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2164         Value* notArg = BinaryOperator::getNotArgument(
2165                            cast<BinaryOperator>(notNode->getInstruction()));
2166         notNode->markFoldedIntoParent();
2167         Value *lhs = subtreeRoot->leftChild()->getValue();
2168         Value *dest = subtreeRoot->getValue();
2169         mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
2170                                        .addReg(dest, MOTy::Def));
2171
2172         if (notArg->getType() == Type::BoolTy)
2173           { // set 1 in result register if result of above is non-zero
2174             mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2175                            .addReg(dest, MOTy::UseAndDef));
2176           }
2177
2178         break;
2179       }
2180
2181       case  39: // bool:   Or(bool, bool)
2182       case 139: // bool:   Or(bool, not)
2183       case 239: // bool:   Or(bool, boolconst)
2184       case 339: // reg :   BOr(reg, reg)
2185       case 539: // reg :   BOr(reg, Constant)
2186         Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
2187         break;
2188
2189       case 439: // bool:   BOr(bool, bnot)
2190       { // Use the argument of NOT as the second argument!
2191         // Mark the NOT node so that no code is generated for it.
2192         // If the type is boolean, set 1 or 0 in the result register.
2193         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2194         Value* notArg = BinaryOperator::getNotArgument(
2195                            cast<BinaryOperator>(notNode->getInstruction()));
2196         notNode->markFoldedIntoParent();
2197         Value *lhs = subtreeRoot->leftChild()->getValue();
2198         Value *dest = subtreeRoot->getValue();
2199
2200         mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
2201                        .addReg(dest, MOTy::Def));
2202
2203         if (notArg->getType() == Type::BoolTy)
2204           { // set 1 in result register if result of above is non-zero
2205             mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2206                            .addReg(dest, MOTy::UseAndDef));
2207           }
2208
2209         break;
2210       }
2211
2212       case  40: // bool:   Xor(bool, bool)
2213       case 140: // bool:   Xor(bool, not)
2214       case 240: // bool:   Xor(bool, boolconst)
2215       case 340: // reg :   BXor(reg, reg)
2216       case 540: // reg :   BXor(reg, Constant)
2217         Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
2218         break;
2219
2220       case 440: // bool:   BXor(bool, bnot)
2221       { // Use the argument of NOT as the second argument!
2222         // Mark the NOT node so that no code is generated for it.
2223         // If the type is boolean, set 1 or 0 in the result register.
2224         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2225         Value* notArg = BinaryOperator::getNotArgument(
2226                            cast<BinaryOperator>(notNode->getInstruction()));
2227         notNode->markFoldedIntoParent();
2228         Value *lhs = subtreeRoot->leftChild()->getValue();
2229         Value *dest = subtreeRoot->getValue();
2230         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
2231                        .addReg(dest, MOTy::Def));
2232
2233         if (notArg->getType() == Type::BoolTy)
2234           { // set 1 in result register if result of above is non-zero
2235             mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2236                            .addReg(dest, MOTy::UseAndDef));
2237           }
2238         break;
2239       }
2240
2241       case 41:  // setCCconst:   SetCC(reg, Constant)
2242       { // Comparison is with a constant:
2243         // 
2244         // If the bool result must be computed into a register (see below),
2245         // and the constant is int ZERO, we can use the MOVR[op] instructions
2246         // and avoid the SUBcc instruction entirely.
2247         // Otherwise this is just the same as case 42, so just fall through.
2248         // 
2249         // The result of the SetCC must be computed and stored in a register if
2250         // it is used outside the current basic block (so it must be computed
2251         // as a boolreg) or it is used by anything other than a branch.
2252         // We will use a conditional move to do this.
2253         // 
2254         Instruction* setCCInstr = subtreeRoot->getInstruction();
2255         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2256                                ! AllUsesAreBranches(setCCInstr));
2257
2258         if (computeBoolVal)
2259           {
2260             InstrTreeNode* constNode = subtreeRoot->rightChild();
2261             assert(constNode &&
2262                    constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2263             Constant *constVal = cast<Constant>(constNode->getValue());
2264             bool isValidConst;
2265             
2266             if ((constVal->getType()->isInteger()
2267                  || isa<PointerType>(constVal->getType()))
2268                 && target.getInstrInfo().ConvertConstantToIntType(target,
2269                              constVal, constVal->getType(), isValidConst) == 0
2270                 && isValidConst)
2271               {
2272                 // That constant is an integer zero after all...
2273                 // Use a MOVR[op] to compute the boolean result
2274                 // Unconditionally set register to 0
2275                 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
2276                                .addRegDef(setCCInstr));
2277                 
2278                 // Now conditionally move 1 into the register.
2279                 // Mark the register as a use (as well as a def) because the old
2280                 // value will be retained if the condition is false.
2281                 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
2282                 mvec.push_back(BuildMI(movOpCode, 3)
2283                                .addReg(subtreeRoot->leftChild()->getValue())
2284                                .addZImm(1).addReg(setCCInstr, MOTy::UseAndDef));
2285                 
2286                 break;
2287               }
2288           }
2289         // ELSE FALL THROUGH
2290       }
2291
2292       case 42:  // bool:   SetCC(reg, reg):
2293       {
2294         // This generates a SUBCC instruction, putting the difference in a
2295         // result reg. if needed, and/or setting a condition code if needed.
2296         // 
2297         Instruction* setCCInstr = subtreeRoot->getInstruction();
2298         Value* leftVal  = subtreeRoot->leftChild()->getValue();
2299         Value* rightVal = subtreeRoot->rightChild()->getValue();
2300         const Type* opType = leftVal->getType();
2301         bool isFPCompare = opType->isFloatingPoint();
2302         
2303         // If the boolean result of the SetCC is used outside the current basic
2304         // block (so it must be computed as a boolreg) or is used by anything
2305         // other than a branch, the boolean must be computed and stored
2306         // in a result register.  We will use a conditional move to do this.
2307         // 
2308         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2309                                ! AllUsesAreBranches(setCCInstr));
2310         
2311         // A TmpInstruction is created to represent the CC "result".
2312         // Unlike other instances of TmpInstruction, this one is used
2313         // by machine code of multiple LLVM instructions, viz.,
2314         // the SetCC and the branch.  Make sure to get the same one!
2315         // Note that we do this even for FP CC registers even though they
2316         // are explicit operands, because the type of the operand
2317         // needs to be a floating point condition code, not an integer
2318         // condition code.  Think of this as casting the bool result to
2319         // a FP condition code register.
2320         // Later, we mark the 4th operand as being a CC register, and as a def.
2321         // 
2322         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
2323                                     setCCInstr->getParent()->getParent(),
2324                                     leftVal->getType(),
2325                                     MachineCodeForInstruction::get(setCCInstr));
2326
2327         // If the operands are signed values smaller than 4 bytes, then they
2328         // must be sign-extended in order to do a valid 32-bit comparison
2329         // and get the right result in the 32-bit CC register (%icc).
2330         // 
2331         Value* leftOpToUse  = leftVal;
2332         Value* rightOpToUse = rightVal;
2333         if (opType->isIntegral() && opType->isSigned()) {
2334           unsigned opSize = target.getTargetData().getTypeSize(opType);
2335           if (opSize < 4) {
2336             MachineCodeForInstruction& mcfi =
2337               MachineCodeForInstruction::get(setCCInstr); 
2338
2339             // create temporary virtual regs. to hold the sign-extensions
2340             leftOpToUse  = new TmpInstruction(mcfi, leftVal);
2341             rightOpToUse = new TmpInstruction(mcfi, rightVal);
2342             
2343             // sign-extend each operand and put the result in the temporary reg.
2344             target.getInstrInfo().CreateSignExtensionInstructions
2345               (target, setCCInstr->getParent()->getParent(),
2346                leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
2347             target.getInstrInfo().CreateSignExtensionInstructions
2348               (target, setCCInstr->getParent()->getParent(),
2349                rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
2350           }
2351         }
2352
2353         if (! isFPCompare) {
2354           // Integer condition: set CC and discard result.
2355           mvec.push_back(BuildMI(V9::SUBccr, 4)
2356                          .addReg(leftOpToUse)
2357                          .addReg(rightOpToUse)
2358                          .addMReg(target.getRegInfo().getZeroRegNum(),MOTy::Def)
2359                          .addCCReg(tmpForCC, MOTy::Def));
2360         } else {
2361           // FP condition: dest of FCMP should be some FCCn register
2362           mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
2363                          .addCCReg(tmpForCC, MOTy::Def)
2364                          .addReg(leftOpToUse)
2365                          .addReg(rightOpToUse));
2366         }
2367         
2368         if (computeBoolVal) {
2369           MachineOpCode movOpCode = (isFPCompare
2370                                      ? ChooseMovFpcciInstruction(subtreeRoot)
2371                                      : ChooseMovpcciForSetCC(subtreeRoot));
2372
2373           // Unconditionally set register to 0
2374           M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
2375           mvec.push_back(M);
2376           
2377           // Now conditionally move 1 into the register.
2378           // Mark the register as a use (as well as a def) because the old
2379           // value will be retained if the condition is false.
2380           M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
2381                .addReg(setCCInstr, MOTy::UseAndDef));
2382           mvec.push_back(M);
2383         }
2384         break;
2385       }    
2386       
2387       case 51:  // reg:   Load(reg)
2388       case 52:  // reg:   Load(ptrreg)
2389         SetOperandsForMemInstr(ChooseLoadInstruction(
2390                                    subtreeRoot->getValue()->getType()),
2391                                mvec, subtreeRoot, target);
2392         break;
2393
2394       case 55:  // reg:   GetElemPtr(reg)
2395       case 56:  // reg:   GetElemPtrIdx(reg,reg)
2396         // If the GetElemPtr was folded into the user (parent), it will be
2397         // caught above.  For other cases, we have to compute the address.
2398         SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
2399         break;
2400
2401       case 57:  // reg:  Alloca: Implement as 1 instruction:
2402       {         //          add %fp, offsetFromFP -> result
2403         AllocationInst* instr =
2404           cast<AllocationInst>(subtreeRoot->getInstruction());
2405         unsigned tsize =
2406           target.getTargetData().getTypeSize(instr->getAllocatedType());
2407         assert(tsize != 0);
2408         CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2409         break;
2410       }
2411
2412       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
2413                 //      mul num, typeSz -> tmp
2414                 //      sub %sp, tmp    -> %sp
2415       {         //      add %sp, frameSizeBelowDynamicArea -> result
2416         AllocationInst* instr =
2417           cast<AllocationInst>(subtreeRoot->getInstruction());
2418         const Type* eltType = instr->getAllocatedType();
2419         
2420         // If #elements is constant, use simpler code for fixed-size allocas
2421         int tsize = (int) target.getTargetData().getTypeSize(eltType);
2422         Value* numElementsVal = NULL;
2423         bool isArray = instr->isArrayAllocation();
2424         
2425         if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
2426           // total size is constant: generate code for fixed-size alloca
2427           unsigned numElements = isArray? 
2428             cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2429           CreateCodeForFixedSizeAlloca(target, instr, tsize,
2430                                        numElements, mvec);
2431         } else {
2432           // total size is not constant.
2433           CreateCodeForVariableSizeAlloca(target, instr, tsize,
2434                                           numElementsVal, mvec);
2435         }
2436         break;
2437       }
2438
2439       case 61:  // reg:   Call
2440       {         // Generate a direct (CALL) or indirect (JMPL) call.
2441                 // Mark the return-address register, the indirection
2442                 // register (for indirect calls), the operands of the Call,
2443                 // and the return value (if any) as implicit operands
2444                 // of the machine instruction.
2445                 // 
2446                 // If this is a varargs function, floating point arguments
2447                 // have to passed in integer registers so insert
2448                 // copy-float-to-int instructions for each float operand.
2449                 // 
2450         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2451         Value *callee = callInstr->getCalledValue();
2452         Function* calledFunc = dyn_cast<Function>(callee);
2453
2454         // Check if this is an intrinsic function that needs a special code
2455         // sequence (e.g., va_start).  Indirect calls cannot be special.
2456         // 
2457         bool specialIntrinsic = false;
2458         LLVMIntrinsic::ID iid;
2459         if (calledFunc && (iid=(LLVMIntrinsic::ID)calledFunc->getIntrinsicID()))
2460           specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
2461
2462         // If not, generate the normal call sequence for the function.
2463         // This can also handle any intrinsics that are just function calls.
2464         // 
2465         if (! specialIntrinsic) {
2466           Function* currentFunc = callInstr->getParent()->getParent();
2467           MachineFunction& MF = MachineFunction::get(currentFunc);
2468           MachineCodeForInstruction& mcfi =
2469             MachineCodeForInstruction::get(callInstr); 
2470           const UltraSparcRegInfo& regInfo =
2471             (UltraSparcRegInfo&) target.getRegInfo();
2472           const TargetFrameInfo& frameInfo = target.getFrameInfo();
2473
2474           // Create hidden virtual register for return address with type void*
2475           TmpInstruction* retAddrReg =
2476             new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
2477
2478           // Generate the machine instruction and its operands.
2479           // Use CALL for direct function calls; this optimistically assumes
2480           // the PC-relative address fits in the CALL address field (22 bits).
2481           // Use JMPL for indirect calls.
2482           // This will be added to mvec later, after operand copies.
2483           // 
2484           MachineInstr* callMI;
2485           if (calledFunc)             // direct function call
2486             callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
2487           else                        // indirect function call
2488             callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
2489                       .addSImm((int64_t)0).addRegDef(retAddrReg));
2490
2491           const FunctionType* funcType =
2492             cast<FunctionType>(cast<PointerType>(callee->getType())
2493                                ->getElementType());
2494           bool isVarArgs = funcType->isVarArg();
2495           bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2496         
2497           // Use a descriptor to pass information about call arguments
2498           // to the register allocator.  This descriptor will be "owned"
2499           // and freed automatically when the MachineCodeForInstruction
2500           // object for the callInstr goes away.
2501           CallArgsDescriptor* argDesc =
2502             new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
2503           assert(callInstr->getOperand(0) == callee
2504                  && "This is assumed in the loop below!");
2505
2506           // Insert sign-extension instructions for small signed values,
2507           // if this is an unknown function (i.e., called via a funcptr)
2508           // or an external one (i.e., which may not be compiled by llc).
2509           // 
2510           if (calledFunc == NULL || calledFunc->isExternal()) {
2511             for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2512               Value* argVal = callInstr->getOperand(i);
2513               const Type* argType = argVal->getType();
2514               if (argType->isIntegral() && argType->isSigned()) {
2515                 unsigned argSize = target.getTargetData().getTypeSize(argType);
2516                 if (argSize <= 4) {
2517                   // create a temporary virtual reg. to hold the sign-extension
2518                   TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
2519
2520                   // sign-extend argVal and put the result in the temporary reg.
2521                   target.getInstrInfo().CreateSignExtensionInstructions
2522                     (target, currentFunc, argVal, argExtend,
2523                      8*argSize, mvec, mcfi);
2524
2525                   // replace argVal with argExtend in CallArgsDescriptor
2526                   argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
2527                 }
2528               }
2529             }
2530           }
2531
2532           // Insert copy instructions to get all the arguments into
2533           // all the places that they need to be.
2534           // 
2535           for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2536             int argNo = i-1;
2537             CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
2538             Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
2539             const Type* argType = argVal->getType();
2540             unsigned regType = regInfo.getRegTypeForDataType(argType);
2541             unsigned argSize = target.getTargetData().getTypeSize(argType);
2542             int regNumForArg = TargetRegInfo::getInvalidRegNum();
2543             unsigned regClassIDOfArgReg;
2544
2545             // Check for FP arguments to varargs functions.
2546             // Any such argument in the first $K$ args must be passed in an
2547             // integer register.  If there is no prototype, it must also
2548             // be passed as an FP register.
2549             // K = #integer argument registers.
2550             bool isFPArg = argVal->getType()->isFloatingPoint();
2551             if (isVarArgs && isFPArg) {
2552
2553               if (noPrototype) {
2554                 // It is a function with no prototype: pass value
2555                 // as an FP value as well as a varargs value.  The FP value
2556                 // may go in a register or on the stack.  The copy instruction
2557                 // to the outgoing reg/stack is created by the normal argument
2558                 // handling code since this is the "normal" passing mode.
2559                 // 
2560                 regNumForArg = regInfo.regNumForFPArg(regType,
2561                                                       false, false, argNo,
2562                                                       regClassIDOfArgReg);
2563                 if (regNumForArg == regInfo.getInvalidRegNum())
2564                   argInfo.setUseStackSlot();
2565                 else
2566                   argInfo.setUseFPArgReg();
2567               }
2568               
2569               // If this arg. is in the first $K$ regs, add special copy-
2570               // float-to-int instructions to pass the value as an int.
2571               // To check if it is in the first $K$, get the register
2572               // number for the arg #i.  These copy instructions are
2573               // generated here because they are extra cases and not needed
2574               // for the normal argument handling (some code reuse is
2575               // possible though -- later).
2576               // 
2577               int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
2578                                                        regClassIDOfArgReg);
2579               if (copyRegNum != regInfo.getInvalidRegNum()) {
2580                 // Create a virtual register to represent copyReg. Mark
2581                 // this vreg as being an implicit operand of the call MI
2582                 const Type* loadTy = (argType == Type::FloatTy
2583                                       ? Type::IntTy : Type::LongTy);
2584                 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
2585                                                              argVal, NULL,
2586                                                              "argRegCopy");
2587                 callMI->addImplicitRef(argVReg);
2588                 
2589                 // Get a temp stack location to use to copy
2590                 // float-to-int via the stack.
2591                 // 
2592                 // FIXME: For now, we allocate permanent space because
2593                 // the stack frame manager does not allow locals to be
2594                 // allocated (e.g., for alloca) after a temp is
2595                 // allocated!
2596                 // 
2597                 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
2598                 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
2599                     
2600                 // Generate the store from FP reg to stack
2601                 unsigned StoreOpcode = ChooseStoreInstruction(argType);
2602                 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
2603                   .addReg(argVal).addMReg(regInfo.getFramePointer())
2604                   .addSImm(tmpOffset);
2605                 mvec.push_back(M);
2606                         
2607                 // Generate the load from stack to int arg reg
2608                 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
2609                 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
2610                   .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
2611                   .addReg(argVReg, MOTy::Def);
2612
2613                 // Mark operand with register it should be assigned
2614                 // both for copy and for the callMI
2615                 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
2616                 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2617                                              copyRegNum);
2618                 mvec.push_back(M);
2619
2620                 // Add info about the argument to the CallArgsDescriptor
2621                 argInfo.setUseIntArgReg();
2622                 argInfo.setArgCopy(copyRegNum);
2623               } else {
2624                 // Cannot fit in first $K$ regs so pass arg on stack
2625                 argInfo.setUseStackSlot();
2626               }
2627             } else if (isFPArg) {
2628               // Get the outgoing arg reg to see if there is one.
2629               regNumForArg = regInfo.regNumForFPArg(regType, false, false,
2630                                                     argNo, regClassIDOfArgReg);
2631               if (regNumForArg == regInfo.getInvalidRegNum())
2632                 argInfo.setUseStackSlot();
2633               else {
2634                 argInfo.setUseFPArgReg();
2635                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2636                                                        regNumForArg);
2637               }
2638             } else {
2639               // Get the outgoing arg reg to see if there is one.
2640               regNumForArg = regInfo.regNumForIntArg(false,false,
2641                                                      argNo, regClassIDOfArgReg);
2642               if (regNumForArg == regInfo.getInvalidRegNum())
2643                 argInfo.setUseStackSlot();
2644               else {
2645                 argInfo.setUseIntArgReg();
2646                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2647                                                        regNumForArg);
2648               }
2649             }                
2650
2651             // 
2652             // Now insert copy instructions to stack slot or arg. register
2653             // 
2654             if (argInfo.usesStackSlot()) {
2655               // Get the stack offset for this argument slot.
2656               // FP args on stack are right justified so adjust offset!
2657               // int arguments are also right justified but they are
2658               // always loaded as a full double-word so the offset does
2659               // not need to be adjusted.
2660               int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
2661               if (argType->isFloatingPoint()) {
2662                 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
2663                 assert(argSize <= slotSize && "Insufficient slot size!");
2664                 argOffset += slotSize - argSize;
2665               }
2666
2667               // Now generate instruction to copy argument to stack
2668               MachineOpCode storeOpCode =
2669                 (argType->isFloatingPoint()
2670                  ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
2671
2672               M = BuildMI(storeOpCode, 3).addReg(argVal)
2673                 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
2674               mvec.push_back(M);
2675             }
2676             else if (regNumForArg != regInfo.getInvalidRegNum()) {
2677
2678               // Create a virtual register to represent the arg reg. Mark
2679               // this vreg as being an implicit operand of the call MI.
2680               TmpInstruction* argVReg = 
2681                 new TmpInstruction(mcfi, argVal, NULL, "argReg");
2682
2683               callMI->addImplicitRef(argVReg);
2684               
2685               // Generate the reg-to-reg copy into the outgoing arg reg.
2686               // -- For FP values, create a FMOVS or FMOVD instruction
2687               // -- For non-FP values, create an add-with-0 instruction
2688               if (argType->isFloatingPoint())
2689                 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
2690                    .addReg(argVal).addReg(argVReg, MOTy::Def));
2691               else
2692                 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
2693                      .addReg(argVal).addSImm((int64_t) 0)
2694                      .addReg(argVReg, MOTy::Def));
2695               
2696               // Mark the operand with the register it should be assigned
2697               M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
2698               callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2699                                            regNumForArg);
2700
2701               mvec.push_back(M);
2702             }
2703             else
2704               assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
2705                      "Arg. not in stack slot, primary or secondary register?");
2706           }
2707
2708           // add call instruction and delay slot before copying return value
2709           mvec.push_back(callMI);
2710           mvec.push_back(BuildMI(V9::NOP, 0));
2711
2712           // Add the return value as an implicit ref.  The call operands
2713           // were added above.  Also, add code to copy out the return value.
2714           // This is always register-to-register for int or FP return values.
2715           // 
2716           if (callInstr->getType() != Type::VoidTy) { 
2717             // Get the return value reg.
2718             const Type* retType = callInstr->getType();
2719
2720             int regNum = (retType->isFloatingPoint()
2721                           ? (unsigned) SparcFloatRegClass::f0 
2722                           : (unsigned) SparcIntRegClass::o0);
2723             unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2724             regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
2725
2726             // Create a virtual register to represent it and mark
2727             // this vreg as being an implicit operand of the call MI
2728             TmpInstruction* retVReg = 
2729               new TmpInstruction(mcfi, callInstr, NULL, "argReg");
2730
2731             callMI->addImplicitRef(retVReg, /*isDef*/ true);
2732
2733             // Generate the reg-to-reg copy from the return value reg.
2734             // -- For FP values, create a FMOVS or FMOVD instruction
2735             // -- For non-FP values, create an add-with-0 instruction
2736             if (retType->isFloatingPoint())
2737               M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2738                    .addReg(retVReg).addReg(callInstr, MOTy::Def));
2739             else
2740               M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2741                    .addReg(retVReg).addSImm((int64_t) 0)
2742                    .addReg(callInstr, MOTy::Def));
2743
2744             // Mark the operand with the register it should be assigned
2745             // Also mark the implicit ref of the call defining this operand
2746             M->SetRegForOperand(0, regNum);
2747             callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
2748
2749             mvec.push_back(M);
2750           }
2751
2752           // For the CALL instruction, the ret. addr. reg. is also implicit
2753           if (isa<Function>(callee))
2754             callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
2755
2756           MF.getInfo()->popAllTempValues();  // free temps used for this inst
2757         }
2758
2759         break;
2760       }
2761       
2762       case 62:  // reg:   Shl(reg, reg)
2763       {
2764         Value* argVal1 = subtreeRoot->leftChild()->getValue();
2765         Value* argVal2 = subtreeRoot->rightChild()->getValue();
2766         Instruction* shlInstr = subtreeRoot->getInstruction();
2767         
2768         const Type* opType = argVal1->getType();
2769         assert((opType->isInteger() || isa<PointerType>(opType)) &&
2770                "Shl unsupported for other types");
2771         unsigned opSize = target.getTargetData().getTypeSize(opType);
2772         
2773         CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2774                                 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
2775                                 argVal1, argVal2, 0, shlInstr, mvec,
2776                                 MachineCodeForInstruction::get(shlInstr));
2777         break;
2778       }
2779       
2780       case 63:  // reg:   Shr(reg, reg)
2781       { 
2782         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2783         assert((opType->isInteger() || isa<PointerType>(opType)) &&
2784                "Shr unsupported for other types");
2785         unsigned opSize = target.getTargetData().getTypeSize(opType);
2786         Add3OperandInstr(opType->isSigned()
2787                          ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
2788                          : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
2789                          subtreeRoot, mvec);
2790         break;
2791       }
2792       
2793       case 64:  // reg:   Phi(reg,reg)
2794         break;                          // don't forward the value
2795
2796       case 65:  // reg:   VaArg(reg)
2797       {
2798         // Use value initialized by va_start as pointer to args on the stack.
2799         // Load argument via current pointer value, then increment pointer.
2800         int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
2801         Instruction* vaArgI = subtreeRoot->getInstruction();
2802         mvec.push_back(BuildMI(V9::LDXi, 3).addReg(vaArgI->getOperand(0)).
2803                        addSImm(0).addRegDef(vaArgI));
2804         mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaArgI->getOperand(0)).
2805                        addSImm(argSize).addRegDef(vaArgI->getOperand(0)));
2806         break;
2807       }
2808       
2809       case 71:  // reg:     VReg
2810       case 72:  // reg:     Constant
2811         break;                          // don't forward the value
2812
2813       default:
2814         assert(0 && "Unrecognized BURG rule");
2815         break;
2816       }
2817     }
2818
2819   if (forwardOperandNum >= 0) {
2820     // We did not generate a machine instruction but need to use operand.
2821     // If user is in the same tree, replace Value in its machine operand.
2822     // If not, insert a copy instruction which should get coalesced away
2823     // by register allocation.
2824     if (subtreeRoot->parent() != NULL)
2825       ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2826     else {
2827       std::vector<MachineInstr*> minstrVec;
2828       Instruction* instr = subtreeRoot->getInstruction();
2829       target.getInstrInfo().
2830         CreateCopyInstructionsByType(target,
2831                                      instr->getParent()->getParent(),
2832                                      instr->getOperand(forwardOperandNum),
2833                                      instr, minstrVec,
2834                                      MachineCodeForInstruction::get(instr));
2835       assert(minstrVec.size() > 0);
2836       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2837     }
2838   }
2839
2840   if (maskUnsignedResult) {
2841     // If result is unsigned and smaller than int reg size,
2842     // we need to clear high bits of result value.
2843     assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2844     Instruction* dest = subtreeRoot->getInstruction();
2845     if (dest->getType()->isUnsigned()) {
2846       unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
2847       if (destSize <= 4) {
2848         // Mask high 64 - N bits, where N = 4*destSize.
2849         
2850         // Use a TmpInstruction to represent the
2851         // intermediate result before masking.  Since those instructions
2852         // have already been generated, go back and substitute tmpI
2853         // for dest in the result position of each one of them.
2854         // 
2855         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
2856         TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
2857                                                   dest, NULL, "maskHi");
2858         Value* srlArgToUse = tmpI;
2859
2860         unsigned numSubst = 0;
2861         for (unsigned i=0, N=mvec.size(); i < N; ++i) {
2862           bool someArgsWereIgnored = false;
2863           numSubst += mvec[i]->substituteValue(dest, tmpI, /*defsOnly*/ true,
2864                                                /*defsAndUses*/ false,
2865                                                someArgsWereIgnored);
2866           assert(!someArgsWereIgnored &&
2867                  "Operand `dest' exists but not replaced: probably bogus!");
2868         }
2869         assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
2870
2871         // Left shift 32-N if size (N) is less than 32 bits.
2872         // Use another tmp. virtual registe to represent this result.
2873         if (destSize < 4) {
2874           srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
2875                                            tmpI, NULL, "maskHi2");
2876           mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
2877                          .addZImm(8*(4-destSize))
2878                          .addReg(srlArgToUse, MOTy::Def));
2879         }
2880
2881         // Logical right shift 32-N to get zero extension in top 64-N bits.
2882         mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
2883                        .addZImm(8*(4-destSize)).addReg(dest, MOTy::Def));
2884
2885       } else if (destSize < 8) {
2886         assert(0 && "Unsupported type size: 32 < size < 64 bits");
2887       }
2888     }
2889   }
2890 }