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/iTerminators.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iOther.h"
22 #include "llvm/Function.h"
23 #include "llvm/Constants.h"
24 #include "llvm/ConstantHandling.h"
25 #include "llvm/Intrinsics.h"
26 #include "Support/MathExtras.h"
30 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
31 std::vector<MachineInstr*>& mvec) {
32 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
33 .addReg(Node->rightChild()->getValue())
34 .addRegDef(Node->getValue()));
39 //---------------------------------------------------------------------------
40 // Function: GetMemInstArgs
43 // Get the pointer value and the index vector for a memory operation
44 // (GetElementPtr, Load, or Store). If all indices of the given memory
45 // operation are constant, fold in constant indices in a chain of
46 // preceding GetElementPtr instructions (if any), and return the
47 // pointer value of the first instruction in the chain.
48 // All folded instructions are marked so no code is generated for them.
51 // Returns the pointer Value to use.
52 // Returns the resulting IndexVector in idxVec.
53 // Returns true/false in allConstantIndices if all indices are/aren't const.
54 //---------------------------------------------------------------------------
57 //---------------------------------------------------------------------------
58 // Function: FoldGetElemChain
61 // Fold a chain of GetElementPtr instructions containing only
62 // constant offsets into an equivalent (Pointer, IndexVector) pair.
63 // Returns the pointer Value, and stores the resulting IndexVector
64 // in argument chainIdxVec. This is a helper function for
65 // FoldConstantIndices that does the actual folding.
66 //---------------------------------------------------------------------------
69 // Check for a constant 0.
73 return (idx == ConstantSInt::getNullValue(idx->getType()));
77 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
78 bool lastInstHasLeadingNonZero)
80 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
81 GetElementPtrInst* gepInst =
82 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
84 // ptr value is not computed in this tree or ptr value does not come from GEP
89 // Return NULL if we don't fold any instructions in.
92 // Now chase the chain of getElementInstr instructions, if any.
93 // Check for any non-constant indices and stop there.
94 // Also, stop if the first index of child is a non-zero array index
95 // and the last index of the current node is a non-array index:
96 // in that case, a non-array declared type is being accessed as an array
97 // which is not type-safe, but could be legal.
99 InstructionNode* ptrChild = gepNode;
100 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
101 ptrChild->getOpLabel() == GetElemPtrIdx))
103 // Child is a GetElemPtr instruction
104 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
105 User::op_iterator OI, firstIdx = gepInst->idx_begin();
106 User::op_iterator lastIdx = gepInst->idx_end();
107 bool allConstantOffsets = true;
109 // The first index of every GEP must be an array index.
110 assert((*firstIdx)->getType() == Type::LongTy &&
111 "INTERNAL ERROR: Structure index for a pointer type!");
113 // If the last instruction had a leading non-zero index, check if the
114 // current one references a sequential (i.e., indexable) type.
115 // If not, the code is not type-safe and we would create an illegal GEP
116 // by folding them, so don't fold any more instructions.
118 if (lastInstHasLeadingNonZero)
119 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
120 break; // cannot fold in any preceding getElementPtr instrs.
122 // Check that all offsets are constant for this instruction
123 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
124 allConstantOffsets = isa<ConstantInt>(*OI);
126 if (allConstantOffsets) {
127 // Get pointer value out of ptrChild.
128 ptrVal = gepInst->getPointerOperand();
130 // Insert its index vector at the start, skipping any leading [0]
131 // Remember the old size to check if anything was inserted.
132 unsigned oldSize = chainIdxVec.size();
133 int firstIsZero = IsZero(*firstIdx);
134 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
136 // Remember if it has leading zero index: it will be discarded later.
137 if (oldSize < chainIdxVec.size())
138 lastInstHasLeadingNonZero = !firstIsZero;
140 // Mark the folded node so no code is generated for it.
141 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
143 // Get the previous GEP instruction and continue trying to fold
144 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
145 } else // cannot fold this getElementPtr instr. or any preceding ones
149 // If the first getElementPtr instruction had a leading [0], add it back.
150 // Note that this instruction is the *last* one that was successfully
151 // folded *and* contributed any indices, in the loop above.
153 if (ptrVal && ! lastInstHasLeadingNonZero)
154 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
160 //---------------------------------------------------------------------------
161 // Function: GetGEPInstArgs
164 // Helper function for GetMemInstArgs that handles the final getElementPtr
165 // instruction used by (or same as) the memory operation.
166 // Extracts the indices of the current instruction and tries to fold in
167 // preceding ones if all indices of the current one are constant.
168 //---------------------------------------------------------------------------
171 GetGEPInstArgs(InstructionNode* gepNode,
172 std::vector<Value*>& idxVec,
173 bool& allConstantIndices)
175 allConstantIndices = true;
176 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
178 // Default pointer is the one from the current instruction.
179 Value* ptrVal = gepI->getPointerOperand();
180 InstrTreeNode* ptrChild = gepNode->leftChild();
182 // Extract the index vector of the GEP instructin.
183 // If all indices are constant and first index is zero, try to fold
184 // in preceding GEPs with all constant indices.
185 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
186 allConstantIndices && OI != OE; ++OI)
187 if (! isa<Constant>(*OI))
188 allConstantIndices = false; // note: this also terminates loop!
190 // If we have only constant indices, fold chains of constant indices
191 // in this and any preceding GetElemPtr instructions.
192 bool foldedGEPs = false;
193 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
194 if (allConstantIndices)
195 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
200 // Append the index vector of the current instruction.
201 // Skip the leading [0] index if preceding GEPs were folded into this.
202 idxVec.insert(idxVec.end(),
203 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
209 //---------------------------------------------------------------------------
210 // Function: GetMemInstArgs
213 // Get the pointer value and the index vector for a memory operation
214 // (GetElementPtr, Load, or Store). If all indices of the given memory
215 // operation are constant, fold in constant indices in a chain of
216 // preceding GetElementPtr instructions (if any), and return the
217 // pointer value of the first instruction in the chain.
218 // All folded instructions are marked so no code is generated for them.
221 // Returns the pointer Value to use.
222 // Returns the resulting IndexVector in idxVec.
223 // Returns true/false in allConstantIndices if all indices are/aren't const.
224 //---------------------------------------------------------------------------
227 GetMemInstArgs(InstructionNode* memInstrNode,
228 std::vector<Value*>& idxVec,
229 bool& allConstantIndices)
231 allConstantIndices = false;
232 Instruction* memInst = memInstrNode->getInstruction();
233 assert(idxVec.size() == 0 && "Need empty vector to return indices");
235 // If there is a GetElemPtr instruction to fold in to this instr,
236 // it must be in the left child for Load and GetElemPtr, and in the
237 // right child for Store instructions.
238 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
239 ? memInstrNode->rightChild()
240 : memInstrNode->leftChild());
242 // Default pointer is the one from the current instruction.
243 Value* ptrVal = ptrChild->getValue();
245 // Find the "last" GetElemPtr instruction: this one or the immediate child.
246 // There will be none if this is a load or a store from a scalar pointer.
247 InstructionNode* gepNode = NULL;
248 if (isa<GetElementPtrInst>(memInst))
249 gepNode = memInstrNode;
250 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
251 // Child of load/store is a GEP and memInst is its only use.
252 // Use its indices and mark it as folded.
253 gepNode = cast<InstructionNode>(ptrChild);
254 gepNode->markFoldedIntoParent();
257 // If there are no indices, return the current pointer.
258 // Else extract the pointer from the GEP and fold the indices.
259 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
264 //************************ Internal Functions ******************************/
267 static inline MachineOpCode
268 ChooseBprInstruction(const InstructionNode* instrNode)
270 MachineOpCode opCode;
272 Instruction* setCCInstr =
273 ((InstructionNode*) instrNode->leftChild())->getInstruction();
275 switch(setCCInstr->getOpcode())
277 case Instruction::SetEQ: opCode = V9::BRZ; break;
278 case Instruction::SetNE: opCode = V9::BRNZ; break;
279 case Instruction::SetLE: opCode = V9::BRLEZ; break;
280 case Instruction::SetGE: opCode = V9::BRGEZ; break;
281 case Instruction::SetLT: opCode = V9::BRLZ; break;
282 case Instruction::SetGT: opCode = V9::BRGZ; break;
284 assert(0 && "Unrecognized VM instruction!");
285 opCode = V9::INVALID_OPCODE;
293 static inline MachineOpCode
294 ChooseBpccInstruction(const InstructionNode* instrNode,
295 const BinaryOperator* setCCInstr)
297 MachineOpCode opCode = V9::INVALID_OPCODE;
299 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
302 switch(setCCInstr->getOpcode())
304 case Instruction::SetEQ: opCode = V9::BE; break;
305 case Instruction::SetNE: opCode = V9::BNE; break;
306 case Instruction::SetLE: opCode = V9::BLE; break;
307 case Instruction::SetGE: opCode = V9::BGE; break;
308 case Instruction::SetLT: opCode = V9::BL; break;
309 case Instruction::SetGT: opCode = V9::BG; break;
311 assert(0 && "Unrecognized VM instruction!");
315 switch(setCCInstr->getOpcode())
317 case Instruction::SetEQ: opCode = V9::BE; break;
318 case Instruction::SetNE: opCode = V9::BNE; break;
319 case Instruction::SetLE: opCode = V9::BLEU; break;
320 case Instruction::SetGE: opCode = V9::BCC; break;
321 case Instruction::SetLT: opCode = V9::BCS; break;
322 case Instruction::SetGT: opCode = V9::BGU; break;
324 assert(0 && "Unrecognized VM instruction!");
332 static inline MachineOpCode
333 ChooseBFpccInstruction(const InstructionNode* instrNode,
334 const BinaryOperator* setCCInstr)
336 MachineOpCode opCode = V9::INVALID_OPCODE;
338 switch(setCCInstr->getOpcode())
340 case Instruction::SetEQ: opCode = V9::FBE; break;
341 case Instruction::SetNE: opCode = V9::FBNE; break;
342 case Instruction::SetLE: opCode = V9::FBLE; break;
343 case Instruction::SetGE: opCode = V9::FBGE; break;
344 case Instruction::SetLT: opCode = V9::FBL; break;
345 case Instruction::SetGT: opCode = V9::FBG; break;
347 assert(0 && "Unrecognized VM instruction!");
355 // Create a unique TmpInstruction for a boolean value,
356 // representing the CC register used by a branch on that value.
357 // For now, hack this using a little static cache of TmpInstructions.
358 // Eventually the entire BURG instruction selection should be put
359 // into a separate class that can hold such information.
360 // The static cache is not too bad because the memory for these
361 // TmpInstructions will be freed along with the rest of the Function anyway.
363 static TmpInstruction*
364 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType,
365 MachineCodeForInstruction& mcfi)
367 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
368 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
369 static const Function *lastFunction = 0;// Use to flush cache between funcs
371 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
373 if (lastFunction != F) {
375 boolToTmpCache.clear();
378 // Look for tmpI and create a new one otherwise. The new value is
379 // directly written to map using the ref returned by operator[].
380 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
382 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
388 static inline MachineOpCode
389 ChooseBccInstruction(const InstructionNode* instrNode,
390 const Type*& setCCType)
392 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
393 assert(setCCNode->getOpLabel() == SetCCOp);
394 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
395 setCCType = setCCInstr->getOperand(0)->getType();
397 if (setCCType->isFloatingPoint())
398 return ChooseBFpccInstruction(instrNode, setCCInstr);
400 return ChooseBpccInstruction(instrNode, setCCInstr);
404 // WARNING: since this function has only one caller, it always returns
405 // the opcode that expects an immediate and a register. If this function
406 // is ever used in cases where an opcode that takes two registers is required,
407 // then modify this function and use convertOpcodeFromRegToImm() where required.
409 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
410 // new cases of opcodes.
411 static inline MachineOpCode
412 ChooseMovFpcciInstruction(const InstructionNode* instrNode)
414 MachineOpCode opCode = V9::INVALID_OPCODE;
416 switch(instrNode->getInstruction()->getOpcode())
418 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
419 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
420 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
421 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
422 case Instruction::SetLT: opCode = V9::MOVFLi; break;
423 case Instruction::SetGT: opCode = V9::MOVFGi; break;
425 assert(0 && "Unrecognized VM instruction!");
433 // ChooseMovpcciForSetCC -- Choose a conditional-move instruction
434 // based on the type of SetCC operation.
436 // WARNING: since this function has only one caller, it always returns
437 // the opcode that expects an immediate and a register. If this function
438 // is ever used in cases where an opcode that takes two registers is required,
439 // then modify this function and use convertOpcodeFromRegToImm() where required.
441 // It will be necessary to expand convertOpcodeFromRegToImm() to handle the
442 // new cases of opcodes.
445 ChooseMovpcciForSetCC(const InstructionNode* instrNode)
447 MachineOpCode opCode = V9::INVALID_OPCODE;
449 const Type* opType = instrNode->leftChild()->getValue()->getType();
450 assert(opType->isIntegral() || isa<PointerType>(opType));
451 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
453 switch(instrNode->getInstruction()->getOpcode())
455 case Instruction::SetEQ: opCode = V9::MOVEi; break;
456 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
457 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
458 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
459 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
460 case Instruction::SetNE: opCode = V9::MOVNEi; break;
461 default: assert(0 && "Unrecognized LLVM instr!"); break;
468 // ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
469 // instruction based on the type of SetCC operation. These instructions
470 // compare a register with 0 and perform the move is the comparison is true.
472 // WARNING: like the previous function, this function it always returns
473 // the opcode that expects an immediate and a register. See above.
476 ChooseMovpregiForSetCC(const InstructionNode* instrNode)
478 MachineOpCode opCode = V9::INVALID_OPCODE;
480 switch(instrNode->getInstruction()->getOpcode())
482 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
483 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
484 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
485 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
486 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
487 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
488 default: assert(0 && "Unrecognized VM instr!"); break;
495 static inline MachineOpCode
496 ChooseConvertToFloatInstr(const TargetMachine& target,
497 OpLabel vopCode, const Type* opType)
499 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
500 "Unrecognized convert-to-float opcode!");
501 assert((opType->isIntegral() || opType->isFloatingPoint() ||
502 isa<PointerType>(opType))
503 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
505 MachineOpCode opCode = V9::INVALID_OPCODE;
507 unsigned opSize = target.getTargetData().getTypeSize(opType);
509 if (opType == Type::FloatTy)
510 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
511 else if (opType == Type::DoubleTy)
512 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
513 else if (opSize <= 4)
514 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
516 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
517 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
523 static inline MachineOpCode
524 ChooseConvertFPToIntInstr(const TargetMachine& target,
525 const Type* destType, const Type* opType)
527 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
528 && "This function should only be called for FLOAT or DOUBLE");
529 assert((destType->isIntegral() || isa<PointerType>(destType))
530 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
532 MachineOpCode opCode = V9::INVALID_OPCODE;
534 unsigned destSize = target.getTargetData().getTypeSize(destType);
536 if (destType == Type::UIntTy)
537 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
538 else if (destSize <= 4)
539 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
541 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
542 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
549 CreateConvertFPToIntInstr(const TargetMachine& target,
552 const Type* destType)
554 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
556 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
557 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
560 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
561 // The FP value must be converted to the dest type in an FP register,
562 // and the result is then copied from FP to int register via memory.
563 // SPARC does not have a float-to-uint conversion, only a float-to-int (fdtoi).
564 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
565 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
566 // Therefore, for converting an FP value to uint32_t, we first need to convert
567 // to uint64_t and then to uint32_t.
570 CreateCodeToConvertFloatToInt(const TargetMachine& target,
573 std::vector<MachineInstr*>& mvec,
574 MachineCodeForInstruction& mcfi)
576 Function* F = destI->getParent()->getParent();
578 // Create a temporary to represent the FP register into which the
579 // int value will placed after conversion. The type of this temporary
580 // depends on the type of FP register to use: single-prec for a 32-bit
581 // int or smaller; double-prec for a 64-bit int.
583 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
585 const Type* castDestType = destI->getType(); // type for the cast instr result
586 const Type* castDestRegType; // type for cast instruction result reg
587 TmpInstruction* destForCast; // dest for cast instruction
588 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
590 // For converting an FP value to uint32_t, we first need to convert to
591 // uint64_t and then to uint32_t, as explained above.
592 if (destI->getType() == Type::UIntTy) {
593 castDestType = Type::ULongTy; // use this instead of type of destI
594 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
595 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
596 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
599 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
600 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
603 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
604 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
607 // Create the fpreg-to-intreg copy code
608 target.getInstrInfo().CreateCodeToCopyFloatToInt(target, F, destForCast,
609 fpToIntCopyDest, mvec, mcfi);
611 // Create the uint64_t to uint32_t conversion, if needed
612 if (destI->getType() == Type::UIntTy)
613 target.getInstrInfo().
614 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
615 /*numLowBits*/ 32, mvec, mcfi);
619 static inline MachineOpCode
620 ChooseAddInstruction(const InstructionNode* instrNode)
622 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
626 static inline MachineInstr*
627 CreateMovFloatInstruction(const InstructionNode* instrNode,
628 const Type* resultType)
630 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
631 .addReg(instrNode->leftChild()->getValue())
632 .addRegDef(instrNode->getValue());
635 static inline MachineInstr*
636 CreateAddConstInstruction(const InstructionNode* instrNode)
638 MachineInstr* minstr = NULL;
640 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
641 assert(isa<Constant>(constOp));
643 // Cases worth optimizing are:
644 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
645 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
647 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
648 double dval = FPC->getValue();
650 minstr = CreateMovFloatInstruction(instrNode,
651 instrNode->getInstruction()->getType());
658 static inline MachineOpCode
659 ChooseSubInstructionByType(const Type* resultType)
661 MachineOpCode opCode = V9::INVALID_OPCODE;
663 if (resultType->isInteger() || isa<PointerType>(resultType)) {
666 switch(resultType->getPrimitiveID())
668 case Type::FloatTyID: opCode = V9::FSUBS; break;
669 case Type::DoubleTyID: opCode = V9::FSUBD; break;
670 default: assert(0 && "Invalid type for SUB instruction"); break;
678 static inline MachineInstr*
679 CreateSubConstInstruction(const InstructionNode* instrNode)
681 MachineInstr* minstr = NULL;
683 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
684 assert(isa<Constant>(constOp));
686 // Cases worth optimizing are:
687 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
688 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
690 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
691 double dval = FPC->getValue();
693 minstr = CreateMovFloatInstruction(instrNode,
694 instrNode->getInstruction()->getType());
701 static inline MachineOpCode
702 ChooseFcmpInstruction(const InstructionNode* instrNode)
704 MachineOpCode opCode = V9::INVALID_OPCODE;
706 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
707 switch(operand->getType()->getPrimitiveID()) {
708 case Type::FloatTyID: opCode = V9::FCMPS; break;
709 case Type::DoubleTyID: opCode = V9::FCMPD; break;
710 default: assert(0 && "Invalid type for FCMP instruction"); break;
717 // Assumes that leftArg and rightArg are both cast instructions.
720 BothFloatToDouble(const InstructionNode* instrNode)
722 InstrTreeNode* leftArg = instrNode->leftChild();
723 InstrTreeNode* rightArg = instrNode->rightChild();
724 InstrTreeNode* leftArgArg = leftArg->leftChild();
725 InstrTreeNode* rightArgArg = rightArg->leftChild();
726 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
728 // Check if both arguments are floats cast to double
729 return (leftArg->getValue()->getType() == Type::DoubleTy &&
730 leftArgArg->getValue()->getType() == Type::FloatTy &&
731 rightArgArg->getValue()->getType() == Type::FloatTy);
735 static inline MachineOpCode
736 ChooseMulInstructionByType(const Type* resultType)
738 MachineOpCode opCode = V9::INVALID_OPCODE;
740 if (resultType->isInteger())
743 switch(resultType->getPrimitiveID())
745 case Type::FloatTyID: opCode = V9::FMULS; break;
746 case Type::DoubleTyID: opCode = V9::FMULD; break;
747 default: assert(0 && "Invalid type for MUL instruction"); break;
755 static inline MachineInstr*
756 CreateIntNegInstruction(const TargetMachine& target,
759 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo().getZeroRegNum())
760 .addReg(vreg).addRegDef(vreg);
764 // Create instruction sequence for any shift operation.
765 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
766 // requires a second instruction for explicit sign-extension.
767 // Note that we only have to worry about a sign-bit appearing in the
768 // most significant bit of the operand after shifting (e.g., bit 32 of
769 // Int or bit 16 of Short), so we do not have to worry about results
770 // that are as large as a normal integer register.
773 CreateShiftInstructions(const TargetMachine& target,
775 MachineOpCode shiftOpCode,
777 Value* optArgVal2, /* Use optArgVal2 if not NULL */
778 unsigned optShiftNum, /* else use optShiftNum */
779 Instruction* destVal,
780 std::vector<MachineInstr*>& mvec,
781 MachineCodeForInstruction& mcfi)
783 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
784 "Large shift sizes unexpected, but can be handled below: "
785 "You need to check whether or not it fits in immed field below");
787 // If this is a logical left shift of a type smaller than the standard
788 // integer reg. size, we have to extend the sign-bit into upper bits
789 // of dest, so we need to put the result of the SLL into a temporary.
791 Value* shiftDest = destVal;
792 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
794 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
795 // put SLL result into a temporary
796 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
799 MachineInstr* M = (optArgVal2 != NULL)
800 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
801 .addReg(shiftDest, MOTy::Def)
802 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
803 .addReg(shiftDest, MOTy::Def);
806 if (shiftDest != destVal) {
807 // extend the sign-bit of the result into all upper bits of dest
808 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
809 target.getInstrInfo().
810 CreateSignExtensionInstructions(target, F, shiftDest, destVal,
811 8*opSize, mvec, mcfi);
816 // Does not create any instructions if we cannot exploit constant to
817 // create a cheaper instruction.
818 // This returns the approximate cost of the instructions generated,
819 // which is used to pick the cheapest when both operands are constant.
821 CreateMulConstInstruction(const TargetMachine &target, Function* F,
822 Value* lval, Value* rval, Instruction* destVal,
823 std::vector<MachineInstr*>& mvec,
824 MachineCodeForInstruction& mcfi)
826 /* Use max. multiply cost, viz., cost of MULX */
827 unsigned cost = target.getInstrInfo().minLatency(V9::MULXr);
828 unsigned firstNewInstr = mvec.size();
830 Value* constOp = rval;
831 if (! isa<Constant>(constOp))
834 // Cases worth optimizing are:
835 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
836 // (2) Multiply by 2^x for integer types: replace with Shift
838 const Type* resultType = destVal->getType();
840 if (resultType->isInteger() || isa<PointerType>(resultType)) {
842 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
843 constOp, constOp->getType(), isValidConst);
846 bool needNeg = false;
852 if (C == 0 || C == 1) {
853 cost = target.getInstrInfo().minLatency(V9::ADDr);
854 unsigned Zero = target.getRegInfo().getZeroRegNum();
857 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
859 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
861 } else if (isPowerOf2(C, pow)) {
862 unsigned opSize = target.getTargetData().getTypeSize(resultType);
863 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
864 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
865 destVal, mvec, mcfi);
868 if (mvec.size() > 0 && needNeg) {
869 // insert <reg = SUB 0, reg> after the instr to flip the sign
870 MachineInstr* M = CreateIntNegInstruction(target, destVal);
875 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
876 double dval = FPC->getValue();
877 if (fabs(dval) == 1) {
878 MachineOpCode opCode = (dval < 0)
879 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
880 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
881 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
886 if (firstNewInstr < mvec.size()) {
888 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
889 cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
896 // Does not create any instructions if we cannot exploit constant to
897 // create a cheaper instruction.
900 CreateCheapestMulConstInstruction(const TargetMachine &target,
902 Value* lval, Value* rval,
903 Instruction* destVal,
904 std::vector<MachineInstr*>& mvec,
905 MachineCodeForInstruction& mcfi)
908 if (isa<Constant>(lval) && isa<Constant>(rval)) {
909 // both operands are constant: evaluate and "set" in dest
910 Constant* P = ConstantFoldBinaryInstruction(Instruction::Mul,
911 cast<Constant>(lval),
912 cast<Constant>(rval));
913 target.getInstrInfo().CreateCodeToLoadConst(target,F,P,destVal,mvec,mcfi);
915 else if (isa<Constant>(rval)) // rval is constant, but not lval
916 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
917 else if (isa<Constant>(lval)) // lval is constant, but not rval
918 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
920 // else neither is constant
924 // Return NULL if we cannot exploit constant to create a cheaper instruction
926 CreateMulInstruction(const TargetMachine &target, Function* F,
927 Value* lval, Value* rval, Instruction* destVal,
928 std::vector<MachineInstr*>& mvec,
929 MachineCodeForInstruction& mcfi,
930 MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
932 unsigned L = mvec.size();
933 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
934 if (mvec.size() == L) {
935 // no instructions were added so create MUL reg, reg, reg.
936 // Use FSMULD if both operands are actually floats cast to doubles.
937 // Otherwise, use the default opcode for the appropriate type.
938 MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
940 : ChooseMulInstructionByType(destVal->getType()));
941 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
942 .addRegDef(destVal));
947 // Generate a divide instruction for Div or Rem.
948 // For Rem, this assumes that the operand type will be signed if the result
949 // type is signed. This is correct because they must have the same sign.
951 static inline MachineOpCode
952 ChooseDivInstruction(TargetMachine &target,
953 const InstructionNode* instrNode)
955 MachineOpCode opCode = V9::INVALID_OPCODE;
957 const Type* resultType = instrNode->getInstruction()->getType();
959 if (resultType->isInteger())
960 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
962 switch(resultType->getPrimitiveID())
964 case Type::FloatTyID: opCode = V9::FDIVS; break;
965 case Type::DoubleTyID: opCode = V9::FDIVD; break;
966 default: assert(0 && "Invalid type for DIV instruction"); break;
973 // Return if we cannot exploit constant to create a cheaper instruction
975 CreateDivConstInstruction(TargetMachine &target,
976 const InstructionNode* instrNode,
977 std::vector<MachineInstr*>& mvec)
979 Value* LHS = instrNode->leftChild()->getValue();
980 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
981 if (!isa<Constant>(constOp))
984 Instruction* destVal = instrNode->getInstruction();
985 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
987 // Cases worth optimizing are:
988 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
989 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
991 const Type* resultType = instrNode->getInstruction()->getType();
993 if (resultType->isInteger()) {
996 int64_t C = (int64_t) target.getInstrInfo().ConvertConstantToIntType(target,
997 constOp, constOp->getType(), isValidConst);
999 bool needNeg = false;
1006 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
1007 .addRegDef(destVal));
1008 } else if (isPowerOf2(C, pow)) {
1010 Value* shiftOperand;
1011 unsigned opSize = target.getTargetData().getTypeSize(resultType);
1013 if (resultType->isSigned()) {
1014 // For N / 2^k, if the operand N is negative,
1015 // we need to add (2^k - 1) before right-shifting by k, i.e.,
1017 // (N / 2^k) = N >> k, if N >= 0;
1018 // (N + 2^k - 1) >> k, if N < 0
1020 // If N is <= 32 bits, use:
1021 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
1022 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1023 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1024 // sra t3, k, result // result = N / 2^k
1026 // If N is 64 bits, use:
1027 // srax N, k-1, t1 // t1 = sign bit in high k positions
1028 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
1029 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
1030 // sra t3, k, result // result = N / 2^k
1032 TmpInstruction *sraTmp, *srlTmp, *addTmp;
1033 MachineCodeForInstruction& mcfi
1034 = MachineCodeForInstruction::get(destVal);
1035 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
1036 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
1037 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
1039 // Create the SRA or SRAX instruction to get the sign bit
1040 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
1042 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
1043 .addRegDef(sraTmp));
1045 // Create the SRL or SRLX instruction to get the sign bit
1046 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
1048 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
1049 .addRegDef(srlTmp));
1051 // Create the ADD instruction to add 2^pow-1 for negative values
1052 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
1053 .addRegDef(addTmp));
1055 // Get the shift operand and "right-shift" opcode to do the divide
1056 shiftOperand = addTmp;
1057 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
1059 // Get the shift operand and "right-shift" opcode to do the divide
1061 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
1064 // Now do the actual shift!
1065 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
1066 .addRegDef(destVal));
1069 if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
1070 // insert <reg = SUB 0, reg> after the instr to flip the sign
1071 mvec.push_back(CreateIntNegInstruction(target, destVal));
1075 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
1076 double dval = FPC->getValue();
1077 if (fabs(dval) == 1) {
1079 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
1080 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
1082 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
1090 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
1091 Instruction* result,
1093 Value* numElementsVal,
1094 std::vector<MachineInstr*>& getMvec)
1096 Value* totalSizeVal;
1098 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
1099 Function *F = result->getParent()->getParent();
1101 // Enforce the alignment constraints on the stack pointer at
1102 // compile time if the total size is a known constant.
1103 if (isa<Constant>(numElementsVal)) {
1105 int64_t numElem = (int64_t) target.getInstrInfo().
1106 ConvertConstantToIntType(target, numElementsVal,
1107 numElementsVal->getType(), isValid);
1108 assert(isValid && "Unexpectedly large array dimension in alloca!");
1109 int64_t total = numElem * tsize;
1110 if (int extra= total % target.getFrameInfo().getStackFrameSizeAlignment())
1111 total += target.getFrameInfo().getStackFrameSizeAlignment() - extra;
1112 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
1114 // The size is not a constant. Generate code to compute it and
1115 // code to pad the size for stack alignment.
1116 // Create a Value to hold the (constant) element size
1117 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
1119 // Create temporary values to hold the result of MUL, SLL, SRL
1120 // To pad `size' to next smallest multiple of 16:
1121 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
1123 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
1124 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
1125 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
1127 // Instruction 1: mul numElements, typeSize -> tmpProd
1128 // This will optimize the MUL as far as possible.
1129 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
1130 mcfi, INVALID_MACHINE_OPCODE);
1132 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
1133 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
1134 .addReg(tmpAdd15, MOTy::Def));
1136 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
1137 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
1138 .addReg(tmpAndf0, MOTy::Def));
1140 totalSizeVal = tmpAndf0;
1143 // Get the constant offset from SP for dynamically allocated storage
1144 // and create a temporary Value to hold it.
1145 MachineFunction& mcInfo = MachineFunction::get(F);
1147 ConstantSInt* dynamicAreaOffset =
1148 ConstantSInt::get(Type::IntTy,
1149 target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
1150 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
1152 unsigned SPReg = target.getRegInfo().getStackPointer();
1154 // Instruction 2: sub %sp, totalSizeVal -> %sp
1155 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
1156 .addMReg(SPReg,MOTy::Def));
1158 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
1159 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
1160 .addRegDef(result));
1165 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
1166 Instruction* result,
1168 unsigned numElements,
1169 std::vector<MachineInstr*>& getMvec)
1171 assert(tsize > 0 && "Illegal (zero) type size for alloca");
1172 assert(result && result->getParent() &&
1173 "Result value is not part of a function?");
1174 Function *F = result->getParent()->getParent();
1175 MachineFunction &mcInfo = MachineFunction::get(F);
1177 // Put the variable in the dynamically sized area of the frame if either:
1178 // (a) The offset is too large to use as an immediate in load/stores
1179 // (check LDX because all load/stores have the same-size immed. field).
1180 // (b) The object is "large", so it could cause many other locals,
1181 // spills, and temporaries to have large offsets.
1182 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
1183 // You've gotta love having only 13 bits for constant offset values :-|.
1185 unsigned paddedSize;
1186 int offsetFromFP = mcInfo.getInfo()->computeOffsetforLocalVar(result,
1188 tsize * numElements);
1190 if (((int)paddedSize) > 8 * target.getFrameInfo().getSizeOfEachArgOnStack() ||
1191 ! target.getInstrInfo().constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
1192 CreateCodeForVariableSizeAlloca(target, result, tsize,
1193 ConstantSInt::get(Type::IntTy,numElements),
1198 // else offset fits in immediate field so go ahead and allocate it.
1199 offsetFromFP = mcInfo.getInfo()->allocateLocalVar(result, tsize *numElements);
1201 // Create a temporary Value to hold the constant offset.
1202 // This is needed because it may not fit in the immediate field.
1203 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
1205 // Instruction 1: add %fp, offsetFromFP -> result
1206 unsigned FPReg = target.getRegInfo().getFramePointer();
1207 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
1208 .addRegDef(result));
1212 //------------------------------------------------------------------------
1213 // Function SetOperandsForMemInstr
1215 // Choose addressing mode for the given load or store instruction.
1216 // Use [reg+reg] if it is an indexed reference, and the index offset is
1217 // not a constant or if it cannot fit in the offset field.
1218 // Use [reg+offset] in all other cases.
1220 // This assumes that all array refs are "lowered" to one of these forms:
1221 // %x = load (subarray*) ptr, constant ; single constant offset
1222 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
1223 // Generally, this should happen via strength reduction + LICM.
1224 // Also, strength reduction should take care of using the same register for
1225 // the loop index variable and an array index, when that is profitable.
1226 //------------------------------------------------------------------------
1229 SetOperandsForMemInstr(unsigned Opcode,
1230 std::vector<MachineInstr*>& mvec,
1231 InstructionNode* vmInstrNode,
1232 const TargetMachine& target)
1234 Instruction* memInst = vmInstrNode->getInstruction();
1235 // Index vector, ptr value, and flag if all indices are const.
1236 std::vector<Value*> idxVec;
1237 bool allConstantIndices;
1238 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
1240 // Now create the appropriate operands for the machine instruction.
1241 // First, initialize so we default to storing the offset in a register.
1242 int64_t smallConstOffset = 0;
1243 Value* valueForRegOffset = NULL;
1244 MachineOperand::MachineOperandType offsetOpType =
1245 MachineOperand::MO_VirtualRegister;
1247 // Check if there is an index vector and if so, compute the
1248 // right offset for structures and for arrays
1250 if (!idxVec.empty()) {
1251 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1253 // If all indices are constant, compute the combined offset directly.
1254 if (allConstantIndices) {
1255 // Compute the offset value using the index vector. Create a
1256 // virtual reg. for it since it may not fit in the immed field.
1257 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
1258 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1260 // There is at least one non-constant offset. Therefore, this must
1261 // be an array ref, and must have been lowered to a single non-zero
1262 // offset. (An extra leading zero offset, if any, can be ignored.)
1263 // Generate code sequence to compute address from index.
1265 bool firstIdxIsZero = IsZero(idxVec[0]);
1266 assert(idxVec.size() == 1U + firstIdxIsZero
1267 && "Array refs must be lowered before Instruction Selection");
1269 Value* idxVal = idxVec[firstIdxIsZero];
1271 std::vector<MachineInstr*> mulVec;
1273 new TmpInstruction(MachineCodeForInstruction::get(memInst),
1274 Type::ULongTy, memInst);
1276 // Get the array type indexed by idxVal, and compute its element size.
1277 // The call to getTypeSize() will fail if size is not constant.
1278 const Type* vecType = (firstIdxIsZero
1279 ? GetElementPtrInst::getIndexedType(ptrType,
1280 std::vector<Value*>(1U, idxVec[0]),
1281 /*AllowCompositeLeaf*/ true)
1283 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1284 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
1285 target.getTargetData().getTypeSize(eltType));
1287 // CreateMulInstruction() folds constants intelligently enough.
1288 CreateMulInstruction(target, memInst->getParent()->getParent(),
1289 idxVal, /* lval, not likely to be const*/
1290 eltSizeVal, /* rval, likely to be constant */
1292 mulVec, MachineCodeForInstruction::get(memInst),
1293 INVALID_MACHINE_OPCODE);
1295 assert(mulVec.size() > 0 && "No multiply code created?");
1296 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
1298 valueForRegOffset = addr;
1301 offsetOpType = MachineOperand::MO_SignExtendedImmed;
1302 smallConstOffset = 0;
1306 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
1307 // For LOAD or GET_ELEMENT_PTR,
1308 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1310 unsigned offsetOpNum, ptrOpNum;
1312 if (memInst->getOpcode() == Instruction::Store) {
1313 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1314 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1315 .addReg(ptrVal).addReg(valueForRegOffset);
1317 Opcode = convertOpcodeFromRegToImm(Opcode);
1318 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
1319 .addReg(ptrVal).addSImm(smallConstOffset);
1322 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
1323 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
1324 .addRegDef(memInst);
1326 Opcode = convertOpcodeFromRegToImm(Opcode);
1327 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
1328 .addRegDef(memInst);
1336 // Substitute operand `operandNum' of the instruction in node `treeNode'
1337 // in place of the use(s) of that instruction in node `parent'.
1338 // Check both explicit and implicit operands!
1339 // Also make sure to skip over a parent who:
1340 // (1) is a list node in the Burg tree, or
1341 // (2) itself had its results forwarded to its parent
1344 ForwardOperand(InstructionNode* treeNode,
1345 InstrTreeNode* parent,
1348 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1350 Instruction* unusedOp = treeNode->getInstruction();
1351 Value* fwdOp = unusedOp->getOperand(operandNum);
1353 // The parent itself may be a list node, so find the real parent instruction
1354 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1356 parent = parent->parent();
1357 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1359 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1361 Instruction* userInstr = parentInstrNode->getInstruction();
1362 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1364 // The parent's mvec would be empty if it was itself forwarded.
1365 // Recursively call ForwardOperand in that case...
1367 if (mvec.size() == 0) {
1368 assert(parent->parent() != NULL &&
1369 "Parent could not have been forwarded, yet has no instructions?");
1370 ForwardOperand(treeNode, parent->parent(), operandNum);
1372 for (unsigned i=0, N=mvec.size(); i < N; i++) {
1373 MachineInstr* minstr = mvec[i];
1374 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
1375 const MachineOperand& mop = minstr->getOperand(i);
1376 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
1377 mop.getVRegValue() == unusedOp)
1379 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
1384 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1385 if (minstr->getImplicitRef(i) == unusedOp)
1386 minstr->setImplicitRef(i, fwdOp);
1393 AllUsesAreBranches(const Instruction* setccI)
1395 for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1397 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
1398 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1403 // Generate code for any intrinsic that needs a special code sequence
1404 // instead of a regular call. If not that kind of intrinsic, do nothing.
1405 // Returns true if code was generated, otherwise false.
1407 bool CodeGenIntrinsic(LLVMIntrinsic::ID iid, CallInst &callInstr,
1408 TargetMachine &target,
1409 std::vector<MachineInstr*>& mvec)
1412 case LLVMIntrinsic::va_start: {
1413 // Get the address of the first vararg value on stack and copy it to
1414 // the argument of va_start(va_list* ap).
1416 Function* func = cast<Function>(callInstr.getParent()->getParent());
1417 int numFixedArgs = func->getFunctionType()->getNumParams();
1418 int fpReg = target.getFrameInfo().getIncomingArgBaseRegNum();
1419 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
1420 int firstVarArgOff = numFixedArgs * argSize + target.getFrameInfo().
1421 getFirstIncomingArgOffset(MachineFunction::get(func), ignore);
1422 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
1423 addReg(callInstr.getOperand(1)));
1427 case LLVMIntrinsic::va_end:
1428 return true; // no-op on Sparc
1430 case LLVMIntrinsic::va_copy:
1431 // Simple copy of current va_list (arg2) to new va_list (arg1)
1432 mvec.push_back(BuildMI(V9::ORr, 3).
1433 addMReg(target.getRegInfo().getZeroRegNum()).
1434 addReg(callInstr.getOperand(2)).
1435 addReg(callInstr.getOperand(1)));
1443 //******************* Externally Visible Functions *************************/
1445 //------------------------------------------------------------------------
1446 // External Function: ThisIsAChainRule
1449 // Check if a given BURG rule is a chain rule.
1450 //------------------------------------------------------------------------
1453 ThisIsAChainRule(int eruleno)
1457 case 111: // stmt: reg
1481 return false; break;
1486 //------------------------------------------------------------------------
1487 // External Function: GetInstructionsByRule
1490 // Choose machine instructions for the SPARC according to the
1491 // patterns chosen by the BURG-generated parser.
1492 //------------------------------------------------------------------------
1495 GetInstructionsByRule(InstructionNode* subtreeRoot,
1498 TargetMachine &target,
1499 std::vector<MachineInstr*>& mvec)
1501 bool checkCast = false; // initialize here to use fall-through
1502 bool maskUnsignedResult = false;
1504 int forwardOperandNum = -1;
1505 unsigned allocaSize = 0;
1506 MachineInstr* M, *M2;
1508 bool foldCase = false;
1512 // If the code for this instruction was folded into the parent (user),
1514 if (subtreeRoot->isFoldedIntoParent())
1518 // Let's check for chain rules outside the switch so that we don't have
1519 // to duplicate the list of chain rule production numbers here again
1521 if (ThisIsAChainRule(ruleForNode))
1523 // Chain rules have a single nonterminal on the RHS.
1524 // Get the rule that matches the RHS non-terminal and use that instead.
1526 assert(nts[0] && ! nts[1]
1527 && "A chain rule should have only one RHS non-terminal!");
1528 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1529 nts = burm_nts[nextRule];
1530 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1534 switch(ruleForNode) {
1535 case 1: // stmt: Ret
1536 case 2: // stmt: RetValue(reg)
1537 { // NOTE: Prepass of register allocation is responsible
1538 // for moving return value to appropriate register.
1539 // Copy the return value to the required return register.
1540 // Mark the return Value as an implicit ref of the RET instr..
1541 // Mark the return-address register as a hidden virtual reg.
1542 // Finally put a NOP in the delay slot.
1543 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
1544 Value* retVal = returnInstr->getReturnValue();
1545 MachineCodeForInstruction& mcfi =
1546 MachineCodeForInstruction::get(returnInstr);
1548 // Create a hidden virtual reg to represent the return address register
1549 // used by the machine instruction but not represented in LLVM.
1551 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
1553 MachineInstr* retMI =
1554 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
1555 .addMReg(target.getRegInfo().getZeroRegNum(), MOTy::Def);
1557 // If there is a value to return, we need to:
1558 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
1559 // (b) Insert a copy to copy the return value to the appropriate reg.
1560 // -- For FP values, create a FMOVS or FMOVD instruction
1561 // -- For non-FP values, create an add-with-0 instruction
1563 if (retVal != NULL) {
1564 const UltraSparcRegInfo& regInfo =
1565 (UltraSparcRegInfo&) target.getRegInfo();
1566 const Type* retType = retVal->getType();
1567 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
1568 unsigned retRegNum = (retType->isFloatingPoint()
1569 ? (unsigned) SparcFloatRegClass::f0
1570 : (unsigned) SparcIntRegClass::i0);
1571 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
1573 // () Insert sign-extension instructions for small signed values.
1575 Value* retValToUse = retVal;
1576 if (retType->isIntegral() && retType->isSigned()) {
1577 unsigned retSize = target.getTargetData().getTypeSize(retType);
1579 // create a temporary virtual reg. to hold the sign-extension
1580 retValToUse = new TmpInstruction(mcfi, retVal);
1582 // sign-extend retVal and put the result in the temporary reg.
1583 target.getInstrInfo().CreateSignExtensionInstructions
1584 (target, returnInstr->getParent()->getParent(),
1585 retVal, retValToUse, 8*retSize, mvec, mcfi);
1589 // (b) Now, insert a copy to to the appropriate register:
1590 // -- For FP values, create a FMOVS or FMOVD instruction
1591 // -- For non-FP values, create an add-with-0 instruction
1593 // First, create a virtual register to represent the register and
1594 // mark this vreg as being an implicit operand of the ret MI.
1595 TmpInstruction* retVReg =
1596 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
1598 retMI->addImplicitRef(retVReg);
1600 if (retType->isFloatingPoint())
1601 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1602 .addReg(retValToUse).addReg(retVReg, MOTy::Def));
1604 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
1605 .addReg(retValToUse).addSImm((int64_t) 0)
1606 .addReg(retVReg, MOTy::Def));
1608 // Mark the operand with the register it should be assigned
1609 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
1610 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
1615 // Now insert the RET instruction and a NOP for the delay slot
1616 mvec.push_back(retMI);
1617 mvec.push_back(BuildMI(V9::NOP, 0));
1622 case 3: // stmt: Store(reg,reg)
1623 case 4: // stmt: Store(reg,ptrreg)
1624 SetOperandsForMemInstr(ChooseStoreInstruction(
1625 subtreeRoot->leftChild()->getValue()->getType()),
1626 mvec, subtreeRoot, target);
1629 case 5: // stmt: BrUncond
1631 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1632 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
1635 mvec.push_back(BuildMI(V9::NOP, 0));
1639 case 206: // stmt: BrCond(setCCconst)
1640 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1641 // If the constant is ZERO, we can use the branch-on-integer-register
1642 // instructions and avoid the SUBcc instruction entirely.
1643 // Otherwise this is just the same as case 5, so just fall through.
1645 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1647 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1648 Constant *constVal = cast<Constant>(constNode->getValue());
1651 if ((constVal->getType()->isInteger()
1652 || isa<PointerType>(constVal->getType()))
1653 && target.getInstrInfo().ConvertConstantToIntType(target,
1654 constVal, constVal->getType(), isValidConst) == 0
1657 // That constant is a zero after all...
1658 // Use the left child of setCC as the first argument!
1659 // Mark the setCC node so that no code is generated for it.
1660 InstructionNode* setCCNode = (InstructionNode*)
1661 subtreeRoot->leftChild();
1662 assert(setCCNode->getOpLabel() == SetCCOp);
1663 setCCNode->markFoldedIntoParent();
1665 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1667 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
1668 .addReg(setCCNode->leftChild()->getValue())
1669 .addPCDisp(brInst->getSuccessor(0));
1673 mvec.push_back(BuildMI(V9::NOP, 0));
1676 mvec.push_back(BuildMI(V9::BA, 1)
1677 .addPCDisp(brInst->getSuccessor(1)));
1680 mvec.push_back(BuildMI(V9::NOP, 0));
1683 // ELSE FALL THROUGH
1686 case 6: // stmt: BrCond(setCC)
1687 { // bool => boolean was computed with SetCC.
1688 // The branch to use depends on whether it is FP, signed, or unsigned.
1689 // If it is an integer CC, we also need to find the unique
1690 // TmpInstruction representing that CC.
1692 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1693 const Type* setCCType;
1694 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
1695 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1696 brInst->getParent()->getParent(),
1698 MachineCodeForInstruction::get(brInst));
1699 M = BuildMI(Opcode, 2).addCCReg(ccValue)
1700 .addPCDisp(brInst->getSuccessor(0));
1704 mvec.push_back(BuildMI(V9::NOP, 0));
1707 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
1710 mvec.push_back(BuildMI(V9::NOP, 0));
1714 case 208: // stmt: BrCond(boolconst)
1716 // boolconst => boolean is a constant; use BA to first or second label
1717 Constant* constVal =
1718 cast<Constant>(subtreeRoot->leftChild()->getValue());
1719 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1721 M = BuildMI(V9::BA, 1).addPCDisp(
1722 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1726 mvec.push_back(BuildMI(V9::NOP, 0));
1730 case 8: // stmt: BrCond(boolreg)
1731 { // boolreg => boolean is recorded in an integer register.
1732 // Use branch-on-integer-register instruction.
1734 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
1735 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
1736 .addPCDisp(BI->getSuccessor(0));
1740 mvec.push_back(BuildMI(V9::NOP, 0));
1743 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
1746 mvec.push_back(BuildMI(V9::NOP, 0));
1750 case 9: // stmt: Switch(reg)
1751 assert(0 && "*** SWITCH instruction is not implemented yet.");
1754 case 10: // reg: VRegList(reg, reg)
1755 assert(0 && "VRegList should never be the topmost non-chain rule");
1758 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
1759 { // First find the unary operand. It may be left or right, usually right.
1760 Instruction* notI = subtreeRoot->getInstruction();
1761 Value* notArg = BinaryOperator::getNotArgument(
1762 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1763 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1765 // Unconditionally set register to 0
1766 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
1768 // Now conditionally move 1 into the register.
1769 // Mark the register as a use (as well as a def) because the old
1770 // value will be retained if the condition is false.
1771 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
1772 .addReg(notI, MOTy::UseAndDef));
1777 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
1778 { // First find the unary operand. It may be left or right, usually right.
1779 Value* notArg = BinaryOperator::getNotArgument(
1780 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1781 unsigned ZeroReg = target.getRegInfo().getZeroRegNum();
1782 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
1783 .addRegDef(subtreeRoot->getValue()));
1787 case 322: // reg: Not(tobool, reg):
1788 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
1790 // Just fall through!
1792 case 22: // reg: ToBoolTy(reg):
1794 Instruction* castI = subtreeRoot->getInstruction();
1795 Value* opVal = subtreeRoot->leftChild()->getValue();
1796 assert(opVal->getType()->isIntegral() ||
1797 isa<PointerType>(opVal->getType()));
1799 // Unconditionally set register to 0
1800 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
1802 // Now conditionally move 1 into the register.
1803 // Mark the register as a use (as well as a def) because the old
1804 // value will be retained if the condition is false.
1805 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
1806 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
1807 .addReg(castI, MOTy::UseAndDef));
1812 case 23: // reg: ToUByteTy(reg)
1813 case 24: // reg: ToSByteTy(reg)
1814 case 25: // reg: ToUShortTy(reg)
1815 case 26: // reg: ToShortTy(reg)
1816 case 27: // reg: ToUIntTy(reg)
1817 case 28: // reg: ToIntTy(reg)
1818 case 29: // reg: ToULongTy(reg)
1819 case 30: // reg: ToLongTy(reg)
1821 //======================================================================
1822 // Rules for integer conversions:
1825 // From ISO 1998 C++ Standard, Sec. 4.7:
1827 // 2. If the destination type is unsigned, the resulting value is
1828 // the least unsigned integer congruent to the source integer
1829 // (modulo 2n where n is the number of bits used to represent the
1830 // unsigned type). [Note: In a two s complement representation,
1831 // this conversion is conceptual and there is no change in the
1832 // bit pattern (if there is no truncation). ]
1834 // 3. If the destination type is signed, the value is unchanged if
1835 // it can be represented in the destination type (and bitfield width);
1836 // otherwise, the value is implementation-defined.
1839 // Since we assume 2s complement representations, this implies:
1841 // -- If operand is smaller than destination, zero-extend or sign-extend
1842 // according to the signedness of the *operand*: source decides:
1843 // (1) If operand is signed, sign-extend it.
1844 // If dest is unsigned, zero-ext the result!
1845 // (2) If operand is unsigned, our current invariant is that
1846 // it's high bits are correct, so zero-extension is not needed.
1848 // -- If operand is same size as or larger than destination,
1849 // zero-extend or sign-extend according to the signedness of
1850 // the *destination*: destination decides:
1851 // (1) If destination is signed, sign-extend (truncating if needed)
1852 // This choice is implementation defined. We sign-extend the
1853 // operand, which matches both Sun's cc and gcc3.2.
1854 // (2) If destination is unsigned, zero-extend (truncating if needed)
1855 //======================================================================
1857 Instruction* destI = subtreeRoot->getInstruction();
1858 Function* currentFunc = destI->getParent()->getParent();
1859 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
1861 Value* opVal = subtreeRoot->leftChild()->getValue();
1862 const Type* opType = opVal->getType();
1863 const Type* destType = destI->getType();
1864 unsigned opSize = target.getTargetData().getTypeSize(opType);
1865 unsigned destSize = target.getTargetData().getTypeSize(destType);
1867 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
1869 if (opType == Type::BoolTy ||
1870 opType == destType ||
1871 isIntegral && opSize == destSize && opSize == 8) {
1872 // nothing to do in all these cases
1873 forwardOperandNum = 0; // forward first operand to user
1875 } else if (opType->isFloatingPoint()) {
1877 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1878 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
1879 maskUnsignedResult = true; // not handled by fp->int code
1881 } else if (isIntegral) {
1883 bool opSigned = opType->isSigned();
1884 bool destSigned = destType->isSigned();
1885 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
1887 assert(! (opSize == destSize && opSigned == destSigned) &&
1888 "How can different int types have same size and signedness?");
1890 bool signExtend = (opSize < destSize && opSigned ||
1891 opSize >= destSize && destSigned);
1893 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
1894 opSigned && !destSigned);
1895 assert(!signAndZeroExtend || signExtend);
1897 bool zeroExtendOnly = opSize >= destSize && !destSigned;
1898 assert(!zeroExtendOnly || !signExtend);
1901 Value* signExtDest = (signAndZeroExtend
1902 ? new TmpInstruction(mcfi, destType, opVal)
1905 target.getInstrInfo().CreateSignExtensionInstructions
1906 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
1908 if (signAndZeroExtend)
1909 target.getInstrInfo().CreateZeroExtensionInstructions
1910 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
1912 else if (zeroExtendOnly) {
1913 target.getInstrInfo().CreateZeroExtensionInstructions
1914 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
1917 forwardOperandNum = 0; // forward first operand to user
1920 assert(0 && "Unrecognized operand type for convert-to-integer");
1925 case 31: // reg: ToFloatTy(reg):
1926 case 32: // reg: ToDoubleTy(reg):
1927 case 232: // reg: ToDoubleTy(Constant):
1929 // If this instruction has a parent (a user) in the tree
1930 // and the user is translated as an FsMULd instruction,
1931 // then the cast is unnecessary. So check that first.
1932 // In the future, we'll want to do the same for the FdMULq instruction,
1933 // so do the check here instead of only for ToFloatTy(reg).
1935 if (subtreeRoot->parent() != NULL) {
1936 const MachineCodeForInstruction& mcfi =
1937 MachineCodeForInstruction::get(
1938 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1939 if (mcfi.size() == 0 || mcfi.front()->getOpCode() == V9::FSMULD)
1940 forwardOperandNum = 0; // forward first operand to user
1943 if (forwardOperandNum != 0) { // we do need the cast
1944 Value* leftVal = subtreeRoot->leftChild()->getValue();
1945 const Type* opType = leftVal->getType();
1946 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
1947 subtreeRoot->getOpLabel(), opType);
1948 if (opCode == V9::NOP) { // no conversion needed
1949 forwardOperandNum = 0; // forward first operand to user
1951 // If the source operand is a non-FP type it must be
1952 // first copied from int to float register via memory!
1953 Instruction *dest = subtreeRoot->getInstruction();
1956 if (! opType->isFloatingPoint()) {
1957 // Create a temporary to represent the FP register
1958 // into which the integer will be copied via memory.
1959 // The type of this temporary will determine the FP
1960 // register used: single-prec for a 32-bit int or smaller,
1961 // double-prec for a 64-bit int.
1964 target.getTargetData().getTypeSize(leftVal->getType());
1965 Type* tmpTypeToUse =
1966 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1967 MachineCodeForInstruction &destMCFI =
1968 MachineCodeForInstruction::get(dest);
1969 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
1971 target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
1972 dest->getParent()->getParent(),
1973 leftVal, cast<Instruction>(srcForCast),
1976 srcForCast = leftVal;
1978 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
1984 case 19: // reg: ToArrayTy(reg):
1985 case 20: // reg: ToPointerTy(reg):
1986 forwardOperandNum = 0; // forward first operand to user
1989 case 233: // reg: Add(reg, Constant)
1990 maskUnsignedResult = true;
1991 M = CreateAddConstInstruction(subtreeRoot);
1996 // ELSE FALL THROUGH
1998 case 33: // reg: Add(reg, reg)
1999 maskUnsignedResult = true;
2000 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
2003 case 234: // reg: Sub(reg, Constant)
2004 maskUnsignedResult = true;
2005 M = CreateSubConstInstruction(subtreeRoot);
2010 // ELSE FALL THROUGH
2012 case 34: // reg: Sub(reg, reg)
2013 maskUnsignedResult = true;
2014 Add3OperandInstr(ChooseSubInstructionByType(
2015 subtreeRoot->getInstruction()->getType()),
2019 case 135: // reg: Mul(todouble, todouble)
2023 case 35: // reg: Mul(reg, reg)
2025 maskUnsignedResult = true;
2026 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2028 : INVALID_MACHINE_OPCODE);
2029 Instruction* mulInstr = subtreeRoot->getInstruction();
2030 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2031 subtreeRoot->leftChild()->getValue(),
2032 subtreeRoot->rightChild()->getValue(),
2034 MachineCodeForInstruction::get(mulInstr),forceOp);
2037 case 335: // reg: Mul(todouble, todoubleConst)
2041 case 235: // reg: Mul(reg, Constant)
2043 maskUnsignedResult = true;
2044 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
2046 : INVALID_MACHINE_OPCODE);
2047 Instruction* mulInstr = subtreeRoot->getInstruction();
2048 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
2049 subtreeRoot->leftChild()->getValue(),
2050 subtreeRoot->rightChild()->getValue(),
2052 MachineCodeForInstruction::get(mulInstr),
2056 case 236: // reg: Div(reg, Constant)
2057 maskUnsignedResult = true;
2059 CreateDivConstInstruction(target, subtreeRoot, mvec);
2060 if (mvec.size() > L)
2062 // ELSE FALL THROUGH
2064 case 36: // reg: Div(reg, reg)
2066 maskUnsignedResult = true;
2068 // If either operand of divide is smaller than 64 bits, we have
2069 // to make sure the unused top bits are correct because they affect
2070 // the result. These bits are already correct for unsigned values.
2071 // They may be incorrect for signed values, so sign extend to fill in.
2072 Instruction* divI = subtreeRoot->getInstruction();
2073 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2074 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2075 Value* divOp1ToUse = divOp1;
2076 Value* divOp2ToUse = divOp2;
2077 if (divI->getType()->isSigned()) {
2078 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
2080 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
2081 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
2082 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
2083 target.getInstrInfo().
2084 CreateSignExtensionInstructions(target,
2085 divI->getParent()->getParent(),
2086 divOp1, divOp1ToUse,
2087 8*opSize, mvec, mcfi);
2088 target.getInstrInfo().
2089 CreateSignExtensionInstructions(target,
2090 divI->getParent()->getParent(),
2091 divOp2, divOp2ToUse,
2092 8*opSize, mvec, mcfi);
2096 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2097 .addReg(divOp1ToUse)
2098 .addReg(divOp2ToUse)
2104 case 37: // reg: Rem(reg, reg)
2105 case 237: // reg: Rem(reg, Constant)
2107 maskUnsignedResult = true;
2109 Instruction* remI = subtreeRoot->getInstruction();
2110 Value* divOp1 = subtreeRoot->leftChild()->getValue();
2111 Value* divOp2 = subtreeRoot->rightChild()->getValue();
2113 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
2115 // If second operand of divide is smaller than 64 bits, we have
2116 // to make sure the unused top bits are correct because they affect
2117 // the result. These bits are already correct for unsigned values.
2118 // They may be incorrect for signed values, so sign extend to fill in.
2120 Value* divOpToUse = divOp2;
2121 if (divOp2->getType()->isSigned()) {
2122 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
2124 divOpToUse = new TmpInstruction(mcfi, divOp2);
2125 target.getInstrInfo().
2126 CreateSignExtensionInstructions(target,
2127 remI->getParent()->getParent(),
2129 8*opSize, mvec, mcfi);
2133 // Now compute: result = rem V1, V2 as:
2134 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
2136 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
2137 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
2139 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
2140 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
2142 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
2143 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
2145 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
2146 .addReg(divOp1).addReg(prod).addRegDef(remI));
2151 case 38: // bool: And(bool, bool)
2152 case 138: // bool: And(bool, not)
2153 case 238: // bool: And(bool, boolconst)
2154 case 338: // reg : BAnd(reg, reg)
2155 case 538: // reg : BAnd(reg, Constant)
2156 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
2159 case 438: // bool: BAnd(bool, bnot)
2160 { // Use the argument of NOT as the second argument!
2161 // Mark the NOT node so that no code is generated for it.
2162 // If the type is boolean, set 1 or 0 in the result register.
2163 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2164 Value* notArg = BinaryOperator::getNotArgument(
2165 cast<BinaryOperator>(notNode->getInstruction()));
2166 notNode->markFoldedIntoParent();
2167 Value *lhs = subtreeRoot->leftChild()->getValue();
2168 Value *dest = subtreeRoot->getValue();
2169 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
2170 .addReg(dest, MOTy::Def));
2172 if (notArg->getType() == Type::BoolTy)
2173 { // set 1 in result register if result of above is non-zero
2174 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2175 .addReg(dest, MOTy::UseAndDef));
2181 case 39: // bool: Or(bool, bool)
2182 case 139: // bool: Or(bool, not)
2183 case 239: // bool: Or(bool, boolconst)
2184 case 339: // reg : BOr(reg, reg)
2185 case 539: // reg : BOr(reg, Constant)
2186 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
2189 case 439: // bool: BOr(bool, bnot)
2190 { // Use the argument of NOT as the second argument!
2191 // Mark the NOT node so that no code is generated for it.
2192 // If the type is boolean, set 1 or 0 in the result register.
2193 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2194 Value* notArg = BinaryOperator::getNotArgument(
2195 cast<BinaryOperator>(notNode->getInstruction()));
2196 notNode->markFoldedIntoParent();
2197 Value *lhs = subtreeRoot->leftChild()->getValue();
2198 Value *dest = subtreeRoot->getValue();
2200 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
2201 .addReg(dest, MOTy::Def));
2203 if (notArg->getType() == Type::BoolTy)
2204 { // set 1 in result register if result of above is non-zero
2205 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2206 .addReg(dest, MOTy::UseAndDef));
2212 case 40: // bool: Xor(bool, bool)
2213 case 140: // bool: Xor(bool, not)
2214 case 240: // bool: Xor(bool, boolconst)
2215 case 340: // reg : BXor(reg, reg)
2216 case 540: // reg : BXor(reg, Constant)
2217 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
2220 case 440: // bool: BXor(bool, bnot)
2221 { // Use the argument of NOT as the second argument!
2222 // Mark the NOT node so that no code is generated for it.
2223 // If the type is boolean, set 1 or 0 in the result register.
2224 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
2225 Value* notArg = BinaryOperator::getNotArgument(
2226 cast<BinaryOperator>(notNode->getInstruction()));
2227 notNode->markFoldedIntoParent();
2228 Value *lhs = subtreeRoot->leftChild()->getValue();
2229 Value *dest = subtreeRoot->getValue();
2230 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
2231 .addReg(dest, MOTy::Def));
2233 if (notArg->getType() == Type::BoolTy)
2234 { // set 1 in result register if result of above is non-zero
2235 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
2236 .addReg(dest, MOTy::UseAndDef));
2241 case 41: // setCCconst: SetCC(reg, Constant)
2242 { // Comparison is with a constant:
2244 // If the bool result must be computed into a register (see below),
2245 // and the constant is int ZERO, we can use the MOVR[op] instructions
2246 // and avoid the SUBcc instruction entirely.
2247 // Otherwise this is just the same as case 42, so just fall through.
2249 // The result of the SetCC must be computed and stored in a register if
2250 // it is used outside the current basic block (so it must be computed
2251 // as a boolreg) or it is used by anything other than a branch.
2252 // We will use a conditional move to do this.
2254 Instruction* setCCInstr = subtreeRoot->getInstruction();
2255 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2256 ! AllUsesAreBranches(setCCInstr));
2260 InstrTreeNode* constNode = subtreeRoot->rightChild();
2262 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2263 Constant *constVal = cast<Constant>(constNode->getValue());
2266 if ((constVal->getType()->isInteger()
2267 || isa<PointerType>(constVal->getType()))
2268 && target.getInstrInfo().ConvertConstantToIntType(target,
2269 constVal, constVal->getType(), isValidConst) == 0
2272 // That constant is an integer zero after all...
2273 // Use a MOVR[op] to compute the boolean result
2274 // Unconditionally set register to 0
2275 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
2276 .addRegDef(setCCInstr));
2278 // Now conditionally move 1 into the register.
2279 // Mark the register as a use (as well as a def) because the old
2280 // value will be retained if the condition is false.
2281 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
2282 mvec.push_back(BuildMI(movOpCode, 3)
2283 .addReg(subtreeRoot->leftChild()->getValue())
2284 .addZImm(1).addReg(setCCInstr, MOTy::UseAndDef));
2289 // ELSE FALL THROUGH
2292 case 42: // bool: SetCC(reg, reg):
2294 // This generates a SUBCC instruction, putting the difference in a
2295 // result reg. if needed, and/or setting a condition code if needed.
2297 Instruction* setCCInstr = subtreeRoot->getInstruction();
2298 Value* leftVal = subtreeRoot->leftChild()->getValue();
2299 Value* rightVal = subtreeRoot->rightChild()->getValue();
2300 const Type* opType = leftVal->getType();
2301 bool isFPCompare = opType->isFloatingPoint();
2303 // If the boolean result of the SetCC is used outside the current basic
2304 // block (so it must be computed as a boolreg) or is used by anything
2305 // other than a branch, the boolean must be computed and stored
2306 // in a result register. We will use a conditional move to do this.
2308 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
2309 ! AllUsesAreBranches(setCCInstr));
2311 // A TmpInstruction is created to represent the CC "result".
2312 // Unlike other instances of TmpInstruction, this one is used
2313 // by machine code of multiple LLVM instructions, viz.,
2314 // the SetCC and the branch. Make sure to get the same one!
2315 // Note that we do this even for FP CC registers even though they
2316 // are explicit operands, because the type of the operand
2317 // needs to be a floating point condition code, not an integer
2318 // condition code. Think of this as casting the bool result to
2319 // a FP condition code register.
2320 // Later, we mark the 4th operand as being a CC register, and as a def.
2322 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
2323 setCCInstr->getParent()->getParent(),
2325 MachineCodeForInstruction::get(setCCInstr));
2327 // If the operands are signed values smaller than 4 bytes, then they
2328 // must be sign-extended in order to do a valid 32-bit comparison
2329 // and get the right result in the 32-bit CC register (%icc).
2331 Value* leftOpToUse = leftVal;
2332 Value* rightOpToUse = rightVal;
2333 if (opType->isIntegral() && opType->isSigned()) {
2334 unsigned opSize = target.getTargetData().getTypeSize(opType);
2336 MachineCodeForInstruction& mcfi =
2337 MachineCodeForInstruction::get(setCCInstr);
2339 // create temporary virtual regs. to hold the sign-extensions
2340 leftOpToUse = new TmpInstruction(mcfi, leftVal);
2341 rightOpToUse = new TmpInstruction(mcfi, rightVal);
2343 // sign-extend each operand and put the result in the temporary reg.
2344 target.getInstrInfo().CreateSignExtensionInstructions
2345 (target, setCCInstr->getParent()->getParent(),
2346 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
2347 target.getInstrInfo().CreateSignExtensionInstructions
2348 (target, setCCInstr->getParent()->getParent(),
2349 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
2353 if (! isFPCompare) {
2354 // Integer condition: set CC and discard result.
2355 mvec.push_back(BuildMI(V9::SUBccr, 4)
2356 .addReg(leftOpToUse)
2357 .addReg(rightOpToUse)
2358 .addMReg(target.getRegInfo().getZeroRegNum(),MOTy::Def)
2359 .addCCReg(tmpForCC, MOTy::Def));
2361 // FP condition: dest of FCMP should be some FCCn register
2362 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
2363 .addCCReg(tmpForCC, MOTy::Def)
2364 .addReg(leftOpToUse)
2365 .addReg(rightOpToUse));
2368 if (computeBoolVal) {
2369 MachineOpCode movOpCode = (isFPCompare
2370 ? ChooseMovFpcciInstruction(subtreeRoot)
2371 : ChooseMovpcciForSetCC(subtreeRoot));
2373 // Unconditionally set register to 0
2374 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
2377 // Now conditionally move 1 into the register.
2378 // Mark the register as a use (as well as a def) because the old
2379 // value will be retained if the condition is false.
2380 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
2381 .addReg(setCCInstr, MOTy::UseAndDef));
2387 case 51: // reg: Load(reg)
2388 case 52: // reg: Load(ptrreg)
2389 SetOperandsForMemInstr(ChooseLoadInstruction(
2390 subtreeRoot->getValue()->getType()),
2391 mvec, subtreeRoot, target);
2394 case 55: // reg: GetElemPtr(reg)
2395 case 56: // reg: GetElemPtrIdx(reg,reg)
2396 // If the GetElemPtr was folded into the user (parent), it will be
2397 // caught above. For other cases, we have to compute the address.
2398 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
2401 case 57: // reg: Alloca: Implement as 1 instruction:
2402 { // add %fp, offsetFromFP -> result
2403 AllocationInst* instr =
2404 cast<AllocationInst>(subtreeRoot->getInstruction());
2406 target.getTargetData().getTypeSize(instr->getAllocatedType());
2408 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2412 case 58: // reg: Alloca(reg): Implement as 3 instructions:
2413 // mul num, typeSz -> tmp
2414 // sub %sp, tmp -> %sp
2415 { // add %sp, frameSizeBelowDynamicArea -> result
2416 AllocationInst* instr =
2417 cast<AllocationInst>(subtreeRoot->getInstruction());
2418 const Type* eltType = instr->getAllocatedType();
2420 // If #elements is constant, use simpler code for fixed-size allocas
2421 int tsize = (int) target.getTargetData().getTypeSize(eltType);
2422 Value* numElementsVal = NULL;
2423 bool isArray = instr->isArrayAllocation();
2425 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
2426 // total size is constant: generate code for fixed-size alloca
2427 unsigned numElements = isArray?
2428 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2429 CreateCodeForFixedSizeAlloca(target, instr, tsize,
2432 // total size is not constant.
2433 CreateCodeForVariableSizeAlloca(target, instr, tsize,
2434 numElementsVal, mvec);
2439 case 61: // reg: Call
2440 { // Generate a direct (CALL) or indirect (JMPL) call.
2441 // Mark the return-address register, the indirection
2442 // register (for indirect calls), the operands of the Call,
2443 // and the return value (if any) as implicit operands
2444 // of the machine instruction.
2446 // If this is a varargs function, floating point arguments
2447 // have to passed in integer registers so insert
2448 // copy-float-to-int instructions for each float operand.
2450 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2451 Value *callee = callInstr->getCalledValue();
2452 Function* calledFunc = dyn_cast<Function>(callee);
2454 // Check if this is an intrinsic function that needs a special code
2455 // sequence (e.g., va_start). Indirect calls cannot be special.
2457 bool specialIntrinsic = false;
2458 LLVMIntrinsic::ID iid;
2459 if (calledFunc && (iid=(LLVMIntrinsic::ID)calledFunc->getIntrinsicID()))
2460 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
2462 // If not, generate the normal call sequence for the function.
2463 // This can also handle any intrinsics that are just function calls.
2465 if (! specialIntrinsic) {
2466 Function* currentFunc = callInstr->getParent()->getParent();
2467 MachineFunction& MF = MachineFunction::get(currentFunc);
2468 MachineCodeForInstruction& mcfi =
2469 MachineCodeForInstruction::get(callInstr);
2470 const UltraSparcRegInfo& regInfo =
2471 (UltraSparcRegInfo&) target.getRegInfo();
2472 const TargetFrameInfo& frameInfo = target.getFrameInfo();
2474 // Create hidden virtual register for return address with type void*
2475 TmpInstruction* retAddrReg =
2476 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
2478 // Generate the machine instruction and its operands.
2479 // Use CALL for direct function calls; this optimistically assumes
2480 // the PC-relative address fits in the CALL address field (22 bits).
2481 // Use JMPL for indirect calls.
2482 // This will be added to mvec later, after operand copies.
2484 MachineInstr* callMI;
2485 if (calledFunc) // direct function call
2486 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
2487 else // indirect function call
2488 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
2489 .addSImm((int64_t)0).addRegDef(retAddrReg));
2491 const FunctionType* funcType =
2492 cast<FunctionType>(cast<PointerType>(callee->getType())
2493 ->getElementType());
2494 bool isVarArgs = funcType->isVarArg();
2495 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2497 // Use a descriptor to pass information about call arguments
2498 // to the register allocator. This descriptor will be "owned"
2499 // and freed automatically when the MachineCodeForInstruction
2500 // object for the callInstr goes away.
2501 CallArgsDescriptor* argDesc =
2502 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
2503 assert(callInstr->getOperand(0) == callee
2504 && "This is assumed in the loop below!");
2506 // Insert sign-extension instructions for small signed values,
2507 // if this is an unknown function (i.e., called via a funcptr)
2508 // or an external one (i.e., which may not be compiled by llc).
2510 if (calledFunc == NULL || calledFunc->isExternal()) {
2511 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2512 Value* argVal = callInstr->getOperand(i);
2513 const Type* argType = argVal->getType();
2514 if (argType->isIntegral() && argType->isSigned()) {
2515 unsigned argSize = target.getTargetData().getTypeSize(argType);
2517 // create a temporary virtual reg. to hold the sign-extension
2518 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
2520 // sign-extend argVal and put the result in the temporary reg.
2521 target.getInstrInfo().CreateSignExtensionInstructions
2522 (target, currentFunc, argVal, argExtend,
2523 8*argSize, mvec, mcfi);
2525 // replace argVal with argExtend in CallArgsDescriptor
2526 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
2532 // Insert copy instructions to get all the arguments into
2533 // all the places that they need to be.
2535 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
2537 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
2538 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
2539 const Type* argType = argVal->getType();
2540 unsigned regType = regInfo.getRegTypeForDataType(argType);
2541 unsigned argSize = target.getTargetData().getTypeSize(argType);
2542 int regNumForArg = TargetRegInfo::getInvalidRegNum();
2543 unsigned regClassIDOfArgReg;
2545 // Check for FP arguments to varargs functions.
2546 // Any such argument in the first $K$ args must be passed in an
2547 // integer register. If there is no prototype, it must also
2548 // be passed as an FP register.
2549 // K = #integer argument registers.
2550 bool isFPArg = argVal->getType()->isFloatingPoint();
2551 if (isVarArgs && isFPArg) {
2554 // It is a function with no prototype: pass value
2555 // as an FP value as well as a varargs value. The FP value
2556 // may go in a register or on the stack. The copy instruction
2557 // to the outgoing reg/stack is created by the normal argument
2558 // handling code since this is the "normal" passing mode.
2560 regNumForArg = regInfo.regNumForFPArg(regType,
2561 false, false, argNo,
2562 regClassIDOfArgReg);
2563 if (regNumForArg == regInfo.getInvalidRegNum())
2564 argInfo.setUseStackSlot();
2566 argInfo.setUseFPArgReg();
2569 // If this arg. is in the first $K$ regs, add special copy-
2570 // float-to-int instructions to pass the value as an int.
2571 // To check if it is in the first $K$, get the register
2572 // number for the arg #i. These copy instructions are
2573 // generated here because they are extra cases and not needed
2574 // for the normal argument handling (some code reuse is
2575 // possible though -- later).
2577 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
2578 regClassIDOfArgReg);
2579 if (copyRegNum != regInfo.getInvalidRegNum()) {
2580 // Create a virtual register to represent copyReg. Mark
2581 // this vreg as being an implicit operand of the call MI
2582 const Type* loadTy = (argType == Type::FloatTy
2583 ? Type::IntTy : Type::LongTy);
2584 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
2587 callMI->addImplicitRef(argVReg);
2589 // Get a temp stack location to use to copy
2590 // float-to-int via the stack.
2592 // FIXME: For now, we allocate permanent space because
2593 // the stack frame manager does not allow locals to be
2594 // allocated (e.g., for alloca) after a temp is
2597 // int tmpOffset = MF.getInfo()->pushTempValue(argSize);
2598 int tmpOffset = MF.getInfo()->allocateLocalVar(argVReg);
2600 // Generate the store from FP reg to stack
2601 unsigned StoreOpcode = ChooseStoreInstruction(argType);
2602 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
2603 .addReg(argVal).addMReg(regInfo.getFramePointer())
2604 .addSImm(tmpOffset);
2607 // Generate the load from stack to int arg reg
2608 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
2609 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
2610 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
2611 .addReg(argVReg, MOTy::Def);
2613 // Mark operand with register it should be assigned
2614 // both for copy and for the callMI
2615 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
2616 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2620 // Add info about the argument to the CallArgsDescriptor
2621 argInfo.setUseIntArgReg();
2622 argInfo.setArgCopy(copyRegNum);
2624 // Cannot fit in first $K$ regs so pass arg on stack
2625 argInfo.setUseStackSlot();
2627 } else if (isFPArg) {
2628 // Get the outgoing arg reg to see if there is one.
2629 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
2630 argNo, regClassIDOfArgReg);
2631 if (regNumForArg == regInfo.getInvalidRegNum())
2632 argInfo.setUseStackSlot();
2634 argInfo.setUseFPArgReg();
2635 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2639 // Get the outgoing arg reg to see if there is one.
2640 regNumForArg = regInfo.regNumForIntArg(false,false,
2641 argNo, regClassIDOfArgReg);
2642 if (regNumForArg == regInfo.getInvalidRegNum())
2643 argInfo.setUseStackSlot();
2645 argInfo.setUseIntArgReg();
2646 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
2652 // Now insert copy instructions to stack slot or arg. register
2654 if (argInfo.usesStackSlot()) {
2655 // Get the stack offset for this argument slot.
2656 // FP args on stack are right justified so adjust offset!
2657 // int arguments are also right justified but they are
2658 // always loaded as a full double-word so the offset does
2659 // not need to be adjusted.
2660 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
2661 if (argType->isFloatingPoint()) {
2662 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
2663 assert(argSize <= slotSize && "Insufficient slot size!");
2664 argOffset += slotSize - argSize;
2667 // Now generate instruction to copy argument to stack
2668 MachineOpCode storeOpCode =
2669 (argType->isFloatingPoint()
2670 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
2672 M = BuildMI(storeOpCode, 3).addReg(argVal)
2673 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
2676 else if (regNumForArg != regInfo.getInvalidRegNum()) {
2678 // Create a virtual register to represent the arg reg. Mark
2679 // this vreg as being an implicit operand of the call MI.
2680 TmpInstruction* argVReg =
2681 new TmpInstruction(mcfi, argVal, NULL, "argReg");
2683 callMI->addImplicitRef(argVReg);
2685 // Generate the reg-to-reg copy into the outgoing arg reg.
2686 // -- For FP values, create a FMOVS or FMOVD instruction
2687 // -- For non-FP values, create an add-with-0 instruction
2688 if (argType->isFloatingPoint())
2689 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
2690 .addReg(argVal).addReg(argVReg, MOTy::Def));
2692 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
2693 .addReg(argVal).addSImm((int64_t) 0)
2694 .addReg(argVReg, MOTy::Def));
2696 // Mark the operand with the register it should be assigned
2697 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
2698 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
2704 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
2705 "Arg. not in stack slot, primary or secondary register?");
2708 // add call instruction and delay slot before copying return value
2709 mvec.push_back(callMI);
2710 mvec.push_back(BuildMI(V9::NOP, 0));
2712 // Add the return value as an implicit ref. The call operands
2713 // were added above. Also, add code to copy out the return value.
2714 // This is always register-to-register for int or FP return values.
2716 if (callInstr->getType() != Type::VoidTy) {
2717 // Get the return value reg.
2718 const Type* retType = callInstr->getType();
2720 int regNum = (retType->isFloatingPoint()
2721 ? (unsigned) SparcFloatRegClass::f0
2722 : (unsigned) SparcIntRegClass::o0);
2723 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2724 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
2726 // Create a virtual register to represent it and mark
2727 // this vreg as being an implicit operand of the call MI
2728 TmpInstruction* retVReg =
2729 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
2731 callMI->addImplicitRef(retVReg, /*isDef*/ true);
2733 // Generate the reg-to-reg copy from the return value reg.
2734 // -- For FP values, create a FMOVS or FMOVD instruction
2735 // -- For non-FP values, create an add-with-0 instruction
2736 if (retType->isFloatingPoint())
2737 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2738 .addReg(retVReg).addReg(callInstr, MOTy::Def));
2740 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2741 .addReg(retVReg).addSImm((int64_t) 0)
2742 .addReg(callInstr, MOTy::Def));
2744 // Mark the operand with the register it should be assigned
2745 // Also mark the implicit ref of the call defining this operand
2746 M->SetRegForOperand(0, regNum);
2747 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
2752 // For the CALL instruction, the ret. addr. reg. is also implicit
2753 if (isa<Function>(callee))
2754 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
2756 MF.getInfo()->popAllTempValues(); // free temps used for this inst
2762 case 62: // reg: Shl(reg, reg)
2764 Value* argVal1 = subtreeRoot->leftChild()->getValue();
2765 Value* argVal2 = subtreeRoot->rightChild()->getValue();
2766 Instruction* shlInstr = subtreeRoot->getInstruction();
2768 const Type* opType = argVal1->getType();
2769 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2770 "Shl unsupported for other types");
2771 unsigned opSize = target.getTargetData().getTypeSize(opType);
2773 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2774 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
2775 argVal1, argVal2, 0, shlInstr, mvec,
2776 MachineCodeForInstruction::get(shlInstr));
2780 case 63: // reg: Shr(reg, reg)
2782 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2783 assert((opType->isInteger() || isa<PointerType>(opType)) &&
2784 "Shr unsupported for other types");
2785 unsigned opSize = target.getTargetData().getTypeSize(opType);
2786 Add3OperandInstr(opType->isSigned()
2787 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
2788 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
2793 case 64: // reg: Phi(reg,reg)
2794 break; // don't forward the value
2796 case 65: // reg: VaArg(reg)
2798 // Use value initialized by va_start as pointer to args on the stack.
2799 // Load argument via current pointer value, then increment pointer.
2800 int argSize = target.getFrameInfo().getSizeOfEachArgOnStack();
2801 Instruction* vaArgI = subtreeRoot->getInstruction();
2802 mvec.push_back(BuildMI(V9::LDXi, 3).addReg(vaArgI->getOperand(0)).
2803 addSImm(0).addRegDef(vaArgI));
2804 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaArgI->getOperand(0)).
2805 addSImm(argSize).addRegDef(vaArgI->getOperand(0)));
2809 case 71: // reg: VReg
2810 case 72: // reg: Constant
2811 break; // don't forward the value
2814 assert(0 && "Unrecognized BURG rule");
2819 if (forwardOperandNum >= 0) {
2820 // We did not generate a machine instruction but need to use operand.
2821 // If user is in the same tree, replace Value in its machine operand.
2822 // If not, insert a copy instruction which should get coalesced away
2823 // by register allocation.
2824 if (subtreeRoot->parent() != NULL)
2825 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2827 std::vector<MachineInstr*> minstrVec;
2828 Instruction* instr = subtreeRoot->getInstruction();
2829 target.getInstrInfo().
2830 CreateCopyInstructionsByType(target,
2831 instr->getParent()->getParent(),
2832 instr->getOperand(forwardOperandNum),
2834 MachineCodeForInstruction::get(instr));
2835 assert(minstrVec.size() > 0);
2836 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2840 if (maskUnsignedResult) {
2841 // If result is unsigned and smaller than int reg size,
2842 // we need to clear high bits of result value.
2843 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2844 Instruction* dest = subtreeRoot->getInstruction();
2845 if (dest->getType()->isUnsigned()) {
2846 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
2847 if (destSize <= 4) {
2848 // Mask high 64 - N bits, where N = 4*destSize.
2850 // Use a TmpInstruction to represent the
2851 // intermediate result before masking. Since those instructions
2852 // have already been generated, go back and substitute tmpI
2853 // for dest in the result position of each one of them.
2855 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
2856 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
2857 dest, NULL, "maskHi");
2858 Value* srlArgToUse = tmpI;
2860 unsigned numSubst = 0;
2861 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
2862 bool someArgsWereIgnored = false;
2863 numSubst += mvec[i]->substituteValue(dest, tmpI, /*defsOnly*/ true,
2864 /*defsAndUses*/ false,
2865 someArgsWereIgnored);
2866 assert(!someArgsWereIgnored &&
2867 "Operand `dest' exists but not replaced: probably bogus!");
2869 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
2871 // Left shift 32-N if size (N) is less than 32 bits.
2872 // Use another tmp. virtual registe to represent this result.
2874 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
2875 tmpI, NULL, "maskHi2");
2876 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
2877 .addZImm(8*(4-destSize))
2878 .addReg(srlArgToUse, MOTy::Def));
2881 // Logical right shift 32-N to get zero extension in top 64-N bits.
2882 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
2883 .addZImm(8*(4-destSize)).addReg(dest, MOTy::Def));
2885 } else if (destSize < 8) {
2886 assert(0 && "Unsupported type size: 32 < size < 64 bits");