1 //===-- SparcV9InstrSelection.cpp -----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // BURS instruction selection for SPARC V9 architecture.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/InstrForest.h"
20 #include "llvm/CodeGen/InstrSelection.h"
21 #include "llvm/CodeGen/MachineCodeForInstruction.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "MachineInstrAnnot.h"
26 #include "SparcV9InstrSelectionSupport.h"
27 #include "SparcV9Internals.h"
28 #include "SparcV9RegClassInfo.h"
29 #include "SparcV9RegInfo.h"
30 #include "Support/MathExtras.h"
36 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
37 std::vector<MachineInstr*>& mvec) {
38 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
39 .addReg(Node->rightChild()->getValue())
40 .addRegDef(Node->getValue()));
44 //---------------------------------------------------------------------------
45 // Function: FoldGetElemChain
48 // Fold a chain of GetElementPtr instructions containing only
49 // constant offsets into an equivalent (Pointer, IndexVector) pair.
50 // Returns the pointer Value, and stores the resulting IndexVector
51 // in argument chainIdxVec. This is a helper function for
52 // FoldConstantIndices that does the actual folding.
53 //---------------------------------------------------------------------------
56 // Check for a constant 0.
60 return (idx == ConstantSInt::getNullValue(idx->getType()));
64 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
65 bool lastInstHasLeadingNonZero)
67 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
68 GetElementPtrInst* gepInst =
69 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
71 // ptr value is not computed in this tree or ptr value does not come from GEP
76 // Return NULL if we don't fold any instructions in.
79 // Now chase the chain of getElementInstr instructions, if any.
80 // Check for any non-constant indices and stop there.
81 // Also, stop if the first index of child is a non-zero array index
82 // and the last index of the current node is a non-array index:
83 // in that case, a non-array declared type is being accessed as an array
84 // which is not type-safe, but could be legal.
86 InstructionNode* ptrChild = gepNode;
87 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
88 ptrChild->getOpLabel() == GetElemPtrIdx))
90 // Child is a GetElemPtr instruction
91 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
92 User::op_iterator OI, firstIdx = gepInst->idx_begin();
93 User::op_iterator lastIdx = gepInst->idx_end();
94 bool allConstantOffsets = true;
96 // The first index of every GEP must be an array index.
97 assert((*firstIdx)->getType() == Type::LongTy &&
98 "INTERNAL ERROR: Structure index for a pointer type!");
100 // If the last instruction had a leading non-zero index, check if the
101 // current one references a sequential (i.e., indexable) type.
102 // If not, the code is not type-safe and we would create an illegal GEP
103 // by folding them, so don't fold any more instructions.
105 if (lastInstHasLeadingNonZero)
106 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
107 break; // cannot fold in any preceding getElementPtr instrs.
109 // Check that all offsets are constant for this instruction
110 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
111 allConstantOffsets = isa<ConstantInt>(*OI);
113 if (allConstantOffsets) {
114 // Get pointer value out of ptrChild.
115 ptrVal = gepInst->getPointerOperand();
117 // Insert its index vector at the start, skipping any leading [0]
118 // Remember the old size to check if anything was inserted.
119 unsigned oldSize = chainIdxVec.size();
120 int firstIsZero = IsZero(*firstIdx);
121 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
123 // Remember if it has leading zero index: it will be discarded later.
124 if (oldSize < chainIdxVec.size())
125 lastInstHasLeadingNonZero = !firstIsZero;
127 // Mark the folded node so no code is generated for it.
128 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
130 // Get the previous GEP instruction and continue trying to fold
131 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
132 } else // cannot fold this getElementPtr instr. or any preceding ones
136 // If the first getElementPtr instruction had a leading [0], add it back.
137 // Note that this instruction is the *last* one that was successfully
138 // folded *and* contributed any indices, in the loop above.
140 if (ptrVal && ! lastInstHasLeadingNonZero)
141 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
147 //---------------------------------------------------------------------------
148 // Function: GetGEPInstArgs
151 // Helper function for GetMemInstArgs that handles the final getElementPtr
152 // instruction used by (or same as) the memory operation.
153 // Extracts the indices of the current instruction and tries to fold in
154 // preceding ones if all indices of the current one are constant.
155 //---------------------------------------------------------------------------
158 GetGEPInstArgs(InstructionNode* gepNode,
159 std::vector<Value*>& idxVec,
160 bool& allConstantIndices)
162 allConstantIndices = true;
163 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
165 // Default pointer is the one from the current instruction.
166 Value* ptrVal = gepI->getPointerOperand();
167 InstrTreeNode* ptrChild = gepNode->leftChild();
169 // Extract the index vector of the GEP instruction.
170 // If all indices are constant and first index is zero, try to fold
171 // in preceding GEPs with all constant indices.
172 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
173 allConstantIndices && OI != OE; ++OI)
174 if (! isa<Constant>(*OI))
175 allConstantIndices = false; // note: this also terminates loop!
177 // If we have only constant indices, fold chains of constant indices
178 // in this and any preceding GetElemPtr instructions.
179 bool foldedGEPs = false;
180 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
181 if (allConstantIndices)
182 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
187 // Append the index vector of the current instruction.
188 // Skip the leading [0] index if preceding GEPs were folded into this.
189 idxVec.insert(idxVec.end(),
190 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
196 //---------------------------------------------------------------------------
197 // Function: GetMemInstArgs
200 // Get the pointer value and the index vector for a memory operation
201 // (GetElementPtr, Load, or Store). If all indices of the given memory
202 // operation are constant, fold in constant indices in a chain of
203 // preceding GetElementPtr instructions (if any), and return the
204 // pointer value of the first instruction in the chain.
205 // All folded instructions are marked so no code is generated for them.
208 // Returns the pointer Value to use.
209 // Returns the resulting IndexVector in idxVec.
210 // Returns true/false in allConstantIndices if all indices are/aren't const.
211 //---------------------------------------------------------------------------
214 GetMemInstArgs(InstructionNode* memInstrNode,
215 std::vector<Value*>& idxVec,
216 bool& allConstantIndices)
218 allConstantIndices = false;
219 Instruction* memInst = memInstrNode->getInstruction();
220 assert(idxVec.size() == 0 && "Need empty vector to return indices");
222 // If there is a GetElemPtr instruction to fold in to this instr,
223 // it must be in the left child for Load and GetElemPtr, and in the
224 // right child for Store instructions.
225 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
226 ? memInstrNode->rightChild()
227 : memInstrNode->leftChild());
229 // Default pointer is the one from the current instruction.
230 Value* ptrVal = ptrChild->getValue();
232 // Find the "last" GetElemPtr instruction: this one or the immediate child.
233 // There will be none if this is a load or a store from a scalar pointer.
234 InstructionNode* gepNode = NULL;
235 if (isa<GetElementPtrInst>(memInst))
236 gepNode = memInstrNode;
237 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
238 // Child of load/store is a GEP and memInst is its only use.
239 // Use its indices and mark it as folded.
240 gepNode = cast<InstructionNode>(ptrChild);
241 gepNode->markFoldedIntoParent();
244 // If there are no indices, return the current pointer.
245 // Else extract the pointer from the GEP and fold the indices.
246 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
251 //************************ Internal Functions ******************************/
254 static inline MachineOpCode
255 ChooseBprInstruction(const InstructionNode* instrNode)
257 MachineOpCode opCode;
259 Instruction* setCCInstr =
260 ((InstructionNode*) instrNode->leftChild())->getInstruction();
262 switch(setCCInstr->getOpcode())
264 case Instruction::SetEQ: opCode = V9::BRZ; break;
265 case Instruction::SetNE: opCode = V9::BRNZ; break;
266 case Instruction::SetLE: opCode = V9::BRLEZ; break;
267 case Instruction::SetGE: opCode = V9::BRGEZ; break;
268 case Instruction::SetLT: opCode = V9::BRLZ; break;
269 case Instruction::SetGT: opCode = V9::BRGZ; break;
271 assert(0 && "Unrecognized VM instruction!");
272 opCode = V9::INVALID_OPCODE;
280 static inline MachineOpCode
281 ChooseBpccInstruction(const InstructionNode* instrNode,
282 const BinaryOperator* setCCInstr)
284 MachineOpCode opCode = V9::INVALID_OPCODE;
286 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
289 switch(setCCInstr->getOpcode())
291 case Instruction::SetEQ: opCode = V9::BE; break;
292 case Instruction::SetNE: opCode = V9::BNE; break;
293 case Instruction::SetLE: opCode = V9::BLE; break;
294 case Instruction::SetGE: opCode = V9::BGE; break;
295 case Instruction::SetLT: opCode = V9::BL; break;
296 case Instruction::SetGT: opCode = V9::BG; break;
298 assert(0 && "Unrecognized VM instruction!");
302 switch(setCCInstr->getOpcode())
304 case Instruction::SetEQ: opCode = V9::BE; break;
305 case Instruction::SetNE: opCode = V9::BNE; break;
306 case Instruction::SetLE: opCode = V9::BLEU; break;
307 case Instruction::SetGE: opCode = V9::BCC; break;
308 case Instruction::SetLT: opCode = V9::BCS; break;
309 case Instruction::SetGT: opCode = V9::BGU; break;
311 assert(0 && "Unrecognized VM instruction!");
319 static inline MachineOpCode
320 ChooseBFpccInstruction(const InstructionNode* instrNode,
321 const BinaryOperator* setCCInstr)
323 MachineOpCode opCode = V9::INVALID_OPCODE;
325 switch(setCCInstr->getOpcode())
327 case Instruction::SetEQ: opCode = V9::FBE; break;
328 case Instruction::SetNE: opCode = V9::FBNE; break;
329 case Instruction::SetLE: opCode = V9::FBLE; break;
330 case Instruction::SetGE: opCode = V9::FBGE; break;
331 case Instruction::SetLT: opCode = V9::FBL; break;
332 case Instruction::SetGT: opCode = V9::FBG; break;
334 assert(0 && "Unrecognized VM instruction!");
342 // Create a unique TmpInstruction for a boolean value,
343 // representing the CC register used by a branch on that value.
344 // For now, hack this using a little static cache of TmpInstructions.
345 // Eventually the entire BURG instruction selection should be put
346 // into a separate class that can hold such information.
347 // The static cache is not too bad because the memory for these
348 // TmpInstructions will be freed along with the rest of the Function anyway.
350 static TmpInstruction*
351 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType,
352 MachineCodeForInstruction& mcfi)
354 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
355 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
356 static const Function *lastFunction = 0;// Use to flush cache between funcs
358 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
360 if (lastFunction != F) {
362 boolToTmpCache.clear();
365 // Look for tmpI and create a new one otherwise. The new value is
366 // directly written to map using the ref returned by operator[].
367 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
369 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
375 static inline MachineOpCode
376 ChooseBccInstruction(const InstructionNode* instrNode,
377 const Type*& setCCType)
379 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
380 assert(setCCNode->getOpLabel() == SetCCOp);
381 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
382 setCCType = setCCInstr->getOperand(0)->getType();
384 if (setCCType->isFloatingPoint())
385 return ChooseBFpccInstruction(instrNode, setCCInstr);
387 return ChooseBpccInstruction(instrNode, setCCInstr);
391 // WARNING: since this function has only one caller, it always returns
392 // the opcode that expects an immediate and a register. If this function
393 // is ever used in cases where an opcode that takes two registers is required,
394 // then modify this function and use convertOpcodeFromRegToImm() where required.
396 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
397 // new cases of opcodes.
398 static inline MachineOpCode
399 ChooseMovFpcciInstruction(const InstructionNode* instrNode)
401 MachineOpCode opCode = V9::INVALID_OPCODE;
403 switch(instrNode->getInstruction()->getOpcode())
405 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
406 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
407 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
408 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
409 case Instruction::SetLT: opCode = V9::MOVFLi; break;
410 case Instruction::SetGT: opCode = V9::MOVFGi; break;
412 assert(0 && "Unrecognized VM instruction!");
420 // ChooseMovpcciForSetCC -- Choose a conditional-move instruction
421 // based on the type of SetCC operation.
423 // WARNING: since this function has only one caller, it always returns
424 // the opcode that expects an immediate and a register. If this function
425 // is ever used in cases where an opcode that takes two registers is required,
426 // then modify this function and use convertOpcodeFromRegToImm() where required.
428 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
429 // new cases of opcodes.
432 ChooseMovpcciForSetCC(const InstructionNode* instrNode)
434 MachineOpCode opCode = V9::INVALID_OPCODE;
436 const Type* opType = instrNode->leftChild()->getValue()->getType();
437 assert(opType->isIntegral() || isa<PointerType>(opType));
438 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
440 switch(instrNode->getInstruction()->getOpcode())
442 case Instruction::SetEQ: opCode = V9::MOVEi; break;
443 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
444 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
445 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
446 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
447 case Instruction::SetNE: opCode = V9::MOVNEi; break;
448 default: assert(0 && "Unrecognized LLVM instr!"); break;
455 // ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
456 // instruction based on the type of SetCC operation. These instructions
457 // compare a register with 0 and perform the move is the comparison is true.
459 // WARNING: like the previous function, this function it always returns
460 // the opcode that expects an immediate and a register. See above.
463 ChooseMovpregiForSetCC(const InstructionNode* instrNode)
465 MachineOpCode opCode = V9::INVALID_OPCODE;
467 switch(instrNode->getInstruction()->getOpcode())
469 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
470 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
471 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
472 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
473 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
474 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
475 default: assert(0 && "Unrecognized VM instr!"); break;
482 static inline MachineOpCode
483 ChooseConvertToFloatInstr(const TargetMachine& target,
484 OpLabel vopCode, const Type* opType)
486 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
487 "Unrecognized convert-to-float opcode!");
488 assert((opType->isIntegral() || opType->isFloatingPoint() ||
489 isa<PointerType>(opType))
490 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
492 MachineOpCode opCode = V9::INVALID_OPCODE;
494 unsigned opSize = target.getTargetData().getTypeSize(opType);
496 if (opType == Type::FloatTy)
497 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
498 else if (opType == Type::DoubleTy)
499 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
500 else if (opSize <= 4)
501 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
503 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
504 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
510 static inline MachineOpCode
511 ChooseConvertFPToIntInstr(const TargetMachine& target,
512 const Type* destType, const Type* opType)
514 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
515 && "This function should only be called for FLOAT or DOUBLE");
516 assert((destType->isIntegral() || isa<PointerType>(destType))
517 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
519 MachineOpCode opCode = V9::INVALID_OPCODE;
521 unsigned destSize = target.getTargetData().getTypeSize(destType);
523 if (destType == Type::UIntTy)
524 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
525 else if (destSize <= 4)
526 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
528 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
529 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
536 CreateConvertFPToIntInstr(const TargetMachine& target,
539 const Type* destType)
541 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
543 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
544 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
547 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
548 // The FP value must be converted to the dest type in an FP register,
549 // and the result is then copied from FP to int register via memory.
550 // SPARC does not have a float-to-uint conversion, only a float-to-int (fdtoi).
551 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
552 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
553 // Therefore, for converting an FP value to uint32_t, we first need to convert
554 // to uint64_t and then to uint32_t.
557 CreateCodeToConvertFloatToInt(const TargetMachine& target,
560 std::vector<MachineInstr*>& mvec,
561 MachineCodeForInstruction& mcfi)
563 Function* F = destI->getParent()->getParent();
565 // Create a temporary to represent the FP register into which the
566 // int value will placed after conversion. The type of this temporary
567 // depends on the type of FP register to use: single-prec for a 32-bit
568 // int or smaller; double-prec for a 64-bit int.
570 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
572 const Type* castDestType = destI->getType(); // type for the cast instr result
573 const Type* castDestRegType; // type for cast instruction result reg
574 TmpInstruction* destForCast; // dest for cast instruction
575 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
577 // For converting an FP value to uint32_t, we first need to convert to
578 // uint64_t and then to uint32_t, as explained above.
579 if (destI->getType() == Type::UIntTy) {
580 castDestType = Type::ULongTy; // use this instead of type of destI
581 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
582 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
583 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
586 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
587 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
590 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
591 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
594 // Create the fpreg-to-intreg copy code
595 CreateCodeToCopyFloatToInt(target, F, destForCast, fpToIntCopyDest, mvec,
598 // Create the uint64_t to uint32_t conversion, if needed
599 if (destI->getType() == Type::UIntTy)
600 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
601 /*numLowBits*/ 32, mvec, mcfi);
605 static inline MachineOpCode
606 ChooseAddInstruction(const InstructionNode* instrNode)
608 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
612 static inline MachineInstr*
613 CreateMovFloatInstruction(const InstructionNode* instrNode,
614 const Type* resultType)
616 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
617 .addReg(instrNode->leftChild()->getValue())
618 .addRegDef(instrNode->getValue());
621 static inline MachineInstr*
622 CreateAddConstInstruction(const InstructionNode* instrNode)
624 MachineInstr* minstr = NULL;
626 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
627 assert(isa<Constant>(constOp));
629 // Cases worth optimizing are:
630 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
631 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
633 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
634 double dval = FPC->getValue();
636 minstr = CreateMovFloatInstruction(instrNode,
637 instrNode->getInstruction()->getType());
644 static inline MachineOpCode
645 ChooseSubInstructionByType(const Type* resultType)
647 MachineOpCode opCode = V9::INVALID_OPCODE;
649 if (resultType->isInteger() || isa<PointerType>(resultType)) {
652 switch(resultType->getTypeID())
654 case Type::FloatTyID: opCode = V9::FSUBS; break;
655 case Type::DoubleTyID: opCode = V9::FSUBD; break;
656 default: assert(0 && "Invalid type for SUB instruction"); break;
664 static inline MachineInstr*
665 CreateSubConstInstruction(const InstructionNode* instrNode)
667 MachineInstr* minstr = NULL;
669 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
670 assert(isa<Constant>(constOp));
672 // Cases worth optimizing are:
673 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
674 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
676 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
677 double dval = FPC->getValue();
679 minstr = CreateMovFloatInstruction(instrNode,
680 instrNode->getInstruction()->getType());
687 static inline MachineOpCode
688 ChooseFcmpInstruction(const InstructionNode* instrNode)
690 MachineOpCode opCode = V9::INVALID_OPCODE;
692 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
693 switch(operand->getType()->getTypeID()) {
694 case Type::FloatTyID: opCode = V9::FCMPS; break;
695 case Type::DoubleTyID: opCode = V9::FCMPD; break;
696 default: assert(0 && "Invalid type for FCMP instruction"); break;
703 // Assumes that leftArg and rightArg are both cast instructions.
706 BothFloatToDouble(const InstructionNode* instrNode)
708 InstrTreeNode* leftArg = instrNode->leftChild();
709 InstrTreeNode* rightArg = instrNode->rightChild();
710 InstrTreeNode* leftArgArg = leftArg->leftChild();
711 InstrTreeNode* rightArgArg = rightArg->leftChild();
712 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
714 // Check if both arguments are floats cast to double
715 return (leftArg->getValue()->getType() == Type::DoubleTy &&
716 leftArgArg->getValue()->getType() == Type::FloatTy &&
717 rightArgArg->getValue()->getType() == Type::FloatTy);
721 static inline MachineOpCode
722 ChooseMulInstructionByType(const Type* resultType)
724 MachineOpCode opCode = V9::INVALID_OPCODE;
726 if (resultType->isInteger())
729 switch(resultType->getTypeID())
731 case Type::FloatTyID: opCode = V9::FMULS; break;
732 case Type::DoubleTyID: opCode = V9::FMULD; break;
733 default: assert(0 && "Invalid type for MUL instruction"); break;
741 static inline MachineInstr*
742 CreateIntNegInstruction(const TargetMachine& target,
745 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
746 .addReg(vreg).addRegDef(vreg);
750 // Create instruction sequence for any shift operation.
751 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
752 // requires a second instruction for explicit sign-extension.
753 // Note that we only have to worry about a sign-bit appearing in the
754 // most significant bit of the operand after shifting (e.g., bit 32 of
755 // Int or bit 16 of Short), so we do not have to worry about results
756 // that are as large as a normal integer register.
759 CreateShiftInstructions(const TargetMachine& target,
761 MachineOpCode shiftOpCode,
763 Value* optArgVal2, /* Use optArgVal2 if not NULL */
764 unsigned optShiftNum, /* else use optShiftNum */
765 Instruction* destVal,
766 std::vector<MachineInstr*>& mvec,
767 MachineCodeForInstruction& mcfi)
769 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
770 "Large shift sizes unexpected, but can be handled below: "
771 "You need to check whether or not it fits in immed field below");
773 // If this is a logical left shift of a type smaller than the standard
774 // integer reg. size, we have to extend the sign-bit into upper bits
775 // of dest, so we need to put the result of the SLL into a temporary.
777 Value* shiftDest = destVal;
778 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
780 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
781 // put SLL result into a temporary
782 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
785 MachineInstr* M = (optArgVal2 != NULL)
786 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
787 .addReg(shiftDest, MachineOperand::Def)
788 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
789 .addReg(shiftDest, MachineOperand::Def);
792 if (shiftDest != destVal) {
793 // extend the sign-bit of the result into all upper bits of dest
794 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
795 CreateSignExtensionInstructions(target, F, shiftDest, destVal, 8*opSize,
801 // Does not create any instructions if we cannot exploit constant to
802 // create a cheaper instruction.
803 // This returns the approximate cost of the instructions generated,
804 // which is used to pick the cheapest when both operands are constant.
806 CreateMulConstInstruction(const TargetMachine &target, Function* F,
807 Value* lval, Value* rval, Instruction* destVal,
808 std::vector<MachineInstr*>& mvec,
809 MachineCodeForInstruction& mcfi)
811 /* Use max. multiply cost, viz., cost of MULX */
812 unsigned cost = target.getInstrInfo()->minLatency(V9::MULXr);
813 unsigned firstNewInstr = mvec.size();
815 Value* constOp = rval;
816 if (! isa<Constant>(constOp))
819 // Cases worth optimizing are:
820 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
821 // (2) Multiply by 2^x for integer types: replace with Shift
823 const Type* resultType = destVal->getType();
825 if (resultType->isInteger() || isa<PointerType>(resultType)) {
827 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
832 bool needNeg = false;
838 if (C == 0 || C == 1) {
839 cost = target.getInstrInfo()->minLatency(V9::ADDr);
840 unsigned Zero = target.getRegInfo()->getZeroRegNum();
843 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
845 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
847 } else if (isPowerOf2(C, pow)) {
848 unsigned opSize = target.getTargetData().getTypeSize(resultType);
849 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
850 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
851 destVal, mvec, mcfi);
854 if (mvec.size() > 0 && needNeg) {
855 // insert <reg = SUB 0, reg> after the instr to flip the sign
856 MachineInstr* M = CreateIntNegInstruction(target, destVal);
861 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
862 double dval = FPC->getValue();
863 if (fabs(dval) == 1) {
864 MachineOpCode opCode = (dval < 0)
865 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
866 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
867 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
872 if (firstNewInstr < mvec.size()) {
874 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
875 cost += target.getInstrInfo()->minLatency(mvec[i]->getOpcode());
882 // Does not create any instructions if we cannot exploit constant to
883 // create a cheaper instruction.
886 CreateCheapestMulConstInstruction(const TargetMachine &target,
888 Value* lval, Value* rval,
889 Instruction* destVal,
890 std::vector<MachineInstr*>& mvec,
891 MachineCodeForInstruction& mcfi)
894 if (isa<Constant>(lval) && isa<Constant>(rval)) {
895 // both operands are constant: evaluate and "set" in dest
896 Constant* P = ConstantExpr::get(Instruction::Mul,
897 cast<Constant>(lval),
898 cast<Constant>(rval));
899 CreateCodeToLoadConst (target, F, P, destVal, mvec, mcfi);
901 else if (isa<Constant>(rval)) // rval is constant, but not lval
902 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
903 else if (isa<Constant>(lval)) // lval is constant, but not rval
904 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
906 // else neither is constant
910 // Return NULL if we cannot exploit constant to create a cheaper instruction
912 CreateMulInstruction(const TargetMachine &target, Function* F,
913 Value* lval, Value* rval, Instruction* destVal,
914 std::vector<MachineInstr*>& mvec,
915 MachineCodeForInstruction& mcfi,
916 MachineOpCode forceMulOp = -1)
918 unsigned L = mvec.size();
919 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
920 if (mvec.size() == L) {
921 // no instructions were added so create MUL reg, reg, reg.
922 // Use FSMULD if both operands are actually floats cast to doubles.
923 // Otherwise, use the default opcode for the appropriate type.
924 MachineOpCode mulOp = ((forceMulOp != -1)
926 : ChooseMulInstructionByType(destVal->getType()));
927 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
928 .addRegDef(destVal));
933 // Generate a divide instruction for Div or Rem.
934 // For Rem, this assumes that the operand type will be signed if the result
935 // type is signed. This is correct because they must have the same sign.
937 static inline MachineOpCode
938 ChooseDivInstruction(TargetMachine &target,
939 const InstructionNode* instrNode)
941 MachineOpCode opCode = V9::INVALID_OPCODE;
943 const Type* resultType = instrNode->getInstruction()->getType();
945 if (resultType->isInteger())
946 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
948 switch(resultType->getTypeID())
950 case Type::FloatTyID: opCode = V9::FDIVS; break;
951 case Type::DoubleTyID: opCode = V9::FDIVD; break;
952 default: assert(0 && "Invalid type for DIV instruction"); break;
959 // Return if we cannot exploit constant to create a cheaper instruction
961 CreateDivConstInstruction(TargetMachine &target,
962 const InstructionNode* instrNode,
963 std::vector<MachineInstr*>& mvec)
965 Value* LHS = instrNode->leftChild()->getValue();
966 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
967 if (!isa<Constant>(constOp))
970 Instruction* destVal = instrNode->getInstruction();
971 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
973 // Cases worth optimizing are:
974 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
975 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
977 const Type* resultType = instrNode->getInstruction()->getType();
979 if (resultType->isInteger()) {
982 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
986 bool needNeg = false;
993 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
994 .addRegDef(destVal));
995 } else if (isPowerOf2(C, pow)) {
998 unsigned opSize = target.getTargetData().getTypeSize(resultType);
1000 if (resultType->isSigned()) {
1001 // For N / 2^k, if the operand N is negative,
1002 // we need to add (2^k - 1) before right-shifting by k, i.e.,
1004 // (N / 2^k) = N >> k, if N >= 0;
1005 // (N + 2^k - 1) >> k, if N < 0
1007 // If N is <= 32 bits, use:
1008 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
1009 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1010 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1011 // sra t3, k, result // result = N / 2^k
1013 // If N is 64 bits, use:
1014 // srax N, k-1, t1 // t1 = sign bit in high k positions
1015 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1016 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1017 // sra t3, k, result // result = N / 2^k
1019 TmpInstruction *sraTmp, *srlTmp, *addTmp;
1020 MachineCodeForInstruction& mcfi
1021 = MachineCodeForInstruction::get(destVal);
1022 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
1023 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
1024 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
1026 // Create the SRA or SRAX instruction to get the sign bit
1027 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
1029 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
1030 .addRegDef(sraTmp));
1032 // Create the SRL or SRLX instruction to get the sign bit
1033 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
1035 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
1036 .addRegDef(srlTmp));
1038 // Create the ADD instruction to add 2^pow-1 for negative values
1039 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
1040 .addRegDef(addTmp));
1042 // Get the shift operand and "right-shift" opcode to do the divide
1043 shiftOperand = addTmp;
1044 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
1046 // Get the shift operand and "right-shift" opcode to do the divide
1048 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
1051 // Now do the actual shift!
1052 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
1053 .addRegDef(destVal));
1056 if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
1057 // insert <reg = SUB 0, reg> after the instr to flip the sign
1058 mvec.push_back(CreateIntNegInstruction(target, destVal));
1062 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
1063 double dval = FPC->getValue();
1064 if (fabs(dval) == 1) {
1066 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
1067 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
1069 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
1077 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
1078 Instruction* result,
1080 Value* numElementsVal,
1081 std::vector<MachineInstr*>& getMvec)
1083 Value* totalSizeVal;
1085 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
1086 Function *F = result->getParent()->getParent();
1088 // Enforce the alignment constraints on the stack pointer at
1089 // compile time if the total size is a known constant.
1090 if (isa<Constant>(numElementsVal)) {
1092 int64_t numElem = (int64_t)
1093 ConvertConstantToIntType(target, numElementsVal,
1094 numElementsVal->getType(), isValid);
1095 assert(isValid && "Unexpectedly large array dimension in alloca!");
1096 int64_t total = numElem * tsize;
1097 if (int extra= total % target.getFrameInfo()->getStackFrameSizeAlignment())
1098 total += target.getFrameInfo()->getStackFrameSizeAlignment() - extra;
1099 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
1101 // The size is not a constant. Generate code to compute it and
1102 // code to pad the size for stack alignment.
1103 // Create a Value to hold the (constant) element size
1104 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1106 // Create temporary values to hold the result of MUL, SLL, SRL
1107 // To pad `size' to next smallest multiple of 16:
1108 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
1110 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
1111 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
1112 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
1114 // Instruction 1: mul numElements, typeSize -> tmpProd
1115 // This will optimize the MUL as far as possible.
1116 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
1119 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
1120 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
1121 .addReg(tmpAdd15, MachineOperand::Def));
1123 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
1124 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
1125 .addReg(tmpAndf0, MachineOperand::Def));
1127 totalSizeVal = tmpAndf0;
1130 // Get the constant offset from SP for dynamically allocated storage
1131 // and create a temporary Value to hold it.
1132 MachineFunction& mcInfo = MachineFunction::get(F);
1134 ConstantSInt* dynamicAreaOffset =
1135 ConstantSInt::get(Type::IntTy,
1136 target.getFrameInfo()->getDynamicAreaOffset(mcInfo,growUp));
1137 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
1139 unsigned SPReg = target.getRegInfo()->getStackPointer();
1141 // Instruction 2: sub %sp, totalSizeVal -> %sp
1142 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
1143 .addMReg(SPReg,MachineOperand::Def));
1145 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1146 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
1147 .addRegDef(result));
1152 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
1153 Instruction* result,
1155 unsigned numElements,
1156 std::vector<MachineInstr*>& getMvec)
1158 assert(result && result->getParent() &&
1159 "Result value is not part of a function?");
1160 Function *F = result->getParent()->getParent();
1161 MachineFunction &mcInfo = MachineFunction::get(F);
1163 // If the alloca is of zero bytes (which is perfectly legal) we bump it up to
1164 // one byte. This is unnecessary, but I really don't want to break any
1165 // fragile logic in this code. FIXME.
1170 // Put the variable in the dynamically sized area of the frame if either:
1171 // (a) The offset is too large to use as an immediate in load/stores
1172 // (check LDX because all load/stores have the same-size immed. field).
1173 // (b) The object is "large", so it could cause many other locals,
1174 // spills, and temporaries to have large offsets.
1175 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
1176 // You've gotta love having only 13 bits for constant offset values :-|.
1178 unsigned paddedSize;
1179 int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
1181 tsize * numElements);
1183 if (((int)paddedSize) > 8 * target.getFrameInfo()->getSizeOfEachArgOnStack() ||
1184 ! target.getInstrInfo()->constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
1185 CreateCodeForVariableSizeAlloca(target, result, tsize,
1186 ConstantSInt::get(Type::IntTy,numElements),
1191 // else offset fits in immediate field so go ahead and allocate it.
1192 offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
1194 // Create a temporary Value to hold the constant offset.
1195 // This is needed because it may not fit in the immediate field.
1196 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1198 // Instruction 1: add %fp, offsetFromFP -> result
1199 unsigned FPReg = target.getRegInfo()->getFramePointer();
1200 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
1201 .addRegDef(result));
1205 //------------------------------------------------------------------------
1206 // Function SetOperandsForMemInstr
1208 // Choose addressing mode for the given load or store instruction.
1209 // Use [reg+reg] if it is an indexed reference, and the index offset is
1210 // not a constant or if it cannot fit in the offset field.
1211 // Use [reg+offset] in all other cases.
1213 // This assumes that all array refs are "lowered" to one of these forms:
1214 // %x = load (subarray*) ptr, constant ; single constant offset
1215 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
1216 // Generally, this should happen via strength reduction + LICM.
1217 // Also, strength reduction should take care of using the same register for
1218 // the loop index variable and an array index, when that is profitable.
1219 //------------------------------------------------------------------------
1222 SetOperandsForMemInstr(unsigned Opcode,
1223 std::vector<MachineInstr*>& mvec,
1224 InstructionNode* vmInstrNode,
1225 const TargetMachine& target)
1227 Instruction* memInst = vmInstrNode->getInstruction();
1228 // Index vector, ptr value, and flag if all indices are const.
1229 std::vector<Value*> idxVec;
1230 bool allConstantIndices;
1231 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
1233 // Now create the appropriate operands for the machine instruction.
1234 // First, initialize so we default to storing the offset in a register.
1235 int64_t smallConstOffset = 0;
1236 Value* valueForRegOffset = NULL;
1237 MachineOperand::MachineOperandType offsetOpType =
1238 MachineOperand::MO_VirtualRegister;
1240 // Check if there is an index vector and if so, compute the
1241 // right offset for structures and for arrays
1243 if (!idxVec.empty()) {
1244 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1246 // If all indices are constant, compute the combined offset directly.
1247 if (allConstantIndices) {
1248 // Compute the offset value using the index vector. Create a
1249 // virtual reg. for it since it may not fit in the immed field.
1250 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
1251 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1253 // There is at least one non-constant offset. Therefore, this must
1254 // be an array ref, and must have been lowered to a single non-zero
1255 // offset. (An extra leading zero offset, if any, can be ignored.)
1256 // Generate code sequence to compute address from index.
1258 bool firstIdxIsZero = IsZero(idxVec[0]);
1259 assert(idxVec.size() == 1U + firstIdxIsZero
1260 && "Array refs must be lowered before Instruction Selection");
1262 Value* idxVal = idxVec[firstIdxIsZero];
1264 std::vector<MachineInstr*> mulVec;
1266 new TmpInstruction(MachineCodeForInstruction::get(memInst),
1267 Type::ULongTy, memInst);
1269 // Get the array type indexed by idxVal, and compute its element size.
1270 // The call to getTypeSize() will fail if size is not constant.
1271 const Type* vecType = (firstIdxIsZero
1272 ? GetElementPtrInst::getIndexedType(ptrType,
1273 std::vector<Value*>(1U, idxVec[0]),
1274 /*AllowCompositeLeaf*/ true)
1276 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1277 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
1278 target.getTargetData().getTypeSize(eltType));
1280 // CreateMulInstruction() folds constants intelligently enough.
1281 CreateMulInstruction(target, memInst->getParent()->getParent(),
1282 idxVal, /* lval, not likely to be const*/
1283 eltSizeVal, /* rval, likely to be constant */
1285 mulVec, MachineCodeForInstruction::get(memInst),
1288 assert(mulVec.size() > 0 && "No multiply code created?");
1289 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
1291 valueForRegOffset = addr;
1294 offsetOpType = MachineOperand::MO_SignExtendedImmed;
1295 smallConstOffset = 0;
1299 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
1300 // For LOAD or GET_ELEMENT_PTR,
1301 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1303 unsigned offsetOpNum, ptrOpNum;
1305 if (memInst->getOpcode() == Instruction::Store) {
1306 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1307 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1308 .addReg(ptrVal).addReg(valueForRegOffset);
1310 Opcode = convertOpcodeFromRegToImm(Opcode);
1311 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1312 .addReg(ptrVal).addSImm(smallConstOffset);
1315 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1316 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
1317 .addRegDef(memInst);
1319 Opcode = convertOpcodeFromRegToImm(Opcode);
1320 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
1321 .addRegDef(memInst);
1329 // Substitute operand `operandNum' of the instruction in node `treeNode'
1330 // in place of the use(s) of that instruction in node `parent'.
1331 // Check both explicit and implicit operands!
1332 // Also make sure to skip over a parent who:
1333 // (1) is a list node in the Burg tree, or
1334 // (2) itself had its results forwarded to its parent
1337 ForwardOperand(InstructionNode* treeNode,
1338 InstrTreeNode* parent,
1341 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1343 Instruction* unusedOp = treeNode->getInstruction();
1344 Value* fwdOp = unusedOp->getOperand(operandNum);
1346 // The parent itself may be a list node, so find the real parent instruction
1347 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1349 parent = parent->parent();
1350 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1352 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1354 Instruction* userInstr = parentInstrNode->getInstruction();
1355 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1357 // The parent's mvec would be empty if it was itself forwarded.
1358 // Recursively call ForwardOperand in that case...
1360 if (mvec.size() == 0) {
1361 assert(parent->parent() != NULL &&
1362 "Parent could not have been forwarded, yet has no instructions?");
1363 ForwardOperand(treeNode, parent->parent(), operandNum);
1365 for (unsigned i=0, N=mvec.size(); i < N; i++) {
1366 MachineInstr* minstr = mvec[i];
1367 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
1368 const MachineOperand& mop = minstr->getOperand(i);
1369 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
1370 mop.getVRegValue() == unusedOp)
1372 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
1377 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1378 if (minstr->getImplicitRef(i) == unusedOp)
1379 minstr->setImplicitRef(i, fwdOp);
1386 AllUsesAreBranches(const Instruction* setccI)
1388 for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1390 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
1391 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1396 // Generate code for any intrinsic that needs a special code sequence
1397 // instead of a regular call. If not that kind of intrinsic, do nothing.
1398 // Returns true if code was generated, otherwise false.
1400 static bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
1401 TargetMachine &target,
1402 std::vector<MachineInstr*>& mvec) {
1405 assert(0 && "Unknown intrinsic function call should have been lowered!");
1406 case Intrinsic::vastart: {
1407 // Get the address of the first incoming vararg argument on the stack
1409 Function* func = cast<Function>(callInstr.getParent()->getParent());
1410 int numFixedArgs = func->getFunctionType()->getNumParams();
1411 int fpReg = target.getFrameInfo()->getIncomingArgBaseRegNum();
1412 int argSize = target.getFrameInfo()->getSizeOfEachArgOnStack();
1413 int firstVarArgOff = numFixedArgs * argSize + target.getFrameInfo()->
1414 getFirstIncomingArgOffset(MachineFunction::get(func), ignore);
1415 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
1416 addRegDef(&callInstr));
1420 case Intrinsic::vaend:
1421 return true; // no-op on SparcV9
1423 case Intrinsic::vacopy:
1424 // Simple copy of current va_list (arg1) to new va_list (result)
1425 mvec.push_back(BuildMI(V9::ORr, 3).
1426 addMReg(target.getRegInfo()->getZeroRegNum()).
1427 addReg(callInstr.getOperand(1)).
1428 addRegDef(&callInstr));
1433 //******************* Externally Visible Functions *************************/
1435 //------------------------------------------------------------------------
1436 // External Function: ThisIsAChainRule
1439 // Check if a given BURG rule is a chain rule.
1440 //------------------------------------------------------------------------
1443 ThisIsAChainRule(int eruleno)
1447 case 111: // stmt: reg
1471 return false; break;
1476 //------------------------------------------------------------------------
1477 // External Function: GetInstructionsByRule
1480 // Choose machine instructions for the SPARC according to the
1481 // patterns chosen by the BURG-generated parser.
1482 //------------------------------------------------------------------------
1485 GetInstructionsByRule(InstructionNode* subtreeRoot,
1488 TargetMachine &target,
1489 std::vector<MachineInstr*>& mvec)
1491 bool checkCast = false; // initialize here to use fall-through
1492 bool maskUnsignedResult = false;
1494 int forwardOperandNum = -1;
1495 unsigned allocaSize = 0;
1496 MachineInstr* M, *M2;
1498 bool foldCase = false;
1502 // If the code for this instruction was folded into the parent (user),
1504 if (subtreeRoot->isFoldedIntoParent())
1508 // Let's check for chain rules outside the switch so that we don't have
1509 // to duplicate the list of chain rule production numbers here again
1511 if (ThisIsAChainRule(ruleForNode)) {
1512 // Chain rules have a single nonterminal on the RHS.
1513 // Get the rule that matches the RHS non-terminal and use that instead.
1515 assert(nts[0] && ! nts[1]
1516 && "A chain rule should have only one RHS non-terminal!");
1517 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1518 nts = burm_nts[nextRule];
1519 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1521 switch(ruleForNode) {
1522 case 1: // stmt: Ret
1523 case 2: // stmt: RetValue(reg)
1524 { // NOTE: Prepass of register allocation is responsible
1525 // for moving return value to appropriate register.
1526 // Copy the return value to the required return register.
1527 // Mark the return Value as an implicit ref of the RET instr..
1528 // Mark the return-address register as a hidden virtual reg.
1529 // Finally put a NOP in the delay slot.
1530 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
1531 Value* retVal = returnInstr->getReturnValue();
1532 MachineCodeForInstruction& mcfi =
1533 MachineCodeForInstruction::get(returnInstr);
1535 // Create a hidden virtual reg to represent the return address register
1536 // used by the machine instruction but not represented in LLVM.
1538 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
1540 MachineInstr* retMI =
1541 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
1542 .addMReg(target.getRegInfo()->getZeroRegNum(), MachineOperand::Def);
1544 // If there is a value to return, we need to:
1545 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
1546 // (b) Insert a copy to copy the return value to the appropriate reg.
1547 // -- For FP values, create a FMOVS or FMOVD instruction
1548 // -- For non-FP values, create an add-with-0 instruction
1550 if (retVal != NULL) {
1551 const SparcV9RegInfo& regInfo =
1552 (SparcV9RegInfo&) *target.getRegInfo();
1553 const Type* retType = retVal->getType();
1554 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
1555 unsigned retRegNum = (retType->isFloatingPoint()
1556 ? (unsigned) SparcV9FloatRegClass::f0
1557 : (unsigned) SparcV9IntRegClass::i0);
1558 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
1560 // () Insert sign-extension instructions for small signed values.
1562 Value* retValToUse = retVal;
1563 if (retType->isIntegral() && retType->isSigned()) {
1564 unsigned retSize = target.getTargetData().getTypeSize(retType);
1566 // create a temporary virtual reg. to hold the sign-extension
1567 retValToUse = new TmpInstruction(mcfi, retVal);
1569 // sign-extend retVal and put the result in the temporary reg.
1570 CreateSignExtensionInstructions
1571 (target, returnInstr->getParent()->getParent(),
1572 retVal, retValToUse, 8*retSize, mvec, mcfi);
1576 // (b) Now, insert a copy to to the appropriate register:
1577 // -- For FP values, create a FMOVS or FMOVD instruction
1578 // -- For non-FP values, create an add-with-0 instruction
1580 // First, create a virtual register to represent the register and
1581 // mark this vreg as being an implicit operand of the ret MI.
1582 TmpInstruction* retVReg =
1583 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
1585 retMI->addImplicitRef(retVReg);
1587 if (retType->isFloatingPoint())
1588 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1589 .addReg(retValToUse).addReg(retVReg, MachineOperand::Def));
1591 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
1592 .addReg(retValToUse).addSImm((int64_t) 0)
1593 .addReg(retVReg, MachineOperand::Def));
1595 // Mark the operand with the register it should be assigned
1596 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
1597 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
1602 // Now insert the RET instruction and a NOP for the delay slot
1603 mvec.push_back(retMI);
1604 mvec.push_back(BuildMI(V9::NOP, 0));
1609 case 3: // stmt: Store(reg,reg)
1610 case 4: // stmt: Store(reg,ptrreg)
1611 SetOperandsForMemInstr(ChooseStoreInstruction(
1612 subtreeRoot->leftChild()->getValue()->getType()),
1613 mvec, subtreeRoot, target);
1616 case 5: // stmt: BrUncond
1618 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1619 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
1622 mvec.push_back(BuildMI(V9::NOP, 0));
1626 case 206: // stmt: BrCond(setCCconst)
1627 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1628 // If the constant is ZERO, we can use the branch-on-integer-register
1629 // instructions and avoid the SUBcc instruction entirely.
1630 // Otherwise this is just the same as case 5, so just fall through.
1632 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1634 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1635 Constant *constVal = cast<Constant>(constNode->getValue());
1638 if ((constVal->getType()->isInteger()
1639 || isa<PointerType>(constVal->getType()))
1640 && ConvertConstantToIntType(target,
1641 constVal, constVal->getType(), isValidConst) == 0
1644 // That constant is a zero after all...
1645 // Use the left child of setCC as the first argument!
1646 // Mark the setCC node so that no code is generated for it.
1647 InstructionNode* setCCNode = (InstructionNode*)
1648 subtreeRoot->leftChild();
1649 assert(setCCNode->getOpLabel() == SetCCOp);
1650 setCCNode->markFoldedIntoParent();
1652 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1654 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
1655 .addReg(setCCNode->leftChild()->getValue())
1656 .addPCDisp(brInst->getSuccessor(0));
1660 mvec.push_back(BuildMI(V9::NOP, 0));
1663 mvec.push_back(BuildMI(V9::BA, 1)
1664 .addPCDisp(brInst->getSuccessor(1)));
1667 mvec.push_back(BuildMI(V9::NOP, 0));
1670 // ELSE FALL THROUGH
1673 case 6: // stmt: BrCond(setCC)
1674 { // bool => boolean was computed with SetCC.
1675 // The branch to use depends on whether it is FP, signed, or unsigned.
1676 // If it is an integer CC, we also need to find the unique
1677 // TmpInstruction representing that CC.
1679 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1680 const Type* setCCType;
1681 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
1682 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1683 brInst->getParent()->getParent(),
1685 MachineCodeForInstruction::get(brInst));
1686 M = BuildMI(Opcode, 2).addCCReg(ccValue)
1687 .addPCDisp(brInst->getSuccessor(0));
1691 mvec.push_back(BuildMI(V9::NOP, 0));
1694 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
1697 mvec.push_back(BuildMI(V9::NOP, 0));
1701 case 208: // stmt: BrCond(boolconst)
1703 // boolconst => boolean is a constant; use BA to first or second label
1704 Constant* constVal =
1705 cast<Constant>(subtreeRoot->leftChild()->getValue());
1706 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1708 M = BuildMI(V9::BA, 1).addPCDisp(
1709 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1713 mvec.push_back(BuildMI(V9::NOP, 0));
1717 case 8: // stmt: BrCond(boolreg)
1718 { // boolreg => boolean is recorded in an integer register.
1719 // Use branch-on-integer-register instruction.
1721 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1722 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
1723 .addPCDisp(BI->getSuccessor(0));
1727 mvec.push_back(BuildMI(V9::NOP, 0));
1730 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
1733 mvec.push_back(BuildMI(V9::NOP, 0));
1737 case 9: // stmt: Switch(reg)
1738 assert(0 && "*** SWITCH instruction is not implemented yet.");
1741 case 10: // reg: VRegList(reg, reg)
1742 assert(0 && "VRegList should never be the topmost non-chain rule");
1745 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
1746 { // First find the unary operand. It may be left or right, usually right.
1747 Instruction* notI = subtreeRoot->getInstruction();
1748 Value* notArg = BinaryOperator::getNotArgument(
1749 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1750 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
1752 // Unconditionally set register to 0
1753 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
1755 // Now conditionally move 1 into the register.
1756 // Mark the register as a use (as well as a def) because the old
1757 // value will be retained if the condition is false.
1758 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
1759 .addReg(notI, MachineOperand::UseAndDef));
1764 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
1765 { // First find the unary operand. It may be left or right, usually right.
1766 Value* notArg = BinaryOperator::getNotArgument(
1767 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1768 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
1769 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
1770 .addRegDef(subtreeRoot->getValue()));
1774 case 322: // reg: Not(tobool, reg):
1775 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
1777 // Just fall through!
1779 case 22: // reg: ToBoolTy(reg):
1781 Instruction* castI = subtreeRoot->getInstruction();
1782 Value* opVal = subtreeRoot->leftChild()->getValue();
1783 assert(opVal->getType()->isIntegral() ||
1784 isa<PointerType>(opVal->getType()));
1786 // Unconditionally set register to 0
1787 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
1789 // Now conditionally move 1 into the register.
1790 // Mark the register as a use (as well as a def) because the old
1791 // value will be retained if the condition is false.
1792 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
1793 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
1794 .addReg(castI, MachineOperand::UseAndDef));
1799 case 23: // reg: ToUByteTy(reg)
1800 case 24: // reg: ToSByteTy(reg)
1801 case 25: // reg: ToUShortTy(reg)
1802 case 26: // reg: ToShortTy(reg)
1803 case 27: // reg: ToUIntTy(reg)
1804 case 28: // reg: ToIntTy(reg)
1805 case 29: // reg: ToULongTy(reg)
1806 case 30: // reg: ToLongTy(reg)
1808 //======================================================================
1809 // Rules for integer conversions:
1812 // From ISO 1998 C++ Standard, Sec. 4.7:
1814 // 2. If the destination type is unsigned, the resulting value is
1815 // the least unsigned integer congruent to the source integer
1816 // (modulo 2n where n is the number of bits used to represent the
1817 // unsigned type). [Note: In a two s complement representation,
1818 // this conversion is conceptual and there is no change in the
1819 // bit pattern (if there is no truncation). ]
1821 // 3. If the destination type is signed, the value is unchanged if
1822 // it can be represented in the destination type (and bitfield width);
1823 // otherwise, the value is implementation-defined.
1826 // Since we assume 2s complement representations, this implies:
1828 // -- If operand is smaller than destination, zero-extend or sign-extend
1829 // according to the signedness of the *operand*: source decides:
1830 // (1) If operand is signed, sign-extend it.
1831 // If dest is unsigned, zero-ext the result!
1832 // (2) If operand is unsigned, our current invariant is that
1833 // it's high bits are correct, so zero-extension is not needed.
1835 // -- If operand is same size as or larger than destination,
1836 // zero-extend or sign-extend according to the signedness of
1837 // the *destination*: destination decides:
1838 // (1) If destination is signed, sign-extend (truncating if needed)
1839 // This choice is implementation defined. We sign-extend the
1840 // operand, which matches both Sun's cc and gcc3.2.
1841 // (2) If destination is unsigned, zero-extend (truncating if needed)
1842 //======================================================================
1844 Instruction* destI = subtreeRoot->getInstruction();
1845 Function* currentFunc = destI->getParent()->getParent();
1846 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
1848 Value* opVal = subtreeRoot->leftChild()->getValue();
1849 const Type* opType = opVal->getType();
1850 const Type* destType = destI->getType();
1851 unsigned opSize = target.getTargetData().getTypeSize(opType);
1852 unsigned destSize = target.getTargetData().getTypeSize(destType);
1854 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
1856 if (opType == Type::BoolTy ||
1857 opType == destType ||
1858 isIntegral && opSize == destSize && opSize == 8) {
1859 // nothing to do in all these cases
1860 forwardOperandNum = 0; // forward first operand to user
1862 } else if (opType->isFloatingPoint()) {
1864 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1865 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
1866 maskUnsignedResult = true; // not handled by fp->int code
1868 } else if (isIntegral) {
1870 bool opSigned = opType->isSigned();
1871 bool destSigned = destType->isSigned();
1872 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
1874 assert(! (opSize == destSize && opSigned == destSigned) &&
1875 "How can different int types have same size and signedness?");
1877 bool signExtend = (opSize < destSize && opSigned ||
1878 opSize >= destSize && destSigned);
1880 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
1881 opSigned && !destSigned);
1882 assert(!signAndZeroExtend || signExtend);
1884 bool zeroExtendOnly = opSize >= destSize && !destSigned;
1885 assert(!zeroExtendOnly || !signExtend);
1888 Value* signExtDest = (signAndZeroExtend
1889 ? new TmpInstruction(mcfi, destType, opVal)
1892 CreateSignExtensionInstructions
1893 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
1895 if (signAndZeroExtend)
1896 CreateZeroExtensionInstructions
1897 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
1899 else if (zeroExtendOnly) {
1900 CreateZeroExtensionInstructions
1901 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
1904 forwardOperandNum = 0; // forward first operand to user
1907 assert(0 && "Unrecognized operand type for convert-to-integer");
1912 case 31: // reg: ToFloatTy(reg):
1913 case 32: // reg: ToDoubleTy(reg):
1914 case 232: // reg: ToDoubleTy(Constant):
1916 // If this instruction has a parent (a user) in the tree
1917 // and the user is translated as an FsMULd instruction,
1918 // then the cast is unnecessary. So check that first.
1919 // In the future, we'll want to do the same for the FdMULq instruction,
1920 // so do the check here instead of only for ToFloatTy(reg).
1922 if (subtreeRoot->parent() != NULL) {
1923 const MachineCodeForInstruction& mcfi =
1924 MachineCodeForInstruction::get(
1925 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1926 if (mcfi.size() == 0 || mcfi.front()->getOpcode() == V9::FSMULD)
1927 forwardOperandNum = 0; // forward first operand to user
1930 if (forwardOperandNum != 0) { // we do need the cast
1931 Value* leftVal = subtreeRoot->leftChild()->getValue();
1932 const Type* opType = leftVal->getType();
1933 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
1934 subtreeRoot->getOpLabel(), opType);
1935 if (opCode == V9::NOP) { // no conversion needed
1936 forwardOperandNum = 0; // forward first operand to user
1938 // If the source operand is a non-FP type it must be
1939 // first copied from int to float register via memory!
1940 Instruction *dest = subtreeRoot->getInstruction();
1943 if (! opType->isFloatingPoint()) {
1944 // Create a temporary to represent the FP register
1945 // into which the integer will be copied via memory.
1946 // The type of this temporary will determine the FP
1947 // register used: single-prec for a 32-bit int or smaller,
1948 // double-prec for a 64-bit int.
1951 target.getTargetData().getTypeSize(leftVal->getType());
1952 Type* tmpTypeToUse =
1953 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1954 MachineCodeForInstruction &destMCFI =
1955 MachineCodeForInstruction::get(dest);
1956 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
1958 CreateCodeToCopyIntToFloat(target,
1959 dest->getParent()->getParent(),
1960 leftVal, cast<Instruction>(srcForCast),
1963 srcForCast = leftVal;
1965 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
1971 case 19: // reg: ToArrayTy(reg):
1972 case 20: // reg: ToPointerTy(reg):
1973 forwardOperandNum = 0; // forward first operand to user
1976 case 233: // reg: Add(reg, Constant)
1977 maskUnsignedResult = true;
1978 M = CreateAddConstInstruction(subtreeRoot);
1983 // ELSE FALL THROUGH
1985 case 33: // reg: Add(reg, reg)
1986 maskUnsignedResult = true;
1987 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
1990 case 234: // reg: Sub(reg, Constant)
1991 maskUnsignedResult = true;
1992 M = CreateSubConstInstruction(subtreeRoot);
1997 // ELSE FALL THROUGH
1999 case 34: // reg: Sub(reg, reg)
2000 maskUnsignedResult = true;
2001 Add3OperandInstr(ChooseSubInstructionByType(
2002 subtreeRoot->getInstruction()->getType()),
2006 case 135: // reg: Mul(todouble, todouble)
2010 case 35: // reg: Mul(reg, reg)
2012 maskUnsignedResult = true;
2013 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2014 ? (MachineOpCode)V9::FSMULD
2016 Instruction* mulInstr = subtreeRoot->getInstruction();
2017 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2018 subtreeRoot->leftChild()->getValue(),
2019 subtreeRoot->rightChild()->getValue(),
2021 MachineCodeForInstruction::get(mulInstr),forceOp);
2024 case 335: // reg: Mul(todouble, todoubleConst)
2028 case 235: // reg: Mul(reg, Constant)
2030 maskUnsignedResult = true;
2031 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2032 ? (MachineOpCode)V9::FSMULD
2034 Instruction* mulInstr = subtreeRoot->getInstruction();
2035 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2036 subtreeRoot->leftChild()->getValue(),
2037 subtreeRoot->rightChild()->getValue(),
2039 MachineCodeForInstruction::get(mulInstr),
2043 case 236: // reg: Div(reg, Constant)
2044 maskUnsignedResult = true;
2046 CreateDivConstInstruction(target, subtreeRoot, mvec);
2047 if (mvec.size() > L)
2049 // ELSE FALL THROUGH
2051 case 36: // reg: Div(reg, reg)
2053 maskUnsignedResult = true;
2055 // If either operand of divide is smaller than 64 bits, we have
2056 // to make sure the unused top bits are correct because they affect
2057 // the result. These bits are already correct for unsigned values.
2058 // They may be incorrect for signed values, so sign extend to fill in.
2059 Instruction* divI = subtreeRoot->getInstruction();
2060 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2061 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2062 Value* divOp1ToUse = divOp1;
2063 Value* divOp2ToUse = divOp2;
2064 if (divI->getType()->isSigned()) {
2065 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
2067 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
2068 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
2069 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
2070 CreateSignExtensionInstructions(target,
2071 divI->getParent()->getParent(),
2072 divOp1, divOp1ToUse,
2073 8*opSize, mvec, mcfi);
2074 CreateSignExtensionInstructions(target,
2075 divI->getParent()->getParent(),
2076 divOp2, divOp2ToUse,
2077 8*opSize, mvec, mcfi);
2081 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2082 .addReg(divOp1ToUse)
2083 .addReg(divOp2ToUse)
2089 case 37: // reg: Rem(reg, reg)
2090 case 237: // reg: Rem(reg, Constant)
2092 maskUnsignedResult = true;
2094 Instruction* remI = subtreeRoot->getInstruction();
2095 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2096 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2098 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
2100 // If second operand of divide is smaller than 64 bits, we have
2101 // to make sure the unused top bits are correct because they affect
2102 // the result. These bits are already correct for unsigned values.
2103 // They may be incorrect for signed values, so sign extend to fill in.
2105 Value* divOpToUse = divOp2;
2106 if (divOp2->getType()->isSigned()) {
2107 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
2109 divOpToUse = new TmpInstruction(mcfi, divOp2);
2110 CreateSignExtensionInstructions(target,
2111 remI->getParent()->getParent(),
2113 8*opSize, mvec, mcfi);
2117 // Now compute: result = rem V1, V2 as:
2118 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
2120 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
2121 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
2123 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2124 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
2126 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
2127 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
2129 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
2130 .addReg(divOp1).addReg(prod).addRegDef(remI));
2135 case 38: // bool: And(bool, bool)
2136 case 138: // bool: And(bool, not)
2137 case 238: // bool: And(bool, boolconst)
2138 case 338: // reg : BAnd(reg, reg)
2139 case 538: // reg : BAnd(reg, Constant)
2140 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
2143 case 438: // bool: BAnd(bool, bnot)
2144 { // Use the argument of NOT as the second argument!
2145 // Mark the NOT node so that no code is generated for it.
2146 // If the type is boolean, set 1 or 0 in the result register.
2147 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2148 Value* notArg = BinaryOperator::getNotArgument(
2149 cast<BinaryOperator>(notNode->getInstruction()));
2150 notNode->markFoldedIntoParent();
2151 Value *lhs = subtreeRoot->leftChild()->getValue();
2152 Value *dest = subtreeRoot->getValue();
2153 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
2154 .addReg(dest, MachineOperand::Def));
2156 if (notArg->getType() == Type::BoolTy) {
2157 // set 1 in result register if result of above is non-zero
2158 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2159 .addReg(dest, MachineOperand::UseAndDef));
2165 case 39: // bool: Or(bool, bool)
2166 case 139: // bool: Or(bool, not)
2167 case 239: // bool: Or(bool, boolconst)
2168 case 339: // reg : BOr(reg, reg)
2169 case 539: // reg : BOr(reg, Constant)
2170 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
2173 case 439: // bool: BOr(bool, bnot)
2174 { // Use the argument of NOT as the second argument!
2175 // Mark the NOT node so that no code is generated for it.
2176 // If the type is boolean, set 1 or 0 in the result register.
2177 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2178 Value* notArg = BinaryOperator::getNotArgument(
2179 cast<BinaryOperator>(notNode->getInstruction()));
2180 notNode->markFoldedIntoParent();
2181 Value *lhs = subtreeRoot->leftChild()->getValue();
2182 Value *dest = subtreeRoot->getValue();
2184 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
2185 .addReg(dest, MachineOperand::Def));
2187 if (notArg->getType() == Type::BoolTy) {
2188 // set 1 in result register if result of above is non-zero
2189 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2190 .addReg(dest, MachineOperand::UseAndDef));
2196 case 40: // bool: Xor(bool, bool)
2197 case 140: // bool: Xor(bool, not)
2198 case 240: // bool: Xor(bool, boolconst)
2199 case 340: // reg : BXor(reg, reg)
2200 case 540: // reg : BXor(reg, Constant)
2201 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
2204 case 440: // bool: BXor(bool, bnot)
2205 { // Use the argument of NOT as the second argument!
2206 // Mark the NOT node so that no code is generated for it.
2207 // If the type is boolean, set 1 or 0 in the result register.
2208 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2209 Value* notArg = BinaryOperator::getNotArgument(
2210 cast<BinaryOperator>(notNode->getInstruction()));
2211 notNode->markFoldedIntoParent();
2212 Value *lhs = subtreeRoot->leftChild()->getValue();
2213 Value *dest = subtreeRoot->getValue();
2214 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
2215 .addReg(dest, MachineOperand::Def));
2217 if (notArg->getType() == Type::BoolTy) {
2218 // set 1 in result register if result of above is non-zero
2219 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2220 .addReg(dest, MachineOperand::UseAndDef));
2225 case 41: // setCCconst: SetCC(reg, Constant)
2226 { // Comparison is with a constant:
2228 // If the bool result must be computed into a register (see below),
2229 // and the constant is int ZERO, we can use the MOVR[op] instructions
2230 // and avoid the SUBcc instruction entirely.
2231 // Otherwise this is just the same as case 42, so just fall through.
2233 // The result of the SetCC must be computed and stored in a register if
2234 // it is used outside the current basic block (so it must be computed
2235 // as a boolreg) or it is used by anything other than a branch.
2236 // We will use a conditional move to do this.
2238 Instruction* setCCInstr = subtreeRoot->getInstruction();
2239 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2240 ! AllUsesAreBranches(setCCInstr));
2242 if (computeBoolVal) {
2243 InstrTreeNode* constNode = subtreeRoot->rightChild();
2245 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2246 Constant *constVal = cast<Constant>(constNode->getValue());
2249 if ((constVal->getType()->isInteger()
2250 || isa<PointerType>(constVal->getType()))
2251 && ConvertConstantToIntType(target,
2252 constVal, constVal->getType(), isValidConst) == 0
2255 // That constant is an integer zero after all...
2256 // Use a MOVR[op] to compute the boolean result
2257 // Unconditionally set register to 0
2258 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
2259 .addRegDef(setCCInstr));
2261 // Now conditionally move 1 into the register.
2262 // Mark the register as a use (as well as a def) because the old
2263 // value will be retained if the condition is false.
2264 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
2265 mvec.push_back(BuildMI(movOpCode, 3)
2266 .addReg(subtreeRoot->leftChild()->getValue())
2268 .addReg(setCCInstr, MachineOperand::UseAndDef));
2273 // ELSE FALL THROUGH
2276 case 42: // bool: SetCC(reg, reg):
2278 // This generates a SUBCC instruction, putting the difference in a
2279 // result reg. if needed, and/or setting a condition code if needed.
2281 Instruction* setCCInstr = subtreeRoot->getInstruction();
2282 Value* leftVal = subtreeRoot->leftChild()->getValue();
2283 Value* rightVal = subtreeRoot->rightChild()->getValue();
2284 const Type* opType = leftVal->getType();
2285 bool isFPCompare = opType->isFloatingPoint();
2287 // If the boolean result of the SetCC is used outside the current basic
2288 // block (so it must be computed as a boolreg) or is used by anything
2289 // other than a branch, the boolean must be computed and stored
2290 // in a result register. We will use a conditional move to do this.
2292 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2293 ! AllUsesAreBranches(setCCInstr));
2295 // A TmpInstruction is created to represent the CC "result".
2296 // Unlike other instances of TmpInstruction, this one is used
2297 // by machine code of multiple LLVM instructions, viz.,
2298 // the SetCC and the branch. Make sure to get the same one!
2299 // Note that we do this even for FP CC registers even though they
2300 // are explicit operands, because the type of the operand
2301 // needs to be a floating point condition code, not an integer
2302 // condition code. Think of this as casting the bool result to
2303 // a FP condition code register.
2304 // Later, we mark the 4th operand as being a CC register, and as a def.
2306 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
2307 setCCInstr->getParent()->getParent(),
2309 MachineCodeForInstruction::get(setCCInstr));
2311 // If the operands are signed values smaller than 4 bytes, then they
2312 // must be sign-extended in order to do a valid 32-bit comparison
2313 // and get the right result in the 32-bit CC register (%icc).
2315 Value* leftOpToUse = leftVal;
2316 Value* rightOpToUse = rightVal;
2317 if (opType->isIntegral() && opType->isSigned()) {
2318 unsigned opSize = target.getTargetData().getTypeSize(opType);
2320 MachineCodeForInstruction& mcfi =
2321 MachineCodeForInstruction::get(setCCInstr);
2323 // create temporary virtual regs. to hold the sign-extensions
2324 leftOpToUse = new TmpInstruction(mcfi, leftVal);
2325 rightOpToUse = new TmpInstruction(mcfi, rightVal);
2327 // sign-extend each operand and put the result in the temporary reg.
2328 CreateSignExtensionInstructions
2329 (target, setCCInstr->getParent()->getParent(),
2330 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
2331 CreateSignExtensionInstructions
2332 (target, setCCInstr->getParent()->getParent(),
2333 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
2337 if (! isFPCompare) {
2338 // Integer condition: set CC and discard result.
2339 mvec.push_back(BuildMI(V9::SUBccr, 4)
2340 .addReg(leftOpToUse)
2341 .addReg(rightOpToUse)
2342 .addMReg(target.getRegInfo()->
2343 getZeroRegNum(), MachineOperand::Def)
2344 .addCCReg(tmpForCC, MachineOperand::Def));
2346 // FP condition: dest of FCMP should be some FCCn register
2347 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
2348 .addCCReg(tmpForCC, MachineOperand::Def)
2349 .addReg(leftOpToUse)
2350 .addReg(rightOpToUse));
2353 if (computeBoolVal) {
2354 MachineOpCode movOpCode = (isFPCompare
2355 ? ChooseMovFpcciInstruction(subtreeRoot)
2356 : ChooseMovpcciForSetCC(subtreeRoot));
2358 // Unconditionally set register to 0
2359 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
2362 // Now conditionally move 1 into the register.
2363 // Mark the register as a use (as well as a def) because the old
2364 // value will be retained if the condition is false.
2365 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
2366 .addReg(setCCInstr, MachineOperand::UseAndDef));
2372 case 51: // reg: Load(reg)
2373 case 52: // reg: Load(ptrreg)
2374 SetOperandsForMemInstr(ChooseLoadInstruction(
2375 subtreeRoot->getValue()->getType()),
2376 mvec, subtreeRoot, target);
2379 case 55: // reg: GetElemPtr(reg)
2380 case 56: // reg: GetElemPtrIdx(reg,reg)
2381 // If the GetElemPtr was folded into the user (parent), it will be
2382 // caught above. For other cases, we have to compute the address.
2383 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
2386 case 57: // reg: Alloca: Implement as 1 instruction:
2387 { // add %fp, offsetFromFP -> result
2388 AllocationInst* instr =
2389 cast<AllocationInst>(subtreeRoot->getInstruction());
2391 target.getTargetData().getTypeSize(instr->getAllocatedType());
2393 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2397 case 58: // reg: Alloca(reg): Implement as 3 instructions:
2398 // mul num, typeSz -> tmp
2399 // sub %sp, tmp -> %sp
2400 { // add %sp, frameSizeBelowDynamicArea -> result
2401 AllocationInst* instr =
2402 cast<AllocationInst>(subtreeRoot->getInstruction());
2403 const Type* eltType = instr->getAllocatedType();
2405 // If #elements is constant, use simpler code for fixed-size allocas
2406 int tsize = (int) target.getTargetData().getTypeSize(eltType);
2407 Value* numElementsVal = NULL;
2408 bool isArray = instr->isArrayAllocation();
2410 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
2411 // total size is constant: generate code for fixed-size alloca
2412 unsigned numElements = isArray?
2413 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2414 CreateCodeForFixedSizeAlloca(target, instr, tsize,
2417 // total size is not constant.
2418 CreateCodeForVariableSizeAlloca(target, instr, tsize,
2419 numElementsVal, mvec);
2424 case 61: // reg: Call
2425 { // Generate a direct (CALL) or indirect (JMPL) call.
2426 // Mark the return-address register, the indirection
2427 // register (for indirect calls), the operands of the Call,
2428 // and the return value (if any) as implicit operands
2429 // of the machine instruction.
2431 // If this is a varargs function, floating point arguments
2432 // have to passed in integer registers so insert
2433 // copy-float-to-int instructions for each float operand.
2435 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2436 Value *callee = callInstr->getCalledValue();
2437 Function* calledFunc = dyn_cast<Function>(callee);
2439 // Check if this is an intrinsic function that needs a special code
2440 // sequence (e.g., va_start). Indirect calls cannot be special.
2442 bool specialIntrinsic = false;
2444 if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
2445 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
2447 // If not, generate the normal call sequence for the function.
2448 // This can also handle any intrinsics that are just function calls.
2450 if (! specialIntrinsic) {
2451 Function* currentFunc = callInstr->getParent()->getParent();
2452 MachineFunction& MF = MachineFunction::get(currentFunc);
2453 MachineCodeForInstruction& mcfi =
2454 MachineCodeForInstruction::get(callInstr);
2455 const SparcV9RegInfo& regInfo =
2456 (SparcV9RegInfo&) *target.getRegInfo();
2457 const TargetFrameInfo& frameInfo = *target.getFrameInfo();
2459 // Create hidden virtual register for return address with type void*
2460 TmpInstruction* retAddrReg =
2461 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
2463 // Generate the machine instruction and its operands.
2464 // Use CALL for direct function calls; this optimistically assumes
2465 // the PC-relative address fits in the CALL address field (22 bits).
2466 // Use JMPL for indirect calls.
2467 // This will be added to mvec later, after operand copies.
2469 MachineInstr* callMI;
2470 if (calledFunc) // direct function call
2471 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
2472 else // indirect function call
2473 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
2474 .addSImm((int64_t)0).addRegDef(retAddrReg));
2476 const FunctionType* funcType =
2477 cast<FunctionType>(cast<PointerType>(callee->getType())
2478 ->getElementType());
2479 bool isVarArgs = funcType->isVarArg();
2480 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2482 // Use a descriptor to pass information about call arguments
2483 // to the register allocator. This descriptor will be "owned"
2484 // and freed automatically when the MachineCodeForInstruction
2485 // object for the callInstr goes away.
2486 CallArgsDescriptor* argDesc =
2487 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
2488 assert(callInstr->getOperand(0) == callee
2489 && "This is assumed in the loop below!");
2491 // Insert sign-extension instructions for small signed values,
2492 // if this is an unknown function (i.e., called via a funcptr)
2493 // or an external one (i.e., which may not be compiled by llc).
2495 if (calledFunc == NULL || calledFunc->isExternal()) {
2496 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2497 Value* argVal = callInstr->getOperand(i);
2498 const Type* argType = argVal->getType();
2499 if (argType->isIntegral() && argType->isSigned()) {
2500 unsigned argSize = target.getTargetData().getTypeSize(argType);
2502 // create a temporary virtual reg. to hold the sign-extension
2503 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
2505 // sign-extend argVal and put the result in the temporary reg.
2506 CreateSignExtensionInstructions
2507 (target, currentFunc, argVal, argExtend,
2508 8*argSize, mvec, mcfi);
2510 // replace argVal with argExtend in CallArgsDescriptor
2511 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
2517 // Insert copy instructions to get all the arguments into
2518 // all the places that they need to be.
2520 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2522 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
2523 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
2524 const Type* argType = argVal->getType();
2525 unsigned regType = regInfo.getRegTypeForDataType(argType);
2526 unsigned argSize = target.getTargetData().getTypeSize(argType);
2527 int regNumForArg = SparcV9RegInfo::getInvalidRegNum();
2528 unsigned regClassIDOfArgReg;
2530 // Check for FP arguments to varargs functions.
2531 // Any such argument in the first $K$ args must be passed in an
2532 // integer register. If there is no prototype, it must also
2533 // be passed as an FP register.
2534 // K = #integer argument registers.
2535 bool isFPArg = argVal->getType()->isFloatingPoint();
2536 if (isVarArgs && isFPArg) {
2539 // It is a function with no prototype: pass value
2540 // as an FP value as well as a varargs value. The FP value
2541 // may go in a register or on the stack. The copy instruction
2542 // to the outgoing reg/stack is created by the normal argument
2543 // handling code since this is the "normal" passing mode.
2545 regNumForArg = regInfo.regNumForFPArg(regType,
2546 false, false, argNo,
2547 regClassIDOfArgReg);
2548 if (regNumForArg == regInfo.getInvalidRegNum())
2549 argInfo.setUseStackSlot();
2551 argInfo.setUseFPArgReg();
2554 // If this arg. is in the first $K$ regs, add special copy-
2555 // float-to-int instructions to pass the value as an int.
2556 // To check if it is in the first $K$, get the register
2557 // number for the arg #i. These copy instructions are
2558 // generated here because they are extra cases and not needed
2559 // for the normal argument handling (some code reuse is
2560 // possible though -- later).
2562 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
2563 regClassIDOfArgReg);
2564 if (copyRegNum != regInfo.getInvalidRegNum()) {
2565 // Create a virtual register to represent copyReg. Mark
2566 // this vreg as being an implicit operand of the call MI
2567 const Type* loadTy = (argType == Type::FloatTy
2568 ? Type::IntTy : Type::LongTy);
2569 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
2572 callMI->addImplicitRef(argVReg);
2574 // Get a temp stack location to use to copy
2575 // float-to-int via the stack.
2577 // FIXME: For now, we allocate permanent space because
2578 // the stack frame manager does not allow locals to be
2579 // allocated (e.g., for alloca) after a temp is
2582 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
2583 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
2585 // Generate the store from FP reg to stack
2586 unsigned StoreOpcode = ChooseStoreInstruction(argType);
2587 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
2588 .addReg(argVal).addMReg(regInfo.getFramePointer())
2589 .addSImm(tmpOffset);
2592 // Generate the load from stack to int arg reg
2593 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
2594 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
2595 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
2596 .addReg(argVReg, MachineOperand::Def);
2598 // Mark operand with register it should be assigned
2599 // both for copy and for the callMI
2600 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
2601 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2605 // Add info about the argument to the CallArgsDescriptor
2606 argInfo.setUseIntArgReg();
2607 argInfo.setArgCopy(copyRegNum);
2609 // Cannot fit in first $K$ regs so pass arg on stack
2610 argInfo.setUseStackSlot();
2612 } else if (isFPArg) {
2613 // Get the outgoing arg reg to see if there is one.
2614 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
2615 argNo, regClassIDOfArgReg);
2616 if (regNumForArg == regInfo.getInvalidRegNum())
2617 argInfo.setUseStackSlot();
2619 argInfo.setUseFPArgReg();
2620 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2624 // Get the outgoing arg reg to see if there is one.
2625 regNumForArg = regInfo.regNumForIntArg(false,false,
2626 argNo, regClassIDOfArgReg);
2627 if (regNumForArg == regInfo.getInvalidRegNum())
2628 argInfo.setUseStackSlot();
2630 argInfo.setUseIntArgReg();
2631 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2637 // Now insert copy instructions to stack slot or arg. register
2639 if (argInfo.usesStackSlot()) {
2640 // Get the stack offset for this argument slot.
2641 // FP args on stack are right justified so adjust offset!
2642 // int arguments are also right justified but they are
2643 // always loaded as a full double-word so the offset does
2644 // not need to be adjusted.
2645 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
2646 if (argType->isFloatingPoint()) {
2647 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
2648 assert(argSize <= slotSize && "Insufficient slot size!");
2649 argOffset += slotSize - argSize;
2652 // Now generate instruction to copy argument to stack
2653 MachineOpCode storeOpCode =
2654 (argType->isFloatingPoint()
2655 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
2657 M = BuildMI(storeOpCode, 3).addReg(argVal)
2658 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
2661 else if (regNumForArg != regInfo.getInvalidRegNum()) {
2663 // Create a virtual register to represent the arg reg. Mark
2664 // this vreg as being an implicit operand of the call MI.
2665 TmpInstruction* argVReg =
2666 new TmpInstruction(mcfi, argVal, NULL, "argReg");
2668 callMI->addImplicitRef(argVReg);
2670 // Generate the reg-to-reg copy into the outgoing arg reg.
2671 // -- For FP values, create a FMOVS or FMOVD instruction
2672 // -- For non-FP values, create an add-with-0 instruction
2673 if (argType->isFloatingPoint())
2674 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
2675 .addReg(argVal).addReg(argVReg, MachineOperand::Def));
2677 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
2678 .addReg(argVal).addSImm((int64_t) 0)
2679 .addReg(argVReg, MachineOperand::Def));
2681 // Mark the operand with the register it should be assigned
2682 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
2683 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2689 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
2690 "Arg. not in stack slot, primary or secondary register?");
2693 // add call instruction and delay slot before copying return value
2694 mvec.push_back(callMI);
2695 mvec.push_back(BuildMI(V9::NOP, 0));
2697 // Add the return value as an implicit ref. The call operands
2698 // were added above. Also, add code to copy out the return value.
2699 // This is always register-to-register for int or FP return values.
2701 if (callInstr->getType() != Type::VoidTy) {
2702 // Get the return value reg.
2703 const Type* retType = callInstr->getType();
2705 int regNum = (retType->isFloatingPoint()
2706 ? (unsigned) SparcV9FloatRegClass::f0
2707 : (unsigned) SparcV9IntRegClass::o0);
2708 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2709 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
2711 // Create a virtual register to represent it and mark
2712 // this vreg as being an implicit operand of the call MI
2713 TmpInstruction* retVReg =
2714 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
2716 callMI->addImplicitRef(retVReg, /*isDef*/ true);
2718 // Generate the reg-to-reg copy from the return value reg.
2719 // -- For FP values, create a FMOVS or FMOVD instruction
2720 // -- For non-FP values, create an add-with-0 instruction
2721 if (retType->isFloatingPoint())
2722 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2723 .addReg(retVReg).addReg(callInstr, MachineOperand::Def));
2725 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2726 .addReg(retVReg).addSImm((int64_t) 0)
2727 .addReg(callInstr, MachineOperand::Def));
2729 // Mark the operand with the register it should be assigned
2730 // Also mark the implicit ref of the call defining this operand
2731 M->SetRegForOperand(0, regNum);
2732 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
2737 // For the CALL instruction, the ret. addr. reg. is also implicit
2738 if (isa<Function>(callee))
2739 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
2741 MF.getInfo()->popAllTempValues(); // free temps used for this inst
2747 case 62: // reg: Shl(reg, reg)
2749 Value* argVal1 = subtreeRoot->leftChild()->getValue();
2750 Value* argVal2 = subtreeRoot->rightChild()->getValue();
2751 Instruction* shlInstr = subtreeRoot->getInstruction();
2753 const Type* opType = argVal1->getType();
2754 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2755 "Shl unsupported for other types");
2756 unsigned opSize = target.getTargetData().getTypeSize(opType);
2758 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2759 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
2760 argVal1, argVal2, 0, shlInstr, mvec,
2761 MachineCodeForInstruction::get(shlInstr));
2765 case 63: // reg: Shr(reg, reg)
2767 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2768 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2769 "Shr unsupported for other types");
2770 unsigned opSize = target.getTargetData().getTypeSize(opType);
2771 Add3OperandInstr(opType->isSigned()
2772 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
2773 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
2778 case 64: // reg: Phi(reg,reg)
2779 break; // don't forward the value
2781 case 65: // reg: VANext(reg): the va_next(va_list, type) instruction
2782 { // Increment the va_list pointer register according to the type.
2783 // All LLVM argument types are <= 64 bits, so use one doubleword.
2784 Instruction* vaNextI = subtreeRoot->getInstruction();
2785 assert(target.getTargetData().getTypeSize(vaNextI->getType()) <= 8 &&
2786 "We assumed that all LLVM parameter types <= 8 bytes!");
2787 int argSize = target.getFrameInfo()->getSizeOfEachArgOnStack();
2788 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaNextI->getOperand(0)).
2789 addSImm(argSize).addRegDef(vaNextI));
2793 case 66: // reg: VAArg (reg): the va_arg instruction
2794 { // Load argument from stack using current va_list pointer value.
2795 // Use 64-bit load for all non-FP args, and LDDF or double for FP.
2796 Instruction* vaArgI = subtreeRoot->getInstruction();
2797 MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
2798 ? (vaArgI->getType() == Type::FloatTy
2799 ? V9::LDFi : V9::LDDFi)
2801 mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
2802 addSImm(0).addRegDef(vaArgI));
2806 case 71: // reg: VReg
2807 case 72: // reg: Constant
2808 break; // don't forward the value
2811 assert(0 && "Unrecognized BURG rule");
2816 if (forwardOperandNum >= 0) {
2817 // We did not generate a machine instruction but need to use operand.
2818 // If user is in the same tree, replace Value in its machine operand.
2819 // If not, insert a copy instruction which should get coalesced away
2820 // by register allocation.
2821 if (subtreeRoot->parent() != NULL)
2822 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2824 std::vector<MachineInstr*> minstrVec;
2825 Instruction* instr = subtreeRoot->getInstruction();
2826 CreateCopyInstructionsByType(target,
2827 instr->getParent()->getParent(),
2828 instr->getOperand(forwardOperandNum),
2830 MachineCodeForInstruction::get(instr));
2831 assert(minstrVec.size() > 0);
2832 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2836 if (maskUnsignedResult) {
2837 // If result is unsigned and smaller than int reg size,
2838 // we need to clear high bits of result value.
2839 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2840 Instruction* dest = subtreeRoot->getInstruction();
2841 if (dest->getType()->isUnsigned()) {
2842 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
2843 if (destSize <= 4) {
2844 // Mask high 64 - N bits, where N = 4*destSize.
2846 // Use a TmpInstruction to represent the
2847 // intermediate result before masking. Since those instructions
2848 // have already been generated, go back and substitute tmpI
2849 // for dest in the result position of each one of them.
2851 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
2852 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
2853 dest, NULL, "maskHi");
2854 Value* srlArgToUse = tmpI;
2856 unsigned numSubst = 0;
2857 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
2859 // Make sure we substitute all occurrences of dest in these instrs.
2860 // Otherwise, we will have bogus code.
2861 bool someArgsWereIgnored = false;
2863 // Make sure not to substitute an upwards-exposed use -- that would
2864 // introduce a use of `tmpI' with no preceding def. Therefore,
2865 // substitute a use or def-and-use operand only if a previous def
2866 // operand has already been substituted (i.e., numSubst > 0).
2868 numSubst += mvec[i]->substituteValue(dest, tmpI,
2869 /*defsOnly*/ numSubst == 0,
2870 /*notDefsAndUses*/ numSubst > 0,
2871 someArgsWereIgnored);
2872 assert(!someArgsWereIgnored &&
2873 "Operand `dest' exists but not replaced: probably bogus!");
2875 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
2877 // Left shift 32-N if size (N) is less than 32 bits.
2878 // Use another tmp. virtual register to represent this result.
2880 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
2881 tmpI, NULL, "maskHi2");
2882 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
2883 .addZImm(8*(4-destSize))
2884 .addReg(srlArgToUse, MachineOperand::Def));
2887 // Logical right shift 32-N to get zero extension in top 64-N bits.
2888 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
2889 .addZImm(8*(4-destSize))
2890 .addReg(dest, MachineOperand::Def));
2892 } else if (destSize < 8) {
2893 assert(0 && "Unsupported type size: 32 < size < 64 bits");