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