1 //===-- SparcInstrSelection.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/ConstantHandling.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/InstrForest.h"
21 #include "llvm/CodeGen/InstrSelection.h"
22 #include "llvm/CodeGen/InstrSelectionSupport.h"
23 #include "llvm/CodeGen/MachineCodeForInstruction.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFunctionInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineInstrAnnot.h"
28 #include "SparcInstrSelectionSupport.h"
29 #include "SparcInternals.h"
30 #include "SparcRegClassInfo.h"
31 #include "SparcRegInfo.h"
32 #include "Support/MathExtras.h"
38 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
39 std::vector<MachineInstr*>& mvec) {
40 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
41 .addReg(Node->rightChild()->getValue())
42 .addRegDef(Node->getValue()));
46 //---------------------------------------------------------------------------
47 // Function: FoldGetElemChain
50 // Fold a chain of GetElementPtr instructions containing only
51 // constant offsets into an equivalent (Pointer, IndexVector) pair.
52 // Returns the pointer Value, and stores the resulting IndexVector
53 // in argument chainIdxVec. This is a helper function for
54 // FoldConstantIndices that does the actual folding.
55 //---------------------------------------------------------------------------
58 // Check for a constant 0.
62 return (idx == ConstantSInt::getNullValue(idx->getType()));
66 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
67 bool lastInstHasLeadingNonZero)
69 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
70 GetElementPtrInst* gepInst =
71 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
73 // ptr value is not computed in this tree or ptr value does not come from GEP
78 // Return NULL if we don't fold any instructions in.
81 // Now chase the chain of getElementInstr instructions, if any.
82 // Check for any non-constant indices and stop there.
83 // Also, stop if the first index of child is a non-zero array index
84 // and the last index of the current node is a non-array index:
85 // in that case, a non-array declared type is being accessed as an array
86 // which is not type-safe, but could be legal.
88 InstructionNode* ptrChild = gepNode;
89 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
90 ptrChild->getOpLabel() == GetElemPtrIdx))
92 // Child is a GetElemPtr instruction
93 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
94 User::op_iterator OI, firstIdx = gepInst->idx_begin();
95 User::op_iterator lastIdx = gepInst->idx_end();
96 bool allConstantOffsets = true;
98 // The first index of every GEP must be an array index.
99 assert((*firstIdx)->getType() == Type::LongTy &&
100 "INTERNAL ERROR: Structure index for a pointer type!");
102 // If the last instruction had a leading non-zero index, check if the
103 // current one references a sequential (i.e., indexable) type.
104 // If not, the code is not type-safe and we would create an illegal GEP
105 // by folding them, so don't fold any more instructions.
107 if (lastInstHasLeadingNonZero)
108 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
109 break; // cannot fold in any preceding getElementPtr instrs.
111 // Check that all offsets are constant for this instruction
112 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
113 allConstantOffsets = isa<ConstantInt>(*OI);
115 if (allConstantOffsets) {
116 // Get pointer value out of ptrChild.
117 ptrVal = gepInst->getPointerOperand();
119 // Insert its index vector at the start, skipping any leading [0]
120 // Remember the old size to check if anything was inserted.
121 unsigned oldSize = chainIdxVec.size();
122 int firstIsZero = IsZero(*firstIdx);
123 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
125 // Remember if it has leading zero index: it will be discarded later.
126 if (oldSize < chainIdxVec.size())
127 lastInstHasLeadingNonZero = !firstIsZero;
129 // Mark the folded node so no code is generated for it.
130 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
132 // Get the previous GEP instruction and continue trying to fold
133 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
134 } else // cannot fold this getElementPtr instr. or any preceding ones
138 // If the first getElementPtr instruction had a leading [0], add it back.
139 // Note that this instruction is the *last* one that was successfully
140 // folded *and* contributed any indices, in the loop above.
142 if (ptrVal && ! lastInstHasLeadingNonZero)
143 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
149 //---------------------------------------------------------------------------
150 // Function: GetGEPInstArgs
153 // Helper function for GetMemInstArgs that handles the final getElementPtr
154 // instruction used by (or same as) the memory operation.
155 // Extracts the indices of the current instruction and tries to fold in
156 // preceding ones if all indices of the current one are constant.
157 //---------------------------------------------------------------------------
160 GetGEPInstArgs(InstructionNode* gepNode,
161 std::vector<Value*>& idxVec,
162 bool& allConstantIndices)
164 allConstantIndices = true;
165 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
167 // Default pointer is the one from the current instruction.
168 Value* ptrVal = gepI->getPointerOperand();
169 InstrTreeNode* ptrChild = gepNode->leftChild();
171 // Extract the index vector of the GEP instruction.
172 // If all indices are constant and first index is zero, try to fold
173 // in preceding GEPs with all constant indices.
174 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
175 allConstantIndices && OI != OE; ++OI)
176 if (! isa<Constant>(*OI))
177 allConstantIndices = false; // note: this also terminates loop!
179 // If we have only constant indices, fold chains of constant indices
180 // in this and any preceding GetElemPtr instructions.
181 bool foldedGEPs = false;
182 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
183 if (allConstantIndices)
184 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
189 // Append the index vector of the current instruction.
190 // Skip the leading [0] index if preceding GEPs were folded into this.
191 idxVec.insert(idxVec.end(),
192 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
198 //---------------------------------------------------------------------------
199 // Function: GetMemInstArgs
202 // Get the pointer value and the index vector for a memory operation
203 // (GetElementPtr, Load, or Store). If all indices of the given memory
204 // operation are constant, fold in constant indices in a chain of
205 // preceding GetElementPtr instructions (if any), and return the
206 // pointer value of the first instruction in the chain.
207 // All folded instructions are marked so no code is generated for them.
210 // Returns the pointer Value to use.
211 // Returns the resulting IndexVector in idxVec.
212 // Returns true/false in allConstantIndices if all indices are/aren't const.
213 //---------------------------------------------------------------------------
216 GetMemInstArgs(InstructionNode* memInstrNode,
217 std::vector<Value*>& idxVec,
218 bool& allConstantIndices)
220 allConstantIndices = false;
221 Instruction* memInst = memInstrNode->getInstruction();
222 assert(idxVec.size() == 0 && "Need empty vector to return indices");
224 // If there is a GetElemPtr instruction to fold in to this instr,
225 // it must be in the left child for Load and GetElemPtr, and in the
226 // right child for Store instructions.
227 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
228 ? memInstrNode->rightChild()
229 : memInstrNode->leftChild());
231 // Default pointer is the one from the current instruction.
232 Value* ptrVal = ptrChild->getValue();
234 // Find the "last" GetElemPtr instruction: this one or the immediate child.
235 // There will be none if this is a load or a store from a scalar pointer.
236 InstructionNode* gepNode = NULL;
237 if (isa<GetElementPtrInst>(memInst))
238 gepNode = memInstrNode;
239 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
240 // Child of load/store is a GEP and memInst is its only use.
241 // Use its indices and mark it as folded.
242 gepNode = cast<InstructionNode>(ptrChild);
243 gepNode->markFoldedIntoParent();
246 // If there are no indices, return the current pointer.
247 // Else extract the pointer from the GEP and fold the indices.
248 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
253 //************************ Internal Functions ******************************/
256 static inline MachineOpCode
257 ChooseBprInstruction(const InstructionNode* instrNode)
259 MachineOpCode opCode;
261 Instruction* setCCInstr =
262 ((InstructionNode*) instrNode->leftChild())->getInstruction();
264 switch(setCCInstr->getOpcode())
266 case Instruction::SetEQ: opCode = V9::BRZ; break;
267 case Instruction::SetNE: opCode = V9::BRNZ; break;
268 case Instruction::SetLE: opCode = V9::BRLEZ; break;
269 case Instruction::SetGE: opCode = V9::BRGEZ; break;
270 case Instruction::SetLT: opCode = V9::BRLZ; break;
271 case Instruction::SetGT: opCode = V9::BRGZ; break;
273 assert(0 && "Unrecognized VM instruction!");
274 opCode = V9::INVALID_OPCODE;
282 static inline MachineOpCode
283 ChooseBpccInstruction(const InstructionNode* instrNode,
284 const BinaryOperator* setCCInstr)
286 MachineOpCode opCode = V9::INVALID_OPCODE;
288 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
291 switch(setCCInstr->getOpcode())
293 case Instruction::SetEQ: opCode = V9::BE; break;
294 case Instruction::SetNE: opCode = V9::BNE; break;
295 case Instruction::SetLE: opCode = V9::BLE; break;
296 case Instruction::SetGE: opCode = V9::BGE; break;
297 case Instruction::SetLT: opCode = V9::BL; break;
298 case Instruction::SetGT: opCode = V9::BG; break;
300 assert(0 && "Unrecognized VM instruction!");
304 switch(setCCInstr->getOpcode())
306 case Instruction::SetEQ: opCode = V9::BE; break;
307 case Instruction::SetNE: opCode = V9::BNE; break;
308 case Instruction::SetLE: opCode = V9::BLEU; break;
309 case Instruction::SetGE: opCode = V9::BCC; break;
310 case Instruction::SetLT: opCode = V9::BCS; break;
311 case Instruction::SetGT: opCode = V9::BGU; break;
313 assert(0 && "Unrecognized VM instruction!");
321 static inline MachineOpCode
322 ChooseBFpccInstruction(const InstructionNode* instrNode,
323 const BinaryOperator* setCCInstr)
325 MachineOpCode opCode = V9::INVALID_OPCODE;
327 switch(setCCInstr->getOpcode())
329 case Instruction::SetEQ: opCode = V9::FBE; break;
330 case Instruction::SetNE: opCode = V9::FBNE; break;
331 case Instruction::SetLE: opCode = V9::FBLE; break;
332 case Instruction::SetGE: opCode = V9::FBGE; break;
333 case Instruction::SetLT: opCode = V9::FBL; break;
334 case Instruction::SetGT: opCode = V9::FBG; break;
336 assert(0 && "Unrecognized VM instruction!");
344 // Create a unique TmpInstruction for a boolean value,
345 // representing the CC register used by a branch on that value.
346 // For now, hack this using a little static cache of TmpInstructions.
347 // Eventually the entire BURG instruction selection should be put
348 // into a separate class that can hold such information.
349 // The static cache is not too bad because the memory for these
350 // TmpInstructions will be freed along with the rest of the Function anyway.
352 static TmpInstruction*
353 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType,
354 MachineCodeForInstruction& mcfi)
356 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
357 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
358 static const Function *lastFunction = 0;// Use to flush cache between funcs
360 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
362 if (lastFunction != F) {
364 boolToTmpCache.clear();
367 // Look for tmpI and create a new one otherwise. The new value is
368 // directly written to map using the ref returned by operator[].
369 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
371 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
377 static inline MachineOpCode
378 ChooseBccInstruction(const InstructionNode* instrNode,
379 const Type*& setCCType)
381 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
382 assert(setCCNode->getOpLabel() == SetCCOp);
383 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
384 setCCType = setCCInstr->getOperand(0)->getType();
386 if (setCCType->isFloatingPoint())
387 return ChooseBFpccInstruction(instrNode, setCCInstr);
389 return ChooseBpccInstruction(instrNode, setCCInstr);
393 // WARNING: since this function has only one caller, it always returns
394 // the opcode that expects an immediate and a register. If this function
395 // is ever used in cases where an opcode that takes two registers is required,
396 // then modify this function and use convertOpcodeFromRegToImm() where required.
398 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
399 // new cases of opcodes.
400 static inline MachineOpCode
401 ChooseMovFpcciInstruction(const InstructionNode* instrNode)
403 MachineOpCode opCode = V9::INVALID_OPCODE;
405 switch(instrNode->getInstruction()->getOpcode())
407 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
408 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
409 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
410 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
411 case Instruction::SetLT: opCode = V9::MOVFLi; break;
412 case Instruction::SetGT: opCode = V9::MOVFGi; break;
414 assert(0 && "Unrecognized VM instruction!");
422 // ChooseMovpcciForSetCC -- Choose a conditional-move instruction
423 // based on the type of SetCC operation.
425 // WARNING: since this function has only one caller, it always returns
426 // the opcode that expects an immediate and a register. If this function
427 // is ever used in cases where an opcode that takes two registers is required,
428 // then modify this function and use convertOpcodeFromRegToImm() where required.
430 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
431 // new cases of opcodes.
434 ChooseMovpcciForSetCC(const InstructionNode* instrNode)
436 MachineOpCode opCode = V9::INVALID_OPCODE;
438 const Type* opType = instrNode->leftChild()->getValue()->getType();
439 assert(opType->isIntegral() || isa<PointerType>(opType));
440 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
442 switch(instrNode->getInstruction()->getOpcode())
444 case Instruction::SetEQ: opCode = V9::MOVEi; break;
445 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
446 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
447 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
448 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
449 case Instruction::SetNE: opCode = V9::MOVNEi; break;
450 default: assert(0 && "Unrecognized LLVM instr!"); break;
457 // ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
458 // instruction based on the type of SetCC operation. These instructions
459 // compare a register with 0 and perform the move is the comparison is true.
461 // WARNING: like the previous function, this function it always returns
462 // the opcode that expects an immediate and a register. See above.
465 ChooseMovpregiForSetCC(const InstructionNode* instrNode)
467 MachineOpCode opCode = V9::INVALID_OPCODE;
469 switch(instrNode->getInstruction()->getOpcode())
471 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
472 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
473 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
474 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
475 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
476 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
477 default: assert(0 && "Unrecognized VM instr!"); break;
484 static inline MachineOpCode
485 ChooseConvertToFloatInstr(const TargetMachine& target,
486 OpLabel vopCode, const Type* opType)
488 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
489 "Unrecognized convert-to-float opcode!");
490 assert((opType->isIntegral() || opType->isFloatingPoint() ||
491 isa<PointerType>(opType))
492 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
494 MachineOpCode opCode = V9::INVALID_OPCODE;
496 unsigned opSize = target.getTargetData().getTypeSize(opType);
498 if (opType == Type::FloatTy)
499 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
500 else if (opType == Type::DoubleTy)
501 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
502 else if (opSize <= 4)
503 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
505 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
506 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
512 static inline MachineOpCode
513 ChooseConvertFPToIntInstr(const TargetMachine& target,
514 const Type* destType, const Type* opType)
516 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
517 && "This function should only be called for FLOAT or DOUBLE");
518 assert((destType->isIntegral() || isa<PointerType>(destType))
519 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
521 MachineOpCode opCode = V9::INVALID_OPCODE;
523 unsigned destSize = target.getTargetData().getTypeSize(destType);
525 if (destType == Type::UIntTy)
526 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
527 else if (destSize <= 4)
528 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
530 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
531 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
538 CreateConvertFPToIntInstr(const TargetMachine& target,
541 const Type* destType)
543 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
545 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
546 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
549 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
550 // The FP value must be converted to the dest type in an FP register,
551 // and the result is then copied from FP to int register via memory.
552 // SPARC does not have a float-to-uint conversion, only a float-to-int (fdtoi).
553 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
554 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
555 // Therefore, for converting an FP value to uint32_t, we first need to convert
556 // to uint64_t and then to uint32_t.
559 CreateCodeToConvertFloatToInt(const TargetMachine& target,
562 std::vector<MachineInstr*>& mvec,
563 MachineCodeForInstruction& mcfi)
565 Function* F = destI->getParent()->getParent();
567 // Create a temporary to represent the FP register into which the
568 // int value will placed after conversion. The type of this temporary
569 // depends on the type of FP register to use: single-prec for a 32-bit
570 // int or smaller; double-prec for a 64-bit int.
572 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
574 const Type* castDestType = destI->getType(); // type for the cast instr result
575 const Type* castDestRegType; // type for cast instruction result reg
576 TmpInstruction* destForCast; // dest for cast instruction
577 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
579 // For converting an FP value to uint32_t, we first need to convert to
580 // uint64_t and then to uint32_t, as explained above.
581 if (destI->getType() == Type::UIntTy) {
582 castDestType = Type::ULongTy; // use this instead of type of destI
583 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
584 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
585 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
588 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
589 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
592 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
593 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
596 // Create the fpreg-to-intreg copy code
597 target.getInstrInfo().CreateCodeToCopyFloatToInt(target, F, destForCast,
598 fpToIntCopyDest, mvec, mcfi);
600 // Create the uint64_t to uint32_t conversion, if needed
601 if (destI->getType() == Type::UIntTy)
602 target.getInstrInfo().
603 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
604 /*numLowBits*/ 32, mvec, mcfi);
608 static inline MachineOpCode
609 ChooseAddInstruction(const InstructionNode* instrNode)
611 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
615 static inline MachineInstr*
616 CreateMovFloatInstruction(const InstructionNode* instrNode,
617 const Type* resultType)
619 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
620 .addReg(instrNode->leftChild()->getValue())
621 .addRegDef(instrNode->getValue());
624 static inline MachineInstr*
625 CreateAddConstInstruction(const InstructionNode* instrNode)
627 MachineInstr* minstr = NULL;
629 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
630 assert(isa<Constant>(constOp));
632 // Cases worth optimizing are:
633 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
634 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
636 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
637 double dval = FPC->getValue();
639 minstr = CreateMovFloatInstruction(instrNode,
640 instrNode->getInstruction()->getType());
647 static inline MachineOpCode
648 ChooseSubInstructionByType(const Type* resultType)
650 MachineOpCode opCode = V9::INVALID_OPCODE;
652 if (resultType->isInteger() || isa<PointerType>(resultType)) {
655 switch(resultType->getPrimitiveID())
657 case Type::FloatTyID: opCode = V9::FSUBS; break;
658 case Type::DoubleTyID: opCode = V9::FSUBD; break;
659 default: assert(0 && "Invalid type for SUB instruction"); break;
667 static inline MachineInstr*
668 CreateSubConstInstruction(const InstructionNode* instrNode)
670 MachineInstr* minstr = NULL;
672 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
673 assert(isa<Constant>(constOp));
675 // Cases worth optimizing are:
676 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
677 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
679 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
680 double dval = FPC->getValue();
682 minstr = CreateMovFloatInstruction(instrNode,
683 instrNode->getInstruction()->getType());
690 static inline MachineOpCode
691 ChooseFcmpInstruction(const InstructionNode* instrNode)
693 MachineOpCode opCode = V9::INVALID_OPCODE;
695 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
696 switch(operand->getType()->getPrimitiveID()) {
697 case Type::FloatTyID: opCode = V9::FCMPS; break;
698 case Type::DoubleTyID: opCode = V9::FCMPD; break;
699 default: assert(0 && "Invalid type for FCMP instruction"); break;
706 // Assumes that leftArg and rightArg are both cast instructions.
709 BothFloatToDouble(const InstructionNode* instrNode)
711 InstrTreeNode* leftArg = instrNode->leftChild();
712 InstrTreeNode* rightArg = instrNode->rightChild();
713 InstrTreeNode* leftArgArg = leftArg->leftChild();
714 InstrTreeNode* rightArgArg = rightArg->leftChild();
715 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
717 // Check if both arguments are floats cast to double
718 return (leftArg->getValue()->getType() == Type::DoubleTy &&
719 leftArgArg->getValue()->getType() == Type::FloatTy &&
720 rightArgArg->getValue()->getType() == Type::FloatTy);
724 static inline MachineOpCode
725 ChooseMulInstructionByType(const Type* resultType)
727 MachineOpCode opCode = V9::INVALID_OPCODE;
729 if (resultType->isInteger())
732 switch(resultType->getPrimitiveID())
734 case Type::FloatTyID: opCode = V9::FMULS; break;
735 case Type::DoubleTyID: opCode = V9::FMULD; break;
736 default: assert(0 && "Invalid type for MUL instruction"); break;
744 static inline MachineInstr*
745 CreateIntNegInstruction(const TargetMachine& target,
748 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo().getZeroRegNum())
749 .addReg(vreg).addRegDef(vreg);
753 // Create instruction sequence for any shift operation.
754 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
755 // requires a second instruction for explicit sign-extension.
756 // Note that we only have to worry about a sign-bit appearing in the
757 // most significant bit of the operand after shifting (e.g., bit 32 of
758 // Int or bit 16 of Short), so we do not have to worry about results
759 // that are as large as a normal integer register.
762 CreateShiftInstructions(const TargetMachine& target,
764 MachineOpCode shiftOpCode,
766 Value* optArgVal2, /* Use optArgVal2 if not NULL */
767 unsigned optShiftNum, /* else use optShiftNum */
768 Instruction* destVal,
769 std::vector<MachineInstr*>& mvec,
770 MachineCodeForInstruction& mcfi)
772 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
773 "Large shift sizes unexpected, but can be handled below: "
774 "You need to check whether or not it fits in immed field below");
776 // If this is a logical left shift of a type smaller than the standard
777 // integer reg. size, we have to extend the sign-bit into upper bits
778 // of dest, so we need to put the result of the SLL into a temporary.
780 Value* shiftDest = destVal;
781 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
783 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
784 // put SLL result into a temporary
785 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
788 MachineInstr* M = (optArgVal2 != NULL)
789 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
790 .addReg(shiftDest, MOTy::Def)
791 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
792 .addReg(shiftDest, MOTy::Def);
795 if (shiftDest != destVal) {
796 // extend the sign-bit of the result into all upper bits of dest
797 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
798 target.getInstrInfo().
799 CreateSignExtensionInstructions(target, F, shiftDest, destVal,
800 8*opSize, mvec, mcfi);
805 // Does not create any instructions if we cannot exploit constant to
806 // create a cheaper instruction.
807 // This returns the approximate cost of the instructions generated,
808 // which is used to pick the cheapest when both operands are constant.
810 CreateMulConstInstruction(const TargetMachine &target, Function* F,
811 Value* lval, Value* rval, Instruction* destVal,
812 std::vector<MachineInstr*>& mvec,
813 MachineCodeForInstruction& mcfi)
815 /* Use max. multiply cost, viz., cost of MULX */
816 unsigned cost = target.getInstrInfo().minLatency(V9::MULXr);
817 unsigned firstNewInstr = mvec.size();
819 Value* constOp = rval;
820 if (! isa<Constant>(constOp))
823 // Cases worth optimizing are:
824 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
825 // (2) Multiply by 2^x for integer types: replace with Shift
827 const Type* resultType = destVal->getType();
829 if (resultType->isInteger() || isa<PointerType>(resultType)) {
831 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
832 constOp, constOp->getType(), isValidConst);
835 bool needNeg = false;
841 if (C == 0 || C == 1) {
842 cost = target.getInstrInfo().minLatency(V9::ADDr);
843 unsigned Zero = target.getRegInfo().getZeroRegNum();
846 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
848 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
850 } else if (isPowerOf2(C, pow)) {
851 unsigned opSize = target.getTargetData().getTypeSize(resultType);
852 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
853 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
854 destVal, mvec, mcfi);
857 if (mvec.size() > 0 && needNeg) {
858 // insert <reg = SUB 0, reg> after the instr to flip the sign
859 MachineInstr* M = CreateIntNegInstruction(target, destVal);
864 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
865 double dval = FPC->getValue();
866 if (fabs(dval) == 1) {
867 MachineOpCode opCode = (dval < 0)
868 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
869 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
870 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
875 if (firstNewInstr < mvec.size()) {
877 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
878 cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
885 // Does not create any instructions if we cannot exploit constant to
886 // create a cheaper instruction.
889 CreateCheapestMulConstInstruction(const TargetMachine &target,
891 Value* lval, Value* rval,
892 Instruction* destVal,
893 std::vector<MachineInstr*>& mvec,
894 MachineCodeForInstruction& mcfi)
897 if (isa<Constant>(lval) && isa<Constant>(rval)) {
898 // both operands are constant: evaluate and "set" in dest
899 Constant* P = ConstantFoldBinaryInstruction(Instruction::Mul,
900 cast<Constant>(lval),
901 cast<Constant>(rval));
902 target.getInstrInfo().CreateCodeToLoadConst(target,F,P,destVal,mvec,mcfi);
904 else if (isa<Constant>(rval)) // rval is constant, but not lval
905 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
906 else if (isa<Constant>(lval)) // lval is constant, but not rval
907 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
909 // else neither is constant
913 // Return NULL if we cannot exploit constant to create a cheaper instruction
915 CreateMulInstruction(const TargetMachine &target, Function* F,
916 Value* lval, Value* rval, Instruction* destVal,
917 std::vector<MachineInstr*>& mvec,
918 MachineCodeForInstruction& mcfi,
919 MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
921 unsigned L = mvec.size();
922 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
923 if (mvec.size() == L) {
924 // no instructions were added so create MUL reg, reg, reg.
925 // Use FSMULD if both operands are actually floats cast to doubles.
926 // Otherwise, use the default opcode for the appropriate type.
927 MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
929 : ChooseMulInstructionByType(destVal->getType()));
930 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
931 .addRegDef(destVal));
936 // Generate a divide instruction for Div or Rem.
937 // For Rem, this assumes that the operand type will be signed if the result
938 // type is signed. This is correct because they must have the same sign.
940 static inline MachineOpCode
941 ChooseDivInstruction(TargetMachine &target,
942 const InstructionNode* instrNode)
944 MachineOpCode opCode = V9::INVALID_OPCODE;
946 const Type* resultType = instrNode->getInstruction()->getType();
948 if (resultType->isInteger())
949 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
951 switch(resultType->getPrimitiveID())
953 case Type::FloatTyID: opCode = V9::FDIVS; break;
954 case Type::DoubleTyID: opCode = V9::FDIVD; break;
955 default: assert(0 && "Invalid type for DIV instruction"); break;
962 // Return if we cannot exploit constant to create a cheaper instruction
964 CreateDivConstInstruction(TargetMachine &target,
965 const InstructionNode* instrNode,
966 std::vector<MachineInstr*>& mvec)
968 Value* LHS = instrNode->leftChild()->getValue();
969 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
970 if (!isa<Constant>(constOp))
973 Instruction* destVal = instrNode->getInstruction();
974 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
976 // Cases worth optimizing are:
977 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
978 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
980 const Type* resultType = instrNode->getInstruction()->getType();
982 if (resultType->isInteger()) {
985 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
986 constOp, constOp->getType(), isValidConst);
988 bool needNeg = false;
995 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
996 .addRegDef(destVal));
997 } else if (isPowerOf2(C, pow)) {
1000 unsigned opSize = target.getTargetData().getTypeSize(resultType);
1002 if (resultType->isSigned()) {
1003 // For N / 2^k, if the operand N is negative,
1004 // we need to add (2^k - 1) before right-shifting by k, i.e.,
1006 // (N / 2^k) = N >> k, if N >= 0;
1007 // (N + 2^k - 1) >> k, if N < 0
1009 // If N is <= 32 bits, use:
1010 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
1011 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1012 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1013 // sra t3, k, result // result = N / 2^k
1015 // If N is 64 bits, use:
1016 // srax N, k-1, t1 // t1 = sign bit in high k positions
1017 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1018 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1019 // sra t3, k, result // result = N / 2^k
1021 TmpInstruction *sraTmp, *srlTmp, *addTmp;
1022 MachineCodeForInstruction& mcfi
1023 = MachineCodeForInstruction::get(destVal);
1024 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
1025 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
1026 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
1028 // Create the SRA or SRAX instruction to get the sign bit
1029 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
1031 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
1032 .addRegDef(sraTmp));
1034 // Create the SRL or SRLX instruction to get the sign bit
1035 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
1037 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
1038 .addRegDef(srlTmp));
1040 // Create the ADD instruction to add 2^pow-1 for negative values
1041 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
1042 .addRegDef(addTmp));
1044 // Get the shift operand and "right-shift" opcode to do the divide
1045 shiftOperand = addTmp;
1046 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
1048 // Get the shift operand and "right-shift" opcode to do the divide
1050 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
1053 // Now do the actual shift!
1054 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
1055 .addRegDef(destVal));
1058 if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
1059 // insert <reg = SUB 0, reg> after the instr to flip the sign
1060 mvec.push_back(CreateIntNegInstruction(target, destVal));
1064 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
1065 double dval = FPC->getValue();
1066 if (fabs(dval) == 1) {
1068 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
1069 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
1071 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
1079 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
1080 Instruction* result,
1082 Value* numElementsVal,
1083 std::vector<MachineInstr*>& getMvec)
1085 Value* totalSizeVal;
1087 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
1088 Function *F = result->getParent()->getParent();
1090 // Enforce the alignment constraints on the stack pointer at
1091 // compile time if the total size is a known constant.
1092 if (isa<Constant>(numElementsVal)) {
1094 int64_t numElem = (int64_t) target.getInstrInfo().
1095 ConvertConstantToIntType(target, numElementsVal,
1096 numElementsVal->getType(), isValid);
1097 assert(isValid && "Unexpectedly large array dimension in alloca!");
1098 int64_t total = numElem * tsize;
1099 if (int extra= total % target.getFrameInfo().getStackFrameSizeAlignment())
1100 total += target.getFrameInfo().getStackFrameSizeAlignment() - extra;
1101 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
1103 // The size is not a constant. Generate code to compute it and
1104 // code to pad the size for stack alignment.
1105 // Create a Value to hold the (constant) element size
1106 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1108 // Create temporary values to hold the result of MUL, SLL, SRL
1109 // To pad `size' to next smallest multiple of 16:
1110 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
1112 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
1113 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
1114 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
1116 // Instruction 1: mul numElements, typeSize -> tmpProd
1117 // This will optimize the MUL as far as possible.
1118 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
1119 mcfi, INVALID_MACHINE_OPCODE);
1121 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
1122 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
1123 .addReg(tmpAdd15, MOTy::Def));
1125 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
1126 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
1127 .addReg(tmpAndf0, MOTy::Def));
1129 totalSizeVal = tmpAndf0;
1132 // Get the constant offset from SP for dynamically allocated storage
1133 // and create a temporary Value to hold it.
1134 MachineFunction& mcInfo = MachineFunction::get(F);
1136 ConstantSInt* dynamicAreaOffset =
1137 ConstantSInt::get(Type::IntTy,
1138 target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
1139 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
1141 unsigned SPReg = target.getRegInfo().getStackPointer();
1143 // Instruction 2: sub %sp, totalSizeVal -> %sp
1144 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
1145 .addMReg(SPReg,MOTy::Def));
1147 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1148 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
1149 .addRegDef(result));
1154 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
1155 Instruction* result,
1157 unsigned numElements,
1158 std::vector<MachineInstr*>& getMvec)
1160 assert(tsize > 0 && "Illegal (zero) type size for alloca");
1161 assert(result && result->getParent() &&
1162 "Result value is not part of a function?");
1163 Function *F = result->getParent()->getParent();
1164 MachineFunction &mcInfo = MachineFunction::get(F);
1166 // Put the variable in the dynamically sized area of the frame if either:
1167 // (a) The offset is too large to use as an immediate in load/stores
1168 // (check LDX because all load/stores have the same-size immed. field).
1169 // (b) The object is "large", so it could cause many other locals,
1170 // spills, and temporaries to have large offsets.
1171 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
1172 // You've gotta love having only 13 bits for constant offset values :-|.
1174 unsigned paddedSize;
1175 int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
1177 tsize * numElements);
1179 if (((int)paddedSize) > 8 * target.getFrameInfo().getSizeOfEachArgOnStack() ||
1180 ! target.getInstrInfo().constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
1181 CreateCodeForVariableSizeAlloca(target, result, tsize,
1182 ConstantSInt::get(Type::IntTy,numElements),
1187 // else offset fits in immediate field so go ahead and allocate it.
1188 offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
1190 // Create a temporary Value to hold the constant offset.
1191 // This is needed because it may not fit in the immediate field.
1192 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1194 // Instruction 1: add %fp, offsetFromFP -> result
1195 unsigned FPReg = target.getRegInfo().getFramePointer();
1196 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
1197 .addRegDef(result));
1201 //------------------------------------------------------------------------
1202 // Function SetOperandsForMemInstr
1204 // Choose addressing mode for the given load or store instruction.
1205 // Use [reg+reg] if it is an indexed reference, and the index offset is
1206 // not a constant or if it cannot fit in the offset field.
1207 // Use [reg+offset] in all other cases.
1209 // This assumes that all array refs are "lowered" to one of these forms:
1210 // %x = load (subarray*) ptr, constant ; single constant offset
1211 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
1212 // Generally, this should happen via strength reduction + LICM.
1213 // Also, strength reduction should take care of using the same register for
1214 // the loop index variable and an array index, when that is profitable.
1215 //------------------------------------------------------------------------
1218 SetOperandsForMemInstr(unsigned Opcode,
1219 std::vector<MachineInstr*>& mvec,
1220 InstructionNode* vmInstrNode,
1221 const TargetMachine& target)
1223 Instruction* memInst = vmInstrNode->getInstruction();
1224 // Index vector, ptr value, and flag if all indices are const.
1225 std::vector<Value*> idxVec;
1226 bool allConstantIndices;
1227 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
1229 // Now create the appropriate operands for the machine instruction.
1230 // First, initialize so we default to storing the offset in a register.
1231 int64_t smallConstOffset = 0;
1232 Value* valueForRegOffset = NULL;
1233 MachineOperand::MachineOperandType offsetOpType =
1234 MachineOperand::MO_VirtualRegister;
1236 // Check if there is an index vector and if so, compute the
1237 // right offset for structures and for arrays
1239 if (!idxVec.empty()) {
1240 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1242 // If all indices are constant, compute the combined offset directly.
1243 if (allConstantIndices) {
1244 // Compute the offset value using the index vector. Create a
1245 // virtual reg. for it since it may not fit in the immed field.
1246 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
1247 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1249 // There is at least one non-constant offset. Therefore, this must
1250 // be an array ref, and must have been lowered to a single non-zero
1251 // offset. (An extra leading zero offset, if any, can be ignored.)
1252 // Generate code sequence to compute address from index.
1254 bool firstIdxIsZero = IsZero(idxVec[0]);
1255 assert(idxVec.size() == 1U + firstIdxIsZero
1256 && "Array refs must be lowered before Instruction Selection");
1258 Value* idxVal = idxVec[firstIdxIsZero];
1260 std::vector<MachineInstr*> mulVec;
1262 new TmpInstruction(MachineCodeForInstruction::get(memInst),
1263 Type::ULongTy, memInst);
1265 // Get the array type indexed by idxVal, and compute its element size.
1266 // The call to getTypeSize() will fail if size is not constant.
1267 const Type* vecType = (firstIdxIsZero
1268 ? GetElementPtrInst::getIndexedType(ptrType,
1269 std::vector<Value*>(1U, idxVec[0]),
1270 /*AllowCompositeLeaf*/ true)
1272 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1273 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
1274 target.getTargetData().getTypeSize(eltType));
1276 // CreateMulInstruction() folds constants intelligently enough.
1277 CreateMulInstruction(target, memInst->getParent()->getParent(),
1278 idxVal, /* lval, not likely to be const*/
1279 eltSizeVal, /* rval, likely to be constant */
1281 mulVec, MachineCodeForInstruction::get(memInst),
1282 INVALID_MACHINE_OPCODE);
1284 assert(mulVec.size() > 0 && "No multiply code created?");
1285 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
1287 valueForRegOffset = addr;
1290 offsetOpType = MachineOperand::MO_SignExtendedImmed;
1291 smallConstOffset = 0;
1295 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
1296 // For LOAD or GET_ELEMENT_PTR,
1297 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1299 unsigned offsetOpNum, ptrOpNum;
1301 if (memInst->getOpcode() == Instruction::Store) {
1302 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1303 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1304 .addReg(ptrVal).addReg(valueForRegOffset);
1306 Opcode = convertOpcodeFromRegToImm(Opcode);
1307 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1308 .addReg(ptrVal).addSImm(smallConstOffset);
1311 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1312 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
1313 .addRegDef(memInst);
1315 Opcode = convertOpcodeFromRegToImm(Opcode);
1316 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
1317 .addRegDef(memInst);
1325 // Substitute operand `operandNum' of the instruction in node `treeNode'
1326 // in place of the use(s) of that instruction in node `parent'.
1327 // Check both explicit and implicit operands!
1328 // Also make sure to skip over a parent who:
1329 // (1) is a list node in the Burg tree, or
1330 // (2) itself had its results forwarded to its parent
1333 ForwardOperand(InstructionNode* treeNode,
1334 InstrTreeNode* parent,
1337 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1339 Instruction* unusedOp = treeNode->getInstruction();
1340 Value* fwdOp = unusedOp->getOperand(operandNum);
1342 // The parent itself may be a list node, so find the real parent instruction
1343 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1345 parent = parent->parent();
1346 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1348 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1350 Instruction* userInstr = parentInstrNode->getInstruction();
1351 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1353 // The parent's mvec would be empty if it was itself forwarded.
1354 // Recursively call ForwardOperand in that case...
1356 if (mvec.size() == 0) {
1357 assert(parent->parent() != NULL &&
1358 "Parent could not have been forwarded, yet has no instructions?");
1359 ForwardOperand(treeNode, parent->parent(), operandNum);
1361 for (unsigned i=0, N=mvec.size(); i < N; i++) {
1362 MachineInstr* minstr = mvec[i];
1363 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
1364 const MachineOperand& mop = minstr->getOperand(i);
1365 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
1366 mop.getVRegValue() == unusedOp)
1368 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
1373 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1374 if (minstr->getImplicitRef(i) == unusedOp)
1375 minstr->setImplicitRef(i, fwdOp);
1382 AllUsesAreBranches(const Instruction* setccI)
1384 for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1386 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
1387 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1392 // Generate code for any intrinsic that needs a special code sequence
1393 // instead of a regular call. If not that kind of intrinsic, do nothing.
1394 // Returns true if code was generated, otherwise false.
1396 bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
1397 TargetMachine &target,
1398 std::vector<MachineInstr*>& mvec)
1401 case Intrinsic::va_start: {
1402 // Get the address of the first incoming vararg argument on the stack
1404 Function* func = cast<Function>(callInstr.getParent()->getParent());
1405 int numFixedArgs = func->getFunctionType()->getNumParams();
1406 int fpReg = target.getFrameInfo().getIncomingArgBaseRegNum();
1407 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
1408 int firstVarArgOff = numFixedArgs * argSize + target.getFrameInfo().
1409 getFirstIncomingArgOffset(MachineFunction::get(func), ignore);
1410 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
1411 addRegDef(&callInstr));
1415 case Intrinsic::va_end:
1416 return true; // no-op on Sparc
1418 case Intrinsic::va_copy:
1419 // Simple copy of current va_list (arg1) to new va_list (result)
1420 mvec.push_back(BuildMI(V9::ORr, 3).
1421 addMReg(target.getRegInfo().getZeroRegNum()).
1422 addReg(callInstr.getOperand(1)).
1423 addRegDef(&callInstr));
1426 case Intrinsic::sigsetjmp:
1427 case Intrinsic::setjmp: {
1428 // act as if we return 0
1429 unsigned g0 = target.getRegInfo().getZeroRegNum();
1430 mvec.push_back(BuildMI(V9::ORr,3).addMReg(g0).addMReg(g0)
1431 .addReg(&callInstr, MOTy::Def));
1435 case Intrinsic::siglongjmp:
1436 case Intrinsic::longjmp: {
1438 Module* M = callInstr.getParent()->getParent()->getParent();
1439 const FunctionType *voidvoidFuncTy =
1440 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
1441 Function *F = M->getOrInsertFunction("abort", voidvoidFuncTy);
1442 assert(F && "Unable to get or create `abort' function declaration");
1444 // Create hidden virtual register for return address with type void*
1445 TmpInstruction* retAddrReg =
1446 new TmpInstruction(MachineCodeForInstruction::get(&callInstr),
1447 PointerType::get(Type::VoidTy), &callInstr);
1449 // Use a descriptor to pass information about call arguments
1450 // to the register allocator. This descriptor will be "owned"
1451 // and freed automatically when the MachineCodeForInstruction
1452 // object for the callInstr goes away.
1453 CallArgsDescriptor* argDesc =
1454 new CallArgsDescriptor(&callInstr, retAddrReg, false, false);
1456 MachineInstr* callMI = BuildMI(V9::CALL, 1).addPCDisp(F);
1457 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
1459 mvec.push_back(callMI);
1460 mvec.push_back(BuildMI(V9::NOP, 0));
1469 //******************* Externally Visible Functions *************************/
1471 //------------------------------------------------------------------------
1472 // External Function: ThisIsAChainRule
1475 // Check if a given BURG rule is a chain rule.
1476 //------------------------------------------------------------------------
1479 ThisIsAChainRule(int eruleno)
1483 case 111: // stmt: reg
1507 return false; break;
1512 //------------------------------------------------------------------------
1513 // External Function: GetInstructionsByRule
1516 // Choose machine instructions for the SPARC according to the
1517 // patterns chosen by the BURG-generated parser.
1518 //------------------------------------------------------------------------
1521 GetInstructionsByRule(InstructionNode* subtreeRoot,
1524 TargetMachine &target,
1525 std::vector<MachineInstr*>& mvec)
1527 bool checkCast = false; // initialize here to use fall-through
1528 bool maskUnsignedResult = false;
1530 int forwardOperandNum = -1;
1531 unsigned allocaSize = 0;
1532 MachineInstr* M, *M2;
1534 bool foldCase = false;
1538 // If the code for this instruction was folded into the parent (user),
1540 if (subtreeRoot->isFoldedIntoParent())
1544 // Let's check for chain rules outside the switch so that we don't have
1545 // to duplicate the list of chain rule production numbers here again
1547 if (ThisIsAChainRule(ruleForNode)) {
1548 // Chain rules have a single nonterminal on the RHS.
1549 // Get the rule that matches the RHS non-terminal and use that instead.
1551 assert(nts[0] && ! nts[1]
1552 && "A chain rule should have only one RHS non-terminal!");
1553 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1554 nts = burm_nts[nextRule];
1555 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1557 switch(ruleForNode) {
1558 case 1: // stmt: Ret
1559 case 2: // stmt: RetValue(reg)
1560 { // NOTE: Prepass of register allocation is responsible
1561 // for moving return value to appropriate register.
1562 // Copy the return value to the required return register.
1563 // Mark the return Value as an implicit ref of the RET instr..
1564 // Mark the return-address register as a hidden virtual reg.
1565 // Finally put a NOP in the delay slot.
1566 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
1567 Value* retVal = returnInstr->getReturnValue();
1568 MachineCodeForInstruction& mcfi =
1569 MachineCodeForInstruction::get(returnInstr);
1571 // Create a hidden virtual reg to represent the return address register
1572 // used by the machine instruction but not represented in LLVM.
1574 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
1576 MachineInstr* retMI =
1577 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
1578 .addMReg(target.getRegInfo().getZeroRegNum(), MOTy::Def);
1580 // If there is a value to return, we need to:
1581 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
1582 // (b) Insert a copy to copy the return value to the appropriate reg.
1583 // -- For FP values, create a FMOVS or FMOVD instruction
1584 // -- For non-FP values, create an add-with-0 instruction
1586 if (retVal != NULL) {
1587 const SparcRegInfo& regInfo =
1588 (SparcRegInfo&) target.getRegInfo();
1589 const Type* retType = retVal->getType();
1590 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
1591 unsigned retRegNum = (retType->isFloatingPoint()
1592 ? (unsigned) SparcFloatRegClass::f0
1593 : (unsigned) SparcIntRegClass::i0);
1594 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
1596 // () Insert sign-extension instructions for small signed values.
1598 Value* retValToUse = retVal;
1599 if (retType->isIntegral() && retType->isSigned()) {
1600 unsigned retSize = target.getTargetData().getTypeSize(retType);
1602 // create a temporary virtual reg. to hold the sign-extension
1603 retValToUse = new TmpInstruction(mcfi, retVal);
1605 // sign-extend retVal and put the result in the temporary reg.
1606 target.getInstrInfo().CreateSignExtensionInstructions
1607 (target, returnInstr->getParent()->getParent(),
1608 retVal, retValToUse, 8*retSize, mvec, mcfi);
1612 // (b) Now, insert a copy to to the appropriate register:
1613 // -- For FP values, create a FMOVS or FMOVD instruction
1614 // -- For non-FP values, create an add-with-0 instruction
1616 // First, create a virtual register to represent the register and
1617 // mark this vreg as being an implicit operand of the ret MI.
1618 TmpInstruction* retVReg =
1619 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
1621 retMI->addImplicitRef(retVReg);
1623 if (retType->isFloatingPoint())
1624 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1625 .addReg(retValToUse).addReg(retVReg, MOTy::Def));
1627 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
1628 .addReg(retValToUse).addSImm((int64_t) 0)
1629 .addReg(retVReg, MOTy::Def));
1631 // Mark the operand with the register it should be assigned
1632 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
1633 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
1638 // Now insert the RET instruction and a NOP for the delay slot
1639 mvec.push_back(retMI);
1640 mvec.push_back(BuildMI(V9::NOP, 0));
1645 case 3: // stmt: Store(reg,reg)
1646 case 4: // stmt: Store(reg,ptrreg)
1647 SetOperandsForMemInstr(ChooseStoreInstruction(
1648 subtreeRoot->leftChild()->getValue()->getType()),
1649 mvec, subtreeRoot, target);
1652 case 5: // stmt: BrUncond
1654 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1655 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
1658 mvec.push_back(BuildMI(V9::NOP, 0));
1662 case 206: // stmt: BrCond(setCCconst)
1663 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1664 // If the constant is ZERO, we can use the branch-on-integer-register
1665 // instructions and avoid the SUBcc instruction entirely.
1666 // Otherwise this is just the same as case 5, so just fall through.
1668 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1670 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1671 Constant *constVal = cast<Constant>(constNode->getValue());
1674 if ((constVal->getType()->isInteger()
1675 || isa<PointerType>(constVal->getType()))
1676 && target.getInstrInfo().ConvertConstantToIntType(target,
1677 constVal, constVal->getType(), isValidConst) == 0
1680 // That constant is a zero after all...
1681 // Use the left child of setCC as the first argument!
1682 // Mark the setCC node so that no code is generated for it.
1683 InstructionNode* setCCNode = (InstructionNode*)
1684 subtreeRoot->leftChild();
1685 assert(setCCNode->getOpLabel() == SetCCOp);
1686 setCCNode->markFoldedIntoParent();
1688 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1690 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
1691 .addReg(setCCNode->leftChild()->getValue())
1692 .addPCDisp(brInst->getSuccessor(0));
1696 mvec.push_back(BuildMI(V9::NOP, 0));
1699 mvec.push_back(BuildMI(V9::BA, 1)
1700 .addPCDisp(brInst->getSuccessor(1)));
1703 mvec.push_back(BuildMI(V9::NOP, 0));
1706 // ELSE FALL THROUGH
1709 case 6: // stmt: BrCond(setCC)
1710 { // bool => boolean was computed with SetCC.
1711 // The branch to use depends on whether it is FP, signed, or unsigned.
1712 // If it is an integer CC, we also need to find the unique
1713 // TmpInstruction representing that CC.
1715 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1716 const Type* setCCType;
1717 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
1718 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1719 brInst->getParent()->getParent(),
1721 MachineCodeForInstruction::get(brInst));
1722 M = BuildMI(Opcode, 2).addCCReg(ccValue)
1723 .addPCDisp(brInst->getSuccessor(0));
1727 mvec.push_back(BuildMI(V9::NOP, 0));
1730 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
1733 mvec.push_back(BuildMI(V9::NOP, 0));
1737 case 208: // stmt: BrCond(boolconst)
1739 // boolconst => boolean is a constant; use BA to first or second label
1740 Constant* constVal =
1741 cast<Constant>(subtreeRoot->leftChild()->getValue());
1742 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1744 M = BuildMI(V9::BA, 1).addPCDisp(
1745 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1749 mvec.push_back(BuildMI(V9::NOP, 0));
1753 case 8: // stmt: BrCond(boolreg)
1754 { // boolreg => boolean is recorded in an integer register.
1755 // Use branch-on-integer-register instruction.
1757 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1758 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
1759 .addPCDisp(BI->getSuccessor(0));
1763 mvec.push_back(BuildMI(V9::NOP, 0));
1766 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
1769 mvec.push_back(BuildMI(V9::NOP, 0));
1773 case 9: // stmt: Switch(reg)
1774 assert(0 && "*** SWITCH instruction is not implemented yet.");
1777 case 10: // reg: VRegList(reg, reg)
1778 assert(0 && "VRegList should never be the topmost non-chain rule");
1781 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
1782 { // First find the unary operand. It may be left or right, usually right.
1783 Instruction* notI = subtreeRoot->getInstruction();
1784 Value* notArg = BinaryOperator::getNotArgument(
1785 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1786 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1788 // Unconditionally set register to 0
1789 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
1791 // Now conditionally move 1 into the register.
1792 // Mark the register as a use (as well as a def) because the old
1793 // value will be retained if the condition is false.
1794 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
1795 .addReg(notI, MOTy::UseAndDef));
1800 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
1801 { // First find the unary operand. It may be left or right, usually right.
1802 Value* notArg = BinaryOperator::getNotArgument(
1803 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1804 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1805 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
1806 .addRegDef(subtreeRoot->getValue()));
1810 case 322: // reg: Not(tobool, reg):
1811 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
1813 // Just fall through!
1815 case 22: // reg: ToBoolTy(reg):
1817 Instruction* castI = subtreeRoot->getInstruction();
1818 Value* opVal = subtreeRoot->leftChild()->getValue();
1819 assert(opVal->getType()->isIntegral() ||
1820 isa<PointerType>(opVal->getType()));
1822 // Unconditionally set register to 0
1823 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
1825 // Now conditionally move 1 into the register.
1826 // Mark the register as a use (as well as a def) because the old
1827 // value will be retained if the condition is false.
1828 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
1829 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
1830 .addReg(castI, MOTy::UseAndDef));
1835 case 23: // reg: ToUByteTy(reg)
1836 case 24: // reg: ToSByteTy(reg)
1837 case 25: // reg: ToUShortTy(reg)
1838 case 26: // reg: ToShortTy(reg)
1839 case 27: // reg: ToUIntTy(reg)
1840 case 28: // reg: ToIntTy(reg)
1841 case 29: // reg: ToULongTy(reg)
1842 case 30: // reg: ToLongTy(reg)
1844 //======================================================================
1845 // Rules for integer conversions:
1848 // From ISO 1998 C++ Standard, Sec. 4.7:
1850 // 2. If the destination type is unsigned, the resulting value is
1851 // the least unsigned integer congruent to the source integer
1852 // (modulo 2n where n is the number of bits used to represent the
1853 // unsigned type). [Note: In a two s complement representation,
1854 // this conversion is conceptual and there is no change in the
1855 // bit pattern (if there is no truncation). ]
1857 // 3. If the destination type is signed, the value is unchanged if
1858 // it can be represented in the destination type (and bitfield width);
1859 // otherwise, the value is implementation-defined.
1862 // Since we assume 2s complement representations, this implies:
1864 // -- If operand is smaller than destination, zero-extend or sign-extend
1865 // according to the signedness of the *operand*: source decides:
1866 // (1) If operand is signed, sign-extend it.
1867 // If dest is unsigned, zero-ext the result!
1868 // (2) If operand is unsigned, our current invariant is that
1869 // it's high bits are correct, so zero-extension is not needed.
1871 // -- If operand is same size as or larger than destination,
1872 // zero-extend or sign-extend according to the signedness of
1873 // the *destination*: destination decides:
1874 // (1) If destination is signed, sign-extend (truncating if needed)
1875 // This choice is implementation defined. We sign-extend the
1876 // operand, which matches both Sun's cc and gcc3.2.
1877 // (2) If destination is unsigned, zero-extend (truncating if needed)
1878 //======================================================================
1880 Instruction* destI = subtreeRoot->getInstruction();
1881 Function* currentFunc = destI->getParent()->getParent();
1882 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
1884 Value* opVal = subtreeRoot->leftChild()->getValue();
1885 const Type* opType = opVal->getType();
1886 const Type* destType = destI->getType();
1887 unsigned opSize = target.getTargetData().getTypeSize(opType);
1888 unsigned destSize = target.getTargetData().getTypeSize(destType);
1890 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
1892 if (opType == Type::BoolTy ||
1893 opType == destType ||
1894 isIntegral && opSize == destSize && opSize == 8) {
1895 // nothing to do in all these cases
1896 forwardOperandNum = 0; // forward first operand to user
1898 } else if (opType->isFloatingPoint()) {
1900 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1901 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
1902 maskUnsignedResult = true; // not handled by fp->int code
1904 } else if (isIntegral) {
1906 bool opSigned = opType->isSigned();
1907 bool destSigned = destType->isSigned();
1908 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
1910 assert(! (opSize == destSize && opSigned == destSigned) &&
1911 "How can different int types have same size and signedness?");
1913 bool signExtend = (opSize < destSize && opSigned ||
1914 opSize >= destSize && destSigned);
1916 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
1917 opSigned && !destSigned);
1918 assert(!signAndZeroExtend || signExtend);
1920 bool zeroExtendOnly = opSize >= destSize && !destSigned;
1921 assert(!zeroExtendOnly || !signExtend);
1924 Value* signExtDest = (signAndZeroExtend
1925 ? new TmpInstruction(mcfi, destType, opVal)
1928 target.getInstrInfo().CreateSignExtensionInstructions
1929 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
1931 if (signAndZeroExtend)
1932 target.getInstrInfo().CreateZeroExtensionInstructions
1933 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
1935 else if (zeroExtendOnly) {
1936 target.getInstrInfo().CreateZeroExtensionInstructions
1937 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
1940 forwardOperandNum = 0; // forward first operand to user
1943 assert(0 && "Unrecognized operand type for convert-to-integer");
1948 case 31: // reg: ToFloatTy(reg):
1949 case 32: // reg: ToDoubleTy(reg):
1950 case 232: // reg: ToDoubleTy(Constant):
1952 // If this instruction has a parent (a user) in the tree
1953 // and the user is translated as an FsMULd instruction,
1954 // then the cast is unnecessary. So check that first.
1955 // In the future, we'll want to do the same for the FdMULq instruction,
1956 // so do the check here instead of only for ToFloatTy(reg).
1958 if (subtreeRoot->parent() != NULL) {
1959 const MachineCodeForInstruction& mcfi =
1960 MachineCodeForInstruction::get(
1961 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1962 if (mcfi.size() == 0 || mcfi.front()->getOpCode() == V9::FSMULD)
1963 forwardOperandNum = 0; // forward first operand to user
1966 if (forwardOperandNum != 0) { // we do need the cast
1967 Value* leftVal = subtreeRoot->leftChild()->getValue();
1968 const Type* opType = leftVal->getType();
1969 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
1970 subtreeRoot->getOpLabel(), opType);
1971 if (opCode == V9::NOP) { // no conversion needed
1972 forwardOperandNum = 0; // forward first operand to user
1974 // If the source operand is a non-FP type it must be
1975 // first copied from int to float register via memory!
1976 Instruction *dest = subtreeRoot->getInstruction();
1979 if (! opType->isFloatingPoint()) {
1980 // Create a temporary to represent the FP register
1981 // into which the integer will be copied via memory.
1982 // The type of this temporary will determine the FP
1983 // register used: single-prec for a 32-bit int or smaller,
1984 // double-prec for a 64-bit int.
1987 target.getTargetData().getTypeSize(leftVal->getType());
1988 Type* tmpTypeToUse =
1989 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1990 MachineCodeForInstruction &destMCFI =
1991 MachineCodeForInstruction::get(dest);
1992 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
1994 target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
1995 dest->getParent()->getParent(),
1996 leftVal, cast<Instruction>(srcForCast),
1999 srcForCast = leftVal;
2001 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
2007 case 19: // reg: ToArrayTy(reg):
2008 case 20: // reg: ToPointerTy(reg):
2009 forwardOperandNum = 0; // forward first operand to user
2012 case 233: // reg: Add(reg, Constant)
2013 maskUnsignedResult = true;
2014 M = CreateAddConstInstruction(subtreeRoot);
2019 // ELSE FALL THROUGH
2021 case 33: // reg: Add(reg, reg)
2022 maskUnsignedResult = true;
2023 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
2026 case 234: // reg: Sub(reg, Constant)
2027 maskUnsignedResult = true;
2028 M = CreateSubConstInstruction(subtreeRoot);
2033 // ELSE FALL THROUGH
2035 case 34: // reg: Sub(reg, reg)
2036 maskUnsignedResult = true;
2037 Add3OperandInstr(ChooseSubInstructionByType(
2038 subtreeRoot->getInstruction()->getType()),
2042 case 135: // reg: Mul(todouble, todouble)
2046 case 35: // reg: Mul(reg, reg)
2048 maskUnsignedResult = true;
2049 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2051 : INVALID_MACHINE_OPCODE);
2052 Instruction* mulInstr = subtreeRoot->getInstruction();
2053 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2054 subtreeRoot->leftChild()->getValue(),
2055 subtreeRoot->rightChild()->getValue(),
2057 MachineCodeForInstruction::get(mulInstr),forceOp);
2060 case 335: // reg: Mul(todouble, todoubleConst)
2064 case 235: // reg: Mul(reg, Constant)
2066 maskUnsignedResult = true;
2067 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2069 : INVALID_MACHINE_OPCODE);
2070 Instruction* mulInstr = subtreeRoot->getInstruction();
2071 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2072 subtreeRoot->leftChild()->getValue(),
2073 subtreeRoot->rightChild()->getValue(),
2075 MachineCodeForInstruction::get(mulInstr),
2079 case 236: // reg: Div(reg, Constant)
2080 maskUnsignedResult = true;
2082 CreateDivConstInstruction(target, subtreeRoot, mvec);
2083 if (mvec.size() > L)
2085 // ELSE FALL THROUGH
2087 case 36: // reg: Div(reg, reg)
2089 maskUnsignedResult = true;
2091 // If either operand of divide is smaller than 64 bits, we have
2092 // to make sure the unused top bits are correct because they affect
2093 // the result. These bits are already correct for unsigned values.
2094 // They may be incorrect for signed values, so sign extend to fill in.
2095 Instruction* divI = subtreeRoot->getInstruction();
2096 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2097 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2098 Value* divOp1ToUse = divOp1;
2099 Value* divOp2ToUse = divOp2;
2100 if (divI->getType()->isSigned()) {
2101 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
2103 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
2104 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
2105 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
2106 target.getInstrInfo().
2107 CreateSignExtensionInstructions(target,
2108 divI->getParent()->getParent(),
2109 divOp1, divOp1ToUse,
2110 8*opSize, mvec, mcfi);
2111 target.getInstrInfo().
2112 CreateSignExtensionInstructions(target,
2113 divI->getParent()->getParent(),
2114 divOp2, divOp2ToUse,
2115 8*opSize, mvec, mcfi);
2119 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2120 .addReg(divOp1ToUse)
2121 .addReg(divOp2ToUse)
2127 case 37: // reg: Rem(reg, reg)
2128 case 237: // reg: Rem(reg, Constant)
2130 maskUnsignedResult = true;
2132 Instruction* remI = subtreeRoot->getInstruction();
2133 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2134 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2136 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
2138 // If second operand of divide is smaller than 64 bits, we have
2139 // to make sure the unused top bits are correct because they affect
2140 // the result. These bits are already correct for unsigned values.
2141 // They may be incorrect for signed values, so sign extend to fill in.
2143 Value* divOpToUse = divOp2;
2144 if (divOp2->getType()->isSigned()) {
2145 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
2147 divOpToUse = new TmpInstruction(mcfi, divOp2);
2148 target.getInstrInfo().
2149 CreateSignExtensionInstructions(target,
2150 remI->getParent()->getParent(),
2152 8*opSize, mvec, mcfi);
2156 // Now compute: result = rem V1, V2 as:
2157 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
2159 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
2160 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
2162 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2163 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
2165 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
2166 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
2168 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
2169 .addReg(divOp1).addReg(prod).addRegDef(remI));
2174 case 38: // bool: And(bool, bool)
2175 case 138: // bool: And(bool, not)
2176 case 238: // bool: And(bool, boolconst)
2177 case 338: // reg : BAnd(reg, reg)
2178 case 538: // reg : BAnd(reg, Constant)
2179 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
2182 case 438: // bool: BAnd(bool, bnot)
2183 { // Use the argument of NOT as the second argument!
2184 // Mark the NOT node so that no code is generated for it.
2185 // If the type is boolean, set 1 or 0 in the result register.
2186 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2187 Value* notArg = BinaryOperator::getNotArgument(
2188 cast<BinaryOperator>(notNode->getInstruction()));
2189 notNode->markFoldedIntoParent();
2190 Value *lhs = subtreeRoot->leftChild()->getValue();
2191 Value *dest = subtreeRoot->getValue();
2192 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
2193 .addReg(dest, MOTy::Def));
2195 if (notArg->getType() == Type::BoolTy) {
2196 // set 1 in result register if result of above is non-zero
2197 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2198 .addReg(dest, MOTy::UseAndDef));
2204 case 39: // bool: Or(bool, bool)
2205 case 139: // bool: Or(bool, not)
2206 case 239: // bool: Or(bool, boolconst)
2207 case 339: // reg : BOr(reg, reg)
2208 case 539: // reg : BOr(reg, Constant)
2209 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
2212 case 439: // bool: BOr(bool, bnot)
2213 { // Use the argument of NOT as the second argument!
2214 // Mark the NOT node so that no code is generated for it.
2215 // If the type is boolean, set 1 or 0 in the result register.
2216 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2217 Value* notArg = BinaryOperator::getNotArgument(
2218 cast<BinaryOperator>(notNode->getInstruction()));
2219 notNode->markFoldedIntoParent();
2220 Value *lhs = subtreeRoot->leftChild()->getValue();
2221 Value *dest = subtreeRoot->getValue();
2223 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
2224 .addReg(dest, MOTy::Def));
2226 if (notArg->getType() == Type::BoolTy) {
2227 // set 1 in result register if result of above is non-zero
2228 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2229 .addReg(dest, MOTy::UseAndDef));
2235 case 40: // bool: Xor(bool, bool)
2236 case 140: // bool: Xor(bool, not)
2237 case 240: // bool: Xor(bool, boolconst)
2238 case 340: // reg : BXor(reg, reg)
2239 case 540: // reg : BXor(reg, Constant)
2240 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
2243 case 440: // bool: BXor(bool, bnot)
2244 { // Use the argument of NOT as the second argument!
2245 // Mark the NOT node so that no code is generated for it.
2246 // If the type is boolean, set 1 or 0 in the result register.
2247 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2248 Value* notArg = BinaryOperator::getNotArgument(
2249 cast<BinaryOperator>(notNode->getInstruction()));
2250 notNode->markFoldedIntoParent();
2251 Value *lhs = subtreeRoot->leftChild()->getValue();
2252 Value *dest = subtreeRoot->getValue();
2253 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
2254 .addReg(dest, MOTy::Def));
2256 if (notArg->getType() == Type::BoolTy) {
2257 // set 1 in result register if result of above is non-zero
2258 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2259 .addReg(dest, MOTy::UseAndDef));
2264 case 41: // setCCconst: SetCC(reg, Constant)
2265 { // Comparison is with a constant:
2267 // If the bool result must be computed into a register (see below),
2268 // and the constant is int ZERO, we can use the MOVR[op] instructions
2269 // and avoid the SUBcc instruction entirely.
2270 // Otherwise this is just the same as case 42, so just fall through.
2272 // The result of the SetCC must be computed and stored in a register if
2273 // it is used outside the current basic block (so it must be computed
2274 // as a boolreg) or it is used by anything other than a branch.
2275 // We will use a conditional move to do this.
2277 Instruction* setCCInstr = subtreeRoot->getInstruction();
2278 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2279 ! AllUsesAreBranches(setCCInstr));
2281 if (computeBoolVal) {
2282 InstrTreeNode* constNode = subtreeRoot->rightChild();
2284 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2285 Constant *constVal = cast<Constant>(constNode->getValue());
2288 if ((constVal->getType()->isInteger()
2289 || isa<PointerType>(constVal->getType()))
2290 && target.getInstrInfo().ConvertConstantToIntType(target,
2291 constVal, constVal->getType(), isValidConst) == 0
2294 // That constant is an integer zero after all...
2295 // Use a MOVR[op] to compute the boolean result
2296 // Unconditionally set register to 0
2297 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
2298 .addRegDef(setCCInstr));
2300 // Now conditionally move 1 into the register.
2301 // Mark the register as a use (as well as a def) because the old
2302 // value will be retained if the condition is false.
2303 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
2304 mvec.push_back(BuildMI(movOpCode, 3)
2305 .addReg(subtreeRoot->leftChild()->getValue())
2306 .addZImm(1).addReg(setCCInstr, MOTy::UseAndDef));
2311 // ELSE FALL THROUGH
2314 case 42: // bool: SetCC(reg, reg):
2316 // This generates a SUBCC instruction, putting the difference in a
2317 // result reg. if needed, and/or setting a condition code if needed.
2319 Instruction* setCCInstr = subtreeRoot->getInstruction();
2320 Value* leftVal = subtreeRoot->leftChild()->getValue();
2321 Value* rightVal = subtreeRoot->rightChild()->getValue();
2322 const Type* opType = leftVal->getType();
2323 bool isFPCompare = opType->isFloatingPoint();
2325 // If the boolean result of the SetCC is used outside the current basic
2326 // block (so it must be computed as a boolreg) or is used by anything
2327 // other than a branch, the boolean must be computed and stored
2328 // in a result register. We will use a conditional move to do this.
2330 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2331 ! AllUsesAreBranches(setCCInstr));
2333 // A TmpInstruction is created to represent the CC "result".
2334 // Unlike other instances of TmpInstruction, this one is used
2335 // by machine code of multiple LLVM instructions, viz.,
2336 // the SetCC and the branch. Make sure to get the same one!
2337 // Note that we do this even for FP CC registers even though they
2338 // are explicit operands, because the type of the operand
2339 // needs to be a floating point condition code, not an integer
2340 // condition code. Think of this as casting the bool result to
2341 // a FP condition code register.
2342 // Later, we mark the 4th operand as being a CC register, and as a def.
2344 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
2345 setCCInstr->getParent()->getParent(),
2347 MachineCodeForInstruction::get(setCCInstr));
2349 // If the operands are signed values smaller than 4 bytes, then they
2350 // must be sign-extended in order to do a valid 32-bit comparison
2351 // and get the right result in the 32-bit CC register (%icc).
2353 Value* leftOpToUse = leftVal;
2354 Value* rightOpToUse = rightVal;
2355 if (opType->isIntegral() && opType->isSigned()) {
2356 unsigned opSize = target.getTargetData().getTypeSize(opType);
2358 MachineCodeForInstruction& mcfi =
2359 MachineCodeForInstruction::get(setCCInstr);
2361 // create temporary virtual regs. to hold the sign-extensions
2362 leftOpToUse = new TmpInstruction(mcfi, leftVal);
2363 rightOpToUse = new TmpInstruction(mcfi, rightVal);
2365 // sign-extend each operand and put the result in the temporary reg.
2366 target.getInstrInfo().CreateSignExtensionInstructions
2367 (target, setCCInstr->getParent()->getParent(),
2368 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
2369 target.getInstrInfo().CreateSignExtensionInstructions
2370 (target, setCCInstr->getParent()->getParent(),
2371 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
2375 if (! isFPCompare) {
2376 // Integer condition: set CC and discard result.
2377 mvec.push_back(BuildMI(V9::SUBccr, 4)
2378 .addReg(leftOpToUse)
2379 .addReg(rightOpToUse)
2380 .addMReg(target.getRegInfo().getZeroRegNum(),MOTy::Def)
2381 .addCCReg(tmpForCC, MOTy::Def));
2383 // FP condition: dest of FCMP should be some FCCn register
2384 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
2385 .addCCReg(tmpForCC, MOTy::Def)
2386 .addReg(leftOpToUse)
2387 .addReg(rightOpToUse));
2390 if (computeBoolVal) {
2391 MachineOpCode movOpCode = (isFPCompare
2392 ? ChooseMovFpcciInstruction(subtreeRoot)
2393 : ChooseMovpcciForSetCC(subtreeRoot));
2395 // Unconditionally set register to 0
2396 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
2399 // Now conditionally move 1 into the register.
2400 // Mark the register as a use (as well as a def) because the old
2401 // value will be retained if the condition is false.
2402 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
2403 .addReg(setCCInstr, MOTy::UseAndDef));
2409 case 51: // reg: Load(reg)
2410 case 52: // reg: Load(ptrreg)
2411 SetOperandsForMemInstr(ChooseLoadInstruction(
2412 subtreeRoot->getValue()->getType()),
2413 mvec, subtreeRoot, target);
2416 case 55: // reg: GetElemPtr(reg)
2417 case 56: // reg: GetElemPtrIdx(reg,reg)
2418 // If the GetElemPtr was folded into the user (parent), it will be
2419 // caught above. For other cases, we have to compute the address.
2420 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
2423 case 57: // reg: Alloca: Implement as 1 instruction:
2424 { // add %fp, offsetFromFP -> result
2425 AllocationInst* instr =
2426 cast<AllocationInst>(subtreeRoot->getInstruction());
2428 target.getTargetData().getTypeSize(instr->getAllocatedType());
2430 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2434 case 58: // reg: Alloca(reg): Implement as 3 instructions:
2435 // mul num, typeSz -> tmp
2436 // sub %sp, tmp -> %sp
2437 { // add %sp, frameSizeBelowDynamicArea -> result
2438 AllocationInst* instr =
2439 cast<AllocationInst>(subtreeRoot->getInstruction());
2440 const Type* eltType = instr->getAllocatedType();
2442 // If #elements is constant, use simpler code for fixed-size allocas
2443 int tsize = (int) target.getTargetData().getTypeSize(eltType);
2444 Value* numElementsVal = NULL;
2445 bool isArray = instr->isArrayAllocation();
2447 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
2448 // total size is constant: generate code for fixed-size alloca
2449 unsigned numElements = isArray?
2450 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2451 CreateCodeForFixedSizeAlloca(target, instr, tsize,
2454 // total size is not constant.
2455 CreateCodeForVariableSizeAlloca(target, instr, tsize,
2456 numElementsVal, mvec);
2461 case 61: // reg: Call
2462 { // Generate a direct (CALL) or indirect (JMPL) call.
2463 // Mark the return-address register, the indirection
2464 // register (for indirect calls), the operands of the Call,
2465 // and the return value (if any) as implicit operands
2466 // of the machine instruction.
2468 // If this is a varargs function, floating point arguments
2469 // have to passed in integer registers so insert
2470 // copy-float-to-int instructions for each float operand.
2472 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2473 Value *callee = callInstr->getCalledValue();
2474 Function* calledFunc = dyn_cast<Function>(callee);
2476 // Check if this is an intrinsic function that needs a special code
2477 // sequence (e.g., va_start). Indirect calls cannot be special.
2479 bool specialIntrinsic = false;
2481 if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
2482 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
2484 // If not, generate the normal call sequence for the function.
2485 // This can also handle any intrinsics that are just function calls.
2487 if (! specialIntrinsic) {
2488 Function* currentFunc = callInstr->getParent()->getParent();
2489 MachineFunction& MF = MachineFunction::get(currentFunc);
2490 MachineCodeForInstruction& mcfi =
2491 MachineCodeForInstruction::get(callInstr);
2492 const SparcRegInfo& regInfo =
2493 (SparcRegInfo&) target.getRegInfo();
2494 const TargetFrameInfo& frameInfo = target.getFrameInfo();
2496 // Create hidden virtual register for return address with type void*
2497 TmpInstruction* retAddrReg =
2498 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
2500 // Generate the machine instruction and its operands.
2501 // Use CALL for direct function calls; this optimistically assumes
2502 // the PC-relative address fits in the CALL address field (22 bits).
2503 // Use JMPL for indirect calls.
2504 // This will be added to mvec later, after operand copies.
2506 MachineInstr* callMI;
2507 if (calledFunc) // direct function call
2508 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
2509 else // indirect function call
2510 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
2511 .addSImm((int64_t)0).addRegDef(retAddrReg));
2513 const FunctionType* funcType =
2514 cast<FunctionType>(cast<PointerType>(callee->getType())
2515 ->getElementType());
2516 bool isVarArgs = funcType->isVarArg();
2517 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2519 // Use a descriptor to pass information about call arguments
2520 // to the register allocator. This descriptor will be "owned"
2521 // and freed automatically when the MachineCodeForInstruction
2522 // object for the callInstr goes away.
2523 CallArgsDescriptor* argDesc =
2524 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
2525 assert(callInstr->getOperand(0) == callee
2526 && "This is assumed in the loop below!");
2528 // Insert sign-extension instructions for small signed values,
2529 // if this is an unknown function (i.e., called via a funcptr)
2530 // or an external one (i.e., which may not be compiled by llc).
2532 if (calledFunc == NULL || calledFunc->isExternal()) {
2533 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2534 Value* argVal = callInstr->getOperand(i);
2535 const Type* argType = argVal->getType();
2536 if (argType->isIntegral() && argType->isSigned()) {
2537 unsigned argSize = target.getTargetData().getTypeSize(argType);
2539 // create a temporary virtual reg. to hold the sign-extension
2540 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
2542 // sign-extend argVal and put the result in the temporary reg.
2543 target.getInstrInfo().CreateSignExtensionInstructions
2544 (target, currentFunc, argVal, argExtend,
2545 8*argSize, mvec, mcfi);
2547 // replace argVal with argExtend in CallArgsDescriptor
2548 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
2554 // Insert copy instructions to get all the arguments into
2555 // all the places that they need to be.
2557 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2559 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
2560 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
2561 const Type* argType = argVal->getType();
2562 unsigned regType = regInfo.getRegTypeForDataType(argType);
2563 unsigned argSize = target.getTargetData().getTypeSize(argType);
2564 int regNumForArg = TargetRegInfo::getInvalidRegNum();
2565 unsigned regClassIDOfArgReg;
2567 // Check for FP arguments to varargs functions.
2568 // Any such argument in the first $K$ args must be passed in an
2569 // integer register. If there is no prototype, it must also
2570 // be passed as an FP register.
2571 // K = #integer argument registers.
2572 bool isFPArg = argVal->getType()->isFloatingPoint();
2573 if (isVarArgs && isFPArg) {
2576 // It is a function with no prototype: pass value
2577 // as an FP value as well as a varargs value. The FP value
2578 // may go in a register or on the stack. The copy instruction
2579 // to the outgoing reg/stack is created by the normal argument
2580 // handling code since this is the "normal" passing mode.
2582 regNumForArg = regInfo.regNumForFPArg(regType,
2583 false, false, argNo,
2584 regClassIDOfArgReg);
2585 if (regNumForArg == regInfo.getInvalidRegNum())
2586 argInfo.setUseStackSlot();
2588 argInfo.setUseFPArgReg();
2591 // If this arg. is in the first $K$ regs, add special copy-
2592 // float-to-int instructions to pass the value as an int.
2593 // To check if it is in the first $K$, get the register
2594 // number for the arg #i. These copy instructions are
2595 // generated here because they are extra cases and not needed
2596 // for the normal argument handling (some code reuse is
2597 // possible though -- later).
2599 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
2600 regClassIDOfArgReg);
2601 if (copyRegNum != regInfo.getInvalidRegNum()) {
2602 // Create a virtual register to represent copyReg. Mark
2603 // this vreg as being an implicit operand of the call MI
2604 const Type* loadTy = (argType == Type::FloatTy
2605 ? Type::IntTy : Type::LongTy);
2606 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
2609 callMI->addImplicitRef(argVReg);
2611 // Get a temp stack location to use to copy
2612 // float-to-int via the stack.
2614 // FIXME: For now, we allocate permanent space because
2615 // the stack frame manager does not allow locals to be
2616 // allocated (e.g., for alloca) after a temp is
2619 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
2620 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
2622 // Generate the store from FP reg to stack
2623 unsigned StoreOpcode = ChooseStoreInstruction(argType);
2624 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
2625 .addReg(argVal).addMReg(regInfo.getFramePointer())
2626 .addSImm(tmpOffset);
2629 // Generate the load from stack to int arg reg
2630 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
2631 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
2632 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
2633 .addReg(argVReg, MOTy::Def);
2635 // Mark operand with register it should be assigned
2636 // both for copy and for the callMI
2637 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
2638 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2642 // Add info about the argument to the CallArgsDescriptor
2643 argInfo.setUseIntArgReg();
2644 argInfo.setArgCopy(copyRegNum);
2646 // Cannot fit in first $K$ regs so pass arg on stack
2647 argInfo.setUseStackSlot();
2649 } else if (isFPArg) {
2650 // Get the outgoing arg reg to see if there is one.
2651 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
2652 argNo, regClassIDOfArgReg);
2653 if (regNumForArg == regInfo.getInvalidRegNum())
2654 argInfo.setUseStackSlot();
2656 argInfo.setUseFPArgReg();
2657 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2661 // Get the outgoing arg reg to see if there is one.
2662 regNumForArg = regInfo.regNumForIntArg(false,false,
2663 argNo, regClassIDOfArgReg);
2664 if (regNumForArg == regInfo.getInvalidRegNum())
2665 argInfo.setUseStackSlot();
2667 argInfo.setUseIntArgReg();
2668 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2674 // Now insert copy instructions to stack slot or arg. register
2676 if (argInfo.usesStackSlot()) {
2677 // Get the stack offset for this argument slot.
2678 // FP args on stack are right justified so adjust offset!
2679 // int arguments are also right justified but they are
2680 // always loaded as a full double-word so the offset does
2681 // not need to be adjusted.
2682 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
2683 if (argType->isFloatingPoint()) {
2684 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
2685 assert(argSize <= slotSize && "Insufficient slot size!");
2686 argOffset += slotSize - argSize;
2689 // Now generate instruction to copy argument to stack
2690 MachineOpCode storeOpCode =
2691 (argType->isFloatingPoint()
2692 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
2694 M = BuildMI(storeOpCode, 3).addReg(argVal)
2695 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
2698 else if (regNumForArg != regInfo.getInvalidRegNum()) {
2700 // Create a virtual register to represent the arg reg. Mark
2701 // this vreg as being an implicit operand of the call MI.
2702 TmpInstruction* argVReg =
2703 new TmpInstruction(mcfi, argVal, NULL, "argReg");
2705 callMI->addImplicitRef(argVReg);
2707 // Generate the reg-to-reg copy into the outgoing arg reg.
2708 // -- For FP values, create a FMOVS or FMOVD instruction
2709 // -- For non-FP values, create an add-with-0 instruction
2710 if (argType->isFloatingPoint())
2711 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
2712 .addReg(argVal).addReg(argVReg, MOTy::Def));
2714 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
2715 .addReg(argVal).addSImm((int64_t) 0)
2716 .addReg(argVReg, MOTy::Def));
2718 // Mark the operand with the register it should be assigned
2719 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
2720 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2726 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
2727 "Arg. not in stack slot, primary or secondary register?");
2730 // add call instruction and delay slot before copying return value
2731 mvec.push_back(callMI);
2732 mvec.push_back(BuildMI(V9::NOP, 0));
2734 // Add the return value as an implicit ref. The call operands
2735 // were added above. Also, add code to copy out the return value.
2736 // This is always register-to-register for int or FP return values.
2738 if (callInstr->getType() != Type::VoidTy) {
2739 // Get the return value reg.
2740 const Type* retType = callInstr->getType();
2742 int regNum = (retType->isFloatingPoint()
2743 ? (unsigned) SparcFloatRegClass::f0
2744 : (unsigned) SparcIntRegClass::o0);
2745 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2746 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
2748 // Create a virtual register to represent it and mark
2749 // this vreg as being an implicit operand of the call MI
2750 TmpInstruction* retVReg =
2751 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
2753 callMI->addImplicitRef(retVReg, /*isDef*/ true);
2755 // Generate the reg-to-reg copy from the return value reg.
2756 // -- For FP values, create a FMOVS or FMOVD instruction
2757 // -- For non-FP values, create an add-with-0 instruction
2758 if (retType->isFloatingPoint())
2759 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2760 .addReg(retVReg).addReg(callInstr, MOTy::Def));
2762 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2763 .addReg(retVReg).addSImm((int64_t) 0)
2764 .addReg(callInstr, MOTy::Def));
2766 // Mark the operand with the register it should be assigned
2767 // Also mark the implicit ref of the call defining this operand
2768 M->SetRegForOperand(0, regNum);
2769 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
2774 // For the CALL instruction, the ret. addr. reg. is also implicit
2775 if (isa<Function>(callee))
2776 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
2778 MF.getInfo()->popAllTempValues(); // free temps used for this inst
2784 case 62: // reg: Shl(reg, reg)
2786 Value* argVal1 = subtreeRoot->leftChild()->getValue();
2787 Value* argVal2 = subtreeRoot->rightChild()->getValue();
2788 Instruction* shlInstr = subtreeRoot->getInstruction();
2790 const Type* opType = argVal1->getType();
2791 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2792 "Shl unsupported for other types");
2793 unsigned opSize = target.getTargetData().getTypeSize(opType);
2795 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2796 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
2797 argVal1, argVal2, 0, shlInstr, mvec,
2798 MachineCodeForInstruction::get(shlInstr));
2802 case 63: // reg: Shr(reg, reg)
2804 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2805 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2806 "Shr unsupported for other types");
2807 unsigned opSize = target.getTargetData().getTypeSize(opType);
2808 Add3OperandInstr(opType->isSigned()
2809 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
2810 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
2815 case 64: // reg: Phi(reg,reg)
2816 break; // don't forward the value
2818 case 65: // reg: VANext(reg): the va_next(va_list, type) instruction
2819 { // Increment the va_list pointer register according to the type.
2820 // All LLVM argument types are <= 64 bits, so use one doubleword.
2821 Instruction* vaNextI = subtreeRoot->getInstruction();
2822 assert(target.getTargetData().getTypeSize(vaNextI->getType()) <= 8 &&
2823 "We assumed that all LLVM parameter types <= 8 bytes!");
2824 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
2825 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaNextI->getOperand(0)).
2826 addSImm(argSize).addRegDef(vaNextI));
2830 case 66: // reg: VAArg (reg): the va_arg instruction
2831 { // Load argument from stack using current va_list pointer value.
2832 // Use 64-bit load for all non-FP args, and LDDF or double for FP.
2833 Instruction* vaArgI = subtreeRoot->getInstruction();
2834 MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
2835 ? (vaArgI->getType() == Type::FloatTy
2836 ? V9::LDFi : V9::LDDFi)
2838 mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
2839 addSImm(0).addRegDef(vaArgI));
2843 case 71: // reg: VReg
2844 case 72: // reg: Constant
2845 break; // don't forward the value
2848 assert(0 && "Unrecognized BURG rule");
2853 if (forwardOperandNum >= 0) {
2854 // We did not generate a machine instruction but need to use operand.
2855 // If user is in the same tree, replace Value in its machine operand.
2856 // If not, insert a copy instruction which should get coalesced away
2857 // by register allocation.
2858 if (subtreeRoot->parent() != NULL)
2859 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2861 std::vector<MachineInstr*> minstrVec;
2862 Instruction* instr = subtreeRoot->getInstruction();
2863 target.getInstrInfo().
2864 CreateCopyInstructionsByType(target,
2865 instr->getParent()->getParent(),
2866 instr->getOperand(forwardOperandNum),
2868 MachineCodeForInstruction::get(instr));
2869 assert(minstrVec.size() > 0);
2870 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2874 if (maskUnsignedResult) {
2875 // If result is unsigned and smaller than int reg size,
2876 // we need to clear high bits of result value.
2877 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2878 Instruction* dest = subtreeRoot->getInstruction();
2879 if (dest->getType()->isUnsigned()) {
2880 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
2881 if (destSize <= 4) {
2882 // Mask high 64 - N bits, where N = 4*destSize.
2884 // Use a TmpInstruction to represent the
2885 // intermediate result before masking. Since those instructions
2886 // have already been generated, go back and substitute tmpI
2887 // for dest in the result position of each one of them.
2889 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
2890 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
2891 dest, NULL, "maskHi");
2892 Value* srlArgToUse = tmpI;
2894 unsigned numSubst = 0;
2895 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
2897 // Make sure we substitute all occurrences of dest in these instrs.
2898 // Otherwise, we will have bogus code.
2899 bool someArgsWereIgnored = false;
2901 // Make sure not to substitute an upwards-exposed use -- that would
2902 // introduce a use of `tmpI' with no preceding def. Therefore,
2903 // substitute a use or def-and-use operand only if a previous def
2904 // operand has already been substituted (i.e., numSusbt > 0).
2906 numSubst += mvec[i]->substituteValue(dest, tmpI,
2907 /*defsOnly*/ numSubst == 0,
2908 /*notDefsAndUses*/ numSubst > 0,
2909 someArgsWereIgnored);
2910 assert(!someArgsWereIgnored &&
2911 "Operand `dest' exists but not replaced: probably bogus!");
2913 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
2915 // Left shift 32-N if size (N) is less than 32 bits.
2916 // Use another tmp. virtual register to represent this result.
2918 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
2919 tmpI, NULL, "maskHi2");
2920 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
2921 .addZImm(8*(4-destSize))
2922 .addReg(srlArgToUse, MOTy::Def));
2925 // Logical right shift 32-N to get zero extension in top 64-N bits.
2926 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
2927 .addZImm(8*(4-destSize)).addReg(dest, MOTy::Def));
2929 } else if (destSize < 8) {
2930 assert(0 && "Unsupported type size: 32 < size < 64 bits");