1 //===-- SparcInstrSelection.cpp -------------------------------------------===//
3 // BURS instruction selection for SPARC V9 architecture.
5 //===----------------------------------------------------------------------===//
7 #include "SparcInternals.h"
8 #include "SparcInstrSelectionSupport.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/CodeGen/InstrSelectionSupport.h"
11 #include "llvm/CodeGen/MachineInstrBuilder.h"
12 #include "llvm/CodeGen/MachineInstrAnnot.h"
13 #include "llvm/CodeGen/InstrForest.h"
14 #include "llvm/CodeGen/InstrSelection.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Constants.h"
22 #include "llvm/ConstantHandling.h"
23 #include "llvm/Intrinsics.h"
24 #include "Support/MathExtras.h"
28 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
29 std::vector<MachineInstr*>& mvec) {
30 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
31 .addReg(Node->rightChild()->getValue())
32 .addRegDef(Node->getValue()));
37 //---------------------------------------------------------------------------
38 // Function: GetMemInstArgs
41 // Get the pointer value and the index vector for a memory operation
42 // (GetElementPtr, Load, or Store). If all indices of the given memory
43 // operation are constant, fold in constant indices in a chain of
44 // preceding GetElementPtr instructions (if any), and return the
45 // pointer value of the first instruction in the chain.
46 // All folded instructions are marked so no code is generated for them.
49 // Returns the pointer Value to use.
50 // Returns the resulting IndexVector in idxVec.
51 // Returns true/false in allConstantIndices if all indices are/aren't const.
52 //---------------------------------------------------------------------------
55 //---------------------------------------------------------------------------
56 // Function: FoldGetElemChain
59 // Fold a chain of GetElementPtr instructions containing only
60 // constant offsets into an equivalent (Pointer, IndexVector) pair.
61 // Returns the pointer Value, and stores the resulting IndexVector
62 // in argument chainIdxVec. This is a helper function for
63 // FoldConstantIndices that does the actual folding.
64 //---------------------------------------------------------------------------
67 // Check for a constant 0.
71 return (idx == ConstantSInt::getNullValue(idx->getType()));
75 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
76 bool lastInstHasLeadingNonZero)
78 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
79 GetElementPtrInst* gepInst =
80 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
82 // ptr value is not computed in this tree or ptr value does not come from GEP
87 // Return NULL if we don't fold any instructions in.
90 // Now chase the chain of getElementInstr instructions, if any.
91 // Check for any non-constant indices and stop there.
92 // Also, stop if the first index of child is a non-zero array index
93 // and the last index of the current node is a non-array index:
94 // in that case, a non-array declared type is being accessed as an array
95 // which is not type-safe, but could be legal.
97 InstructionNode* ptrChild = gepNode;
98 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
99 ptrChild->getOpLabel() == GetElemPtrIdx))
101 // Child is a GetElemPtr instruction
102 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
103 User::op_iterator OI, firstIdx = gepInst->idx_begin();
104 User::op_iterator lastIdx = gepInst->idx_end();
105 bool allConstantOffsets = true;
107 // The first index of every GEP must be an array index.
108 assert((*firstIdx)->getType() == Type::LongTy &&
109 "INTERNAL ERROR: Structure index for a pointer type!");
111 // If the last instruction had a leading non-zero index, check if the
112 // current one references a sequential (i.e., indexable) type.
113 // If not, the code is not type-safe and we would create an illegal GEP
114 // by folding them, so don't fold any more instructions.
116 if (lastInstHasLeadingNonZero)
117 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
118 break; // cannot fold in any preceding getElementPtr instrs.
120 // Check that all offsets are constant for this instruction
121 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
122 allConstantOffsets = isa<ConstantInt>(*OI);
124 if (allConstantOffsets) {
125 // Get pointer value out of ptrChild.
126 ptrVal = gepInst->getPointerOperand();
128 // Insert its index vector at the start, skipping any leading [0]
129 // Remember the old size to check if anything was inserted.
130 unsigned oldSize = chainIdxVec.size();
131 int firstIsZero = IsZero(*firstIdx);
132 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
134 // Remember if it has leading zero index: it will be discarded later.
135 if (oldSize < chainIdxVec.size())
136 lastInstHasLeadingNonZero = !firstIsZero;
138 // Mark the folded node so no code is generated for it.
139 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
141 // Get the previous GEP instruction and continue trying to fold
142 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
143 } else // cannot fold this getElementPtr instr. or any preceding ones
147 // If the first getElementPtr instruction had a leading [0], add it back.
148 // Note that this instruction is the *last* one that was successfully
149 // folded *and* contributed any indices, in the loop above.
151 if (ptrVal && ! lastInstHasLeadingNonZero)
152 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
158 //---------------------------------------------------------------------------
159 // Function: GetGEPInstArgs
162 // Helper function for GetMemInstArgs that handles the final getElementPtr
163 // instruction used by (or same as) the memory operation.
164 // Extracts the indices of the current instruction and tries to fold in
165 // preceding ones if all indices of the current one are constant.
166 //---------------------------------------------------------------------------
169 GetGEPInstArgs(InstructionNode* gepNode,
170 std::vector<Value*>& idxVec,
171 bool& allConstantIndices)
173 allConstantIndices = true;
174 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
176 // Default pointer is the one from the current instruction.
177 Value* ptrVal = gepI->getPointerOperand();
178 InstrTreeNode* ptrChild = gepNode->leftChild();
180 // Extract the index vector of the GEP instruction.
181 // If all indices are constant and first index is zero, try to fold
182 // in preceding GEPs with all constant indices.
183 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
184 allConstantIndices && OI != OE; ++OI)
185 if (! isa<Constant>(*OI))
186 allConstantIndices = false; // note: this also terminates loop!
188 // If we have only constant indices, fold chains of constant indices
189 // in this and any preceding GetElemPtr instructions.
190 bool foldedGEPs = false;
191 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
192 if (allConstantIndices)
193 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
198 // Append the index vector of the current instruction.
199 // Skip the leading [0] index if preceding GEPs were folded into this.
200 idxVec.insert(idxVec.end(),
201 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
207 //---------------------------------------------------------------------------
208 // Function: GetMemInstArgs
211 // Get the pointer value and the index vector for a memory operation
212 // (GetElementPtr, Load, or Store). If all indices of the given memory
213 // operation are constant, fold in constant indices in a chain of
214 // preceding GetElementPtr instructions (if any), and return the
215 // pointer value of the first instruction in the chain.
216 // All folded instructions are marked so no code is generated for them.
219 // Returns the pointer Value to use.
220 // Returns the resulting IndexVector in idxVec.
221 // Returns true/false in allConstantIndices if all indices are/aren't const.
222 //---------------------------------------------------------------------------
225 GetMemInstArgs(InstructionNode* memInstrNode,
226 std::vector<Value*>& idxVec,
227 bool& allConstantIndices)
229 allConstantIndices = false;
230 Instruction* memInst = memInstrNode->getInstruction();
231 assert(idxVec.size() == 0 && "Need empty vector to return indices");
233 // If there is a GetElemPtr instruction to fold in to this instr,
234 // it must be in the left child for Load and GetElemPtr, and in the
235 // right child for Store instructions.
236 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
237 ? memInstrNode->rightChild()
238 : memInstrNode->leftChild());
240 // Default pointer is the one from the current instruction.
241 Value* ptrVal = ptrChild->getValue();
243 // Find the "last" GetElemPtr instruction: this one or the immediate child.
244 // There will be none if this is a load or a store from a scalar pointer.
245 InstructionNode* gepNode = NULL;
246 if (isa<GetElementPtrInst>(memInst))
247 gepNode = memInstrNode;
248 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
249 // Child of load/store is a GEP and memInst is its only use.
250 // Use its indices and mark it as folded.
251 gepNode = cast<InstructionNode>(ptrChild);
252 gepNode->markFoldedIntoParent();
255 // If there are no indices, return the current pointer.
256 // Else extract the pointer from the GEP and fold the indices.
257 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
262 //************************ Internal Functions ******************************/
265 static inline MachineOpCode
266 ChooseBprInstruction(const InstructionNode* instrNode)
268 MachineOpCode opCode;
270 Instruction* setCCInstr =
271 ((InstructionNode*) instrNode->leftChild())->getInstruction();
273 switch(setCCInstr->getOpcode())
275 case Instruction::SetEQ: opCode = V9::BRZ; break;
276 case Instruction::SetNE: opCode = V9::BRNZ; break;
277 case Instruction::SetLE: opCode = V9::BRLEZ; break;
278 case Instruction::SetGE: opCode = V9::BRGEZ; break;
279 case Instruction::SetLT: opCode = V9::BRLZ; break;
280 case Instruction::SetGT: opCode = V9::BRGZ; break;
282 assert(0 && "Unrecognized VM instruction!");
283 opCode = V9::INVALID_OPCODE;
291 static inline MachineOpCode
292 ChooseBpccInstruction(const InstructionNode* instrNode,
293 const BinaryOperator* setCCInstr)
295 MachineOpCode opCode = V9::INVALID_OPCODE;
297 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
300 switch(setCCInstr->getOpcode())
302 case Instruction::SetEQ: opCode = V9::BE; break;
303 case Instruction::SetNE: opCode = V9::BNE; break;
304 case Instruction::SetLE: opCode = V9::BLE; break;
305 case Instruction::SetGE: opCode = V9::BGE; break;
306 case Instruction::SetLT: opCode = V9::BL; break;
307 case Instruction::SetGT: opCode = V9::BG; break;
309 assert(0 && "Unrecognized VM instruction!");
313 switch(setCCInstr->getOpcode())
315 case Instruction::SetEQ: opCode = V9::BE; break;
316 case Instruction::SetNE: opCode = V9::BNE; break;
317 case Instruction::SetLE: opCode = V9::BLEU; break;
318 case Instruction::SetGE: opCode = V9::BCC; break;
319 case Instruction::SetLT: opCode = V9::BCS; break;
320 case Instruction::SetGT: opCode = V9::BGU; break;
322 assert(0 && "Unrecognized VM instruction!");
330 static inline MachineOpCode
331 ChooseBFpccInstruction(const InstructionNode* instrNode,
332 const BinaryOperator* setCCInstr)
334 MachineOpCode opCode = V9::INVALID_OPCODE;
336 switch(setCCInstr->getOpcode())
338 case Instruction::SetEQ: opCode = V9::FBE; break;
339 case Instruction::SetNE: opCode = V9::FBNE; break;
340 case Instruction::SetLE: opCode = V9::FBLE; break;
341 case Instruction::SetGE: opCode = V9::FBGE; break;
342 case Instruction::SetLT: opCode = V9::FBL; break;
343 case Instruction::SetGT: opCode = V9::FBG; break;
345 assert(0 && "Unrecognized VM instruction!");
353 // Create a unique TmpInstruction for a boolean value,
354 // representing the CC register used by a branch on that value.
355 // For now, hack this using a little static cache of TmpInstructions.
356 // Eventually the entire BURG instruction selection should be put
357 // into a separate class that can hold such information.
358 // The static cache is not too bad because the memory for these
359 // TmpInstructions will be freed along with the rest of the Function anyway.
361 static TmpInstruction*
362 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType,
363 MachineCodeForInstruction& mcfi)
365 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
366 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
367 static const Function *lastFunction = 0;// Use to flush cache between funcs
369 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
371 if (lastFunction != F) {
373 boolToTmpCache.clear();
376 // Look for tmpI and create a new one otherwise. The new value is
377 // directly written to map using the ref returned by operator[].
378 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
380 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
386 static inline MachineOpCode
387 ChooseBccInstruction(const InstructionNode* instrNode,
388 const Type*& setCCType)
390 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
391 assert(setCCNode->getOpLabel() == SetCCOp);
392 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
393 setCCType = setCCInstr->getOperand(0)->getType();
395 if (setCCType->isFloatingPoint())
396 return ChooseBFpccInstruction(instrNode, setCCInstr);
398 return ChooseBpccInstruction(instrNode, setCCInstr);
402 // WARNING: since this function has only one caller, it always returns
403 // the opcode that expects an immediate and a register. If this function
404 // is ever used in cases where an opcode that takes two registers is required,
405 // then modify this function and use convertOpcodeFromRegToImm() where required.
407 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
408 // new cases of opcodes.
409 static inline MachineOpCode
410 ChooseMovFpcciInstruction(const InstructionNode* instrNode)
412 MachineOpCode opCode = V9::INVALID_OPCODE;
414 switch(instrNode->getInstruction()->getOpcode())
416 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
417 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
418 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
419 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
420 case Instruction::SetLT: opCode = V9::MOVFLi; break;
421 case Instruction::SetGT: opCode = V9::MOVFGi; break;
423 assert(0 && "Unrecognized VM instruction!");
431 // ChooseMovpcciForSetCC -- Choose a conditional-move instruction
432 // based on the type of SetCC operation.
434 // WARNING: since this function has only one caller, it always returns
435 // the opcode that expects an immediate and a register. If this function
436 // is ever used in cases where an opcode that takes two registers is required,
437 // then modify this function and use convertOpcodeFromRegToImm() where required.
439 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
440 // new cases of opcodes.
443 ChooseMovpcciForSetCC(const InstructionNode* instrNode)
445 MachineOpCode opCode = V9::INVALID_OPCODE;
447 const Type* opType = instrNode->leftChild()->getValue()->getType();
448 assert(opType->isIntegral() || isa<PointerType>(opType));
449 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
451 switch(instrNode->getInstruction()->getOpcode())
453 case Instruction::SetEQ: opCode = V9::MOVEi; break;
454 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
455 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
456 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
457 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
458 case Instruction::SetNE: opCode = V9::MOVNEi; break;
459 default: assert(0 && "Unrecognized LLVM instr!"); break;
466 // ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
467 // instruction based on the type of SetCC operation. These instructions
468 // compare a register with 0 and perform the move is the comparison is true.
470 // WARNING: like the previous function, this function it always returns
471 // the opcode that expects an immediate and a register. See above.
474 ChooseMovpregiForSetCC(const InstructionNode* instrNode)
476 MachineOpCode opCode = V9::INVALID_OPCODE;
478 switch(instrNode->getInstruction()->getOpcode())
480 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
481 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
482 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
483 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
484 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
485 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
486 default: assert(0 && "Unrecognized VM instr!"); break;
493 static inline MachineOpCode
494 ChooseConvertToFloatInstr(const TargetMachine& target,
495 OpLabel vopCode, const Type* opType)
497 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
498 "Unrecognized convert-to-float opcode!");
499 assert((opType->isIntegral() || opType->isFloatingPoint() ||
500 isa<PointerType>(opType))
501 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
503 MachineOpCode opCode = V9::INVALID_OPCODE;
505 unsigned opSize = target.getTargetData().getTypeSize(opType);
507 if (opType == Type::FloatTy)
508 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
509 else if (opType == Type::DoubleTy)
510 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
511 else if (opSize <= 4)
512 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
514 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
515 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
521 static inline MachineOpCode
522 ChooseConvertFPToIntInstr(const TargetMachine& target,
523 const Type* destType, const Type* opType)
525 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
526 && "This function should only be called for FLOAT or DOUBLE");
527 assert((destType->isIntegral() || isa<PointerType>(destType))
528 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
530 MachineOpCode opCode = V9::INVALID_OPCODE;
532 unsigned destSize = target.getTargetData().getTypeSize(destType);
534 if (destType == Type::UIntTy)
535 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
536 else if (destSize <= 4)
537 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
539 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
540 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
547 CreateConvertFPToIntInstr(const TargetMachine& target,
550 const Type* destType)
552 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
554 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
555 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
558 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
559 // The FP value must be converted to the dest type in an FP register,
560 // and the result is then copied from FP to int register via memory.
561 // SPARC does not have a float-to-uint conversion, only a float-to-int (fdtoi).
562 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
563 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
564 // Therefore, for converting an FP value to uint32_t, we first need to convert
565 // to uint64_t and then to uint32_t.
568 CreateCodeToConvertFloatToInt(const TargetMachine& target,
571 std::vector<MachineInstr*>& mvec,
572 MachineCodeForInstruction& mcfi)
574 Function* F = destI->getParent()->getParent();
576 // Create a temporary to represent the FP register into which the
577 // int value will placed after conversion. The type of this temporary
578 // depends on the type of FP register to use: single-prec for a 32-bit
579 // int or smaller; double-prec for a 64-bit int.
581 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
583 const Type* castDestType = destI->getType(); // type for the cast instr result
584 const Type* castDestRegType; // type for cast instruction result reg
585 TmpInstruction* destForCast; // dest for cast instruction
586 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
588 // For converting an FP value to uint32_t, we first need to convert to
589 // uint64_t and then to uint32_t, as explained above.
590 if (destI->getType() == Type::UIntTy) {
591 castDestType = Type::ULongTy; // use this instead of type of destI
592 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
593 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
594 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
597 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
598 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
601 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
602 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
605 // Create the fpreg-to-intreg copy code
606 target.getInstrInfo().CreateCodeToCopyFloatToInt(target, F, destForCast,
607 fpToIntCopyDest, mvec, mcfi);
609 // Create the uint64_t to uint32_t conversion, if needed
610 if (destI->getType() == Type::UIntTy)
611 target.getInstrInfo().
612 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
613 /*numLowBits*/ 32, mvec, mcfi);
617 static inline MachineOpCode
618 ChooseAddInstruction(const InstructionNode* instrNode)
620 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
624 static inline MachineInstr*
625 CreateMovFloatInstruction(const InstructionNode* instrNode,
626 const Type* resultType)
628 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
629 .addReg(instrNode->leftChild()->getValue())
630 .addRegDef(instrNode->getValue());
633 static inline MachineInstr*
634 CreateAddConstInstruction(const InstructionNode* instrNode)
636 MachineInstr* minstr = NULL;
638 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
639 assert(isa<Constant>(constOp));
641 // Cases worth optimizing are:
642 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
643 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
645 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
646 double dval = FPC->getValue();
648 minstr = CreateMovFloatInstruction(instrNode,
649 instrNode->getInstruction()->getType());
656 static inline MachineOpCode
657 ChooseSubInstructionByType(const Type* resultType)
659 MachineOpCode opCode = V9::INVALID_OPCODE;
661 if (resultType->isInteger() || isa<PointerType>(resultType)) {
664 switch(resultType->getPrimitiveID())
666 case Type::FloatTyID: opCode = V9::FSUBS; break;
667 case Type::DoubleTyID: opCode = V9::FSUBD; break;
668 default: assert(0 && "Invalid type for SUB instruction"); break;
676 static inline MachineInstr*
677 CreateSubConstInstruction(const InstructionNode* instrNode)
679 MachineInstr* minstr = NULL;
681 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
682 assert(isa<Constant>(constOp));
684 // Cases worth optimizing are:
685 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
686 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
688 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
689 double dval = FPC->getValue();
691 minstr = CreateMovFloatInstruction(instrNode,
692 instrNode->getInstruction()->getType());
699 static inline MachineOpCode
700 ChooseFcmpInstruction(const InstructionNode* instrNode)
702 MachineOpCode opCode = V9::INVALID_OPCODE;
704 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
705 switch(operand->getType()->getPrimitiveID()) {
706 case Type::FloatTyID: opCode = V9::FCMPS; break;
707 case Type::DoubleTyID: opCode = V9::FCMPD; break;
708 default: assert(0 && "Invalid type for FCMP instruction"); break;
715 // Assumes that leftArg and rightArg are both cast instructions.
718 BothFloatToDouble(const InstructionNode* instrNode)
720 InstrTreeNode* leftArg = instrNode->leftChild();
721 InstrTreeNode* rightArg = instrNode->rightChild();
722 InstrTreeNode* leftArgArg = leftArg->leftChild();
723 InstrTreeNode* rightArgArg = rightArg->leftChild();
724 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
726 // Check if both arguments are floats cast to double
727 return (leftArg->getValue()->getType() == Type::DoubleTy &&
728 leftArgArg->getValue()->getType() == Type::FloatTy &&
729 rightArgArg->getValue()->getType() == Type::FloatTy);
733 static inline MachineOpCode
734 ChooseMulInstructionByType(const Type* resultType)
736 MachineOpCode opCode = V9::INVALID_OPCODE;
738 if (resultType->isInteger())
741 switch(resultType->getPrimitiveID())
743 case Type::FloatTyID: opCode = V9::FMULS; break;
744 case Type::DoubleTyID: opCode = V9::FMULD; break;
745 default: assert(0 && "Invalid type for MUL instruction"); break;
753 static inline MachineInstr*
754 CreateIntNegInstruction(const TargetMachine& target,
757 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo().getZeroRegNum())
758 .addReg(vreg).addRegDef(vreg);
762 // Create instruction sequence for any shift operation.
763 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
764 // requires a second instruction for explicit sign-extension.
765 // Note that we only have to worry about a sign-bit appearing in the
766 // most significant bit of the operand after shifting (e.g., bit 32 of
767 // Int or bit 16 of Short), so we do not have to worry about results
768 // that are as large as a normal integer register.
771 CreateShiftInstructions(const TargetMachine& target,
773 MachineOpCode shiftOpCode,
775 Value* optArgVal2, /* Use optArgVal2 if not NULL */
776 unsigned optShiftNum, /* else use optShiftNum */
777 Instruction* destVal,
778 std::vector<MachineInstr*>& mvec,
779 MachineCodeForInstruction& mcfi)
781 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
782 "Large shift sizes unexpected, but can be handled below: "
783 "You need to check whether or not it fits in immed field below");
785 // If this is a logical left shift of a type smaller than the standard
786 // integer reg. size, we have to extend the sign-bit into upper bits
787 // of dest, so we need to put the result of the SLL into a temporary.
789 Value* shiftDest = destVal;
790 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
792 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
793 // put SLL result into a temporary
794 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
797 MachineInstr* M = (optArgVal2 != NULL)
798 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
799 .addReg(shiftDest, MOTy::Def)
800 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
801 .addReg(shiftDest, MOTy::Def);
804 if (shiftDest != destVal) {
805 // extend the sign-bit of the result into all upper bits of dest
806 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
807 target.getInstrInfo().
808 CreateSignExtensionInstructions(target, F, shiftDest, destVal,
809 8*opSize, mvec, mcfi);
814 // Does not create any instructions if we cannot exploit constant to
815 // create a cheaper instruction.
816 // This returns the approximate cost of the instructions generated,
817 // which is used to pick the cheapest when both operands are constant.
819 CreateMulConstInstruction(const TargetMachine &target, Function* F,
820 Value* lval, Value* rval, Instruction* destVal,
821 std::vector<MachineInstr*>& mvec,
822 MachineCodeForInstruction& mcfi)
824 /* Use max. multiply cost, viz., cost of MULX */
825 unsigned cost = target.getInstrInfo().minLatency(V9::MULXr);
826 unsigned firstNewInstr = mvec.size();
828 Value* constOp = rval;
829 if (! isa<Constant>(constOp))
832 // Cases worth optimizing are:
833 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
834 // (2) Multiply by 2^x for integer types: replace with Shift
836 const Type* resultType = destVal->getType();
838 if (resultType->isInteger() || isa<PointerType>(resultType)) {
840 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
841 constOp, constOp->getType(), isValidConst);
844 bool needNeg = false;
850 if (C == 0 || C == 1) {
851 cost = target.getInstrInfo().minLatency(V9::ADDr);
852 unsigned Zero = target.getRegInfo().getZeroRegNum();
855 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
857 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
859 } else if (isPowerOf2(C, pow)) {
860 unsigned opSize = target.getTargetData().getTypeSize(resultType);
861 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
862 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
863 destVal, mvec, mcfi);
866 if (mvec.size() > 0 && needNeg) {
867 // insert <reg = SUB 0, reg> after the instr to flip the sign
868 MachineInstr* M = CreateIntNegInstruction(target, destVal);
873 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
874 double dval = FPC->getValue();
875 if (fabs(dval) == 1) {
876 MachineOpCode opCode = (dval < 0)
877 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
878 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
879 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
884 if (firstNewInstr < mvec.size()) {
886 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
887 cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
894 // Does not create any instructions if we cannot exploit constant to
895 // create a cheaper instruction.
898 CreateCheapestMulConstInstruction(const TargetMachine &target,
900 Value* lval, Value* rval,
901 Instruction* destVal,
902 std::vector<MachineInstr*>& mvec,
903 MachineCodeForInstruction& mcfi)
906 if (isa<Constant>(lval) && isa<Constant>(rval)) {
907 // both operands are constant: evaluate and "set" in dest
908 Constant* P = ConstantFoldBinaryInstruction(Instruction::Mul,
909 cast<Constant>(lval),
910 cast<Constant>(rval));
911 target.getInstrInfo().CreateCodeToLoadConst(target,F,P,destVal,mvec,mcfi);
913 else if (isa<Constant>(rval)) // rval is constant, but not lval
914 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
915 else if (isa<Constant>(lval)) // lval is constant, but not rval
916 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
918 // else neither is constant
922 // Return NULL if we cannot exploit constant to create a cheaper instruction
924 CreateMulInstruction(const TargetMachine &target, Function* F,
925 Value* lval, Value* rval, Instruction* destVal,
926 std::vector<MachineInstr*>& mvec,
927 MachineCodeForInstruction& mcfi,
928 MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
930 unsigned L = mvec.size();
931 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
932 if (mvec.size() == L) {
933 // no instructions were added so create MUL reg, reg, reg.
934 // Use FSMULD if both operands are actually floats cast to doubles.
935 // Otherwise, use the default opcode for the appropriate type.
936 MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
938 : ChooseMulInstructionByType(destVal->getType()));
939 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
940 .addRegDef(destVal));
945 // Generate a divide instruction for Div or Rem.
946 // For Rem, this assumes that the operand type will be signed if the result
947 // type is signed. This is correct because they must have the same sign.
949 static inline MachineOpCode
950 ChooseDivInstruction(TargetMachine &target,
951 const InstructionNode* instrNode)
953 MachineOpCode opCode = V9::INVALID_OPCODE;
955 const Type* resultType = instrNode->getInstruction()->getType();
957 if (resultType->isInteger())
958 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
960 switch(resultType->getPrimitiveID())
962 case Type::FloatTyID: opCode = V9::FDIVS; break;
963 case Type::DoubleTyID: opCode = V9::FDIVD; break;
964 default: assert(0 && "Invalid type for DIV instruction"); break;
971 // Return if we cannot exploit constant to create a cheaper instruction
973 CreateDivConstInstruction(TargetMachine &target,
974 const InstructionNode* instrNode,
975 std::vector<MachineInstr*>& mvec)
977 Value* LHS = instrNode->leftChild()->getValue();
978 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
979 if (!isa<Constant>(constOp))
982 Instruction* destVal = instrNode->getInstruction();
983 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
985 // Cases worth optimizing are:
986 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
987 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
989 const Type* resultType = instrNode->getInstruction()->getType();
991 if (resultType->isInteger()) {
994 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
995 constOp, constOp->getType(), isValidConst);
997 bool needNeg = false;
1004 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
1005 .addRegDef(destVal));
1006 } else if (isPowerOf2(C, pow)) {
1008 Value* shiftOperand;
1009 unsigned opSize = target.getTargetData().getTypeSize(resultType);
1011 if (resultType->isSigned()) {
1012 // For N / 2^k, if the operand N is negative,
1013 // we need to add (2^k - 1) before right-shifting by k, i.e.,
1015 // (N / 2^k) = N >> k, if N >= 0;
1016 // (N + 2^k - 1) >> k, if N < 0
1018 // If N is <= 32 bits, use:
1019 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
1020 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1021 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1022 // sra t3, k, result // result = N / 2^k
1024 // If N is 64 bits, use:
1025 // srax N, k-1, t1 // t1 = sign bit in high k positions
1026 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1027 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1028 // sra t3, k, result // result = N / 2^k
1030 TmpInstruction *sraTmp, *srlTmp, *addTmp;
1031 MachineCodeForInstruction& mcfi
1032 = MachineCodeForInstruction::get(destVal);
1033 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
1034 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
1035 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
1037 // Create the SRA or SRAX instruction to get the sign bit
1038 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
1040 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
1041 .addRegDef(sraTmp));
1043 // Create the SRL or SRLX instruction to get the sign bit
1044 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
1046 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
1047 .addRegDef(srlTmp));
1049 // Create the ADD instruction to add 2^pow-1 for negative values
1050 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
1051 .addRegDef(addTmp));
1053 // Get the shift operand and "right-shift" opcode to do the divide
1054 shiftOperand = addTmp;
1055 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
1057 // Get the shift operand and "right-shift" opcode to do the divide
1059 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
1062 // Now do the actual shift!
1063 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
1064 .addRegDef(destVal));
1067 if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
1068 // insert <reg = SUB 0, reg> after the instr to flip the sign
1069 mvec.push_back(CreateIntNegInstruction(target, destVal));
1073 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
1074 double dval = FPC->getValue();
1075 if (fabs(dval) == 1) {
1077 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
1078 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
1080 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
1088 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
1089 Instruction* result,
1091 Value* numElementsVal,
1092 std::vector<MachineInstr*>& getMvec)
1094 Value* totalSizeVal;
1096 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
1097 Function *F = result->getParent()->getParent();
1099 // Enforce the alignment constraints on the stack pointer at
1100 // compile time if the total size is a known constant.
1101 if (isa<Constant>(numElementsVal)) {
1103 int64_t numElem = (int64_t) target.getInstrInfo().
1104 ConvertConstantToIntType(target, numElementsVal,
1105 numElementsVal->getType(), isValid);
1106 assert(isValid && "Unexpectedly large array dimension in alloca!");
1107 int64_t total = numElem * tsize;
1108 if (int extra= total % target.getFrameInfo().getStackFrameSizeAlignment())
1109 total += target.getFrameInfo().getStackFrameSizeAlignment() - extra;
1110 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
1112 // The size is not a constant. Generate code to compute it and
1113 // code to pad the size for stack alignment.
1114 // Create a Value to hold the (constant) element size
1115 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1117 // Create temporary values to hold the result of MUL, SLL, SRL
1118 // To pad `size' to next smallest multiple of 16:
1119 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
1121 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
1122 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
1123 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
1125 // Instruction 1: mul numElements, typeSize -> tmpProd
1126 // This will optimize the MUL as far as possible.
1127 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
1128 mcfi, INVALID_MACHINE_OPCODE);
1130 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
1131 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
1132 .addReg(tmpAdd15, MOTy::Def));
1134 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
1135 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
1136 .addReg(tmpAndf0, MOTy::Def));
1138 totalSizeVal = tmpAndf0;
1141 // Get the constant offset from SP for dynamically allocated storage
1142 // and create a temporary Value to hold it.
1143 MachineFunction& mcInfo = MachineFunction::get(F);
1145 ConstantSInt* dynamicAreaOffset =
1146 ConstantSInt::get(Type::IntTy,
1147 target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
1148 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
1150 unsigned SPReg = target.getRegInfo().getStackPointer();
1152 // Instruction 2: sub %sp, totalSizeVal -> %sp
1153 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
1154 .addMReg(SPReg,MOTy::Def));
1156 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1157 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
1158 .addRegDef(result));
1163 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
1164 Instruction* result,
1166 unsigned numElements,
1167 std::vector<MachineInstr*>& getMvec)
1169 assert(tsize > 0 && "Illegal (zero) type size for alloca");
1170 assert(result && result->getParent() &&
1171 "Result value is not part of a function?");
1172 Function *F = result->getParent()->getParent();
1173 MachineFunction &mcInfo = MachineFunction::get(F);
1175 // Put the variable in the dynamically sized area of the frame if either:
1176 // (a) The offset is too large to use as an immediate in load/stores
1177 // (check LDX because all load/stores have the same-size immed. field).
1178 // (b) The object is "large", so it could cause many other locals,
1179 // spills, and temporaries to have large offsets.
1180 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
1181 // You've gotta love having only 13 bits for constant offset values :-|.
1183 unsigned paddedSize;
1184 int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
1186 tsize * numElements);
1188 if (((int)paddedSize) > 8 * target.getFrameInfo().getSizeOfEachArgOnStack() ||
1189 ! target.getInstrInfo().constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
1190 CreateCodeForVariableSizeAlloca(target, result, tsize,
1191 ConstantSInt::get(Type::IntTy,numElements),
1196 // else offset fits in immediate field so go ahead and allocate it.
1197 offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
1199 // Create a temporary Value to hold the constant offset.
1200 // This is needed because it may not fit in the immediate field.
1201 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1203 // Instruction 1: add %fp, offsetFromFP -> result
1204 unsigned FPReg = target.getRegInfo().getFramePointer();
1205 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
1206 .addRegDef(result));
1210 //------------------------------------------------------------------------
1211 // Function SetOperandsForMemInstr
1213 // Choose addressing mode for the given load or store instruction.
1214 // Use [reg+reg] if it is an indexed reference, and the index offset is
1215 // not a constant or if it cannot fit in the offset field.
1216 // Use [reg+offset] in all other cases.
1218 // This assumes that all array refs are "lowered" to one of these forms:
1219 // %x = load (subarray*) ptr, constant ; single constant offset
1220 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
1221 // Generally, this should happen via strength reduction + LICM.
1222 // Also, strength reduction should take care of using the same register for
1223 // the loop index variable and an array index, when that is profitable.
1224 //------------------------------------------------------------------------
1227 SetOperandsForMemInstr(unsigned Opcode,
1228 std::vector<MachineInstr*>& mvec,
1229 InstructionNode* vmInstrNode,
1230 const TargetMachine& target)
1232 Instruction* memInst = vmInstrNode->getInstruction();
1233 // Index vector, ptr value, and flag if all indices are const.
1234 std::vector<Value*> idxVec;
1235 bool allConstantIndices;
1236 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
1238 // Now create the appropriate operands for the machine instruction.
1239 // First, initialize so we default to storing the offset in a register.
1240 int64_t smallConstOffset = 0;
1241 Value* valueForRegOffset = NULL;
1242 MachineOperand::MachineOperandType offsetOpType =
1243 MachineOperand::MO_VirtualRegister;
1245 // Check if there is an index vector and if so, compute the
1246 // right offset for structures and for arrays
1248 if (!idxVec.empty()) {
1249 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1251 // If all indices are constant, compute the combined offset directly.
1252 if (allConstantIndices) {
1253 // Compute the offset value using the index vector. Create a
1254 // virtual reg. for it since it may not fit in the immed field.
1255 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
1256 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1258 // There is at least one non-constant offset. Therefore, this must
1259 // be an array ref, and must have been lowered to a single non-zero
1260 // offset. (An extra leading zero offset, if any, can be ignored.)
1261 // Generate code sequence to compute address from index.
1263 bool firstIdxIsZero = IsZero(idxVec[0]);
1264 assert(idxVec.size() == 1U + firstIdxIsZero
1265 && "Array refs must be lowered before Instruction Selection");
1267 Value* idxVal = idxVec[firstIdxIsZero];
1269 std::vector<MachineInstr*> mulVec;
1271 new TmpInstruction(MachineCodeForInstruction::get(memInst),
1272 Type::ULongTy, memInst);
1274 // Get the array type indexed by idxVal, and compute its element size.
1275 // The call to getTypeSize() will fail if size is not constant.
1276 const Type* vecType = (firstIdxIsZero
1277 ? GetElementPtrInst::getIndexedType(ptrType,
1278 std::vector<Value*>(1U, idxVec[0]),
1279 /*AllowCompositeLeaf*/ true)
1281 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1282 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
1283 target.getTargetData().getTypeSize(eltType));
1285 // CreateMulInstruction() folds constants intelligently enough.
1286 CreateMulInstruction(target, memInst->getParent()->getParent(),
1287 idxVal, /* lval, not likely to be const*/
1288 eltSizeVal, /* rval, likely to be constant */
1290 mulVec, MachineCodeForInstruction::get(memInst),
1291 INVALID_MACHINE_OPCODE);
1293 assert(mulVec.size() > 0 && "No multiply code created?");
1294 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
1296 valueForRegOffset = addr;
1299 offsetOpType = MachineOperand::MO_SignExtendedImmed;
1300 smallConstOffset = 0;
1304 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
1305 // For LOAD or GET_ELEMENT_PTR,
1306 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1308 unsigned offsetOpNum, ptrOpNum;
1310 if (memInst->getOpcode() == Instruction::Store) {
1311 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1312 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1313 .addReg(ptrVal).addReg(valueForRegOffset);
1315 Opcode = convertOpcodeFromRegToImm(Opcode);
1316 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1317 .addReg(ptrVal).addSImm(smallConstOffset);
1320 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1321 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
1322 .addRegDef(memInst);
1324 Opcode = convertOpcodeFromRegToImm(Opcode);
1325 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
1326 .addRegDef(memInst);
1334 // Substitute operand `operandNum' of the instruction in node `treeNode'
1335 // in place of the use(s) of that instruction in node `parent'.
1336 // Check both explicit and implicit operands!
1337 // Also make sure to skip over a parent who:
1338 // (1) is a list node in the Burg tree, or
1339 // (2) itself had its results forwarded to its parent
1342 ForwardOperand(InstructionNode* treeNode,
1343 InstrTreeNode* parent,
1346 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1348 Instruction* unusedOp = treeNode->getInstruction();
1349 Value* fwdOp = unusedOp->getOperand(operandNum);
1351 // The parent itself may be a list node, so find the real parent instruction
1352 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1354 parent = parent->parent();
1355 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1357 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1359 Instruction* userInstr = parentInstrNode->getInstruction();
1360 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1362 // The parent's mvec would be empty if it was itself forwarded.
1363 // Recursively call ForwardOperand in that case...
1365 if (mvec.size() == 0) {
1366 assert(parent->parent() != NULL &&
1367 "Parent could not have been forwarded, yet has no instructions?");
1368 ForwardOperand(treeNode, parent->parent(), operandNum);
1370 for (unsigned i=0, N=mvec.size(); i < N; i++) {
1371 MachineInstr* minstr = mvec[i];
1372 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
1373 const MachineOperand& mop = minstr->getOperand(i);
1374 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
1375 mop.getVRegValue() == unusedOp)
1377 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
1382 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1383 if (minstr->getImplicitRef(i) == unusedOp)
1384 minstr->setImplicitRef(i, fwdOp);
1391 AllUsesAreBranches(const Instruction* setccI)
1393 for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1395 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
1396 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1401 // Generate code for any intrinsic that needs a special code sequence
1402 // instead of a regular call. If not that kind of intrinsic, do nothing.
1403 // Returns true if code was generated, otherwise false.
1405 bool CodeGenIntrinsic(LLVMIntrinsic::ID iid, CallInst &callInstr,
1406 TargetMachine &target,
1407 std::vector<MachineInstr*>& mvec)
1410 case LLVMIntrinsic::va_start: {
1411 // FIXME: this needs to be updated!
1414 // Get the address of the first vararg value on stack and copy it to
1415 // the argument of va_start(va_list* ap).
1417 Function* func = cast<Function>(callInstr.getParent()->getParent());
1418 int numFixedArgs = func->getFunctionType()->getNumParams();
1419 int fpReg = target.getFrameInfo().getIncomingArgBaseRegNum();
1420 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
1421 int firstVarArgOff = numFixedArgs * argSize + target.getFrameInfo().
1422 getFirstIncomingArgOffset(MachineFunction::get(func), ignore);
1423 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
1424 addRegDef(callInstr.getOperand(1)));
1428 case LLVMIntrinsic::va_end:
1429 return true; // no-op on Sparc
1431 case LLVMIntrinsic::va_copy:
1432 // FIXME: this needs to be updated!
1435 // Simple copy of current va_list (arg2) to new va_list (arg1)
1436 mvec.push_back(BuildMI(V9::ORr, 3).
1437 addMReg(target.getRegInfo().getZeroRegNum()).
1438 addReg(callInstr.getOperand(2)).
1439 addReg(callInstr.getOperand(1)));
1442 case LLVMIntrinsic::sigsetjmp:
1443 case LLVMIntrinsic::setjmp: {
1444 // act as if we return 0
1445 unsigned g0 = target.getRegInfo().getZeroRegNum();
1446 mvec.push_back(BuildMI(V9::ORr,3).addMReg(g0).addMReg(g0)
1447 .addReg(&callInstr, MOTy::Def));
1451 case LLVMIntrinsic::siglongjmp:
1452 case LLVMIntrinsic::longjmp: {
1454 Module* M = callInstr.getParent()->getParent()->getParent();
1455 const FunctionType *voidvoidFuncTy =
1456 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
1457 Function *F = M->getOrInsertFunction("abort", voidvoidFuncTy);
1458 assert(F && "Unable to get or create `abort' function declaration");
1460 // Create hidden virtual register for return address with type void*
1461 TmpInstruction* retAddrReg =
1462 new TmpInstruction(MachineCodeForInstruction::get(&callInstr),
1463 PointerType::get(Type::VoidTy), &callInstr);
1465 // Use a descriptor to pass information about call arguments
1466 // to the register allocator. This descriptor will be "owned"
1467 // and freed automatically when the MachineCodeForInstruction
1468 // object for the callInstr goes away.
1469 CallArgsDescriptor* argDesc =
1470 new CallArgsDescriptor(&callInstr, retAddrReg, false, false);
1472 MachineInstr* callMI = BuildMI(V9::CALL, 1).addPCDisp(F);
1473 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
1475 mvec.push_back(callMI);
1476 mvec.push_back(BuildMI(V9::NOP, 0));
1485 //******************* Externally Visible Functions *************************/
1487 //------------------------------------------------------------------------
1488 // External Function: ThisIsAChainRule
1491 // Check if a given BURG rule is a chain rule.
1492 //------------------------------------------------------------------------
1495 ThisIsAChainRule(int eruleno)
1499 case 111: // stmt: reg
1523 return false; break;
1528 //------------------------------------------------------------------------
1529 // External Function: GetInstructionsByRule
1532 // Choose machine instructions for the SPARC according to the
1533 // patterns chosen by the BURG-generated parser.
1534 //------------------------------------------------------------------------
1537 GetInstructionsByRule(InstructionNode* subtreeRoot,
1540 TargetMachine &target,
1541 std::vector<MachineInstr*>& mvec)
1543 bool checkCast = false; // initialize here to use fall-through
1544 bool maskUnsignedResult = false;
1546 int forwardOperandNum = -1;
1547 unsigned allocaSize = 0;
1548 MachineInstr* M, *M2;
1550 bool foldCase = false;
1554 // If the code for this instruction was folded into the parent (user),
1556 if (subtreeRoot->isFoldedIntoParent())
1560 // Let's check for chain rules outside the switch so that we don't have
1561 // to duplicate the list of chain rule production numbers here again
1563 if (ThisIsAChainRule(ruleForNode))
1565 // Chain rules have a single nonterminal on the RHS.
1566 // Get the rule that matches the RHS non-terminal and use that instead.
1568 assert(nts[0] && ! nts[1]
1569 && "A chain rule should have only one RHS non-terminal!");
1570 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1571 nts = burm_nts[nextRule];
1572 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1576 switch(ruleForNode) {
1577 case 1: // stmt: Ret
1578 case 2: // stmt: RetValue(reg)
1579 { // NOTE: Prepass of register allocation is responsible
1580 // for moving return value to appropriate register.
1581 // Copy the return value to the required return register.
1582 // Mark the return Value as an implicit ref of the RET instr..
1583 // Mark the return-address register as a hidden virtual reg.
1584 // Finally put a NOP in the delay slot.
1585 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
1586 Value* retVal = returnInstr->getReturnValue();
1587 MachineCodeForInstruction& mcfi =
1588 MachineCodeForInstruction::get(returnInstr);
1590 // Create a hidden virtual reg to represent the return address register
1591 // used by the machine instruction but not represented in LLVM.
1593 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
1595 MachineInstr* retMI =
1596 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
1597 .addMReg(target.getRegInfo().getZeroRegNum(), MOTy::Def);
1599 // If there is a value to return, we need to:
1600 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
1601 // (b) Insert a copy to copy the return value to the appropriate reg.
1602 // -- For FP values, create a FMOVS or FMOVD instruction
1603 // -- For non-FP values, create an add-with-0 instruction
1605 if (retVal != NULL) {
1606 const UltraSparcRegInfo& regInfo =
1607 (UltraSparcRegInfo&) target.getRegInfo();
1608 const Type* retType = retVal->getType();
1609 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
1610 unsigned retRegNum = (retType->isFloatingPoint()
1611 ? (unsigned) SparcFloatRegClass::f0
1612 : (unsigned) SparcIntRegClass::i0);
1613 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
1615 // () Insert sign-extension instructions for small signed values.
1617 Value* retValToUse = retVal;
1618 if (retType->isIntegral() && retType->isSigned()) {
1619 unsigned retSize = target.getTargetData().getTypeSize(retType);
1621 // create a temporary virtual reg. to hold the sign-extension
1622 retValToUse = new TmpInstruction(mcfi, retVal);
1624 // sign-extend retVal and put the result in the temporary reg.
1625 target.getInstrInfo().CreateSignExtensionInstructions
1626 (target, returnInstr->getParent()->getParent(),
1627 retVal, retValToUse, 8*retSize, mvec, mcfi);
1631 // (b) Now, insert a copy to to the appropriate register:
1632 // -- For FP values, create a FMOVS or FMOVD instruction
1633 // -- For non-FP values, create an add-with-0 instruction
1635 // First, create a virtual register to represent the register and
1636 // mark this vreg as being an implicit operand of the ret MI.
1637 TmpInstruction* retVReg =
1638 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
1640 retMI->addImplicitRef(retVReg);
1642 if (retType->isFloatingPoint())
1643 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1644 .addReg(retValToUse).addReg(retVReg, MOTy::Def));
1646 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
1647 .addReg(retValToUse).addSImm((int64_t) 0)
1648 .addReg(retVReg, MOTy::Def));
1650 // Mark the operand with the register it should be assigned
1651 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
1652 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
1657 // Now insert the RET instruction and a NOP for the delay slot
1658 mvec.push_back(retMI);
1659 mvec.push_back(BuildMI(V9::NOP, 0));
1664 case 3: // stmt: Store(reg,reg)
1665 case 4: // stmt: Store(reg,ptrreg)
1666 SetOperandsForMemInstr(ChooseStoreInstruction(
1667 subtreeRoot->leftChild()->getValue()->getType()),
1668 mvec, subtreeRoot, target);
1671 case 5: // stmt: BrUncond
1673 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1674 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
1677 mvec.push_back(BuildMI(V9::NOP, 0));
1681 case 206: // stmt: BrCond(setCCconst)
1682 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1683 // If the constant is ZERO, we can use the branch-on-integer-register
1684 // instructions and avoid the SUBcc instruction entirely.
1685 // Otherwise this is just the same as case 5, so just fall through.
1687 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1689 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1690 Constant *constVal = cast<Constant>(constNode->getValue());
1693 if ((constVal->getType()->isInteger()
1694 || isa<PointerType>(constVal->getType()))
1695 && target.getInstrInfo().ConvertConstantToIntType(target,
1696 constVal, constVal->getType(), isValidConst) == 0
1699 // That constant is a zero after all...
1700 // Use the left child of setCC as the first argument!
1701 // Mark the setCC node so that no code is generated for it.
1702 InstructionNode* setCCNode = (InstructionNode*)
1703 subtreeRoot->leftChild();
1704 assert(setCCNode->getOpLabel() == SetCCOp);
1705 setCCNode->markFoldedIntoParent();
1707 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1709 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
1710 .addReg(setCCNode->leftChild()->getValue())
1711 .addPCDisp(brInst->getSuccessor(0));
1715 mvec.push_back(BuildMI(V9::NOP, 0));
1718 mvec.push_back(BuildMI(V9::BA, 1)
1719 .addPCDisp(brInst->getSuccessor(1)));
1722 mvec.push_back(BuildMI(V9::NOP, 0));
1725 // ELSE FALL THROUGH
1728 case 6: // stmt: BrCond(setCC)
1729 { // bool => boolean was computed with SetCC.
1730 // The branch to use depends on whether it is FP, signed, or unsigned.
1731 // If it is an integer CC, we also need to find the unique
1732 // TmpInstruction representing that CC.
1734 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1735 const Type* setCCType;
1736 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
1737 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1738 brInst->getParent()->getParent(),
1740 MachineCodeForInstruction::get(brInst));
1741 M = BuildMI(Opcode, 2).addCCReg(ccValue)
1742 .addPCDisp(brInst->getSuccessor(0));
1746 mvec.push_back(BuildMI(V9::NOP, 0));
1749 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
1752 mvec.push_back(BuildMI(V9::NOP, 0));
1756 case 208: // stmt: BrCond(boolconst)
1758 // boolconst => boolean is a constant; use BA to first or second label
1759 Constant* constVal =
1760 cast<Constant>(subtreeRoot->leftChild()->getValue());
1761 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1763 M = BuildMI(V9::BA, 1).addPCDisp(
1764 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1768 mvec.push_back(BuildMI(V9::NOP, 0));
1772 case 8: // stmt: BrCond(boolreg)
1773 { // boolreg => boolean is recorded in an integer register.
1774 // Use branch-on-integer-register instruction.
1776 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1777 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
1778 .addPCDisp(BI->getSuccessor(0));
1782 mvec.push_back(BuildMI(V9::NOP, 0));
1785 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
1788 mvec.push_back(BuildMI(V9::NOP, 0));
1792 case 9: // stmt: Switch(reg)
1793 assert(0 && "*** SWITCH instruction is not implemented yet.");
1796 case 10: // reg: VRegList(reg, reg)
1797 assert(0 && "VRegList should never be the topmost non-chain rule");
1800 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
1801 { // First find the unary operand. It may be left or right, usually right.
1802 Instruction* notI = subtreeRoot->getInstruction();
1803 Value* notArg = BinaryOperator::getNotArgument(
1804 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1805 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1807 // Unconditionally set register to 0
1808 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
1810 // Now conditionally move 1 into the register.
1811 // Mark the register as a use (as well as a def) because the old
1812 // value will be retained if the condition is false.
1813 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
1814 .addReg(notI, MOTy::UseAndDef));
1819 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
1820 { // First find the unary operand. It may be left or right, usually right.
1821 Value* notArg = BinaryOperator::getNotArgument(
1822 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1823 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1824 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
1825 .addRegDef(subtreeRoot->getValue()));
1829 case 322: // reg: Not(tobool, reg):
1830 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
1832 // Just fall through!
1834 case 22: // reg: ToBoolTy(reg):
1836 Instruction* castI = subtreeRoot->getInstruction();
1837 Value* opVal = subtreeRoot->leftChild()->getValue();
1838 assert(opVal->getType()->isIntegral() ||
1839 isa<PointerType>(opVal->getType()));
1841 // Unconditionally set register to 0
1842 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
1844 // Now conditionally move 1 into the register.
1845 // Mark the register as a use (as well as a def) because the old
1846 // value will be retained if the condition is false.
1847 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
1848 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
1849 .addReg(castI, MOTy::UseAndDef));
1854 case 23: // reg: ToUByteTy(reg)
1855 case 24: // reg: ToSByteTy(reg)
1856 case 25: // reg: ToUShortTy(reg)
1857 case 26: // reg: ToShortTy(reg)
1858 case 27: // reg: ToUIntTy(reg)
1859 case 28: // reg: ToIntTy(reg)
1860 case 29: // reg: ToULongTy(reg)
1861 case 30: // reg: ToLongTy(reg)
1863 //======================================================================
1864 // Rules for integer conversions:
1867 // From ISO 1998 C++ Standard, Sec. 4.7:
1869 // 2. If the destination type is unsigned, the resulting value is
1870 // the least unsigned integer congruent to the source integer
1871 // (modulo 2n where n is the number of bits used to represent the
1872 // unsigned type). [Note: In a two s complement representation,
1873 // this conversion is conceptual and there is no change in the
1874 // bit pattern (if there is no truncation). ]
1876 // 3. If the destination type is signed, the value is unchanged if
1877 // it can be represented in the destination type (and bitfield width);
1878 // otherwise, the value is implementation-defined.
1881 // Since we assume 2s complement representations, this implies:
1883 // -- If operand is smaller than destination, zero-extend or sign-extend
1884 // according to the signedness of the *operand*: source decides:
1885 // (1) If operand is signed, sign-extend it.
1886 // If dest is unsigned, zero-ext the result!
1887 // (2) If operand is unsigned, our current invariant is that
1888 // it's high bits are correct, so zero-extension is not needed.
1890 // -- If operand is same size as or larger than destination,
1891 // zero-extend or sign-extend according to the signedness of
1892 // the *destination*: destination decides:
1893 // (1) If destination is signed, sign-extend (truncating if needed)
1894 // This choice is implementation defined. We sign-extend the
1895 // operand, which matches both Sun's cc and gcc3.2.
1896 // (2) If destination is unsigned, zero-extend (truncating if needed)
1897 //======================================================================
1899 Instruction* destI = subtreeRoot->getInstruction();
1900 Function* currentFunc = destI->getParent()->getParent();
1901 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
1903 Value* opVal = subtreeRoot->leftChild()->getValue();
1904 const Type* opType = opVal->getType();
1905 const Type* destType = destI->getType();
1906 unsigned opSize = target.getTargetData().getTypeSize(opType);
1907 unsigned destSize = target.getTargetData().getTypeSize(destType);
1909 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
1911 if (opType == Type::BoolTy ||
1912 opType == destType ||
1913 isIntegral && opSize == destSize && opSize == 8) {
1914 // nothing to do in all these cases
1915 forwardOperandNum = 0; // forward first operand to user
1917 } else if (opType->isFloatingPoint()) {
1919 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1920 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
1921 maskUnsignedResult = true; // not handled by fp->int code
1923 } else if (isIntegral) {
1925 bool opSigned = opType->isSigned();
1926 bool destSigned = destType->isSigned();
1927 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
1929 assert(! (opSize == destSize && opSigned == destSigned) &&
1930 "How can different int types have same size and signedness?");
1932 bool signExtend = (opSize < destSize && opSigned ||
1933 opSize >= destSize && destSigned);
1935 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
1936 opSigned && !destSigned);
1937 assert(!signAndZeroExtend || signExtend);
1939 bool zeroExtendOnly = opSize >= destSize && !destSigned;
1940 assert(!zeroExtendOnly || !signExtend);
1943 Value* signExtDest = (signAndZeroExtend
1944 ? new TmpInstruction(mcfi, destType, opVal)
1947 target.getInstrInfo().CreateSignExtensionInstructions
1948 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
1950 if (signAndZeroExtend)
1951 target.getInstrInfo().CreateZeroExtensionInstructions
1952 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
1954 else if (zeroExtendOnly) {
1955 target.getInstrInfo().CreateZeroExtensionInstructions
1956 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
1959 forwardOperandNum = 0; // forward first operand to user
1962 assert(0 && "Unrecognized operand type for convert-to-integer");
1967 case 31: // reg: ToFloatTy(reg):
1968 case 32: // reg: ToDoubleTy(reg):
1969 case 232: // reg: ToDoubleTy(Constant):
1971 // If this instruction has a parent (a user) in the tree
1972 // and the user is translated as an FsMULd instruction,
1973 // then the cast is unnecessary. So check that first.
1974 // In the future, we'll want to do the same for the FdMULq instruction,
1975 // so do the check here instead of only for ToFloatTy(reg).
1977 if (subtreeRoot->parent() != NULL) {
1978 const MachineCodeForInstruction& mcfi =
1979 MachineCodeForInstruction::get(
1980 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1981 if (mcfi.size() == 0 || mcfi.front()->getOpCode() == V9::FSMULD)
1982 forwardOperandNum = 0; // forward first operand to user
1985 if (forwardOperandNum != 0) { // we do need the cast
1986 Value* leftVal = subtreeRoot->leftChild()->getValue();
1987 const Type* opType = leftVal->getType();
1988 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
1989 subtreeRoot->getOpLabel(), opType);
1990 if (opCode == V9::NOP) { // no conversion needed
1991 forwardOperandNum = 0; // forward first operand to user
1993 // If the source operand is a non-FP type it must be
1994 // first copied from int to float register via memory!
1995 Instruction *dest = subtreeRoot->getInstruction();
1998 if (! opType->isFloatingPoint()) {
1999 // Create a temporary to represent the FP register
2000 // into which the integer will be copied via memory.
2001 // The type of this temporary will determine the FP
2002 // register used: single-prec for a 32-bit int or smaller,
2003 // double-prec for a 64-bit int.
2006 target.getTargetData().getTypeSize(leftVal->getType());
2007 Type* tmpTypeToUse =
2008 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
2009 MachineCodeForInstruction &destMCFI =
2010 MachineCodeForInstruction::get(dest);
2011 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
2013 target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
2014 dest->getParent()->getParent(),
2015 leftVal, cast<Instruction>(srcForCast),
2018 srcForCast = leftVal;
2020 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
2026 case 19: // reg: ToArrayTy(reg):
2027 case 20: // reg: ToPointerTy(reg):
2028 forwardOperandNum = 0; // forward first operand to user
2031 case 233: // reg: Add(reg, Constant)
2032 maskUnsignedResult = true;
2033 M = CreateAddConstInstruction(subtreeRoot);
2038 // ELSE FALL THROUGH
2040 case 33: // reg: Add(reg, reg)
2041 maskUnsignedResult = true;
2042 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
2045 case 234: // reg: Sub(reg, Constant)
2046 maskUnsignedResult = true;
2047 M = CreateSubConstInstruction(subtreeRoot);
2052 // ELSE FALL THROUGH
2054 case 34: // reg: Sub(reg, reg)
2055 maskUnsignedResult = true;
2056 Add3OperandInstr(ChooseSubInstructionByType(
2057 subtreeRoot->getInstruction()->getType()),
2061 case 135: // reg: Mul(todouble, todouble)
2065 case 35: // reg: Mul(reg, reg)
2067 maskUnsignedResult = true;
2068 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2070 : INVALID_MACHINE_OPCODE);
2071 Instruction* mulInstr = subtreeRoot->getInstruction();
2072 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2073 subtreeRoot->leftChild()->getValue(),
2074 subtreeRoot->rightChild()->getValue(),
2076 MachineCodeForInstruction::get(mulInstr),forceOp);
2079 case 335: // reg: Mul(todouble, todoubleConst)
2083 case 235: // reg: Mul(reg, Constant)
2085 maskUnsignedResult = true;
2086 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2088 : INVALID_MACHINE_OPCODE);
2089 Instruction* mulInstr = subtreeRoot->getInstruction();
2090 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2091 subtreeRoot->leftChild()->getValue(),
2092 subtreeRoot->rightChild()->getValue(),
2094 MachineCodeForInstruction::get(mulInstr),
2098 case 236: // reg: Div(reg, Constant)
2099 maskUnsignedResult = true;
2101 CreateDivConstInstruction(target, subtreeRoot, mvec);
2102 if (mvec.size() > L)
2104 // ELSE FALL THROUGH
2106 case 36: // reg: Div(reg, reg)
2108 maskUnsignedResult = true;
2110 // If either operand of divide is smaller than 64 bits, we have
2111 // to make sure the unused top bits are correct because they affect
2112 // the result. These bits are already correct for unsigned values.
2113 // They may be incorrect for signed values, so sign extend to fill in.
2114 Instruction* divI = subtreeRoot->getInstruction();
2115 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2116 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2117 Value* divOp1ToUse = divOp1;
2118 Value* divOp2ToUse = divOp2;
2119 if (divI->getType()->isSigned()) {
2120 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
2122 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
2123 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
2124 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
2125 target.getInstrInfo().
2126 CreateSignExtensionInstructions(target,
2127 divI->getParent()->getParent(),
2128 divOp1, divOp1ToUse,
2129 8*opSize, mvec, mcfi);
2130 target.getInstrInfo().
2131 CreateSignExtensionInstructions(target,
2132 divI->getParent()->getParent(),
2133 divOp2, divOp2ToUse,
2134 8*opSize, mvec, mcfi);
2138 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2139 .addReg(divOp1ToUse)
2140 .addReg(divOp2ToUse)
2146 case 37: // reg: Rem(reg, reg)
2147 case 237: // reg: Rem(reg, Constant)
2149 maskUnsignedResult = true;
2151 Instruction* remI = subtreeRoot->getInstruction();
2152 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2153 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2155 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
2157 // If second operand of divide is smaller than 64 bits, we have
2158 // to make sure the unused top bits are correct because they affect
2159 // the result. These bits are already correct for unsigned values.
2160 // They may be incorrect for signed values, so sign extend to fill in.
2162 Value* divOpToUse = divOp2;
2163 if (divOp2->getType()->isSigned()) {
2164 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
2166 divOpToUse = new TmpInstruction(mcfi, divOp2);
2167 target.getInstrInfo().
2168 CreateSignExtensionInstructions(target,
2169 remI->getParent()->getParent(),
2171 8*opSize, mvec, mcfi);
2175 // Now compute: result = rem V1, V2 as:
2176 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
2178 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
2179 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
2181 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2182 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
2184 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
2185 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
2187 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
2188 .addReg(divOp1).addReg(prod).addRegDef(remI));
2193 case 38: // bool: And(bool, bool)
2194 case 138: // bool: And(bool, not)
2195 case 238: // bool: And(bool, boolconst)
2196 case 338: // reg : BAnd(reg, reg)
2197 case 538: // reg : BAnd(reg, Constant)
2198 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
2201 case 438: // bool: BAnd(bool, bnot)
2202 { // Use the argument of NOT as the second argument!
2203 // Mark the NOT node so that no code is generated for it.
2204 // If the type is boolean, set 1 or 0 in the result register.
2205 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2206 Value* notArg = BinaryOperator::getNotArgument(
2207 cast<BinaryOperator>(notNode->getInstruction()));
2208 notNode->markFoldedIntoParent();
2209 Value *lhs = subtreeRoot->leftChild()->getValue();
2210 Value *dest = subtreeRoot->getValue();
2211 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
2212 .addReg(dest, MOTy::Def));
2214 if (notArg->getType() == Type::BoolTy)
2215 { // set 1 in result register if result of above is non-zero
2216 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2217 .addReg(dest, MOTy::UseAndDef));
2223 case 39: // bool: Or(bool, bool)
2224 case 139: // bool: Or(bool, not)
2225 case 239: // bool: Or(bool, boolconst)
2226 case 339: // reg : BOr(reg, reg)
2227 case 539: // reg : BOr(reg, Constant)
2228 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
2231 case 439: // bool: BOr(bool, bnot)
2232 { // Use the argument of NOT as the second argument!
2233 // Mark the NOT node so that no code is generated for it.
2234 // If the type is boolean, set 1 or 0 in the result register.
2235 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2236 Value* notArg = BinaryOperator::getNotArgument(
2237 cast<BinaryOperator>(notNode->getInstruction()));
2238 notNode->markFoldedIntoParent();
2239 Value *lhs = subtreeRoot->leftChild()->getValue();
2240 Value *dest = subtreeRoot->getValue();
2242 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
2243 .addReg(dest, MOTy::Def));
2245 if (notArg->getType() == Type::BoolTy)
2246 { // set 1 in result register if result of above is non-zero
2247 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2248 .addReg(dest, MOTy::UseAndDef));
2254 case 40: // bool: Xor(bool, bool)
2255 case 140: // bool: Xor(bool, not)
2256 case 240: // bool: Xor(bool, boolconst)
2257 case 340: // reg : BXor(reg, reg)
2258 case 540: // reg : BXor(reg, Constant)
2259 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
2262 case 440: // bool: BXor(bool, bnot)
2263 { // Use the argument of NOT as the second argument!
2264 // Mark the NOT node so that no code is generated for it.
2265 // If the type is boolean, set 1 or 0 in the result register.
2266 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2267 Value* notArg = BinaryOperator::getNotArgument(
2268 cast<BinaryOperator>(notNode->getInstruction()));
2269 notNode->markFoldedIntoParent();
2270 Value *lhs = subtreeRoot->leftChild()->getValue();
2271 Value *dest = subtreeRoot->getValue();
2272 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
2273 .addReg(dest, MOTy::Def));
2275 if (notArg->getType() == Type::BoolTy)
2276 { // set 1 in result register if result of above is non-zero
2277 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2278 .addReg(dest, MOTy::UseAndDef));
2283 case 41: // setCCconst: SetCC(reg, Constant)
2284 { // Comparison is with a constant:
2286 // If the bool result must be computed into a register (see below),
2287 // and the constant is int ZERO, we can use the MOVR[op] instructions
2288 // and avoid the SUBcc instruction entirely.
2289 // Otherwise this is just the same as case 42, so just fall through.
2291 // The result of the SetCC must be computed and stored in a register if
2292 // it is used outside the current basic block (so it must be computed
2293 // as a boolreg) or it is used by anything other than a branch.
2294 // We will use a conditional move to do this.
2296 Instruction* setCCInstr = subtreeRoot->getInstruction();
2297 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2298 ! AllUsesAreBranches(setCCInstr));
2302 InstrTreeNode* constNode = subtreeRoot->rightChild();
2304 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2305 Constant *constVal = cast<Constant>(constNode->getValue());
2308 if ((constVal->getType()->isInteger()
2309 || isa<PointerType>(constVal->getType()))
2310 && target.getInstrInfo().ConvertConstantToIntType(target,
2311 constVal, constVal->getType(), isValidConst) == 0
2314 // That constant is an integer zero after all...
2315 // Use a MOVR[op] to compute the boolean result
2316 // Unconditionally set register to 0
2317 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
2318 .addRegDef(setCCInstr));
2320 // Now conditionally move 1 into the register.
2321 // Mark the register as a use (as well as a def) because the old
2322 // value will be retained if the condition is false.
2323 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
2324 mvec.push_back(BuildMI(movOpCode, 3)
2325 .addReg(subtreeRoot->leftChild()->getValue())
2326 .addZImm(1).addReg(setCCInstr, MOTy::UseAndDef));
2331 // ELSE FALL THROUGH
2334 case 42: // bool: SetCC(reg, reg):
2336 // This generates a SUBCC instruction, putting the difference in a
2337 // result reg. if needed, and/or setting a condition code if needed.
2339 Instruction* setCCInstr = subtreeRoot->getInstruction();
2340 Value* leftVal = subtreeRoot->leftChild()->getValue();
2341 Value* rightVal = subtreeRoot->rightChild()->getValue();
2342 const Type* opType = leftVal->getType();
2343 bool isFPCompare = opType->isFloatingPoint();
2345 // If the boolean result of the SetCC is used outside the current basic
2346 // block (so it must be computed as a boolreg) or is used by anything
2347 // other than a branch, the boolean must be computed and stored
2348 // in a result register. We will use a conditional move to do this.
2350 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2351 ! AllUsesAreBranches(setCCInstr));
2353 // A TmpInstruction is created to represent the CC "result".
2354 // Unlike other instances of TmpInstruction, this one is used
2355 // by machine code of multiple LLVM instructions, viz.,
2356 // the SetCC and the branch. Make sure to get the same one!
2357 // Note that we do this even for FP CC registers even though they
2358 // are explicit operands, because the type of the operand
2359 // needs to be a floating point condition code, not an integer
2360 // condition code. Think of this as casting the bool result to
2361 // a FP condition code register.
2362 // Later, we mark the 4th operand as being a CC register, and as a def.
2364 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
2365 setCCInstr->getParent()->getParent(),
2367 MachineCodeForInstruction::get(setCCInstr));
2369 // If the operands are signed values smaller than 4 bytes, then they
2370 // must be sign-extended in order to do a valid 32-bit comparison
2371 // and get the right result in the 32-bit CC register (%icc).
2373 Value* leftOpToUse = leftVal;
2374 Value* rightOpToUse = rightVal;
2375 if (opType->isIntegral() && opType->isSigned()) {
2376 unsigned opSize = target.getTargetData().getTypeSize(opType);
2378 MachineCodeForInstruction& mcfi =
2379 MachineCodeForInstruction::get(setCCInstr);
2381 // create temporary virtual regs. to hold the sign-extensions
2382 leftOpToUse = new TmpInstruction(mcfi, leftVal);
2383 rightOpToUse = new TmpInstruction(mcfi, rightVal);
2385 // sign-extend each operand and put the result in the temporary reg.
2386 target.getInstrInfo().CreateSignExtensionInstructions
2387 (target, setCCInstr->getParent()->getParent(),
2388 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
2389 target.getInstrInfo().CreateSignExtensionInstructions
2390 (target, setCCInstr->getParent()->getParent(),
2391 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
2395 if (! isFPCompare) {
2396 // Integer condition: set CC and discard result.
2397 mvec.push_back(BuildMI(V9::SUBccr, 4)
2398 .addReg(leftOpToUse)
2399 .addReg(rightOpToUse)
2400 .addMReg(target.getRegInfo().getZeroRegNum(),MOTy::Def)
2401 .addCCReg(tmpForCC, MOTy::Def));
2403 // FP condition: dest of FCMP should be some FCCn register
2404 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
2405 .addCCReg(tmpForCC, MOTy::Def)
2406 .addReg(leftOpToUse)
2407 .addReg(rightOpToUse));
2410 if (computeBoolVal) {
2411 MachineOpCode movOpCode = (isFPCompare
2412 ? ChooseMovFpcciInstruction(subtreeRoot)
2413 : ChooseMovpcciForSetCC(subtreeRoot));
2415 // Unconditionally set register to 0
2416 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
2419 // Now conditionally move 1 into the register.
2420 // Mark the register as a use (as well as a def) because the old
2421 // value will be retained if the condition is false.
2422 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
2423 .addReg(setCCInstr, MOTy::UseAndDef));
2429 case 51: // reg: Load(reg)
2430 case 52: // reg: Load(ptrreg)
2431 SetOperandsForMemInstr(ChooseLoadInstruction(
2432 subtreeRoot->getValue()->getType()),
2433 mvec, subtreeRoot, target);
2436 case 55: // reg: GetElemPtr(reg)
2437 case 56: // reg: GetElemPtrIdx(reg,reg)
2438 // If the GetElemPtr was folded into the user (parent), it will be
2439 // caught above. For other cases, we have to compute the address.
2440 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
2443 case 57: // reg: Alloca: Implement as 1 instruction:
2444 { // add %fp, offsetFromFP -> result
2445 AllocationInst* instr =
2446 cast<AllocationInst>(subtreeRoot->getInstruction());
2448 target.getTargetData().getTypeSize(instr->getAllocatedType());
2450 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2454 case 58: // reg: Alloca(reg): Implement as 3 instructions:
2455 // mul num, typeSz -> tmp
2456 // sub %sp, tmp -> %sp
2457 { // add %sp, frameSizeBelowDynamicArea -> result
2458 AllocationInst* instr =
2459 cast<AllocationInst>(subtreeRoot->getInstruction());
2460 const Type* eltType = instr->getAllocatedType();
2462 // If #elements is constant, use simpler code for fixed-size allocas
2463 int tsize = (int) target.getTargetData().getTypeSize(eltType);
2464 Value* numElementsVal = NULL;
2465 bool isArray = instr->isArrayAllocation();
2467 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
2468 // total size is constant: generate code for fixed-size alloca
2469 unsigned numElements = isArray?
2470 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2471 CreateCodeForFixedSizeAlloca(target, instr, tsize,
2474 // total size is not constant.
2475 CreateCodeForVariableSizeAlloca(target, instr, tsize,
2476 numElementsVal, mvec);
2481 case 61: // reg: Call
2482 { // Generate a direct (CALL) or indirect (JMPL) call.
2483 // Mark the return-address register, the indirection
2484 // register (for indirect calls), the operands of the Call,
2485 // and the return value (if any) as implicit operands
2486 // of the machine instruction.
2488 // If this is a varargs function, floating point arguments
2489 // have to passed in integer registers so insert
2490 // copy-float-to-int instructions for each float operand.
2492 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2493 Value *callee = callInstr->getCalledValue();
2494 Function* calledFunc = dyn_cast<Function>(callee);
2496 // Check if this is an intrinsic function that needs a special code
2497 // sequence (e.g., va_start). Indirect calls cannot be special.
2499 bool specialIntrinsic = false;
2500 LLVMIntrinsic::ID iid;
2501 if (calledFunc && (iid=(LLVMIntrinsic::ID)calledFunc->getIntrinsicID()))
2502 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
2504 // If not, generate the normal call sequence for the function.
2505 // This can also handle any intrinsics that are just function calls.
2507 if (! specialIntrinsic) {
2508 Function* currentFunc = callInstr->getParent()->getParent();
2509 MachineFunction& MF = MachineFunction::get(currentFunc);
2510 MachineCodeForInstruction& mcfi =
2511 MachineCodeForInstruction::get(callInstr);
2512 const UltraSparcRegInfo& regInfo =
2513 (UltraSparcRegInfo&) target.getRegInfo();
2514 const TargetFrameInfo& frameInfo = target.getFrameInfo();
2516 // Create hidden virtual register for return address with type void*
2517 TmpInstruction* retAddrReg =
2518 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
2520 // Generate the machine instruction and its operands.
2521 // Use CALL for direct function calls; this optimistically assumes
2522 // the PC-relative address fits in the CALL address field (22 bits).
2523 // Use JMPL for indirect calls.
2524 // This will be added to mvec later, after operand copies.
2526 MachineInstr* callMI;
2527 if (calledFunc) // direct function call
2528 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
2529 else // indirect function call
2530 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
2531 .addSImm((int64_t)0).addRegDef(retAddrReg));
2533 const FunctionType* funcType =
2534 cast<FunctionType>(cast<PointerType>(callee->getType())
2535 ->getElementType());
2536 bool isVarArgs = funcType->isVarArg();
2537 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2539 // Use a descriptor to pass information about call arguments
2540 // to the register allocator. This descriptor will be "owned"
2541 // and freed automatically when the MachineCodeForInstruction
2542 // object for the callInstr goes away.
2543 CallArgsDescriptor* argDesc =
2544 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
2545 assert(callInstr->getOperand(0) == callee
2546 && "This is assumed in the loop below!");
2548 // Insert sign-extension instructions for small signed values,
2549 // if this is an unknown function (i.e., called via a funcptr)
2550 // or an external one (i.e., which may not be compiled by llc).
2552 if (calledFunc == NULL || calledFunc->isExternal()) {
2553 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2554 Value* argVal = callInstr->getOperand(i);
2555 const Type* argType = argVal->getType();
2556 if (argType->isIntegral() && argType->isSigned()) {
2557 unsigned argSize = target.getTargetData().getTypeSize(argType);
2559 // create a temporary virtual reg. to hold the sign-extension
2560 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
2562 // sign-extend argVal and put the result in the temporary reg.
2563 target.getInstrInfo().CreateSignExtensionInstructions
2564 (target, currentFunc, argVal, argExtend,
2565 8*argSize, mvec, mcfi);
2567 // replace argVal with argExtend in CallArgsDescriptor
2568 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
2574 // Insert copy instructions to get all the arguments into
2575 // all the places that they need to be.
2577 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2579 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
2580 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
2581 const Type* argType = argVal->getType();
2582 unsigned regType = regInfo.getRegTypeForDataType(argType);
2583 unsigned argSize = target.getTargetData().getTypeSize(argType);
2584 int regNumForArg = TargetRegInfo::getInvalidRegNum();
2585 unsigned regClassIDOfArgReg;
2587 // Check for FP arguments to varargs functions.
2588 // Any such argument in the first $K$ args must be passed in an
2589 // integer register. If there is no prototype, it must also
2590 // be passed as an FP register.
2591 // K = #integer argument registers.
2592 bool isFPArg = argVal->getType()->isFloatingPoint();
2593 if (isVarArgs && isFPArg) {
2596 // It is a function with no prototype: pass value
2597 // as an FP value as well as a varargs value. The FP value
2598 // may go in a register or on the stack. The copy instruction
2599 // to the outgoing reg/stack is created by the normal argument
2600 // handling code since this is the "normal" passing mode.
2602 regNumForArg = regInfo.regNumForFPArg(regType,
2603 false, false, argNo,
2604 regClassIDOfArgReg);
2605 if (regNumForArg == regInfo.getInvalidRegNum())
2606 argInfo.setUseStackSlot();
2608 argInfo.setUseFPArgReg();
2611 // If this arg. is in the first $K$ regs, add special copy-
2612 // float-to-int instructions to pass the value as an int.
2613 // To check if it is in the first $K$, get the register
2614 // number for the arg #i. These copy instructions are
2615 // generated here because they are extra cases and not needed
2616 // for the normal argument handling (some code reuse is
2617 // possible though -- later).
2619 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
2620 regClassIDOfArgReg);
2621 if (copyRegNum != regInfo.getInvalidRegNum()) {
2622 // Create a virtual register to represent copyReg. Mark
2623 // this vreg as being an implicit operand of the call MI
2624 const Type* loadTy = (argType == Type::FloatTy
2625 ? Type::IntTy : Type::LongTy);
2626 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
2629 callMI->addImplicitRef(argVReg);
2631 // Get a temp stack location to use to copy
2632 // float-to-int via the stack.
2634 // FIXME: For now, we allocate permanent space because
2635 // the stack frame manager does not allow locals to be
2636 // allocated (e.g., for alloca) after a temp is
2639 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
2640 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
2642 // Generate the store from FP reg to stack
2643 unsigned StoreOpcode = ChooseStoreInstruction(argType);
2644 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
2645 .addReg(argVal).addMReg(regInfo.getFramePointer())
2646 .addSImm(tmpOffset);
2649 // Generate the load from stack to int arg reg
2650 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
2651 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
2652 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
2653 .addReg(argVReg, MOTy::Def);
2655 // Mark operand with register it should be assigned
2656 // both for copy and for the callMI
2657 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
2658 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2662 // Add info about the argument to the CallArgsDescriptor
2663 argInfo.setUseIntArgReg();
2664 argInfo.setArgCopy(copyRegNum);
2666 // Cannot fit in first $K$ regs so pass arg on stack
2667 argInfo.setUseStackSlot();
2669 } else if (isFPArg) {
2670 // Get the outgoing arg reg to see if there is one.
2671 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
2672 argNo, regClassIDOfArgReg);
2673 if (regNumForArg == regInfo.getInvalidRegNum())
2674 argInfo.setUseStackSlot();
2676 argInfo.setUseFPArgReg();
2677 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2681 // Get the outgoing arg reg to see if there is one.
2682 regNumForArg = regInfo.regNumForIntArg(false,false,
2683 argNo, regClassIDOfArgReg);
2684 if (regNumForArg == regInfo.getInvalidRegNum())
2685 argInfo.setUseStackSlot();
2687 argInfo.setUseIntArgReg();
2688 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2694 // Now insert copy instructions to stack slot or arg. register
2696 if (argInfo.usesStackSlot()) {
2697 // Get the stack offset for this argument slot.
2698 // FP args on stack are right justified so adjust offset!
2699 // int arguments are also right justified but they are
2700 // always loaded as a full double-word so the offset does
2701 // not need to be adjusted.
2702 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
2703 if (argType->isFloatingPoint()) {
2704 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
2705 assert(argSize <= slotSize && "Insufficient slot size!");
2706 argOffset += slotSize - argSize;
2709 // Now generate instruction to copy argument to stack
2710 MachineOpCode storeOpCode =
2711 (argType->isFloatingPoint()
2712 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
2714 M = BuildMI(storeOpCode, 3).addReg(argVal)
2715 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
2718 else if (regNumForArg != regInfo.getInvalidRegNum()) {
2720 // Create a virtual register to represent the arg reg. Mark
2721 // this vreg as being an implicit operand of the call MI.
2722 TmpInstruction* argVReg =
2723 new TmpInstruction(mcfi, argVal, NULL, "argReg");
2725 callMI->addImplicitRef(argVReg);
2727 // Generate the reg-to-reg copy into the outgoing arg reg.
2728 // -- For FP values, create a FMOVS or FMOVD instruction
2729 // -- For non-FP values, create an add-with-0 instruction
2730 if (argType->isFloatingPoint())
2731 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
2732 .addReg(argVal).addReg(argVReg, MOTy::Def));
2734 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
2735 .addReg(argVal).addSImm((int64_t) 0)
2736 .addReg(argVReg, MOTy::Def));
2738 // Mark the operand with the register it should be assigned
2739 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
2740 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2746 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
2747 "Arg. not in stack slot, primary or secondary register?");
2750 // add call instruction and delay slot before copying return value
2751 mvec.push_back(callMI);
2752 mvec.push_back(BuildMI(V9::NOP, 0));
2754 // Add the return value as an implicit ref. The call operands
2755 // were added above. Also, add code to copy out the return value.
2756 // This is always register-to-register for int or FP return values.
2758 if (callInstr->getType() != Type::VoidTy) {
2759 // Get the return value reg.
2760 const Type* retType = callInstr->getType();
2762 int regNum = (retType->isFloatingPoint()
2763 ? (unsigned) SparcFloatRegClass::f0
2764 : (unsigned) SparcIntRegClass::o0);
2765 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2766 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
2768 // Create a virtual register to represent it and mark
2769 // this vreg as being an implicit operand of the call MI
2770 TmpInstruction* retVReg =
2771 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
2773 callMI->addImplicitRef(retVReg, /*isDef*/ true);
2775 // Generate the reg-to-reg copy from the return value reg.
2776 // -- For FP values, create a FMOVS or FMOVD instruction
2777 // -- For non-FP values, create an add-with-0 instruction
2778 if (retType->isFloatingPoint())
2779 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2780 .addReg(retVReg).addReg(callInstr, MOTy::Def));
2782 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2783 .addReg(retVReg).addSImm((int64_t) 0)
2784 .addReg(callInstr, MOTy::Def));
2786 // Mark the operand with the register it should be assigned
2787 // Also mark the implicit ref of the call defining this operand
2788 M->SetRegForOperand(0, regNum);
2789 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
2794 // For the CALL instruction, the ret. addr. reg. is also implicit
2795 if (isa<Function>(callee))
2796 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
2798 MF.getInfo()->popAllTempValues(); // free temps used for this inst
2804 case 62: // reg: Shl(reg, reg)
2806 Value* argVal1 = subtreeRoot->leftChild()->getValue();
2807 Value* argVal2 = subtreeRoot->rightChild()->getValue();
2808 Instruction* shlInstr = subtreeRoot->getInstruction();
2810 const Type* opType = argVal1->getType();
2811 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2812 "Shl unsupported for other types");
2813 unsigned opSize = target.getTargetData().getTypeSize(opType);
2815 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2816 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
2817 argVal1, argVal2, 0, shlInstr, mvec,
2818 MachineCodeForInstruction::get(shlInstr));
2822 case 63: // reg: Shr(reg, reg)
2824 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2825 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2826 "Shr unsupported for other types");
2827 unsigned opSize = target.getTargetData().getTypeSize(opType);
2828 Add3OperandInstr(opType->isSigned()
2829 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
2830 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
2835 case 64: // reg: Phi(reg,reg)
2836 break; // don't forward the value
2838 case 65: // reg: VANext(reg): the va_next instruction
2839 case 66: // reg: VAArg (reg): the va_arg instruction
2841 abort(); // FIXME: This is incorrect!
2843 // Use value initialized by va_start as pointer to args on the stack.
2844 // Load argument via current pointer value, then increment pointer.
2845 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
2846 Instruction* vaArgI = subtreeRoot->getInstruction();
2847 MachineOpCode loadOp = vaArgI->getType()->isFloatingPoint()? V9::LDDFi
2849 mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
2850 addSImm(0).addRegDef(vaArgI));
2851 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaArgI->getOperand(0)).
2852 addSImm(argSize).addRegDef(vaArgI->getOperand(0)));
2857 case 71: // reg: VReg
2858 case 72: // reg: Constant
2859 break; // don't forward the value
2862 assert(0 && "Unrecognized BURG rule");
2867 if (forwardOperandNum >= 0) {
2868 // We did not generate a machine instruction but need to use operand.
2869 // If user is in the same tree, replace Value in its machine operand.
2870 // If not, insert a copy instruction which should get coalesced away
2871 // by register allocation.
2872 if (subtreeRoot->parent() != NULL)
2873 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2875 std::vector<MachineInstr*> minstrVec;
2876 Instruction* instr = subtreeRoot->getInstruction();
2877 target.getInstrInfo().
2878 CreateCopyInstructionsByType(target,
2879 instr->getParent()->getParent(),
2880 instr->getOperand(forwardOperandNum),
2882 MachineCodeForInstruction::get(instr));
2883 assert(minstrVec.size() > 0);
2884 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2888 if (maskUnsignedResult) {
2889 // If result is unsigned and smaller than int reg size,
2890 // we need to clear high bits of result value.
2891 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2892 Instruction* dest = subtreeRoot->getInstruction();
2893 if (dest->getType()->isUnsigned()) {
2894 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
2895 if (destSize <= 4) {
2896 // Mask high 64 - N bits, where N = 4*destSize.
2898 // Use a TmpInstruction to represent the
2899 // intermediate result before masking. Since those instructions
2900 // have already been generated, go back and substitute tmpI
2901 // for dest in the result position of each one of them.
2903 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
2904 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
2905 dest, NULL, "maskHi");
2906 Value* srlArgToUse = tmpI;
2908 unsigned numSubst = 0;
2909 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
2911 // Make sure we substitute all occurrences of dest in these instrs.
2912 // Otherwise, we will have bogus code.
2913 bool someArgsWereIgnored = false;
2915 // Make sure not to substitute an upwards-exposed use -- that would
2916 // introduce a use of `tmpI' with no preceding def. Therefore,
2917 // substitute a use or def-and-use operand only if a previous def
2918 // operand has already been substituted (i.e., numSusbt > 0).
2920 numSubst += mvec[i]->substituteValue(dest, tmpI,
2921 /*defsOnly*/ numSubst == 0,
2922 /*notDefsAndUses*/ numSubst > 0,
2923 someArgsWereIgnored);
2924 assert(!someArgsWereIgnored &&
2925 "Operand `dest' exists but not replaced: probably bogus!");
2927 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
2929 // Left shift 32-N if size (N) is less than 32 bits.
2930 // Use another tmp. virtual register to represent this result.
2932 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
2933 tmpI, NULL, "maskHi2");
2934 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
2935 .addZImm(8*(4-destSize))
2936 .addReg(srlArgToUse, MOTy::Def));
2939 // Logical right shift 32-N to get zero extension in top 64-N bits.
2940 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
2941 .addZImm(8*(4-destSize)).addReg(dest, MOTy::Def));
2943 } else if (destSize < 8) {
2944 assert(0 && "Unsupported type size: 32 < size < 64 bits");