1 //===- SparcV9BurgISel.cpp - SparcV9 BURG-based Instruction Selector ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // SparcV9 BURG-based instruction selector. It uses the SSA graph to
11 // construct a forest of BURG instruction trees (class InstrForest) and then
12 // uses the BURG-generated tree grammar (BURM) to find the optimal instruction
13 // sequences for the SparcV9.
15 //===----------------------------------------------------------------------===//
17 #include "MachineInstrAnnot.h"
18 #include "SparcV9BurgISel.h"
19 #include "SparcV9InstrForest.h"
20 #include "SparcV9Internals.h"
21 #include "SparcV9TmpInstr.h"
22 #include "SparcV9FrameInfo.h"
23 #include "SparcV9RegisterInfo.h"
24 #include "MachineFunctionInfo.h"
25 #include "llvm/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Type.h"
40 #include "llvm/Config/alloca.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/LeakDetector.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/hash_map"
51 //==------------------------------------------------------------------------==//
52 // InstrForest (V9ISel BURG instruction trees) implementation
53 //==------------------------------------------------------------------------==//
57 class InstructionNode : public InstrTreeNode {
58 bool codeIsFoldedIntoParent;
61 InstructionNode(Instruction *_instr);
63 Instruction *getInstruction() const {
64 assert(treeNodeType == NTInstructionNode);
65 return cast<Instruction>(val);
68 void markFoldedIntoParent() { codeIsFoldedIntoParent = true; }
69 bool isFoldedIntoParent() { return codeIsFoldedIntoParent; }
71 // Methods to support type inquiry through isa, cast, and dyn_cast:
72 static inline bool classof(const InstructionNode *N) { return true; }
73 static inline bool classof(const InstrTreeNode *N) {
74 return N->getNodeType() == InstrTreeNode::NTInstructionNode;
78 virtual void dumpNode(int indent) const;
81 class VRegListNode : public InstrTreeNode {
83 VRegListNode() : InstrTreeNode(NTVRegListNode, 0) { opLabel = VRegListOp; }
84 // Methods to support type inquiry through isa, cast, and dyn_cast:
85 static inline bool classof(const VRegListNode *N) { return true; }
86 static inline bool classof(const InstrTreeNode *N) {
87 return N->getNodeType() == InstrTreeNode::NTVRegListNode;
90 virtual void dumpNode(int indent) const;
93 class VRegNode : public InstrTreeNode {
95 VRegNode(Value* _val) : InstrTreeNode(NTVRegNode, _val) {
98 // Methods to support type inquiry through isa, cast, and dyn_cast:
99 static inline bool classof(const VRegNode *N) { return true; }
100 static inline bool classof(const InstrTreeNode *N) {
101 return N->getNodeType() == InstrTreeNode::NTVRegNode;
104 virtual void dumpNode(int indent) const;
107 class ConstantNode : public InstrTreeNode {
109 ConstantNode(Constant *constVal)
110 : InstrTreeNode(NTConstNode, (Value*)constVal) {
111 opLabel = ConstantNodeOp;
113 Constant *getConstVal() const { return (Constant*) val;}
114 // Methods to support type inquiry through isa, cast, and dyn_cast:
115 static inline bool classof(const ConstantNode *N) { return true; }
116 static inline bool classof(const InstrTreeNode *N) {
117 return N->getNodeType() == InstrTreeNode::NTConstNode;
120 virtual void dumpNode(int indent) const;
123 class LabelNode : public InstrTreeNode {
125 LabelNode(BasicBlock* BB) : InstrTreeNode(NTLabelNode, (Value*)BB) {
126 opLabel = LabelNodeOp;
128 BasicBlock *getBasicBlock() const { return (BasicBlock*)val;}
129 // Methods to support type inquiry through isa, cast, and dyn_cast:
130 static inline bool classof(const LabelNode *N) { return true; }
131 static inline bool classof(const InstrTreeNode *N) {
132 return N->getNodeType() == InstrTreeNode::NTLabelNode;
135 virtual void dumpNode(int indent) const;
138 /// InstrForest - A forest of instruction trees for a single function.
139 /// The goal of InstrForest is to group instructions into a single
140 /// tree if one or more of them might be potentially combined into a
141 /// single complex instruction in the target machine. We group two
142 /// instructions O and I if: (1) Instruction O computes an operand used
143 /// by instruction I, and (2) O and I are part of the same basic block,
144 /// and (3) O has only a single use, viz., I.
146 class InstrForest : private hash_map<const Instruction *, InstructionNode*> {
148 // Use a vector for the root set to get a deterministic iterator
149 // for stable code generation. Even though we need to erase nodes
150 // during forest construction, a vector should still be efficient
151 // because the elements to erase are nearly always near the end.
152 typedef std::vector<InstructionNode*> RootSet;
153 typedef RootSet:: iterator root_iterator;
154 typedef RootSet::const_iterator const_root_iterator;
160 /*ctor*/ InstrForest (Function *F);
161 /*dtor*/ ~InstrForest ();
163 /// getTreeNodeForInstr - Returns the tree node for an Instruction.
165 inline InstructionNode *getTreeNodeForInstr(Instruction* instr) {
166 return (*this)[instr];
169 /// Iterators for the root nodes for all the trees.
171 const_root_iterator roots_begin() const { return treeRoots.begin(); }
172 root_iterator roots_begin() { return treeRoots.begin(); }
173 const_root_iterator roots_end () const { return treeRoots.end(); }
174 root_iterator roots_end () { return treeRoots.end(); }
179 // Methods used to build the instruction forest.
180 void eraseRoot (InstructionNode* node);
181 void setLeftChild (InstrTreeNode* parent, InstrTreeNode* child);
182 void setRightChild(InstrTreeNode* parent, InstrTreeNode* child);
183 void setParent (InstrTreeNode* child, InstrTreeNode* parent);
184 void noteTreeNodeForInstr(Instruction* instr, InstructionNode* treeNode);
185 InstructionNode* buildTreeForInstruction(Instruction* instr);
188 void InstrTreeNode::dump(int dumpChildren, int indent) const {
193 LeftChild->dump(dumpChildren, indent+1);
195 RightChild->dump(dumpChildren, indent+1);
199 InstructionNode::InstructionNode(Instruction* I)
200 : InstrTreeNode(NTInstructionNode, I), codeIsFoldedIntoParent(false) {
201 opLabel = I->getOpcode();
203 // Distinguish special cases of some instructions such as Ret and Br
205 if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue()) {
206 opLabel = RetValueOp; // ret(value) operation
208 else if (opLabel ==Instruction::Br && !cast<BranchInst>(I)->isUnconditional())
210 opLabel = BrCondOp; // br(cond) operation
211 } else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT) {
212 opLabel = SetCCOp; // common label for all SetCC ops
213 } else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0) {
214 opLabel = AllocaN; // Alloca(ptr, N) operation
215 } else if (opLabel == Instruction::GetElementPtr &&
216 cast<GetElementPtrInst>(I)->hasIndices()) {
217 opLabel = opLabel + 100; // getElem with index vector
218 } else if (opLabel == Instruction::Xor &&
219 BinaryOperator::isNot(I)) {
220 opLabel = (I->getType() == Type::BoolTy)? NotOp // boolean Not operator
221 : BNotOp; // bitwise Not operator
222 } else if (opLabel == Instruction::And || opLabel == Instruction::Or ||
223 opLabel == Instruction::Xor) {
224 // Distinguish bitwise operators from logical operators!
225 if (I->getType() != Type::BoolTy)
226 opLabel = opLabel + 100; // bitwise operator
227 } else if (opLabel == Instruction::Cast) {
228 const Type *ITy = I->getType();
229 switch(ITy->getTypeID())
231 case Type::BoolTyID: opLabel = ToBoolTy; break;
232 case Type::UByteTyID: opLabel = ToUByteTy; break;
233 case Type::SByteTyID: opLabel = ToSByteTy; break;
234 case Type::UShortTyID: opLabel = ToUShortTy; break;
235 case Type::ShortTyID: opLabel = ToShortTy; break;
236 case Type::UIntTyID: opLabel = ToUIntTy; break;
237 case Type::IntTyID: opLabel = ToIntTy; break;
238 case Type::ULongTyID: opLabel = ToULongTy; break;
239 case Type::LongTyID: opLabel = ToLongTy; break;
240 case Type::FloatTyID: opLabel = ToFloatTy; break;
241 case Type::DoubleTyID: opLabel = ToDoubleTy; break;
242 case Type::ArrayTyID: opLabel = ToArrayTy; break;
243 case Type::PointerTyID: opLabel = ToPointerTy; break;
245 // Just use `Cast' opcode otherwise. It's probably ignored.
251 void InstructionNode::dumpNode(int indent) const {
252 for (int i=0; i < indent; i++)
254 std::cerr << getInstruction()->getOpcodeName()
255 << " [label " << getOpLabel() << "]" << "\n";
258 void VRegListNode::dumpNode(int indent) const {
259 for (int i=0; i < indent; i++)
262 std::cerr << "List" << "\n";
265 void VRegNode::dumpNode(int indent) const {
266 for (int i=0; i < indent; i++)
268 std::cerr << "VReg " << *getValue() << "\n";
271 void ConstantNode::dumpNode(int indent) const {
272 for (int i=0; i < indent; i++)
274 std::cerr << "Constant " << *getValue() << "\n";
277 void LabelNode::dumpNode(int indent) const {
278 for (int i=0; i < indent; i++)
281 std::cerr << "Label " << *getValue() << "\n";
284 /// InstrForest ctor - Create a forest of instruction trees for a
287 InstrForest::InstrForest(Function *F) {
288 for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
289 for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
290 buildTreeForInstruction(I);
294 InstrForest::~InstrForest() {
295 for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
298 void InstrForest::dump() const {
299 for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
300 (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
303 inline void InstrForest::eraseRoot(InstructionNode* node) {
304 for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
307 treeRoots.erase(RI.base()-1);
310 inline void InstrForest::noteTreeNodeForInstr(Instruction *instr,
311 InstructionNode *treeNode) {
312 (*this)[instr] = treeNode;
313 treeRoots.push_back(treeNode); // mark node as root of a new tree
316 inline void InstrForest::setLeftChild(InstrTreeNode *parent,
317 InstrTreeNode *child) {
318 parent->LeftChild = child;
319 child->Parent = parent;
320 if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
321 eraseRoot(instrNode); // no longer a tree root
324 inline void InstrForest::setRightChild(InstrTreeNode *parent,
325 InstrTreeNode *child) {
326 parent->RightChild = child;
327 child->Parent = parent;
328 if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
329 eraseRoot(instrNode); // no longer a tree root
332 InstructionNode* InstrForest::buildTreeForInstruction(Instruction *instr) {
333 InstructionNode *treeNode = getTreeNodeForInstr(instr);
335 // treeNode has already been constructed for this instruction
336 assert(treeNode->getInstruction() == instr);
340 // Otherwise, create a new tree node for this instruction.
341 treeNode = new InstructionNode(instr);
342 noteTreeNodeForInstr(instr, treeNode);
344 if (instr->getOpcode() == Instruction::Call) {
345 // Operands of call instruction
349 // If the instruction has more than 2 instruction operands,
350 // then we need to create artificial list nodes to hold them.
351 // (Note that we only count operands that get tree nodes, and not
352 // others such as branch labels for a branch or switch instruction.)
353 // To do this efficiently, we'll walk all operands, build treeNodes
354 // for all appropriate operands and save them in an array. We then
355 // insert children at the end, creating list nodes where needed.
356 // As a performance optimization, allocate a child array only
357 // if a fixed array is too small.
359 InstrTreeNode** childArray = new InstrTreeNode*[instr->getNumOperands()];
361 // Walk the operands of the instruction
362 for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end();
366 // Check if the operand is a data value, not an branch label, type,
367 // method or module. If the operand is an address type (i.e., label
368 // or method) that is used in an non-branching operation, e.g., `add'.
369 // that should be considered a data value.
370 // Check latter condition here just to simplify the next IF.
371 bool includeAddressOperand =
372 (isa<BasicBlock>(operand) || isa<Function>(operand))
373 && !instr->isTerminator();
375 if (includeAddressOperand || isa<Instruction>(operand) ||
376 isa<Constant>(operand) || isa<Argument>(operand)) {
377 // This operand is a data value.
378 // An instruction that computes the incoming value is added as a
379 // child of the current instruction if:
380 // the value has only a single use
381 // AND both instructions are in the same basic block.
382 // AND the current instruction is not a PHI (because the incoming
383 // value is conceptually in a predecessor block,
384 // even though it may be in the same static block)
385 // (Note that if the value has only a single use (viz., `instr'),
386 // the def of the value can be safely moved just before instr
387 // and therefore it is safe to combine these two instructions.)
388 // In all other cases, the virtual register holding the value
389 // is used directly, i.e., made a child of the instruction node.
390 InstrTreeNode* opTreeNode;
391 if (isa<Instruction>(operand) && operand->hasOneUse() &&
392 cast<Instruction>(operand)->getParent() == instr->getParent() &&
393 instr->getOpcode() != Instruction::PHI &&
394 instr->getOpcode() != Instruction::Call) {
395 // Recursively create a treeNode for it.
396 opTreeNode = buildTreeForInstruction((Instruction*)operand);
397 } else if (Constant *CPV = dyn_cast<Constant>(operand)) {
398 if (isa<GlobalValue>(CPV))
399 opTreeNode = new VRegNode(operand);
400 else if (isa<UndefValue>(CPV)) {
402 ConstantNode(Constant::getNullValue(CPV->getType()));
404 // Create a leaf node for a constant
405 opTreeNode = new ConstantNode(CPV);
408 // Create a leaf node for the virtual register
409 opTreeNode = new VRegNode(operand);
412 childArray[numChildren++] = opTreeNode;
416 // Add any selected operands as children in the tree.
417 // Certain instructions can have more than 2 in some instances (viz.,
418 // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
419 // array or struct). Make the operands of every such instruction into
420 // a right-leaning binary tree with the operand nodes at the leaves
421 // and VRegList nodes as internal nodes.
422 InstrTreeNode *parent = treeNode;
424 if (numChildren > 2) {
425 unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
426 assert(instrOpcode == Instruction::PHI ||
427 instrOpcode == Instruction::Call ||
428 instrOpcode == Instruction::Load ||
429 instrOpcode == Instruction::Store ||
430 instrOpcode == Instruction::GetElementPtr);
433 // Insert the first child as a direct child
434 if (numChildren >= 1)
435 setLeftChild(parent, childArray[0]);
439 // Create a list node for children 2 .. N-1, if any
440 for (n = numChildren-1; n >= 2; n--) {
441 // We have more than two children
442 InstrTreeNode *listNode = new VRegListNode();
443 setRightChild(parent, listNode);
444 setLeftChild(listNode, childArray[numChildren - n]);
448 // Now insert the last remaining child (if any).
449 if (numChildren >= 2) {
451 setRightChild(parent, childArray[numChildren - 1]);
454 delete [] childArray;
457 //==------------------------------------------------------------------------==//
458 // V9ISel Command-line options and declarations
459 //==------------------------------------------------------------------------==//
462 /// Allow the user to select the amount of debugging information printed
465 enum SelectDebugLevel_t {
467 Select_PrintMachineCode,
468 Select_DebugInstTrees,
469 Select_DebugBurgTrees,
471 cl::opt<SelectDebugLevel_t>
472 SelectDebugLevel("dselect", cl::Hidden,
473 cl::desc("enable instruction selection debug information"),
475 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
476 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
477 clEnumValN(Select_DebugInstTrees, "i",
478 "print debugging info for instruction selection"),
479 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"),
483 /// V9ISel - This is the FunctionPass that drives the instruction selection
484 /// process on the SparcV9 target.
486 class V9ISel : public FunctionPass {
487 TargetMachine &Target;
488 void InsertCodeForPhis(Function &F);
489 void InsertPhiElimInstructions(BasicBlock *BB,
490 const std::vector<MachineInstr*>& CpVec);
491 void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
492 void PostprocessMachineCodeForTree(InstructionNode* instrNode,
493 int ruleForNode, short* nts);
495 V9ISel(TargetMachine &TM) : Target(TM) {}
497 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
498 AU.setPreservesCFG();
501 bool runOnFunction(Function &F);
502 virtual const char *getPassName() const {
503 return "SparcV9 BURG Instruction Selector";
509 //==------------------------------------------------------------------------==//
510 // Various V9ISel helper functions
511 //==------------------------------------------------------------------------==//
513 static const uint32_t MAXLO = (1 << 10) - 1; // set bits set by %lo(*)
514 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
516 /// ConvertConstantToIntType - Function to get the value of an integral
517 /// constant in the form that must be put into the machine register. The
518 /// specified constant is interpreted as (i.e., converted if necessary to) the
519 /// specified destination type. The result is always returned as an uint64_t,
520 /// since the representation of int64_t and uint64_t are identical. The
521 /// argument can be any known const. isValidConstant is set to true if a valid
522 /// constant was found.
524 uint64_t ConvertConstantToIntType(const TargetMachine &target, const Value *V,
525 const Type *destType, bool &isValidConstant) {
526 isValidConstant = false;
529 if (! destType->isIntegral() && ! isa<PointerType>(destType))
532 if (! isa<Constant>(V) || isa<GlobalValue>(V))
535 // GlobalValue: no conversions needed: get value and return it
536 if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
537 isValidConstant = true; // may be overwritten by recursive call
538 return ConvertConstantToIntType(target, GV, destType, isValidConstant);
541 // ConstantBool: no conversions needed: get value and return it
542 if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
543 isValidConstant = true;
544 return (uint64_t) CB->getValue();
547 // ConstantPointerNull: it's really just a big, shiny version of zero.
548 if (isa<ConstantPointerNull>(V)) {
549 isValidConstant = true;
553 // For other types of constants, some conversion may be needed.
554 // First, extract the constant operand according to its own type
555 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556 switch(CE->getOpcode()) {
557 case Instruction::Cast: // recursively get the value as cast
558 C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
561 default: // not simplifying other ConstantExprs
564 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
565 isValidConstant = true;
566 C = CI->getRawValue();
567 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
568 isValidConstant = true;
569 double fC = CFP->getValue();
570 C = (destType->isSigned()? (uint64_t) (int64_t) fC
572 } else if (isa<UndefValue>(V)) {
573 isValidConstant = true;
577 // Now if a valid value was found, convert it to destType.
578 if (isValidConstant) {
579 unsigned opSize = target.getTargetData().getTypeSize(V->getType());
580 unsigned destSize = target.getTargetData().getTypeSize(destType);
581 uint64_t maskHi = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
582 assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
584 if (destType->isSigned()) {
585 if (opSize > destSize) // operand is larger than dest:
586 C = C & maskHi; // mask high bits
588 if (opSize > destSize ||
589 (opSize == destSize && ! V->getType()->isSigned()))
590 if (C & (1U << (8*destSize - 1)))
591 C = C | ~maskHi; // sign-extend from destSize to 64 bits
594 if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
595 // operand is larger than dest,
596 // OR both are equal but smaller than the full register size
597 // AND operand is signed, so it may have extra sign bits:
607 /// CreateSETUWConst - Copy a 32-bit unsigned constant into the register
608 /// `dest', using SETHI, OR in the worst case. This function correctly emulates
609 /// the SETUW pseudo-op for SPARC v9 (if argument isSigned == false). The
610 /// isSigned=true case is used to implement SETSW without duplicating code. It
611 /// optimizes some common cases:
612 /// (1) Small value that fits in simm13 field of OR: don't need SETHI.
613 /// (2) isSigned = true and C is a small negative signed value, i.e.,
614 /// high bits are 1, and the remaining bits fit in simm13(OR).
616 CreateSETUWConst(uint32_t C,
617 Instruction* dest, std::vector<MachineInstr*>& mvec,
618 MachineCodeForInstruction& mcfi, Value* val, bool isSigned = false) {
619 MachineInstr *miSETHI = NULL, *miOR = NULL;
621 // In order to get efficient code, we should not generate the SETHI if
622 // all high bits are 1 (i.e., this is a small signed value that fits in
623 // the simm13 field of OR). So we check for and handle that case specially.
624 // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
625 // In fact, sC == -sC, so we have to check for this explicitly.
626 int32_t sC = (int32_t) C;
627 bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
629 //Create TmpInstruction for intermediate values
630 TmpInstruction *tmpReg = 0;
632 // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
633 if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
634 tmpReg = new TmpInstruction(mcfi, PointerType::get(val->getType()), (Instruction*) val);
635 miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(tmpReg);
636 miSETHI->getOperand(0).markHi32();
637 mvec.push_back(miSETHI);
640 // Set the low 10 or 12 bits in dest. This is necessary if no SETHI
641 // was generated, or if the low 10 bits are non-zero.
642 if (miSETHI==NULL || C & MAXLO) {
644 // unsigned value with high-order bits set using SETHI
645 miOR = BuildMI(V9::ORi,3).addReg(tmpReg).addZImm(C).addRegDef(dest);
646 miOR->getOperand(1).markLo32();
648 // unsigned or small signed value that fits in simm13 field of OR
649 assert(smallNegValue || (C & ~MAXSIMM) == 0);
650 miOR = BuildMI(V9::ORi, 3).addMReg(SparcV9::g0)
651 .addSImm(sC).addRegDef(dest);
653 mvec.push_back(miOR);
656 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg).addMReg(SparcV9::g0).addRegDef(dest));
658 assert((miSETHI || miOR) && "Oops, no code was generated!");
661 /// CreateSETSWConst - Set a 32-bit signed constant in the register `dest',
662 /// with sign-extension to 64 bits. This uses SETHI, OR, SRA in the worst case.
663 /// This function correctly emulates the SETSW pseudo-op for SPARC v9. It
664 /// optimizes the same cases as SETUWConst, plus:
665 /// (1) SRA is not needed for positive or small negative values.
668 CreateSETSWConst(int32_t C,
669 Instruction* dest, std::vector<MachineInstr*>& mvec,
670 MachineCodeForInstruction& mcfi, Value* val) {
672 //TmpInstruction for intermediate values
673 TmpInstruction *tmpReg = new TmpInstruction(mcfi, (Instruction*) val);
675 // Set the low 32 bits of dest
676 CreateSETUWConst((uint32_t) C, tmpReg, mvec, mcfi, val, /*isSigned*/true);
678 // Sign-extend to the high 32 bits if needed.
679 // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
680 if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
681 mvec.push_back(BuildMI(V9::SRAi5,3).addReg(tmpReg).addZImm(0).addRegDef(dest));
683 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg).addMReg(SparcV9::g0).addRegDef(dest));
686 /// CreateSETXConst - Set a 64-bit signed or unsigned constant in the
687 /// register `dest'. Use SETUWConst for each 32 bit word, plus a
688 /// left-shift-by-32 in between. This function correctly emulates the SETX
689 /// pseudo-op for SPARC v9. It optimizes the same cases as SETUWConst for each
693 CreateSETXConst(uint64_t C,
694 Instruction* tmpReg, Instruction* dest,
695 std::vector<MachineInstr*>& mvec,
696 MachineCodeForInstruction& mcfi, Value* val) {
697 assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
701 // Code to set the upper 32 bits of the value in register `tmpReg'
702 CreateSETUWConst((C >> 32), tmpReg, mvec, mcfi, val);
704 //TmpInstruction for intermediate values
705 TmpInstruction *tmpReg2 = new TmpInstruction(mcfi, (Instruction*) val);
707 // Shift tmpReg left by 32 bits
708 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
709 .addRegDef(tmpReg2));
711 //TmpInstruction for intermediate values
712 TmpInstruction *tmpReg3 = new TmpInstruction(mcfi, (Instruction*) val);
714 // Code to set the low 32 bits of the value in register `dest'
715 CreateSETUWConst(C, tmpReg3, mvec, mcfi, val);
717 // dest = OR(tmpReg, dest)
718 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg3).addReg(tmpReg2).addRegDef(dest));
721 /// CreateSETUWLabel - Set a 32-bit constant (given by a symbolic label) in
722 /// the register `dest'.
725 CreateSETUWLabel(Value* val,
726 Instruction* dest, std::vector<MachineInstr*>& mvec) {
729 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get((Instruction*) val);
730 TmpInstruction* tmpReg = new TmpInstruction(mcfi, val);
732 // Set the high 22 bits in dest
733 MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(tmpReg);
734 MI->getOperand(0).markHi32();
737 // Set the low 10 bits in dest
738 MI = BuildMI(V9::ORr, 3).addReg(tmpReg).addReg(val).addRegDef(dest);
739 MI->getOperand(1).markLo32();
743 /// CreateSETXLabel - Set a 64-bit constant (given by a symbolic label) in the
747 CreateSETXLabel(Value* val, Instruction* tmpReg,
748 Instruction* dest, std::vector<MachineInstr*>& mvec,
749 MachineCodeForInstruction& mcfi) {
750 assert(isa<Constant>(val) &&
751 "I only know about constant values and global addresses");
755 MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
756 MI->getOperand(0).markHi64();
759 TmpInstruction* tmpReg2 =
760 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
762 MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg2);
763 MI->getOperand(1).markLo64();
767 TmpInstruction* tmpReg3 =
768 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
770 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg2).addZImm(32)
771 .addRegDef(tmpReg3));
774 TmpInstruction* tmpReg4 =
775 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
776 MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg4);
777 MI->getOperand(0).markHi32();
780 TmpInstruction* tmpReg5 =
781 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
782 MI = BuildMI(V9::ORr, 3).addReg(tmpReg4).addReg(tmpReg3).addRegDef(tmpReg5);
785 MI = BuildMI(V9::ORi, 3).addReg(tmpReg5).addPCDisp(val).addRegDef(dest);
786 MI->getOperand(1).markLo32();
790 /// CreateUIntSetInstruction - Create code to Set an unsigned constant in the
791 /// register `dest'. Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst
792 /// as needed. CreateSETSWConst is an optimization for the case that the
793 /// unsigned value has all ones in the 33 high bits (so that sign-extension sets
797 CreateUIntSetInstruction(uint64_t C, Instruction* dest,
798 std::vector<MachineInstr*>& mvec,
799 MachineCodeForInstruction& mcfi, Value* val) {
800 static const uint64_t lo32 = (uint32_t) ~0;
801 if (C <= lo32) // High 32 bits are 0. Set low 32 bits.
802 CreateSETUWConst((uint32_t) C, dest, mvec, mcfi, val);
803 else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
804 // All high 33 (not 32) bits are 1s: sign-extension will take care
805 // of high 32 bits, so use the sequence for signed int
806 CreateSETSWConst((int32_t) C, dest, mvec, mcfi, val);
807 } else if (C > lo32) {
808 // C does not fit in 32 bits
809 TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
810 CreateSETXConst(C, tmpReg, dest, mvec, mcfi, val);
814 /// CreateIntSetInstruction - Create code to Set a signed constant in the
815 /// register `dest'. Really the same as CreateUIntSetInstruction.
818 CreateIntSetInstruction(int64_t C, Instruction* dest,
819 std::vector<MachineInstr*>& mvec,
820 MachineCodeForInstruction& mcfi, Value* val) {
821 CreateUIntSetInstruction((uint64_t) C, dest, mvec, mcfi, val);
824 /// MaxConstantsTableTy - Table mapping LLVM opcodes to the max. immediate
825 /// constant usable for that operation in the SparcV9 backend. Used by
826 /// ConstantMayNotFitInImmedField().
828 struct MaxConstantsTableTy {
829 // Entry == 0 ==> no immediate constant field exists at all.
830 // Entry > 0 ==> abs(immediate constant) <= Entry
831 std::vector<int> tbl;
833 int getMaxConstantForInstr (unsigned llvmOpCode);
834 MaxConstantsTableTy ();
835 unsigned size() const { return tbl.size (); }
836 int &operator[] (unsigned index) { return tbl[index]; }
839 int MaxConstantsTableTy::getMaxConstantForInstr(unsigned llvmOpCode) {
840 int modelOpCode = -1;
842 if (llvmOpCode >= Instruction::BinaryOpsBegin &&
843 llvmOpCode < Instruction::BinaryOpsEnd)
844 modelOpCode = V9::ADDi;
847 case Instruction::Ret: modelOpCode = V9::JMPLCALLi; break;
849 case Instruction::Malloc:
850 case Instruction::Alloca:
851 case Instruction::GetElementPtr:
852 case Instruction::PHI:
853 case Instruction::Cast:
854 case Instruction::Call: modelOpCode = V9::ADDi; break;
856 case Instruction::Shl:
857 case Instruction::Shr: modelOpCode = V9::SLLXi6; break;
862 return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
865 MaxConstantsTableTy::MaxConstantsTableTy () : tbl (Instruction::OtherOpsEnd) {
867 assert(tbl.size() == Instruction::OtherOpsEnd &&
868 "assignments below will be illegal!");
869 for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
870 tbl[op] = getMaxConstantForInstr(op);
871 for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
872 tbl[op] = getMaxConstantForInstr(op);
873 for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
874 tbl[op] = getMaxConstantForInstr(op);
875 for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
876 tbl[op] = getMaxConstantForInstr(op);
879 bool ConstantMayNotFitInImmedField(const Constant* CV, const Instruction* I) {
880 // The one and only MaxConstantsTable, used only by this function.
881 static MaxConstantsTableTy MaxConstantsTable;
883 if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
886 // can always use %g0
887 if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV))
890 if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
893 if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
894 return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
896 if (isa<ConstantBool>(CV))
897 return 1 > MaxConstantsTable[I->getOpcode()];
902 /// ChooseLoadInstruction - Return the appropriate load instruction opcode
903 /// based on the given LLVM value type.
905 static inline MachineOpCode ChooseLoadInstruction(const Type *DestTy) {
906 switch (DestTy->getTypeID()) {
908 case Type::UByteTyID: return V9::LDUBr;
909 case Type::SByteTyID: return V9::LDSBr;
910 case Type::UShortTyID: return V9::LDUHr;
911 case Type::ShortTyID: return V9::LDSHr;
912 case Type::UIntTyID: return V9::LDUWr;
913 case Type::IntTyID: return V9::LDSWr;
914 case Type::PointerTyID:
915 case Type::ULongTyID:
916 case Type::LongTyID: return V9::LDXr;
917 case Type::FloatTyID: return V9::LDFr;
918 case Type::DoubleTyID: return V9::LDDFr;
919 default: assert(0 && "Invalid type for Load instruction");
924 /// ChooseStoreInstruction - Return the appropriate store instruction opcode
925 /// based on the given LLVM value type.
927 static inline MachineOpCode ChooseStoreInstruction(const Type *DestTy) {
928 switch (DestTy->getTypeID()) {
930 case Type::UByteTyID:
931 case Type::SByteTyID: return V9::STBr;
932 case Type::UShortTyID:
933 case Type::ShortTyID: return V9::STHr;
935 case Type::IntTyID: return V9::STWr;
936 case Type::PointerTyID:
937 case Type::ULongTyID:
938 case Type::LongTyID: return V9::STXr;
939 case Type::FloatTyID: return V9::STFr;
940 case Type::DoubleTyID: return V9::STDFr;
941 default: assert(0 && "Invalid type for Store instruction");
946 static inline MachineOpCode ChooseAddInstructionByType(const Type* resultType) {
947 MachineOpCode opCode = V9::INVALID_OPCODE;
948 if (resultType->isIntegral() || isa<PointerType>(resultType)
949 || isa<FunctionType>(resultType) || resultType == Type::LabelTy) {
952 switch(resultType->getTypeID()) {
953 case Type::FloatTyID: opCode = V9::FADDS; break;
954 case Type::DoubleTyID: opCode = V9::FADDD; break;
955 default: assert(0 && "Invalid type for ADD instruction"); break;
961 /// convertOpcodeFromRegToImm - Because the SparcV9 instruction selector likes
962 /// to re-write operands to instructions, making them change from a Value*
963 /// (virtual register) to a Constant* (making an immediate field), we need to
964 /// change the opcode from a register-based instruction to an immediate-based
965 /// instruction, hence this mapping.
967 static unsigned convertOpcodeFromRegToImm(unsigned Opcode) {
970 case V9::ADDr: return V9::ADDi;
971 case V9::ADDccr: return V9::ADDcci;
972 case V9::ADDCr: return V9::ADDCi;
973 case V9::ADDCccr: return V9::ADDCcci;
974 case V9::SUBr: return V9::SUBi;
975 case V9::SUBccr: return V9::SUBcci;
976 case V9::SUBCr: return V9::SUBCi;
977 case V9::SUBCccr: return V9::SUBCcci;
978 case V9::MULXr: return V9::MULXi;
979 case V9::SDIVXr: return V9::SDIVXi;
980 case V9::UDIVXr: return V9::UDIVXi;
983 case V9::ANDr: return V9::ANDi;
984 case V9::ANDccr: return V9::ANDcci;
985 case V9::ANDNr: return V9::ANDNi;
986 case V9::ANDNccr: return V9::ANDNcci;
987 case V9::ORr: return V9::ORi;
988 case V9::ORccr: return V9::ORcci;
989 case V9::ORNr: return V9::ORNi;
990 case V9::ORNccr: return V9::ORNcci;
991 case V9::XORr: return V9::XORi;
992 case V9::XORccr: return V9::XORcci;
993 case V9::XNORr: return V9::XNORi;
994 case V9::XNORccr: return V9::XNORcci;
997 case V9::SLLr5: return V9::SLLi5;
998 case V9::SRLr5: return V9::SRLi5;
999 case V9::SRAr5: return V9::SRAi5;
1000 case V9::SLLXr6: return V9::SLLXi6;
1001 case V9::SRLXr6: return V9::SRLXi6;
1002 case V9::SRAXr6: return V9::SRAXi6;
1004 /* Conditional move on int comparison with zero */
1005 case V9::MOVRZr: return V9::MOVRZi;
1006 case V9::MOVRLEZr: return V9::MOVRLEZi;
1007 case V9::MOVRLZr: return V9::MOVRLZi;
1008 case V9::MOVRNZr: return V9::MOVRNZi;
1009 case V9::MOVRGZr: return V9::MOVRGZi;
1010 case V9::MOVRGEZr: return V9::MOVRGEZi;
1013 /* Conditional move on int condition code */
1014 case V9::MOVAr: return V9::MOVAi;
1015 case V9::MOVNr: return V9::MOVNi;
1016 case V9::MOVNEr: return V9::MOVNEi;
1017 case V9::MOVEr: return V9::MOVEi;
1018 case V9::MOVGr: return V9::MOVGi;
1019 case V9::MOVLEr: return V9::MOVLEi;
1020 case V9::MOVGEr: return V9::MOVGEi;
1021 case V9::MOVLr: return V9::MOVLi;
1022 case V9::MOVGUr: return V9::MOVGUi;
1023 case V9::MOVLEUr: return V9::MOVLEUi;
1024 case V9::MOVCCr: return V9::MOVCCi;
1025 case V9::MOVCSr: return V9::MOVCSi;
1026 case V9::MOVPOSr: return V9::MOVPOSi;
1027 case V9::MOVNEGr: return V9::MOVNEGi;
1028 case V9::MOVVCr: return V9::MOVVCi;
1029 case V9::MOVVSr: return V9::MOVVSi;
1031 /* Conditional move of int reg on fp condition code */
1032 case V9::MOVFAr: return V9::MOVFAi;
1033 case V9::MOVFNr: return V9::MOVFNi;
1034 case V9::MOVFUr: return V9::MOVFUi;
1035 case V9::MOVFGr: return V9::MOVFGi;
1036 case V9::MOVFUGr: return V9::MOVFUGi;
1037 case V9::MOVFLr: return V9::MOVFLi;
1038 case V9::MOVFULr: return V9::MOVFULi;
1039 case V9::MOVFLGr: return V9::MOVFLGi;
1040 case V9::MOVFNEr: return V9::MOVFNEi;
1041 case V9::MOVFEr: return V9::MOVFEi;
1042 case V9::MOVFUEr: return V9::MOVFUEi;
1043 case V9::MOVFGEr: return V9::MOVFGEi;
1044 case V9::MOVFUGEr: return V9::MOVFUGEi;
1045 case V9::MOVFLEr: return V9::MOVFLEi;
1046 case V9::MOVFULEr: return V9::MOVFULEi;
1047 case V9::MOVFOr: return V9::MOVFOi;
1050 case V9::LDSBr: return V9::LDSBi;
1051 case V9::LDSHr: return V9::LDSHi;
1052 case V9::LDSWr: return V9::LDSWi;
1053 case V9::LDUBr: return V9::LDUBi;
1054 case V9::LDUHr: return V9::LDUHi;
1055 case V9::LDUWr: return V9::LDUWi;
1056 case V9::LDXr: return V9::LDXi;
1057 case V9::LDFr: return V9::LDFi;
1058 case V9::LDDFr: return V9::LDDFi;
1059 case V9::LDQFr: return V9::LDQFi;
1060 case V9::LDFSRr: return V9::LDFSRi;
1061 case V9::LDXFSRr: return V9::LDXFSRi;
1064 case V9::STBr: return V9::STBi;
1065 case V9::STHr: return V9::STHi;
1066 case V9::STWr: return V9::STWi;
1067 case V9::STXr: return V9::STXi;
1068 case V9::STFr: return V9::STFi;
1069 case V9::STDFr: return V9::STDFi;
1070 case V9::STFSRr: return V9::STFSRi;
1071 case V9::STXFSRr: return V9::STXFSRi;
1074 case V9::JMPLCALLr: return V9::JMPLCALLi;
1075 case V9::JMPLRETr: return V9::JMPLRETi;
1077 /* save and restore */
1078 case V9::SAVEr: return V9::SAVEi;
1079 case V9::RESTOREr: return V9::RESTOREi;
1082 // It's already in correct format
1083 // Or, it's just not handled yet, but an assert() would break LLC
1085 std::cerr << "Unhandled opcode in convertOpcodeFromRegToImm(): " << Opcode
1092 /// CreateCodeToLoadConst - Create an instruction sequence to put the
1093 /// constant `val' into the virtual register `dest'. `val' may be a Constant or
1094 /// a GlobalValue, viz., the constant address of a global variable or function.
1095 /// The generated instructions are returned in `mvec'. Any temp. registers
1096 /// (TmpInstruction) created are recorded in mcfi. Any stack space required is
1097 /// allocated via MachineFunction.
1099 void CreateCodeToLoadConst(const TargetMachine& target, Function* F,
1100 Value* val, Instruction* dest,
1101 std::vector<MachineInstr*>& mvec,
1102 MachineCodeForInstruction& mcfi) {
1103 assert(isa<Constant>(val) &&
1104 "I only know about constant values and global addresses");
1106 // Use a "set" instruction for known constants or symbolic constants (labels)
1107 // that can go in an integer reg.
1108 // We have to use a "load" instruction for all other constants,
1109 // in particular, floating point constants.
1110 const Type* valType = val->getType();
1112 if (isa<GlobalValue>(val)) {
1113 TmpInstruction* tmpReg =
1114 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
1115 CreateSETXLabel(val, tmpReg, dest, mvec, mcfi);
1120 uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
1122 if (dest->getType()->isSigned())
1123 CreateUIntSetInstruction(C, dest, mvec, mcfi, val);
1125 CreateIntSetInstruction((int64_t) C, dest, mvec, mcfi, val);
1128 // Make an instruction sequence to load the constant, viz:
1129 // SETX <addr-of-constant>, tmpReg, addrReg
1130 // LOAD /*addr*/ addrReg, /*offset*/ 0, dest
1131 // First, create a tmp register to be used by the SETX sequence.
1132 TmpInstruction* tmpReg =
1133 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1135 // Create another TmpInstruction for the address register
1136 TmpInstruction* addrReg =
1137 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1139 // Get the constant pool index for this constant
1140 MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
1141 Constant *C = cast<Constant>(val);
1142 unsigned CPI = CP->getConstantPoolIndex(C);
1144 // Put the address of the constant into a register
1147 MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
1148 MI->getOperand(0).markHi64();
1151 //Create another tmp register for the SETX sequence to preserve SSA
1152 TmpInstruction* tmpReg2 =
1153 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1155 MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
1156 .addRegDef(tmpReg2);
1157 MI->getOperand(1).markLo64();
1160 //Create another tmp register for the SETX sequence to preserve SSA
1161 TmpInstruction* tmpReg3 =
1162 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1164 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg2).addZImm(32)
1165 .addRegDef(tmpReg3));
1166 MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
1167 MI->getOperand(0).markHi32();
1170 // Create another TmpInstruction for the address register
1171 TmpInstruction* addrReg2 =
1172 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1175 MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg3).addRegDef(addrReg2);
1178 // Create another TmpInstruction for the address register
1179 TmpInstruction* addrReg3 =
1180 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1182 MI = BuildMI(V9::ORi, 3).addReg(addrReg2).addConstantPoolIndex(CPI)
1183 .addRegDef(addrReg3);
1184 MI->getOperand(1).markLo32();
1187 // Now load the constant from out ConstantPool label
1188 unsigned Opcode = ChooseLoadInstruction(val->getType());
1189 Opcode = convertOpcodeFromRegToImm(Opcode);
1190 mvec.push_back(BuildMI(Opcode, 3)
1191 .addReg(addrReg3).addSImm((int64_t)0).addRegDef(dest));
1195 /// CreateCodeToCopyFloatToInt - Similarly, create an instruction sequence
1196 /// to copy an FP register `val' to an integer register `dest' by copying to
1197 /// memory and back. The generated instructions are returned in `mvec'. Any
1198 /// temp. virtual registers (TmpInstruction) created are recorded in mcfi.
1199 /// Temporary stack space required is allocated via MachineFunction.
1201 void CreateCodeToCopyFloatToInt(const TargetMachine& target, Function* F,
1202 Value* val, Instruction* dest,
1203 std::vector<MachineInstr*>& mvec,
1204 MachineCodeForInstruction& mcfi) {
1205 const Type* opTy = val->getType();
1206 const Type* destTy = dest->getType();
1207 assert(opTy->isFloatingPoint() && "Source type must be float/double");
1208 assert((destTy->isIntegral() || isa<PointerType>(destTy))
1209 && "Dest type must be integer, bool or pointer");
1211 // FIXME: For now, we allocate permanent space because the stack frame
1212 // manager does not allow locals to be allocated (e.g., for alloca) after
1213 // a temp is allocated!
1214 int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val);
1216 unsigned FPReg = target.getRegInfo()->getFramePointer();
1218 // Store instruction stores `val' to [%fp+offset].
1219 // The store opCode is based only the source value being copied.
1220 unsigned StoreOpcode = ChooseStoreInstruction(opTy);
1221 StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1222 mvec.push_back(BuildMI(StoreOpcode, 3)
1223 .addReg(val).addMReg(FPReg).addSImm(offset));
1225 // Load instruction loads [%fp+offset] to `dest'.
1226 // The type of the load opCode is the integer type that matches the
1227 // source type in size:
1228 // On SparcV9: int for float, long for double.
1229 // Note that we *must* use signed loads even for unsigned dest types, to
1230 // ensure correct sign-extension for UByte, UShort or UInt:
1231 const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
1232 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
1233 LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1234 mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
1235 .addSImm(offset).addRegDef(dest));
1238 /// CreateBitExtensionInstructions - Helper function for sign-extension and
1239 /// zero-extension. For SPARC v9, we sign-extend the given operand using SLL;
1243 CreateBitExtensionInstructions(bool signExtend, const TargetMachine& target,
1244 Function* F, Value* srcVal, Value* destVal,
1245 unsigned int numLowBits,
1246 std::vector<MachineInstr*>& mvec,
1247 MachineCodeForInstruction& mcfi) {
1250 assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
1252 if (numLowBits < 32) {
1253 // SLL is needed since operand size is < 32 bits.
1254 TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
1255 srcVal, destVal, "make32");
1256 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
1257 .addZImm(32-numLowBits).addRegDef(tmpI));
1261 mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
1262 .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
1265 /// CreateSignExtensionInstructions - Create instruction sequence to produce
1266 /// a sign-extended register value from an arbitrary-sized integer value (sized
1267 /// in bits, not bytes). The generated instructions are returned in `mvec'. Any
1268 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1269 /// space required is allocated via MachineFunction.
1271 void CreateSignExtensionInstructions(const TargetMachine& target,
1272 Function* F, Value* srcVal, Value* destVal,
1273 unsigned int numLowBits,
1274 std::vector<MachineInstr*>& mvec,
1275 MachineCodeForInstruction& mcfi) {
1276 CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
1277 destVal, numLowBits, mvec, mcfi);
1280 /// CreateZeroExtensionInstructions - Create instruction sequence to produce
1281 /// a zero-extended register value from an arbitrary-sized integer value (sized
1282 /// in bits, not bytes). For SPARC v9, we sign-extend the given operand using
1283 /// SLL; SRL. The generated instructions are returned in `mvec'. Any temp.
1284 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1285 /// required is allocated via MachineFunction.
1287 void CreateZeroExtensionInstructions(const TargetMachine& target,
1288 Function* F, Value* srcVal, Value* destVal,
1289 unsigned int numLowBits,
1290 std::vector<MachineInstr*>& mvec,
1291 MachineCodeForInstruction& mcfi) {
1292 CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
1293 destVal, numLowBits, mvec, mcfi);
1296 /// CreateCodeToCopyIntToFloat - Create an instruction sequence to copy an
1297 /// integer register `val' to a floating point register `dest' by copying to
1298 /// memory and back. val must be an integral type. dest must be a Float or
1299 /// Double. The generated instructions are returned in `mvec'. Any temp.
1300 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1301 /// required is allocated via MachineFunction.
1303 void CreateCodeToCopyIntToFloat(const TargetMachine& target,
1304 Function* F, Value* val, Instruction* dest,
1305 std::vector<MachineInstr*>& mvec,
1306 MachineCodeForInstruction& mcfi) {
1307 assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
1308 && "Source type must be integral (integer or bool) or pointer");
1309 assert(dest->getType()->isFloatingPoint()
1310 && "Dest type must be float/double");
1312 // Get a stack slot to use for the copy
1313 int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val);
1315 // Get the size of the source value being copied.
1316 size_t srcSize = target.getTargetData().getTypeSize(val->getType());
1318 // Store instruction stores `val' to [%fp+offset].
1319 // The store and load opCodes are based on the size of the source value.
1320 // If the value is smaller than 32 bits, we must sign- or zero-extend it
1321 // to 32 bits since the load-float will load 32 bits.
1322 // Note that the store instruction is the same for signed and unsigned ints.
1323 const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
1324 Value* storeVal = val;
1325 if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
1326 // sign- or zero-extend respectively
1327 storeVal = new TmpInstruction(mcfi, storeType, val);
1328 if (val->getType()->isSigned())
1329 CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1332 CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1336 unsigned FPReg = target.getRegInfo()->getFramePointer();
1337 unsigned StoreOpcode = ChooseStoreInstruction(storeType);
1338 StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1339 mvec.push_back(BuildMI(StoreOpcode, 3)
1340 .addReg(storeVal).addMReg(FPReg).addSImm(offset));
1342 // Load instruction loads [%fp+offset] to `dest'.
1343 // The type of the load opCode is the floating point type that matches the
1344 // stored type in size:
1345 // On SparcV9: float for int or smaller, double for long.
1346 const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1347 unsigned LoadOpcode = ChooseLoadInstruction(loadType);
1348 LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1349 mvec.push_back(BuildMI(LoadOpcode, 3)
1350 .addMReg(FPReg).addSImm(offset).addRegDef(dest));
1353 /// InsertCodeToLoadConstant - Generates code to load the constant
1354 /// into a TmpInstruction (virtual reg) and returns the virtual register.
1356 static TmpInstruction*
1357 InsertCodeToLoadConstant(Function *F, Value* opValue, Instruction* vmInstr,
1358 std::vector<MachineInstr*>& loadConstVec,
1359 TargetMachine& target) {
1360 // Create a tmp virtual register to hold the constant.
1361 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
1362 TmpInstruction* tmpReg = new TmpInstruction(mcfi, opValue);
1364 CreateCodeToLoadConst(target, F, opValue, tmpReg, loadConstVec, mcfi);
1366 // Record the mapping from the tmp VM instruction to machine instruction.
1367 // Do this for all machine instructions that were not mapped to any
1368 // other temp values created by
1369 // tmpReg->addMachineInstruction(loadConstVec.back());
1373 MachineOperand::MachineOperandType
1374 ChooseRegOrImmed(int64_t intValue, bool isSigned,
1375 MachineOpCode opCode, const TargetMachine& target,
1376 bool canUseImmed, unsigned int& getMachineRegNum,
1377 int64_t& getImmedValue) {
1378 MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
1379 getMachineRegNum = 0;
1383 target.getInstrInfo()->constantFitsInImmedField(opCode, intValue)) {
1384 opType = isSigned? MachineOperand::MO_SignExtendedImmed
1385 : MachineOperand::MO_UnextendedImmed;
1386 getImmedValue = intValue;
1387 } else if (intValue == 0 &&
1388 target.getRegInfo()->getZeroRegNum() != (unsigned)-1) {
1389 opType = MachineOperand::MO_MachineRegister;
1390 getMachineRegNum = target.getRegInfo()->getZeroRegNum();
1396 MachineOperand::MachineOperandType
1397 ChooseRegOrImmed(Value* val,
1398 MachineOpCode opCode, const TargetMachine& target,
1399 bool canUseImmed, unsigned int& getMachineRegNum,
1400 int64_t& getImmedValue) {
1401 getMachineRegNum = 0;
1404 // To use reg or immed, constant needs to be integer, bool, or a NULL pointer.
1405 // ConvertConstantToIntType() does the right conversions.
1406 bool isValidConstant;
1407 uint64_t valueToUse =
1408 ConvertConstantToIntType(target, val, val->getType(), isValidConstant);
1409 if (! isValidConstant)
1410 return MachineOperand::MO_VirtualRegister;
1412 // Now check if the constant value fits in the IMMED field.
1413 return ChooseRegOrImmed((int64_t) valueToUse, val->getType()->isSigned(),
1414 opCode, target, canUseImmed,
1415 getMachineRegNum, getImmedValue);
1418 /// CreateCopyInstructionsByType - Create instruction(s) to copy src to dest,
1419 /// for arbitrary types. The generated instructions are returned in `mvec'. Any
1420 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1421 /// space required is allocated via MachineFunction.
1423 void CreateCopyInstructionsByType(const TargetMachine& target,
1424 Function *F, Value* src, Instruction* dest,
1425 std::vector<MachineInstr*>& mvec,
1426 MachineCodeForInstruction& mcfi) {
1427 bool loadConstantToReg = false;
1428 const Type* resultType = dest->getType();
1429 MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1430 assert (opCode != V9::INVALID_OPCODE
1431 && "Unsupported result type in CreateCopyInstructionsByType()");
1433 // If `src' is a constant that doesn't fit in the immed field or if it is
1434 // a global variable (i.e., a constant address), generate a load
1435 // instruction instead of an add.
1436 if (isa<GlobalValue>(src))
1437 loadConstantToReg = true;
1438 else if (isa<Constant>(src)) {
1439 unsigned int machineRegNum;
1441 MachineOperand::MachineOperandType opType =
1442 ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1443 machineRegNum, immedValue);
1445 if (opType == MachineOperand::MO_VirtualRegister)
1446 loadConstantToReg = true;
1449 if (loadConstantToReg) {
1450 // `src' is constant and cannot fit in immed field for the ADD.
1451 // Insert instructions to "load" the constant into a register.
1452 CreateCodeToLoadConst(target, F, src, dest, mvec, mcfi);
1454 // Create a reg-to-reg copy instruction for the given type:
1455 // -- For FP values, create a FMOVS or FMOVD instruction
1456 // -- For non-FP values, create an add-with-0 instruction (opCode as above)
1457 // Make `src' the second operand, in case it is a small constant!
1459 if (resultType->isFloatingPoint())
1460 MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1461 .addReg(src).addRegDef(dest));
1463 const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
1464 MI = (BuildMI(opCode, 3)
1465 .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
1471 /// FixConstantOperandsForInstr - Make a machine instruction use its constant
1472 /// operands more efficiently. If the constant is 0, then use the hardwired 0
1473 /// register, if any. Else, if the constant fits in the IMMEDIATE field, then
1474 /// use that field. Otherwise, else create instructions to put the constant
1475 /// into a register, either directly or by loading explicitly from the constant
1476 /// pool. In the first 2 cases, the operand of `minstr' is modified in place.
1477 /// Returns a vector of machine instructions generated for operands that fall
1478 /// under case 3; these must be inserted before `minstr'.
1480 std::vector<MachineInstr*>
1481 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
1482 TargetMachine& target) {
1483 std::vector<MachineInstr*> MVec;
1485 MachineOpCode opCode = minstr->getOpcode();
1486 const TargetInstrInfo& instrInfo = *target.getInstrInfo();
1487 int resultPos = instrInfo.get(opCode).resultPos;
1488 int immedPos = instrInfo.getImmedConstantPos(opCode);
1490 Function *F = vmInstr->getParent()->getParent();
1492 for (unsigned op=0; op < minstr->getNumOperands(); op++) {
1493 const MachineOperand& mop = minstr->getOperand(op);
1495 // Skip the result position, preallocated machine registers, or operands
1496 // that cannot be constants (CC regs or PC-relative displacements)
1497 if (resultPos == (int)op ||
1498 mop.getType() == MachineOperand::MO_MachineRegister ||
1499 mop.getType() == MachineOperand::MO_CCRegister ||
1500 mop.getType() == MachineOperand::MO_PCRelativeDisp)
1503 bool constantThatMustBeLoaded = false;
1504 unsigned int machineRegNum = 0;
1505 int64_t immedValue = 0;
1506 Value* opValue = NULL;
1507 MachineOperand::MachineOperandType opType =
1508 MachineOperand::MO_VirtualRegister;
1510 // Operand may be a virtual register or a compile-time constant
1511 if (mop.getType() == MachineOperand::MO_VirtualRegister) {
1512 assert(mop.getVRegValue() != NULL);
1513 opValue = mop.getVRegValue();
1514 if (Constant *opConst = dyn_cast<Constant>(opValue))
1515 if (!isa<GlobalValue>(opConst)) {
1516 opType = ChooseRegOrImmed(opConst, opCode, target,
1517 (immedPos == (int)op), machineRegNum,
1519 if (opType == MachineOperand::MO_VirtualRegister)
1520 constantThatMustBeLoaded = true;
1523 // If the operand is from the constant pool, don't try to change it.
1524 if (mop.getType() == MachineOperand::MO_ConstantPoolIndex) {
1527 assert(mop.isImmediate());
1528 bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
1530 // Bit-selection flags indicate an instruction that is extracting
1531 // bits from its operand so ignore this even if it is a big constant.
1532 if (mop.isHiBits32() || mop.isLoBits32() ||
1533 mop.isHiBits64() || mop.isLoBits64())
1536 opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
1537 opCode, target, (immedPos == (int)op),
1538 machineRegNum, immedValue);
1540 if (opType == MachineOperand::MO_SignExtendedImmed ||
1541 opType == MachineOperand::MO_UnextendedImmed) {
1542 // The optype is an immediate value
1543 // This means we need to change the opcode, e.g. ADDr -> ADDi
1544 unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1545 minstr->setOpcode(newOpcode);
1548 if (opType == mop.getType())
1549 continue; // no change: this is the most common case
1551 if (opType == MachineOperand::MO_VirtualRegister) {
1552 constantThatMustBeLoaded = true;
1554 ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
1555 : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
1559 if (opType == MachineOperand::MO_MachineRegister)
1560 minstr->SetMachineOperandReg(op, machineRegNum);
1561 else if (opType == MachineOperand::MO_SignExtendedImmed ||
1562 opType == MachineOperand::MO_UnextendedImmed) {
1563 minstr->SetMachineOperandConst(op, opType, immedValue);
1564 // The optype is or has become an immediate
1565 // This means we need to change the opcode, e.g. ADDr -> ADDi
1566 unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1567 minstr->setOpcode(newOpcode);
1568 } else if (constantThatMustBeLoaded ||
1569 (opValue && isa<GlobalValue>(opValue)))
1570 { // opValue is a constant that must be explicitly loaded into a reg
1572 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
1574 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
1579 // Also, check for implicit operands used by the machine instruction
1580 // (no need to check those defined since they cannot be constants).
1582 // -- arguments to a Call
1583 // -- return value of a Return
1584 // Any such operand that is a constant value needs to be fixed also.
1585 // The current instructions with implicit refs (viz., Call and Return)
1586 // have no immediate fields, so the constant always needs to be loaded
1588 bool isCall = instrInfo.isCall(opCode);
1589 unsigned lastCallArgNum = 0; // unused if not a call
1590 CallArgsDescriptor* argDesc = NULL; // unused if not a call
1592 argDesc = CallArgsDescriptor::get(minstr);
1594 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
1595 if (isa<Constant>(minstr->getImplicitRef(i))) {
1596 Value* oldVal = minstr->getImplicitRef(i);
1597 TmpInstruction* tmpReg =
1598 InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
1599 minstr->setImplicitRef(i, tmpReg);
1602 // find and replace the argument in the CallArgsDescriptor
1603 unsigned i=lastCallArgNum;
1604 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
1606 assert(i < argDesc->getNumArgs() &&
1607 "Constant operands to a call *must* be in the arg list");
1609 argDesc->getArgInfo(i).replaceArgVal(tmpReg);
1616 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
1617 std::vector<MachineInstr*>& mvec) {
1618 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
1619 .addReg(Node->rightChild()->getValue())
1620 .addRegDef(Node->getValue()));
1623 /// IsZero - Check for a constant 0.
1625 static inline bool IsZero(Value* idx) {
1626 return (isa<Constant>(idx) && cast<Constant>(idx)->isNullValue()) ||
1627 isa<UndefValue>(idx);
1630 /// FoldGetElemChain - Fold a chain of GetElementPtr instructions containing
1631 /// only constant offsets into an equivalent (Pointer, IndexVector) pair.
1632 /// Returns the pointer Value, and stores the resulting IndexVector in argument
1633 /// chainIdxVec. This is a helper function for FoldConstantIndices that does the
1637 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
1638 bool lastInstHasLeadingNonZero) {
1639 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
1640 GetElementPtrInst* gepInst =
1641 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
1643 // ptr value is not computed in this tree or ptr value does not come from GEP
1645 if (gepInst == NULL)
1648 // Return NULL if we don't fold any instructions in.
1649 Value* ptrVal = NULL;
1651 // Now chase the chain of getElementInstr instructions, if any.
1652 // Check for any non-constant indices and stop there.
1653 // Also, stop if the first index of child is a non-zero array index
1654 // and the last index of the current node is a non-array index:
1655 // in that case, a non-array declared type is being accessed as an array
1656 // which is not type-safe, but could be legal.
1657 InstructionNode* ptrChild = gepNode;
1658 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
1659 ptrChild->getOpLabel() == GetElemPtrIdx)) {
1660 // Child is a GetElemPtr instruction
1661 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
1662 User::op_iterator OI, firstIdx = gepInst->idx_begin();
1663 User::op_iterator lastIdx = gepInst->idx_end();
1664 bool allConstantOffsets = true;
1666 // The first index of every GEP must be an array index.
1667 assert((*firstIdx)->getType() == Type::LongTy &&
1668 "INTERNAL ERROR: Structure index for a pointer type!");
1670 // If the last instruction had a leading non-zero index, check if the
1671 // current one references a sequential (i.e., indexable) type.
1672 // If not, the code is not type-safe and we would create an illegal GEP
1673 // by folding them, so don't fold any more instructions.
1674 if (lastInstHasLeadingNonZero)
1675 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
1676 break; // cannot fold in any preceding getElementPtr instrs.
1678 // Check that all offsets are constant for this instruction
1679 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
1680 allConstantOffsets = isa<ConstantInt>(*OI);
1682 if (allConstantOffsets) {
1683 // Get pointer value out of ptrChild.
1684 ptrVal = gepInst->getPointerOperand();
1686 // Insert its index vector at the start, skipping any leading [0]
1687 // Remember the old size to check if anything was inserted.
1688 unsigned oldSize = chainIdxVec.size();
1689 int firstIsZero = IsZero(*firstIdx);
1690 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
1692 // Remember if it has leading zero index: it will be discarded later.
1693 if (oldSize < chainIdxVec.size())
1694 lastInstHasLeadingNonZero = !firstIsZero;
1696 // Mark the folded node so no code is generated for it.
1697 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
1699 // Get the previous GEP instruction and continue trying to fold
1700 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
1701 } else // cannot fold this getElementPtr instr. or any preceding ones
1705 // If the first getElementPtr instruction had a leading [0], add it back.
1706 // Note that this instruction is the *last* one that was successfully
1707 // folded *and* contributed any indices, in the loop above.
1708 if (ptrVal && ! lastInstHasLeadingNonZero)
1709 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
1714 /// GetGEPInstArgs - Helper function for GetMemInstArgs that handles the
1715 /// final getElementPtr instruction used by (or same as) the memory operation.
1716 /// Extracts the indices of the current instruction and tries to fold in
1717 /// preceding ones if all indices of the current one are constant.
1719 static Value *GetGEPInstArgs(InstructionNode *gepNode,
1720 std::vector<Value *> &idxVec,
1721 bool &allConstantIndices) {
1722 allConstantIndices = true;
1723 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
1725 // Default pointer is the one from the current instruction.
1726 Value* ptrVal = gepI->getPointerOperand();
1727 InstrTreeNode* ptrChild = gepNode->leftChild();
1729 // Extract the index vector of the GEP instruction.
1730 // If all indices are constant and first index is zero, try to fold
1731 // in preceding GEPs with all constant indices.
1732 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
1733 allConstantIndices && OI != OE; ++OI)
1734 if (! isa<Constant>(*OI))
1735 allConstantIndices = false; // note: this also terminates loop!
1737 // If we have only constant indices, fold chains of constant indices
1738 // in this and any preceding GetElemPtr instructions.
1739 bool foldedGEPs = false;
1740 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
1741 if (allConstantIndices)
1742 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
1747 // Append the index vector of the current instruction.
1748 // Skip the leading [0] index if preceding GEPs were folded into this.
1749 idxVec.insert(idxVec.end(),
1750 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
1756 /// GetMemInstArgs - Get the pointer value and the index vector for a memory
1757 /// operation (GetElementPtr, Load, or Store). If all indices of the given
1758 /// memory operation are constant, fold in constant indices in a chain of
1759 /// preceding GetElementPtr instructions (if any), and return the pointer value
1760 /// of the first instruction in the chain. All folded instructions are marked so
1761 /// no code is generated for them. Returns the pointer Value to use, and
1762 /// returns the resulting IndexVector in idxVec. Sets allConstantIndices
1763 /// to true/false if all indices are/aren't const.
1765 static Value *GetMemInstArgs(InstructionNode *memInstrNode,
1766 std::vector<Value*> &idxVec,
1767 bool& allConstantIndices) {
1768 allConstantIndices = false;
1769 Instruction* memInst = memInstrNode->getInstruction();
1770 assert(idxVec.size() == 0 && "Need empty vector to return indices");
1772 // If there is a GetElemPtr instruction to fold in to this instr,
1773 // it must be in the left child for Load and GetElemPtr, and in the
1774 // right child for Store instructions.
1775 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
1776 ? memInstrNode->rightChild()
1777 : memInstrNode->leftChild());
1779 // Default pointer is the one from the current instruction.
1780 Value* ptrVal = ptrChild->getValue();
1782 // Find the "last" GetElemPtr instruction: this one or the immediate child.
1783 // There will be none if this is a load or a store from a scalar pointer.
1784 InstructionNode* gepNode = NULL;
1785 if (isa<GetElementPtrInst>(memInst))
1786 gepNode = memInstrNode;
1787 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
1788 // Child of load/store is a GEP and memInst is its only use.
1789 // Use its indices and mark it as folded.
1790 gepNode = cast<InstructionNode>(ptrChild);
1791 gepNode->markFoldedIntoParent();
1794 // If there are no indices, return the current pointer.
1795 // Else extract the pointer from the GEP and fold the indices.
1796 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
1800 static inline MachineOpCode
1801 ChooseBprInstruction(const InstructionNode* instrNode) {
1802 MachineOpCode opCode;
1804 Instruction* setCCInstr =
1805 ((InstructionNode*) instrNode->leftChild())->getInstruction();
1807 switch(setCCInstr->getOpcode()) {
1808 case Instruction::SetEQ: opCode = V9::BRZ; break;
1809 case Instruction::SetNE: opCode = V9::BRNZ; break;
1810 case Instruction::SetLE: opCode = V9::BRLEZ; break;
1811 case Instruction::SetGE: opCode = V9::BRGEZ; break;
1812 case Instruction::SetLT: opCode = V9::BRLZ; break;
1813 case Instruction::SetGT: opCode = V9::BRGZ; break;
1815 assert(0 && "Unrecognized VM instruction!");
1816 opCode = V9::INVALID_OPCODE;
1823 static inline MachineOpCode
1824 ChooseBpccInstruction(const InstructionNode* instrNode,
1825 const BinaryOperator* setCCInstr) {
1826 MachineOpCode opCode = V9::INVALID_OPCODE;
1828 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
1831 switch(setCCInstr->getOpcode()) {
1832 case Instruction::SetEQ: opCode = V9::BE; break;
1833 case Instruction::SetNE: opCode = V9::BNE; break;
1834 case Instruction::SetLE: opCode = V9::BLE; break;
1835 case Instruction::SetGE: opCode = V9::BGE; break;
1836 case Instruction::SetLT: opCode = V9::BL; break;
1837 case Instruction::SetGT: opCode = V9::BG; break;
1839 assert(0 && "Unrecognized VM instruction!");
1843 switch(setCCInstr->getOpcode()) {
1844 case Instruction::SetEQ: opCode = V9::BE; break;
1845 case Instruction::SetNE: opCode = V9::BNE; break;
1846 case Instruction::SetLE: opCode = V9::BLEU; break;
1847 case Instruction::SetGE: opCode = V9::BCC; break;
1848 case Instruction::SetLT: opCode = V9::BCS; break;
1849 case Instruction::SetGT: opCode = V9::BGU; break;
1851 assert(0 && "Unrecognized VM instruction!");
1859 static inline MachineOpCode
1860 ChooseBFpccInstruction(const InstructionNode* instrNode,
1861 const BinaryOperator* setCCInstr) {
1862 MachineOpCode opCode = V9::INVALID_OPCODE;
1864 switch(setCCInstr->getOpcode()) {
1865 case Instruction::SetEQ: opCode = V9::FBE; break;
1866 case Instruction::SetNE: opCode = V9::FBNE; break;
1867 case Instruction::SetLE: opCode = V9::FBLE; break;
1868 case Instruction::SetGE: opCode = V9::FBGE; break;
1869 case Instruction::SetLT: opCode = V9::FBL; break;
1870 case Instruction::SetGT: opCode = V9::FBG; break;
1872 assert(0 && "Unrecognized VM instruction!");
1879 // GetTmpForCC - Create a unique TmpInstruction for a boolean value,
1880 // representing the CC register used by a branch on that value.
1881 // For now, hack this using a little static cache of TmpInstructions.
1882 // Eventually the entire BURG instruction selection should be put
1883 // into a separate class that can hold such information.
1884 // The static cache is not too bad because the memory for these
1885 // TmpInstructions will be freed along with the rest of the Function anyway.
1887 static TmpInstruction *GetTmpForCC (Value* boolVal, const Function *F,
1889 MachineCodeForInstruction& mcfi) {
1890 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
1891 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
1892 static const Function *lastFunction = 0;// Use to flush cache between funcs
1894 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
1896 if (lastFunction != F) {
1898 boolToTmpCache.clear();
1901 // Look for tmpI and create a new one otherwise. The new value is
1902 // directly written to map using the ref returned by operator[].
1903 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
1905 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
1910 static inline MachineOpCode
1911 ChooseBccInstruction(const InstructionNode* instrNode, const Type*& setCCType) {
1912 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
1913 assert(setCCNode->getOpLabel() == SetCCOp);
1914 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
1915 setCCType = setCCInstr->getOperand(0)->getType();
1917 if (setCCType->isFloatingPoint())
1918 return ChooseBFpccInstruction(instrNode, setCCInstr);
1920 return ChooseBpccInstruction(instrNode, setCCInstr);
1923 /// ChooseMovFpcciInstruction - WARNING: since this function has only one
1924 /// caller, it always returns the opcode that expects an immediate and a
1925 /// register. If this function is ever used in cases where an opcode that takes
1926 /// two registers is required, then modify this function and use
1927 /// convertOpcodeFromRegToImm() where required. It will be necessary to expand
1928 /// convertOpcodeFromRegToImm() to handle the new cases of opcodes.
1930 static inline MachineOpCode
1931 ChooseMovFpcciInstruction(const InstructionNode* instrNode) {
1932 MachineOpCode opCode = V9::INVALID_OPCODE;
1934 switch(instrNode->getInstruction()->getOpcode()) {
1935 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
1936 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
1937 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
1938 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
1939 case Instruction::SetLT: opCode = V9::MOVFLi; break;
1940 case Instruction::SetGT: opCode = V9::MOVFGi; break;
1942 assert(0 && "Unrecognized VM instruction!");
1949 /// ChooseMovpcciForSetCC -- Choose a conditional-move instruction
1950 /// based on the type of SetCC operation.
1952 /// WARNING: like the previous function, this function always returns
1953 /// the opcode that expects an immediate and a register. See above.
1955 static MachineOpCode ChooseMovpcciForSetCC(const InstructionNode* instrNode) {
1956 MachineOpCode opCode = V9::INVALID_OPCODE;
1958 const Type* opType = instrNode->leftChild()->getValue()->getType();
1959 assert(opType->isIntegral() || isa<PointerType>(opType));
1960 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
1962 switch(instrNode->getInstruction()->getOpcode()) {
1963 case Instruction::SetEQ: opCode = V9::MOVEi; break;
1964 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
1965 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
1966 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
1967 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
1968 case Instruction::SetNE: opCode = V9::MOVNEi; break;
1969 default: assert(0 && "Unrecognized LLVM instr!"); break;
1975 /// ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
1976 /// instruction based on the type of SetCC operation. These instructions
1977 /// compare a register with 0 and perform the move is the comparison is true.
1979 /// WARNING: like the previous function, this function it always returns
1980 /// the opcode that expects an immediate and a register. See above.
1982 static MachineOpCode ChooseMovpregiForSetCC(const InstructionNode* instrNode) {
1983 MachineOpCode opCode = V9::INVALID_OPCODE;
1985 switch(instrNode->getInstruction()->getOpcode()) {
1986 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
1987 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
1988 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
1989 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
1990 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
1991 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
1992 default: assert(0 && "Unrecognized VM instr!"); break;
1998 static inline MachineOpCode
1999 ChooseConvertToFloatInstr(const TargetMachine& target,
2000 OpLabel vopCode, const Type* opType) {
2001 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
2002 "Unrecognized convert-to-float opcode!");
2003 assert((opType->isIntegral() || opType->isFloatingPoint() ||
2004 isa<PointerType>(opType))
2005 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
2007 MachineOpCode opCode = V9::INVALID_OPCODE;
2009 unsigned opSize = target.getTargetData().getTypeSize(opType);
2011 if (opType == Type::FloatTy)
2012 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
2013 else if (opType == Type::DoubleTy)
2014 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
2015 else if (opSize <= 4)
2016 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
2018 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
2019 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
2025 static inline MachineOpCode
2026 ChooseConvertFPToIntInstr(const TargetMachine& target,
2027 const Type* destType, const Type* opType) {
2028 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
2029 && "This function should only be called for FLOAT or DOUBLE");
2030 assert((destType->isIntegral() || isa<PointerType>(destType))
2031 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
2033 MachineOpCode opCode = V9::INVALID_OPCODE;
2035 unsigned destSize = target.getTargetData().getTypeSize(destType);
2037 if (destType == Type::UIntTy)
2038 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
2039 else if (destSize <= 4)
2040 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
2042 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
2043 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
2049 static MachineInstr*
2050 CreateConvertFPToIntInstr(const TargetMachine& target, Value* srcVal,
2051 Value* destVal, const Type* destType) {
2052 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
2054 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
2055 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
2058 /// CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned
2059 /// integer. The FP value must be converted to the dest type in an FP register,
2060 /// and the result is then copied from FP to int register via memory. SPARC
2061 /// does not have a float-to-uint conversion, only a float-to-int (fdtoi).
2062 /// Since fdtoi converts to signed integers, any FP value V between MAXINT+1 and
2063 /// MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
2064 /// Therefore, for converting an FP value to uint32_t, we first need to convert
2065 /// to uint64_t and then to uint32_t.
2068 CreateCodeToConvertFloatToInt(const TargetMachine& target,
2069 Value* opVal, Instruction* destI,
2070 std::vector<MachineInstr*>& mvec,
2071 MachineCodeForInstruction& mcfi) {
2072 Function* F = destI->getParent()->getParent();
2074 // Create a temporary to represent the FP register into which the
2075 // int value will placed after conversion. The type of this temporary
2076 // depends on the type of FP register to use: single-prec for a 32-bit
2077 // int or smaller; double-prec for a 64-bit int.
2078 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
2080 const Type* castDestType = destI->getType(); // type for the cast instr result
2081 const Type* castDestRegType; // type for cast instruction result reg
2082 TmpInstruction* destForCast; // dest for cast instruction
2083 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
2085 // For converting an FP value to uint32_t, we first need to convert to
2086 // uint64_t and then to uint32_t, as explained above.
2087 if (destI->getType() == Type::UIntTy) {
2088 castDestType = Type::ULongTy; // use this instead of type of destI
2089 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
2090 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2091 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
2093 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
2094 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2097 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
2098 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
2101 // Create the fpreg-to-intreg copy code
2102 CreateCodeToCopyFloatToInt(target, F, destForCast, fpToIntCopyDest, mvec,
2105 // Create the uint64_t to uint32_t conversion, if needed
2106 if (destI->getType() == Type::UIntTy)
2107 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
2108 /*numLowBits*/ 32, mvec, mcfi);
2111 static inline MachineOpCode
2112 ChooseAddInstruction(const InstructionNode* instrNode) {
2113 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
2116 static inline MachineInstr*
2117 CreateMovFloatInstruction(const InstructionNode* instrNode,
2118 const Type* resultType) {
2119 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
2120 .addReg(instrNode->leftChild()->getValue())
2121 .addRegDef(instrNode->getValue());
2124 static inline MachineInstr*
2125 CreateAddConstInstruction(const InstructionNode* instrNode) {
2126 MachineInstr* minstr = NULL;
2128 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2129 assert(isa<Constant>(constOp));
2131 // Cases worth optimizing are:
2132 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
2133 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
2134 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2135 double dval = FPC->getValue();
2137 minstr = CreateMovFloatInstruction(instrNode,
2138 instrNode->getInstruction()->getType());
2144 static inline MachineOpCode ChooseSubInstructionByType(const Type* resultType) {
2145 MachineOpCode opCode = V9::INVALID_OPCODE;
2147 if (resultType->isInteger() || isa<PointerType>(resultType)) {
2150 switch(resultType->getTypeID()) {
2151 case Type::FloatTyID: opCode = V9::FSUBS; break;
2152 case Type::DoubleTyID: opCode = V9::FSUBD; break;
2153 default: assert(0 && "Invalid type for SUB instruction"); break;
2160 static inline MachineInstr*
2161 CreateSubConstInstruction(const InstructionNode* instrNode) {
2162 MachineInstr* minstr = NULL;
2164 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2165 assert(isa<Constant>(constOp));
2167 // Cases worth optimizing are:
2168 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
2169 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
2170 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2171 double dval = FPC->getValue();
2173 minstr = CreateMovFloatInstruction(instrNode,
2174 instrNode->getInstruction()->getType());
2180 static inline MachineOpCode
2181 ChooseFcmpInstruction(const InstructionNode* instrNode) {
2182 MachineOpCode opCode = V9::INVALID_OPCODE;
2184 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
2185 switch(operand->getType()->getTypeID()) {
2186 case Type::FloatTyID: opCode = V9::FCMPS; break;
2187 case Type::DoubleTyID: opCode = V9::FCMPD; break;
2188 default: assert(0 && "Invalid type for FCMP instruction"); break;
2194 /// BothFloatToDouble - Assumes that leftArg and rightArg of instrNode are both
2195 /// cast instructions. Returns true if both are floats cast to double.
2197 static inline bool BothFloatToDouble(const InstructionNode* instrNode) {
2198 InstrTreeNode* leftArg = instrNode->leftChild();
2199 InstrTreeNode* rightArg = instrNode->rightChild();
2200 InstrTreeNode* leftArgArg = leftArg->leftChild();
2201 InstrTreeNode* rightArgArg = rightArg->leftChild();
2202 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
2203 return (leftArg->getValue()->getType() == Type::DoubleTy &&
2204 leftArgArg->getValue()->getType() == Type::FloatTy &&
2205 rightArgArg->getValue()->getType() == Type::FloatTy);
2208 static inline MachineOpCode ChooseMulInstructionByType(const Type* resultType) {
2209 MachineOpCode opCode = V9::INVALID_OPCODE;
2211 if (resultType->isInteger())
2214 switch(resultType->getTypeID()) {
2215 case Type::FloatTyID: opCode = V9::FMULS; break;
2216 case Type::DoubleTyID: opCode = V9::FMULD; break;
2217 default: assert(0 && "Invalid type for MUL instruction"); break;
2223 static inline MachineInstr*
2224 CreateIntNegInstruction(const TargetMachine& target, Value* vreg) {
2225 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
2226 .addReg(vreg).addRegDef(vreg);
2229 /// CreateShiftInstructions - Create instruction sequence for any shift
2230 /// operation. SLL or SLLX on an operand smaller than the integer reg. size
2231 /// (64bits) requires a second instruction for explicit sign-extension. Note
2232 /// that we only have to worry about a sign-bit appearing in the most
2233 /// significant bit of the operand after shifting (e.g., bit 32 of Int or bit 16
2234 /// of Short), so we do not have to worry about results that are as large as a
2235 /// normal integer register.
2238 CreateShiftInstructions(const TargetMachine& target, Function* F,
2239 MachineOpCode shiftOpCode, Value* argVal1,
2240 Value* optArgVal2, /* Use optArgVal2 if not NULL */
2241 unsigned optShiftNum, /* else use optShiftNum */
2242 Instruction* destVal, std::vector<MachineInstr*>& mvec,
2243 MachineCodeForInstruction& mcfi) {
2244 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
2245 "Large shift sizes unexpected, but can be handled below: "
2246 "You need to check whether or not it fits in immed field below");
2248 // If this is a logical left shift of a type smaller than the standard
2249 // integer reg. size, we have to extend the sign-bit into upper bits
2250 // of dest, so we need to put the result of the SLL into a temporary.
2251 Value* shiftDest = destVal;
2252 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
2254 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
2255 // put SLL result into a temporary
2256 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
2259 MachineInstr* M = (optArgVal2 != NULL)
2260 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
2261 .addReg(shiftDest, MachineOperand::Def)
2262 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
2263 .addReg(shiftDest, MachineOperand::Def);
2266 if (shiftDest != destVal) {
2267 // extend the sign-bit of the result into all upper bits of dest
2268 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
2269 CreateSignExtensionInstructions(target, F, shiftDest, destVal, 8*opSize,
2274 /// CreateMulConstInstruction - Does not create any instructions if we
2275 /// cannot exploit constant to create a cheaper instruction. This returns the
2276 /// approximate cost of the instructions generated, which is used to pick the
2277 /// cheapest when both operands are constant.
2280 CreateMulConstInstruction(const TargetMachine &target, Function* F,
2281 Value* lval, Value* rval, Instruction* destVal,
2282 std::vector<MachineInstr*>& mvec,
2283 MachineCodeForInstruction& mcfi) {
2284 // Use max. multiply cost, viz., cost of MULX
2285 unsigned cost = target.getInstrInfo()->minLatency(V9::MULXr);
2286 unsigned firstNewInstr = mvec.size();
2288 Value* constOp = rval;
2289 if (! isa<Constant>(constOp))
2292 // Cases worth optimizing are:
2293 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
2294 // (2) Multiply by 2^x for integer types: replace with Shift
2295 const Type* resultType = destVal->getType();
2297 if (resultType->isInteger() || isa<PointerType>(resultType)) {
2299 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2304 bool needNeg = false;
2310 if (C == 0 || C == 1) {
2311 cost = target.getInstrInfo()->minLatency(V9::ADDr);
2312 unsigned Zero = target.getRegInfo()->getZeroRegNum();
2315 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
2317 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
2319 } else if (isPowerOf2(C, pow)) {
2320 unsigned opSize = target.getTargetData().getTypeSize(resultType);
2321 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
2322 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
2323 destVal, mvec, mcfi);
2326 if (mvec.size() > 0 && needNeg) {
2327 // insert <reg = SUB 0, reg> after the instr to flip the sign
2328 MachineInstr* M = CreateIntNegInstruction(target, destVal);
2333 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2334 double dval = FPC->getValue();
2335 if (fabs(dval) == 1) {
2336 MachineOpCode opCode = (dval < 0)
2337 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2338 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2339 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
2344 if (firstNewInstr < mvec.size()) {
2346 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
2347 cost += target.getInstrInfo()->minLatency(mvec[i]->getOpcode());
2353 /// CreateCheapestMulConstInstruction - Does not create any instructions
2354 /// if we cannot exploit constant to create a cheaper instruction.
2357 CreateCheapestMulConstInstruction(const TargetMachine &target, Function* F,
2358 Value* lval, Value* rval,
2359 Instruction* destVal,
2360 std::vector<MachineInstr*>& mvec,
2361 MachineCodeForInstruction& mcfi) {
2363 if (isa<Constant>(lval) && isa<Constant>(rval)) {
2364 // both operands are constant: evaluate and "set" in dest
2365 Constant* P = ConstantExpr::get(Instruction::Mul,
2366 cast<Constant>(lval),
2367 cast<Constant>(rval));
2368 CreateCodeToLoadConst (target, F, P, destVal, mvec, mcfi);
2370 else if (isa<Constant>(rval)) // rval is constant, but not lval
2371 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2372 else if (isa<Constant>(lval)) // lval is constant, but not rval
2373 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2375 // else neither is constant
2379 /// CreateMulInstruction - Returns NULL if we cannot exploit constant
2380 /// to create a cheaper instruction.
2383 CreateMulInstruction(const TargetMachine &target, Function* F,
2384 Value* lval, Value* rval, Instruction* destVal,
2385 std::vector<MachineInstr*>& mvec,
2386 MachineCodeForInstruction& mcfi,
2387 MachineOpCode forceMulOp = -1) {
2388 unsigned L = mvec.size();
2389 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
2390 if (mvec.size() == L) {
2391 // no instructions were added so create MUL reg, reg, reg.
2392 // Use FSMULD if both operands are actually floats cast to doubles.
2393 // Otherwise, use the default opcode for the appropriate type.
2394 MachineOpCode mulOp = ((forceMulOp != -1)
2396 : ChooseMulInstructionByType(destVal->getType()));
2397 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
2398 .addRegDef(destVal));
2402 /// ChooseDivInstruction - Generate a divide instruction for Div or Rem.
2403 /// For Rem, this assumes that the operand type will be signed if the result
2404 /// type is signed. This is correct because they must have the same sign.
2406 static inline MachineOpCode
2407 ChooseDivInstruction(TargetMachine &target, const InstructionNode* instrNode) {
2408 MachineOpCode opCode = V9::INVALID_OPCODE;
2410 const Type* resultType = instrNode->getInstruction()->getType();
2412 if (resultType->isInteger())
2413 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
2415 switch(resultType->getTypeID()) {
2416 case Type::FloatTyID: opCode = V9::FDIVS; break;
2417 case Type::DoubleTyID: opCode = V9::FDIVD; break;
2418 default: assert(0 && "Invalid type for DIV instruction"); break;
2424 /// CreateDivConstInstruction - Return if we cannot exploit constant to create
2425 /// a cheaper instruction.
2427 static void CreateDivConstInstruction(TargetMachine &target,
2428 const InstructionNode* instrNode,
2429 std::vector<MachineInstr*>& mvec) {
2430 Value* LHS = instrNode->leftChild()->getValue();
2431 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2432 if (!isa<Constant>(constOp))
2435 Instruction* destVal = instrNode->getInstruction();
2436 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
2438 // Cases worth optimizing are:
2439 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
2440 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
2441 const Type* resultType = instrNode->getInstruction()->getType();
2443 if (resultType->isInteger()) {
2446 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2450 bool needNeg = false;
2457 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
2458 .addRegDef(destVal));
2459 } else if (isPowerOf2(C, pow)) {
2461 Value* shiftOperand;
2462 unsigned opSize = target.getTargetData().getTypeSize(resultType);
2464 if (resultType->isSigned()) {
2465 // For N / 2^k, if the operand N is negative,
2466 // we need to add (2^k - 1) before right-shifting by k, i.e.,
2468 // (N / 2^k) = N >> k, if N >= 0;
2469 // (N + 2^k - 1) >> k, if N < 0
2471 // If N is <= 32 bits, use:
2472 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
2473 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
2474 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
2475 // sra t3, k, result // result = N / 2^k
2477 // If N is 64 bits, use:
2478 // srax N, k-1, t1 // t1 = sign bit in high k positions
2479 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
2480 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
2481 // sra t3, k, result // result = N / 2^k
2482 TmpInstruction *sraTmp, *srlTmp, *addTmp;
2483 MachineCodeForInstruction& mcfi
2484 = MachineCodeForInstruction::get(destVal);
2485 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
2486 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
2487 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
2489 // Create the SRA or SRAX instruction to get the sign bit
2490 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
2492 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
2493 .addRegDef(sraTmp));
2495 // Create the SRL or SRLX instruction to get the sign bit
2496 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
2498 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
2499 .addRegDef(srlTmp));
2501 // Create the ADD instruction to add 2^pow-1 for negative values
2502 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
2503 .addRegDef(addTmp));
2505 // Get the shift operand and "right-shift" opcode to do the divide
2506 shiftOperand = addTmp;
2507 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
2509 // Get the shift operand and "right-shift" opcode to do the divide
2511 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
2514 // Now do the actual shift!
2515 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
2516 .addRegDef(destVal));
2519 if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
2520 // insert <reg = SUB 0, reg> after the instr to flip the sign
2521 mvec.push_back(CreateIntNegInstruction(target, destVal));
2525 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2526 double dval = FPC->getValue();
2527 if (fabs(dval) == 1) {
2529 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2530 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2532 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
2538 static void CreateCodeForVariableSizeAlloca(const TargetMachine& target,
2539 Instruction* result, unsigned tsize,
2540 Value* numElementsVal,
2541 std::vector<MachineInstr*>& getMvec)
2543 Value* totalSizeVal;
2545 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
2546 Function *F = result->getParent()->getParent();
2548 // Enforce the alignment constraints on the stack pointer at
2549 // compile time if the total size is a known constant.
2550 if (isa<Constant>(numElementsVal)) {
2552 int64_t numElem = (int64_t)
2553 ConvertConstantToIntType(target, numElementsVal,
2554 numElementsVal->getType(), isValid);
2555 assert(isValid && "Unexpectedly large array dimension in alloca!");
2556 int64_t total = numElem * tsize;
2557 if (int extra= total % SparcV9FrameInfo::StackFrameSizeAlignment)
2558 total += SparcV9FrameInfo::StackFrameSizeAlignment - extra;
2559 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
2561 // The size is not a constant. Generate code to compute it and
2562 // code to pad the size for stack alignment.
2563 // Create a Value to hold the (constant) element size
2564 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
2566 // Create temporary values to hold the result of MUL, SLL, SRL
2567 // To pad `size' to next smallest multiple of 16:
2568 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
2569 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
2570 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
2571 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
2573 // Instruction 1: mul numElements, typeSize -> tmpProd
2574 // This will optimize the MUL as far as possible.
2575 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
2578 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
2579 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
2580 .addReg(tmpAdd15, MachineOperand::Def));
2582 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
2583 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
2584 .addReg(tmpAndf0, MachineOperand::Def));
2586 totalSizeVal = tmpAndf0;
2589 // Get the constant offset from SP for dynamically allocated storage
2590 // and create a temporary Value to hold it.
2591 MachineFunction& mcInfo = MachineFunction::get(F);
2593 ConstantSInt* dynamicAreaOffset =
2594 ConstantSInt::get(Type::IntTy,
2595 target.getFrameInfo()->getDynamicAreaOffset(mcInfo,growUp));
2596 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
2598 unsigned SPReg = target.getRegInfo()->getStackPointer();
2600 // Instruction 2: sub %sp, totalSizeVal -> %sp
2601 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
2602 .addMReg(SPReg,MachineOperand::Def));
2604 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
2605 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
2606 .addRegDef(result));
2610 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
2611 Instruction* result, unsigned tsize,
2612 unsigned numElements,
2613 std::vector<MachineInstr*>& getMvec) {
2614 assert(result && result->getParent() &&
2615 "Result value is not part of a function?");
2616 Function *F = result->getParent()->getParent();
2617 MachineFunction &mcInfo = MachineFunction::get(F);
2619 // If the alloca is of zero bytes (which is perfectly legal) we bump it up to
2620 // one byte. This is unnecessary, but I really don't want to break any
2621 // fragile logic in this code. FIXME.
2625 // Put the variable in the dynamically sized area of the frame if either:
2626 // (a) The offset is too large to use as an immediate in load/stores
2627 // (check LDX because all load/stores have the same-size immed. field).
2628 // (b) The object is "large", so it could cause many other locals,
2629 // spills, and temporaries to have large offsets.
2630 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
2631 // You've gotta love having only 13 bits for constant offset values :-|.
2633 unsigned paddedSize;
2634 int offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->computeOffsetforLocalVar(result,
2636 tsize * numElements);
2638 if (((int)paddedSize) > 8 * SparcV9FrameInfo::SizeOfEachArgOnStack ||
2639 !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
2640 CreateCodeForVariableSizeAlloca(target, result, tsize,
2641 ConstantSInt::get(Type::IntTy,numElements),
2646 // else offset fits in immediate field so go ahead and allocate it.
2647 offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(result, tsize *numElements);
2649 // Create a temporary Value to hold the constant offset.
2650 // This is needed because it may not fit in the immediate field.
2651 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
2653 // Instruction 1: add %fp, offsetFromFP -> result
2654 unsigned FPReg = target.getRegInfo()->getFramePointer();
2655 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
2656 .addRegDef(result));
2659 /// SetOperandsForMemInstr - Choose addressing mode for the given load or store
2660 /// instruction. Use [reg+reg] if it is an indexed reference, and the index
2661 /// offset is not a constant or if it cannot fit in the offset field. Use
2662 /// [reg+offset] in all other cases. This assumes that all array refs are
2663 /// "lowered" to one of these forms:
2664 /// %x = load (subarray*) ptr, constant ; single constant offset
2665 /// %x = load (subarray*) ptr, offsetVal ; single non-constant offset
2666 /// Generally, this should happen via strength reduction + LICM. Also, strength
2667 /// reduction should take care of using the same register for the loop index
2668 /// variable and an array index, when that is profitable.
2670 static void SetOperandsForMemInstr(unsigned Opcode,
2671 std::vector<MachineInstr*>& mvec,
2672 InstructionNode* vmInstrNode,
2673 const TargetMachine& target) {
2674 Instruction* memInst = vmInstrNode->getInstruction();
2675 // Index vector, ptr value, and flag if all indices are const.
2676 std::vector<Value*> idxVec;
2677 bool allConstantIndices;
2678 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
2680 // Now create the appropriate operands for the machine instruction.
2681 // First, initialize so we default to storing the offset in a register.
2682 int64_t smallConstOffset = 0;
2683 Value* valueForRegOffset = NULL;
2684 MachineOperand::MachineOperandType offsetOpType =
2685 MachineOperand::MO_VirtualRegister;
2687 // Check if there is an index vector and if so, compute the
2688 // right offset for structures and for arrays
2689 if (!idxVec.empty()) {
2690 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
2692 // If all indices are constant, compute the combined offset directly.
2693 if (allConstantIndices) {
2694 // Compute the offset value using the index vector. Create a
2695 // virtual reg. for it since it may not fit in the immed field.
2696 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
2697 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
2699 // There is at least one non-constant offset. Therefore, this must
2700 // be an array ref, and must have been lowered to a single non-zero
2701 // offset. (An extra leading zero offset, if any, can be ignored.)
2702 // Generate code sequence to compute address from index.
2703 bool firstIdxIsZero = IsZero(idxVec[0]);
2704 assert(idxVec.size() == 1U + firstIdxIsZero
2705 && "Array refs must be lowered before Instruction Selection");
2707 Value* idxVal = idxVec[firstIdxIsZero];
2709 std::vector<MachineInstr*> mulVec;
2711 new TmpInstruction(MachineCodeForInstruction::get(memInst),
2712 Type::ULongTy, memInst);
2714 // Get the array type indexed by idxVal, and compute its element size.
2715 // The call to getTypeSize() will fail if size is not constant.
2716 const Type* vecType = (firstIdxIsZero
2717 ? GetElementPtrInst::getIndexedType(ptrType,
2718 std::vector<Value*>(1U, idxVec[0]),
2719 /*AllowCompositeLeaf*/ true)
2721 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
2722 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
2723 target.getTargetData().getTypeSize(eltType));
2725 // CreateMulInstruction() folds constants intelligently enough.
2726 CreateMulInstruction(target, memInst->getParent()->getParent(),
2727 idxVal, /* lval, not likely to be const*/
2728 eltSizeVal, /* rval, likely to be constant */
2730 mulVec, MachineCodeForInstruction::get(memInst),
2733 assert(mulVec.size() > 0 && "No multiply code created?");
2734 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
2736 valueForRegOffset = addr;
2739 offsetOpType = MachineOperand::MO_SignExtendedImmed;
2740 smallConstOffset = 0;
2744 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
2745 // For LOAD or GET_ELEMENT_PTR,
2746 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
2747 unsigned offsetOpNum, ptrOpNum;
2749 if (memInst->getOpcode() == Instruction::Store) {
2750 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2751 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2752 .addReg(ptrVal).addReg(valueForRegOffset);
2754 Opcode = convertOpcodeFromRegToImm(Opcode);
2755 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2756 .addReg(ptrVal).addSImm(smallConstOffset);
2759 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2760 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
2761 .addRegDef(memInst);
2763 Opcode = convertOpcodeFromRegToImm(Opcode);
2764 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
2765 .addRegDef(memInst);
2771 /// ForwardOperand - Substitute operand `operandNum' of the instruction in
2772 /// node `treeNode' in place of the use(s) of that instruction in node `parent'.
2773 /// Check both explicit and implicit operands! Also make sure to skip over a
2774 /// parent who: (1) is a list node in the Burg tree, or (2) itself had its
2775 /// results forwarded to its parent.
2777 static void ForwardOperand (InstructionNode *treeNode, InstrTreeNode *parent,
2779 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
2781 Instruction* unusedOp = treeNode->getInstruction();
2782 Value* fwdOp = unusedOp->getOperand(operandNum);
2784 // The parent itself may be a list node, so find the real parent instruction
2785 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode) {
2786 parent = parent->parent();
2787 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
2789 InstructionNode* parentInstrNode = (InstructionNode*) parent;
2791 Instruction* userInstr = parentInstrNode->getInstruction();
2792 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
2794 // The parent's mvec would be empty if it was itself forwarded.
2795 // Recursively call ForwardOperand in that case...
2797 if (mvec.size() == 0) {
2798 assert(parent->parent() != NULL &&
2799 "Parent could not have been forwarded, yet has no instructions?");
2800 ForwardOperand(treeNode, parent->parent(), operandNum);
2802 for (unsigned i=0, N=mvec.size(); i < N; i++) {
2803 MachineInstr* minstr = mvec[i];
2804 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
2805 const MachineOperand& mop = minstr->getOperand(i);
2806 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
2807 mop.getVRegValue() == unusedOp) {
2808 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
2813 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
2814 if (minstr->getImplicitRef(i) == unusedOp)
2815 minstr->setImplicitRef(i, fwdOp);
2820 /// AllUsesAreBranches - Returns true if all the uses of I are
2821 /// Branch instructions, false otherwise.
2823 inline bool AllUsesAreBranches(const Instruction* I) {
2824 for (Value::use_const_iterator UI=I->use_begin(), UE=I->use_end();
2826 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
2827 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
2832 /// CodeGenIntrinsic - Generate code for any intrinsic that needs a special
2833 /// code sequence instead of a regular call. If not that kind of intrinsic, do
2834 /// nothing. Returns true if code was generated, otherwise false.
2836 static bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
2837 TargetMachine &target,
2838 std::vector<MachineInstr*>& mvec) {
2841 assert(0 && "Unknown intrinsic function call should have been lowered!");
2842 case Intrinsic::vastart: {
2843 // Get the address of the first incoming vararg argument on the stack
2844 Function* func = cast<Function>(callInstr.getParent()->getParent());
2845 int numFixedArgs = func->getFunctionType()->getNumParams();
2846 int fpReg = SparcV9::i6;
2847 int firstVarArgOff = numFixedArgs * 8 +
2848 SparcV9FrameInfo::FirstIncomingArgOffsetFromFP;
2849 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
2850 addRegDef(&callInstr));
2854 case Intrinsic::vaend:
2855 return true; // no-op on SparcV9
2857 case Intrinsic::vacopy:
2858 // Simple copy of current va_list (arg1) to new va_list (result)
2859 mvec.push_back(BuildMI(V9::ORr, 3).
2860 addMReg(target.getRegInfo()->getZeroRegNum()).
2861 addReg(callInstr.getOperand(1)).
2862 addRegDef(&callInstr));
2867 /// ThisIsAChainRule - returns true if the given BURG rule is a chain rule.
2869 extern bool ThisIsAChainRule(int eruleno) {
2871 case 111: // stmt: reg
2895 return false; break;
2899 /// GetInstructionsByRule - Choose machine instructions for the
2900 /// SPARC V9 according to the patterns chosen by the BURG-generated parser.
2901 /// This is where most of the work in the V9 instruction selector gets done.
2903 void GetInstructionsByRule(InstructionNode* subtreeRoot, int ruleForNode,
2904 short* nts, TargetMachine &target,
2905 std::vector<MachineInstr*>& mvec) {
2906 bool checkCast = false; // initialize here to use fall-through
2907 bool maskUnsignedResult = false;
2909 int forwardOperandNum = -1;
2910 unsigned allocaSize = 0;
2911 MachineInstr* M, *M2;
2913 bool foldCase = false;
2917 // If the code for this instruction was folded into the parent (user),
2919 if (subtreeRoot->isFoldedIntoParent())
2922 // Let's check for chain rules outside the switch so that we don't have
2923 // to duplicate the list of chain rule production numbers here again
2924 if (ThisIsAChainRule(ruleForNode)) {
2925 // Chain rules have a single nonterminal on the RHS.
2926 // Get the rule that matches the RHS non-terminal and use that instead.
2927 assert(nts[0] && ! nts[1]
2928 && "A chain rule should have only one RHS non-terminal!");
2929 nextRule = burm_rule(subtreeRoot->state, nts[0]);
2930 nts = burm_nts[nextRule];
2931 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
2933 switch(ruleForNode) {
2934 case 1: // stmt: Ret
2935 case 2: // stmt: RetValue(reg)
2936 { // NOTE: Prepass of register allocation is responsible
2937 // for moving return value to appropriate register.
2938 // Copy the return value to the required return register.
2939 // Mark the return Value as an implicit ref of the RET instr..
2940 // Mark the return-address register as a hidden virtual reg.
2941 // Finally put a NOP in the delay slot.
2942 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
2943 Value* retVal = returnInstr->getReturnValue();
2944 MachineCodeForInstruction& mcfi =
2945 MachineCodeForInstruction::get(returnInstr);
2947 // Create a hidden virtual reg to represent the return address register
2948 // used by the machine instruction but not represented in LLVM.
2949 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
2951 MachineInstr* retMI =
2952 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
2953 .addMReg(target.getRegInfo()->getZeroRegNum(), MachineOperand::Def);
2955 // If there is a value to return, we need to:
2956 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
2957 // (b) Insert a copy to copy the return value to the appropriate reg.
2958 // -- For FP values, create a FMOVS or FMOVD instruction
2959 // -- For non-FP values, create an add-with-0 instruction
2960 if (retVal != NULL) {
2961 const SparcV9RegInfo& regInfo =
2962 (SparcV9RegInfo&) *target.getRegInfo();
2963 const Type* retType = retVal->getType();
2964 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2965 unsigned retRegNum = (retType->isFloatingPoint()
2966 ? (unsigned) SparcV9FloatRegClass::f0
2967 : (unsigned) SparcV9IntRegClass::i0);
2968 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
2970 // Insert sign-extension instructions for small signed values.
2971 Value* retValToUse = retVal;
2972 if (retType->isIntegral() && retType->isSigned()) {
2973 unsigned retSize = target.getTargetData().getTypeSize(retType);
2975 // Create a temporary virtual reg. to hold the sign-extension.
2976 retValToUse = new TmpInstruction(mcfi, retVal);
2978 // Sign-extend retVal and put the result in the temporary reg.
2979 CreateSignExtensionInstructions
2980 (target, returnInstr->getParent()->getParent(),
2981 retVal, retValToUse, 8*retSize, mvec, mcfi);
2985 // (b) Now, insert a copy to to the appropriate register:
2986 // -- For FP values, create a FMOVS or FMOVD instruction
2987 // -- For non-FP values, create an add-with-0 instruction
2988 // First, create a virtual register to represent the register and
2989 // mark this vreg as being an implicit operand of the ret MI.
2990 TmpInstruction* retVReg =
2991 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
2993 retMI->addImplicitRef(retVReg);
2995 if (retType->isFloatingPoint())
2996 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2997 .addReg(retValToUse).addReg(retVReg, MachineOperand::Def));
2999 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
3000 .addReg(retValToUse).addSImm((int64_t) 0)
3001 .addReg(retVReg, MachineOperand::Def));
3003 // Mark the operand with the register it should be assigned
3004 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
3005 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
3010 // Now insert the RET instruction and a NOP for the delay slot
3011 mvec.push_back(retMI);
3012 mvec.push_back(BuildMI(V9::NOP, 0));
3017 case 3: // stmt: Store(reg,reg)
3018 case 4: // stmt: Store(reg,ptrreg)
3019 SetOperandsForMemInstr(ChooseStoreInstruction(
3020 subtreeRoot->leftChild()->getValue()->getType()),
3021 mvec, subtreeRoot, target);
3024 case 5: // stmt: BrUncond
3026 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3027 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
3030 mvec.push_back(BuildMI(V9::NOP, 0));
3034 case 206: // stmt: BrCond(setCCconst)
3035 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
3036 // If the constant is ZERO, we can use the branch-on-integer-register
3037 // instructions and avoid the SUBcc instruction entirely.
3038 // Otherwise this is just the same as case 5, so just fall through.
3040 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
3042 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3043 Constant *constVal = cast<Constant>(constNode->getValue());
3046 if ((constVal->getType()->isInteger()
3047 || isa<PointerType>(constVal->getType()))
3048 && ConvertConstantToIntType(target,
3049 constVal, constVal->getType(), isValidConst) == 0
3052 // That constant is a zero after all...
3053 // Use the left child of setCC as the first argument!
3054 // Mark the setCC node so that no code is generated for it.
3055 InstructionNode* setCCNode = (InstructionNode*)
3056 subtreeRoot->leftChild();
3057 assert(setCCNode->getOpLabel() == SetCCOp);
3058 setCCNode->markFoldedIntoParent();
3060 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
3062 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
3063 .addReg(setCCNode->leftChild()->getValue())
3064 .addPCDisp(brInst->getSuccessor(0));
3068 mvec.push_back(BuildMI(V9::NOP, 0));
3071 mvec.push_back(BuildMI(V9::BA, 1)
3072 .addPCDisp(brInst->getSuccessor(1)));
3075 mvec.push_back(BuildMI(V9::NOP, 0));
3078 // ELSE FALL THROUGH
3081 case 6: // stmt: BrCond(setCC)
3082 { // bool => boolean was computed with SetCC.
3083 // The branch to use depends on whether it is FP, signed, or unsigned.
3084 // If it is an integer CC, we also need to find the unique
3085 // TmpInstruction representing that CC.
3087 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
3088 const Type* setCCType;
3089 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
3090 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
3091 brInst->getParent()->getParent(),
3093 MachineCodeForInstruction::get(brInst));
3094 M = BuildMI(Opcode, 2).addCCReg(ccValue)
3095 .addPCDisp(brInst->getSuccessor(0));
3099 mvec.push_back(BuildMI(V9::NOP, 0));
3102 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
3105 mvec.push_back(BuildMI(V9::NOP, 0));
3109 case 208: // stmt: BrCond(boolconst)
3111 // boolconst => boolean is a constant; use BA to first or second label
3112 Constant* constVal =
3113 cast<Constant>(subtreeRoot->leftChild()->getValue());
3114 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
3116 M = BuildMI(V9::BA, 1).addPCDisp(
3117 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
3121 mvec.push_back(BuildMI(V9::NOP, 0));
3125 case 8: // stmt: BrCond(boolreg)
3126 { // boolreg => boolean is recorded in an integer register.
3127 // Use branch-on-integer-register instruction.
3129 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3130 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
3131 .addPCDisp(BI->getSuccessor(0));
3135 mvec.push_back(BuildMI(V9::NOP, 0));
3138 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
3141 mvec.push_back(BuildMI(V9::NOP, 0));
3145 case 9: // stmt: Switch(reg)
3146 assert(0 && "*** SWITCH instruction is not implemented yet.");
3149 case 10: // reg: VRegList(reg, reg)
3150 assert(0 && "VRegList should never be the topmost non-chain rule");
3153 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
3154 { // First find the unary operand. It may be left or right, usually right.
3155 Instruction* notI = subtreeRoot->getInstruction();
3156 Value* notArg = BinaryOperator::getNotArgument(
3157 cast<BinaryOperator>(subtreeRoot->getInstruction()));
3158 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3160 // Unconditionally set register to 0
3161 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
3163 // Now conditionally move 1 into the register.
3164 // Mark the register as a use (as well as a def) because the old
3165 // value will be retained if the condition is false.
3166 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
3167 .addReg(notI, MachineOperand::UseAndDef));
3172 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
3173 { // First find the unary operand. It may be left or right, usually right.
3174 Value* notArg = BinaryOperator::getNotArgument(
3175 cast<BinaryOperator>(subtreeRoot->getInstruction()));
3176 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3177 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
3178 .addRegDef(subtreeRoot->getValue()));
3182 case 322: // reg: Not(tobool, reg):
3183 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
3185 // Just fall through!
3187 case 22: // reg: ToBoolTy(reg):
3189 Instruction* castI = subtreeRoot->getInstruction();
3190 Value* opVal = subtreeRoot->leftChild()->getValue();
3191 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(castI);
3192 TmpInstruction* tempReg =
3193 new TmpInstruction(mcfi, opVal);
3197 assert(opVal->getType()->isIntegral() ||
3198 isa<PointerType>(opVal->getType()));
3200 // Unconditionally set register to 0
3201 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
3203 // Now conditionally move 1 into the register.
3204 // Mark the register as a use (as well as a def) because the old
3205 // value will be retained if the condition is false.
3206 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
3207 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
3208 .addReg(castI, MachineOperand::UseAndDef));
3213 case 23: // reg: ToUByteTy(reg)
3214 case 24: // reg: ToSByteTy(reg)
3215 case 25: // reg: ToUShortTy(reg)
3216 case 26: // reg: ToShortTy(reg)
3217 case 27: // reg: ToUIntTy(reg)
3218 case 28: // reg: ToIntTy(reg)
3219 case 29: // reg: ToULongTy(reg)
3220 case 30: // reg: ToLongTy(reg)
3222 //======================================================================
3223 // Rules for integer conversions:
3226 // From ISO 1998 C++ Standard, Sec. 4.7:
3228 // 2. If the destination type is unsigned, the resulting value is
3229 // the least unsigned integer congruent to the source integer
3230 // (modulo 2n where n is the number of bits used to represent the
3231 // unsigned type). [Note: In a two s complement representation,
3232 // this conversion is conceptual and there is no change in the
3233 // bit pattern (if there is no truncation). ]
3235 // 3. If the destination type is signed, the value is unchanged if
3236 // it can be represented in the destination type (and bitfield width);
3237 // otherwise, the value is implementation-defined.
3240 // Since we assume 2s complement representations, this implies:
3242 // -- If operand is smaller than destination, zero-extend or sign-extend
3243 // according to the signedness of the *operand*: source decides:
3244 // (1) If operand is signed, sign-extend it.
3245 // If dest is unsigned, zero-ext the result!
3246 // (2) If operand is unsigned, our current invariant is that
3247 // it's high bits are correct, so zero-extension is not needed.
3249 // -- If operand is same size as or larger than destination,
3250 // zero-extend or sign-extend according to the signedness of
3251 // the *destination*: destination decides:
3252 // (1) If destination is signed, sign-extend (truncating if needed)
3253 // This choice is implementation defined. We sign-extend the
3254 // operand, which matches both Sun's cc and gcc3.2.
3255 // (2) If destination is unsigned, zero-extend (truncating if needed)
3256 //======================================================================
3258 Instruction* destI = subtreeRoot->getInstruction();
3259 Function* currentFunc = destI->getParent()->getParent();
3260 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
3262 Value* opVal = subtreeRoot->leftChild()->getValue();
3263 const Type* opType = opVal->getType();
3264 const Type* destType = destI->getType();
3265 unsigned opSize = target.getTargetData().getTypeSize(opType);
3266 unsigned destSize = target.getTargetData().getTypeSize(destType);
3268 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
3270 if (opType == Type::BoolTy ||
3271 opType == destType ||
3272 isIntegral && opSize == destSize && opSize == 8) {
3273 // nothing to do in all these cases
3274 forwardOperandNum = 0; // forward first operand to user
3276 } else if (opType->isFloatingPoint()) {
3278 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
3279 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
3280 maskUnsignedResult = true; // not handled by fp->int code
3282 } else if (isIntegral) {
3284 bool opSigned = opType->isSigned();
3285 bool destSigned = destType->isSigned();
3286 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
3288 assert(! (opSize == destSize && opSigned == destSigned) &&
3289 "How can different int types have same size and signedness?");
3291 bool signExtend = (opSize < destSize && opSigned ||
3292 opSize >= destSize && destSigned);
3294 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
3295 opSigned && !destSigned);
3296 assert(!signAndZeroExtend || signExtend);
3298 bool zeroExtendOnly = opSize >= destSize && !destSigned;
3299 assert(!zeroExtendOnly || !signExtend);
3302 Value* signExtDest = (signAndZeroExtend
3303 ? new TmpInstruction(mcfi, destType, opVal)
3306 CreateSignExtensionInstructions
3307 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
3309 if (signAndZeroExtend)
3310 CreateZeroExtensionInstructions
3311 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
3313 else if (zeroExtendOnly) {
3314 CreateZeroExtensionInstructions
3315 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
3318 forwardOperandNum = 0; // forward first operand to user
3321 assert(0 && "Unrecognized operand type for convert-to-integer");
3326 case 31: // reg: ToFloatTy(reg):
3327 case 32: // reg: ToDoubleTy(reg):
3328 case 232: // reg: ToDoubleTy(Constant):
3330 // If this instruction has a parent (a user) in the tree
3331 // and the user is translated as an FsMULd instruction,
3332 // then the cast is unnecessary. So check that first.
3333 // In the future, we'll want to do the same for the FdMULq instruction,
3334 // so do the check here instead of only for ToFloatTy(reg).
3336 if (subtreeRoot->parent() != NULL) {
3337 const MachineCodeForInstruction& mcfi =
3338 MachineCodeForInstruction::get(
3339 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
3340 if (mcfi.size() == 0 || mcfi.front()->getOpcode() == V9::FSMULD)
3341 forwardOperandNum = 0; // forward first operand to user
3344 if (forwardOperandNum != 0) { // we do need the cast
3345 Value* leftVal = subtreeRoot->leftChild()->getValue();
3346 const Type* opType = leftVal->getType();
3347 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
3348 subtreeRoot->getOpLabel(), opType);
3349 if (opCode == V9::NOP) { // no conversion needed
3350 forwardOperandNum = 0; // forward first operand to user
3352 // If the source operand is a non-FP type it must be
3353 // first copied from int to float register via memory!
3354 Instruction *dest = subtreeRoot->getInstruction();
3357 if (! opType->isFloatingPoint()) {
3358 // Create a temporary to represent the FP register
3359 // into which the integer will be copied via memory.
3360 // The type of this temporary will determine the FP
3361 // register used: single-prec for a 32-bit int or smaller,
3362 // double-prec for a 64-bit int.
3365 target.getTargetData().getTypeSize(leftVal->getType());
3366 Type* tmpTypeToUse =
3367 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
3368 MachineCodeForInstruction &destMCFI =
3369 MachineCodeForInstruction::get(dest);
3370 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
3372 CreateCodeToCopyIntToFloat(target,
3373 dest->getParent()->getParent(),
3374 leftVal, cast<Instruction>(srcForCast),
3377 srcForCast = leftVal;
3379 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
3385 case 19: // reg: ToArrayTy(reg):
3386 case 20: // reg: ToPointerTy(reg):
3387 forwardOperandNum = 0; // forward first operand to user
3390 case 233: // reg: Add(reg, Constant)
3391 maskUnsignedResult = true;
3392 M = CreateAddConstInstruction(subtreeRoot);
3397 // ELSE FALL THROUGH
3399 case 33: // reg: Add(reg, reg)
3400 maskUnsignedResult = true;
3401 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
3404 case 234: // reg: Sub(reg, Constant)
3405 maskUnsignedResult = true;
3406 M = CreateSubConstInstruction(subtreeRoot);
3411 // ELSE FALL THROUGH
3413 case 34: // reg: Sub(reg, reg)
3414 maskUnsignedResult = true;
3415 Add3OperandInstr(ChooseSubInstructionByType(
3416 subtreeRoot->getInstruction()->getType()),
3420 case 135: // reg: Mul(todouble, todouble)
3424 case 35: // reg: Mul(reg, reg)
3426 maskUnsignedResult = true;
3427 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3428 ? (MachineOpCode)V9::FSMULD
3430 Instruction* mulInstr = subtreeRoot->getInstruction();
3431 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3432 subtreeRoot->leftChild()->getValue(),
3433 subtreeRoot->rightChild()->getValue(),
3435 MachineCodeForInstruction::get(mulInstr),forceOp);
3438 case 335: // reg: Mul(todouble, todoubleConst)
3442 case 235: // reg: Mul(reg, Constant)
3444 maskUnsignedResult = true;
3445 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3446 ? (MachineOpCode)V9::FSMULD
3448 Instruction* mulInstr = subtreeRoot->getInstruction();
3449 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3450 subtreeRoot->leftChild()->getValue(),
3451 subtreeRoot->rightChild()->getValue(),
3453 MachineCodeForInstruction::get(mulInstr),
3457 case 236: // reg: Div(reg, Constant)
3458 maskUnsignedResult = true;
3460 CreateDivConstInstruction(target, subtreeRoot, mvec);
3461 if (mvec.size() > L)
3463 // ELSE FALL THROUGH
3465 case 36: // reg: Div(reg, reg)
3467 maskUnsignedResult = true;
3469 // If either operand of divide is smaller than 64 bits, we have
3470 // to make sure the unused top bits are correct because they affect
3471 // the result. These bits are already correct for unsigned values.
3472 // They may be incorrect for signed values, so sign extend to fill in.
3473 Instruction* divI = subtreeRoot->getInstruction();
3474 Value* divOp1 = subtreeRoot->leftChild()->getValue();
3475 Value* divOp2 = subtreeRoot->rightChild()->getValue();
3476 Value* divOp1ToUse = divOp1;
3477 Value* divOp2ToUse = divOp2;
3478 if (divI->getType()->isSigned()) {
3479 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
3481 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
3482 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
3483 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
3484 CreateSignExtensionInstructions(target,
3485 divI->getParent()->getParent(),
3486 divOp1, divOp1ToUse,
3487 8*opSize, mvec, mcfi);
3488 CreateSignExtensionInstructions(target,
3489 divI->getParent()->getParent(),
3490 divOp2, divOp2ToUse,
3491 8*opSize, mvec, mcfi);
3495 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3496 .addReg(divOp1ToUse)
3497 .addReg(divOp2ToUse)
3503 case 37: // reg: Rem(reg, reg)
3504 case 237: // reg: Rem(reg, Constant)
3506 maskUnsignedResult = true;
3508 Instruction* remI = subtreeRoot->getInstruction();
3509 Value* divOp1 = subtreeRoot->leftChild()->getValue();
3510 Value* divOp2 = subtreeRoot->rightChild()->getValue();
3512 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
3514 // If second operand of divide is smaller than 64 bits, we have
3515 // to make sure the unused top bits are correct because they affect
3516 // the result. These bits are already correct for unsigned values.
3517 // They may be incorrect for signed values, so sign extend to fill in.
3519 Value* divOpToUse = divOp2;
3520 if (divOp2->getType()->isSigned()) {
3521 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
3523 divOpToUse = new TmpInstruction(mcfi, divOp2);
3524 CreateSignExtensionInstructions(target,
3525 remI->getParent()->getParent(),
3527 8*opSize, mvec, mcfi);
3531 // Now compute: result = rem V1, V2 as:
3532 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
3534 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
3535 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
3537 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3538 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
3540 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
3541 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
3543 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
3544 .addReg(divOp1).addReg(prod).addRegDef(remI));
3549 case 38: // bool: And(bool, bool)
3550 case 138: // bool: And(bool, not)
3551 case 238: // bool: And(bool, boolconst)
3552 case 338: // reg : BAnd(reg, reg)
3553 case 538: // reg : BAnd(reg, Constant)
3554 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
3557 case 438: // bool: BAnd(bool, bnot)
3558 { // Use the argument of NOT as the second argument!
3559 // Mark the NOT node so that no code is generated for it.
3560 // If the type is boolean, set 1 or 0 in the result register.
3561 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3562 Value* notArg = BinaryOperator::getNotArgument(
3563 cast<BinaryOperator>(notNode->getInstruction()));
3564 notNode->markFoldedIntoParent();
3565 Value *lhs = subtreeRoot->leftChild()->getValue();
3566 Value *dest = subtreeRoot->getValue();
3567 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
3568 .addReg(dest, MachineOperand::Def));
3570 if (notArg->getType() == Type::BoolTy) {
3571 // set 1 in result register if result of above is non-zero
3572 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3573 .addReg(dest, MachineOperand::UseAndDef));
3579 case 39: // bool: Or(bool, bool)
3580 case 139: // bool: Or(bool, not)
3581 case 239: // bool: Or(bool, boolconst)
3582 case 339: // reg : BOr(reg, reg)
3583 case 539: // reg : BOr(reg, Constant)
3584 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
3587 case 439: // bool: BOr(bool, bnot)
3588 { // Use the argument of NOT as the second argument!
3589 // Mark the NOT node so that no code is generated for it.
3590 // If the type is boolean, set 1 or 0 in the result register.
3591 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3592 Value* notArg = BinaryOperator::getNotArgument(
3593 cast<BinaryOperator>(notNode->getInstruction()));
3594 notNode->markFoldedIntoParent();
3595 Value *lhs = subtreeRoot->leftChild()->getValue();
3596 Value *dest = subtreeRoot->getValue();
3598 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
3599 .addReg(dest, MachineOperand::Def));
3601 if (notArg->getType() == Type::BoolTy) {
3602 // set 1 in result register if result of above is non-zero
3603 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3604 .addReg(dest, MachineOperand::UseAndDef));
3610 case 40: // bool: Xor(bool, bool)
3611 case 140: // bool: Xor(bool, not)
3612 case 240: // bool: Xor(bool, boolconst)
3613 case 340: // reg : BXor(reg, reg)
3614 case 540: // reg : BXor(reg, Constant)
3615 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
3618 case 440: // bool: BXor(bool, bnot)
3619 { // Use the argument of NOT as the second argument!
3620 // Mark the NOT node so that no code is generated for it.
3621 // If the type is boolean, set 1 or 0 in the result register.
3622 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3623 Value* notArg = BinaryOperator::getNotArgument(
3624 cast<BinaryOperator>(notNode->getInstruction()));
3625 notNode->markFoldedIntoParent();
3626 Value *lhs = subtreeRoot->leftChild()->getValue();
3627 Value *dest = subtreeRoot->getValue();
3628 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
3629 .addReg(dest, MachineOperand::Def));
3631 if (notArg->getType() == Type::BoolTy) {
3632 // set 1 in result register if result of above is non-zero
3633 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3634 .addReg(dest, MachineOperand::UseAndDef));
3639 case 41: // setCCconst: SetCC(reg, Constant)
3640 { // Comparison is with a constant:
3642 // If the bool result must be computed into a register (see below),
3643 // and the constant is int ZERO, we can use the MOVR[op] instructions
3644 // and avoid the SUBcc instruction entirely.
3645 // Otherwise this is just the same as case 42, so just fall through.
3647 // The result of the SetCC must be computed and stored in a register if
3648 // it is used outside the current basic block (so it must be computed
3649 // as a boolreg) or it is used by anything other than a branch.
3650 // We will use a conditional move to do this.
3652 Instruction* setCCInstr = subtreeRoot->getInstruction();
3653 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3654 ! AllUsesAreBranches(setCCInstr));
3656 if (computeBoolVal) {
3657 InstrTreeNode* constNode = subtreeRoot->rightChild();
3659 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3660 Constant *constVal = cast<Constant>(constNode->getValue());
3663 if ((constVal->getType()->isInteger()
3664 || isa<PointerType>(constVal->getType()))
3665 && ConvertConstantToIntType(target,
3666 constVal, constVal->getType(), isValidConst) == 0
3669 // That constant is an integer zero after all...
3670 // Use a MOVR[op] to compute the boolean result
3671 // Unconditionally set register to 0
3672 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
3673 .addRegDef(setCCInstr));
3675 // Now conditionally move 1 into the register.
3676 // Mark the register as a use (as well as a def) because the old
3677 // value will be retained if the condition is false.
3678 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
3679 mvec.push_back(BuildMI(movOpCode, 3)
3680 .addReg(subtreeRoot->leftChild()->getValue())
3682 .addReg(setCCInstr, MachineOperand::UseAndDef));
3687 // ELSE FALL THROUGH
3690 case 42: // bool: SetCC(reg, reg):
3692 // This generates a SUBCC instruction, putting the difference in a
3693 // result reg. if needed, and/or setting a condition code if needed.
3695 Instruction* setCCInstr = subtreeRoot->getInstruction();
3696 Value* leftVal = subtreeRoot->leftChild()->getValue();
3697 Value* rightVal = subtreeRoot->rightChild()->getValue();
3698 const Type* opType = leftVal->getType();
3699 bool isFPCompare = opType->isFloatingPoint();
3701 // If the boolean result of the SetCC is used outside the current basic
3702 // block (so it must be computed as a boolreg) or is used by anything
3703 // other than a branch, the boolean must be computed and stored
3704 // in a result register. We will use a conditional move to do this.
3706 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3707 ! AllUsesAreBranches(setCCInstr));
3709 // A TmpInstruction is created to represent the CC "result".
3710 // Unlike other instances of TmpInstruction, this one is used
3711 // by machine code of multiple LLVM instructions, viz.,
3712 // the SetCC and the branch. Make sure to get the same one!
3713 // Note that we do this even for FP CC registers even though they
3714 // are explicit operands, because the type of the operand
3715 // needs to be a floating point condition code, not an integer
3716 // condition code. Think of this as casting the bool result to
3717 // a FP condition code register.
3718 // Later, we mark the 4th operand as being a CC register, and as a def.
3720 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
3721 setCCInstr->getParent()->getParent(),
3723 MachineCodeForInstruction::get(setCCInstr));
3725 // If the operands are signed values smaller than 4 bytes, then they
3726 // must be sign-extended in order to do a valid 32-bit comparison
3727 // and get the right result in the 32-bit CC register (%icc).
3729 Value* leftOpToUse = leftVal;
3730 Value* rightOpToUse = rightVal;
3731 if (opType->isIntegral() && opType->isSigned()) {
3732 unsigned opSize = target.getTargetData().getTypeSize(opType);
3734 MachineCodeForInstruction& mcfi =
3735 MachineCodeForInstruction::get(setCCInstr);
3737 // create temporary virtual regs. to hold the sign-extensions
3738 leftOpToUse = new TmpInstruction(mcfi, leftVal);
3739 rightOpToUse = new TmpInstruction(mcfi, rightVal);
3741 // sign-extend each operand and put the result in the temporary reg.
3742 CreateSignExtensionInstructions
3743 (target, setCCInstr->getParent()->getParent(),
3744 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
3745 CreateSignExtensionInstructions
3746 (target, setCCInstr->getParent()->getParent(),
3747 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
3751 if (! isFPCompare) {
3752 // Integer condition: set CC and discard result.
3753 mvec.push_back(BuildMI(V9::SUBccr, 4)
3754 .addReg(leftOpToUse)
3755 .addReg(rightOpToUse)
3756 .addMReg(target.getRegInfo()->
3757 getZeroRegNum(), MachineOperand::Def)
3758 .addCCReg(tmpForCC, MachineOperand::Def));
3760 // FP condition: dest of FCMP should be some FCCn register
3761 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
3762 .addCCReg(tmpForCC, MachineOperand::Def)
3763 .addReg(leftOpToUse)
3764 .addReg(rightOpToUse));
3767 if (computeBoolVal) {
3768 MachineOpCode movOpCode = (isFPCompare
3769 ? ChooseMovFpcciInstruction(subtreeRoot)
3770 : ChooseMovpcciForSetCC(subtreeRoot));
3772 // Unconditionally set register to 0
3773 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
3776 // Now conditionally move 1 into the register.
3777 // Mark the register as a use (as well as a def) because the old
3778 // value will be retained if the condition is false.
3779 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
3780 .addReg(setCCInstr, MachineOperand::UseAndDef));
3786 case 51: // reg: Load(reg)
3787 case 52: // reg: Load(ptrreg)
3788 SetOperandsForMemInstr(ChooseLoadInstruction(
3789 subtreeRoot->getValue()->getType()),
3790 mvec, subtreeRoot, target);
3793 case 55: // reg: GetElemPtr(reg)
3794 case 56: // reg: GetElemPtrIdx(reg,reg)
3795 // If the GetElemPtr was folded into the user (parent), it will be
3796 // caught above. For other cases, we have to compute the address.
3797 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
3800 case 57: // reg: Alloca: Implement as 1 instruction:
3801 { // add %fp, offsetFromFP -> result
3802 AllocationInst* instr =
3803 cast<AllocationInst>(subtreeRoot->getInstruction());
3805 target.getTargetData().getTypeSize(instr->getAllocatedType());
3807 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
3811 case 58: // reg: Alloca(reg): Implement as 3 instructions:
3812 // mul num, typeSz -> tmp
3813 // sub %sp, tmp -> %sp
3814 { // add %sp, frameSizeBelowDynamicArea -> result
3815 AllocationInst* instr =
3816 cast<AllocationInst>(subtreeRoot->getInstruction());
3817 const Type* eltType = instr->getAllocatedType();
3819 // If #elements is constant, use simpler code for fixed-size allocas
3820 int tsize = (int) target.getTargetData().getTypeSize(eltType);
3821 Value* numElementsVal = NULL;
3822 bool isArray = instr->isArrayAllocation();
3824 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
3825 // total size is constant: generate code for fixed-size alloca
3826 unsigned numElements = isArray?
3827 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
3828 CreateCodeForFixedSizeAlloca(target, instr, tsize,
3831 // total size is not constant.
3832 CreateCodeForVariableSizeAlloca(target, instr, tsize,
3833 numElementsVal, mvec);
3838 case 61: // reg: Call
3839 { // Generate a direct (CALL) or indirect (JMPL) call.
3840 // Mark the return-address register, the indirection
3841 // register (for indirect calls), the operands of the Call,
3842 // and the return value (if any) as implicit operands
3843 // of the machine instruction.
3845 // If this is a varargs function, floating point arguments
3846 // have to passed in integer registers so insert
3847 // copy-float-to-int instructions for each float operand.
3849 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
3850 Value *callee = callInstr->getCalledValue();
3851 Function* calledFunc = dyn_cast<Function>(callee);
3853 // Check if this is an intrinsic function that needs a special code
3854 // sequence (e.g., va_start). Indirect calls cannot be special.
3856 bool specialIntrinsic = false;
3858 if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
3859 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
3861 // If not, generate the normal call sequence for the function.
3862 // This can also handle any intrinsics that are just function calls.
3864 if (! specialIntrinsic) {
3865 Function* currentFunc = callInstr->getParent()->getParent();
3866 MachineFunction& MF = MachineFunction::get(currentFunc);
3867 MachineCodeForInstruction& mcfi =
3868 MachineCodeForInstruction::get(callInstr);
3869 const SparcV9RegInfo& regInfo =
3870 (SparcV9RegInfo&) *target.getRegInfo();
3871 const TargetFrameInfo& frameInfo = *target.getFrameInfo();
3873 // Create hidden virtual register for return address with type void*
3874 TmpInstruction* retAddrReg =
3875 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
3877 // Generate the machine instruction and its operands.
3878 // Use CALL for direct function calls; this optimistically assumes
3879 // the PC-relative address fits in the CALL address field (22 bits).
3880 // Use JMPL for indirect calls.
3881 // This will be added to mvec later, after operand copies.
3883 MachineInstr* callMI;
3884 if (calledFunc) // direct function call
3885 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
3886 else // indirect function call
3887 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
3888 .addSImm((int64_t)0).addRegDef(retAddrReg));
3890 const FunctionType* funcType =
3891 cast<FunctionType>(cast<PointerType>(callee->getType())
3892 ->getElementType());
3893 bool isVarArgs = funcType->isVarArg();
3894 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
3896 // Use a descriptor to pass information about call arguments
3897 // to the register allocator. This descriptor will be "owned"
3898 // and freed automatically when the MachineCodeForInstruction
3899 // object for the callInstr goes away.
3900 CallArgsDescriptor* argDesc =
3901 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
3902 assert(callInstr->getOperand(0) == callee
3903 && "This is assumed in the loop below!");
3905 // Insert sign-extension instructions for small signed values,
3906 // if this is an unknown function (i.e., called via a funcptr)
3907 // or an external one (i.e., which may not be compiled by llc).
3909 if (calledFunc == NULL || calledFunc->isExternal()) {
3910 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3911 Value* argVal = callInstr->getOperand(i);
3912 const Type* argType = argVal->getType();
3913 if (argType->isIntegral() && argType->isSigned()) {
3914 unsigned argSize = target.getTargetData().getTypeSize(argType);
3916 // create a temporary virtual reg. to hold the sign-extension
3917 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
3919 // sign-extend argVal and put the result in the temporary reg.
3920 CreateSignExtensionInstructions
3921 (target, currentFunc, argVal, argExtend,
3922 8*argSize, mvec, mcfi);
3924 // replace argVal with argExtend in CallArgsDescriptor
3925 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
3931 // Insert copy instructions to get all the arguments into
3932 // all the places that they need to be.
3934 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3936 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
3937 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
3938 const Type* argType = argVal->getType();
3939 unsigned regType = regInfo.getRegTypeForDataType(argType);
3940 unsigned argSize = target.getTargetData().getTypeSize(argType);
3941 int regNumForArg = SparcV9RegInfo::getInvalidRegNum();
3942 unsigned regClassIDOfArgReg;
3944 // Check for FP arguments to varargs functions.
3945 // Any such argument in the first $K$ args must be passed in an
3946 // integer register. If there is no prototype, it must also
3947 // be passed as an FP register.
3948 // K = #integer argument registers.
3949 bool isFPArg = argVal->getType()->isFloatingPoint();
3950 if (isVarArgs && isFPArg) {
3953 // It is a function with no prototype: pass value
3954 // as an FP value as well as a varargs value. The FP value
3955 // may go in a register or on the stack. The copy instruction
3956 // to the outgoing reg/stack is created by the normal argument
3957 // handling code since this is the "normal" passing mode.
3959 regNumForArg = regInfo.regNumForFPArg(regType,
3960 false, false, argNo,
3961 regClassIDOfArgReg);
3962 if (regNumForArg == regInfo.getInvalidRegNum())
3963 argInfo.setUseStackSlot();
3965 argInfo.setUseFPArgReg();
3968 // If this arg. is in the first $K$ regs, add special copy-
3969 // float-to-int instructions to pass the value as an int.
3970 // To check if it is in the first $K$, get the register
3971 // number for the arg #i. These copy instructions are
3972 // generated here because they are extra cases and not needed
3973 // for the normal argument handling (some code reuse is
3974 // possible though -- later).
3976 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
3977 regClassIDOfArgReg);
3978 if (copyRegNum != regInfo.getInvalidRegNum()) {
3979 // Create a virtual register to represent copyReg. Mark
3980 // this vreg as being an implicit operand of the call MI
3981 const Type* loadTy = (argType == Type::FloatTy
3982 ? Type::IntTy : Type::LongTy);
3983 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
3986 callMI->addImplicitRef(argVReg);
3988 // Get a temp stack location to use to copy
3989 // float-to-int via the stack.
3991 // FIXME: For now, we allocate permanent space because
3992 // the stack frame manager does not allow locals to be
3993 // allocated (e.g., for alloca) after a temp is
3996 // int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->pushTempValue(argSize);
3997 int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(argVReg);
3999 // Generate the store from FP reg to stack
4000 unsigned StoreOpcode = ChooseStoreInstruction(argType);
4001 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
4002 .addReg(argVal).addMReg(regInfo.getFramePointer())
4003 .addSImm(tmpOffset);
4006 // Generate the load from stack to int arg reg
4007 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
4008 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
4009 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
4010 .addReg(argVReg, MachineOperand::Def);
4012 // Mark operand with register it should be assigned
4013 // both for copy and for the callMI
4014 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
4015 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4019 // Add info about the argument to the CallArgsDescriptor
4020 argInfo.setUseIntArgReg();
4021 argInfo.setArgCopy(copyRegNum);
4023 // Cannot fit in first $K$ regs so pass arg on stack
4024 argInfo.setUseStackSlot();
4026 } else if (isFPArg) {
4027 // Get the outgoing arg reg to see if there is one.
4028 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
4029 argNo, regClassIDOfArgReg);
4030 if (regNumForArg == regInfo.getInvalidRegNum())
4031 argInfo.setUseStackSlot();
4033 argInfo.setUseFPArgReg();
4034 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
4038 // Get the outgoing arg reg to see if there is one.
4039 regNumForArg = regInfo.regNumForIntArg(false,false,
4040 argNo, regClassIDOfArgReg);
4041 if (regNumForArg == regInfo.getInvalidRegNum())
4042 argInfo.setUseStackSlot();
4044 argInfo.setUseIntArgReg();
4045 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
4051 // Now insert copy instructions to stack slot or arg. register
4053 if (argInfo.usesStackSlot()) {
4054 // Get the stack offset for this argument slot.
4055 // FP args on stack are right justified so adjust offset!
4056 // int arguments are also right justified but they are
4057 // always loaded as a full double-word so the offset does
4058 // not need to be adjusted.
4059 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
4060 if (argType->isFloatingPoint()) {
4061 unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4062 assert(argSize <= slotSize && "Insufficient slot size!");
4063 argOffset += slotSize - argSize;
4066 // Now generate instruction to copy argument to stack
4067 MachineOpCode storeOpCode =
4068 (argType->isFloatingPoint()
4069 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
4071 M = BuildMI(storeOpCode, 3).addReg(argVal)
4072 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
4075 else if (regNumForArg != regInfo.getInvalidRegNum()) {
4077 // Create a virtual register to represent the arg reg. Mark
4078 // this vreg as being an implicit operand of the call MI.
4079 TmpInstruction* argVReg =
4080 new TmpInstruction(mcfi, argVal, NULL, "argReg");
4082 callMI->addImplicitRef(argVReg);
4084 // Generate the reg-to-reg copy into the outgoing arg reg.
4085 // -- For FP values, create a FMOVS or FMOVD instruction
4086 // -- For non-FP values, create an add-with-0 instruction
4087 if (argType->isFloatingPoint())
4088 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
4089 .addReg(argVal).addReg(argVReg, MachineOperand::Def));
4091 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
4092 .addReg(argVal).addSImm((int64_t) 0)
4093 .addReg(argVReg, MachineOperand::Def));
4095 // Mark the operand with the register it should be assigned
4096 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
4097 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4103 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
4104 "Arg. not in stack slot, primary or secondary register?");
4107 // add call instruction and delay slot before copying return value
4108 mvec.push_back(callMI);
4109 mvec.push_back(BuildMI(V9::NOP, 0));
4111 // Add the return value as an implicit ref. The call operands
4112 // were added above. Also, add code to copy out the return value.
4113 // This is always register-to-register for int or FP return values.
4115 if (callInstr->getType() != Type::VoidTy) {
4116 // Get the return value reg.
4117 const Type* retType = callInstr->getType();
4119 int regNum = (retType->isFloatingPoint()
4120 ? (unsigned) SparcV9FloatRegClass::f0
4121 : (unsigned) SparcV9IntRegClass::o0);
4122 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
4123 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
4125 // Create a virtual register to represent it and mark
4126 // this vreg as being an implicit operand of the call MI
4127 TmpInstruction* retVReg =
4128 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
4130 callMI->addImplicitRef(retVReg, /*isDef*/ true);
4132 // Generate the reg-to-reg copy from the return value reg.
4133 // -- For FP values, create a FMOVS or FMOVD instruction
4134 // -- For non-FP values, create an add-with-0 instruction
4135 if (retType->isFloatingPoint())
4136 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
4137 .addReg(retVReg).addReg(callInstr, MachineOperand::Def));
4139 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
4140 .addReg(retVReg).addSImm((int64_t) 0)
4141 .addReg(callInstr, MachineOperand::Def));
4143 // Mark the operand with the register it should be assigned
4144 // Also mark the implicit ref of the call defining this operand
4145 M->SetRegForOperand(0, regNum);
4146 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
4151 // For the CALL instruction, the ret. addr. reg. is also implicit
4152 if (isa<Function>(callee))
4153 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
4155 MF.getInfo<SparcV9FunctionInfo>()->popAllTempValues(); // free temps used for this inst
4161 case 62: // reg: Shl(reg, reg)
4163 Value* argVal1 = subtreeRoot->leftChild()->getValue();
4164 Value* argVal2 = subtreeRoot->rightChild()->getValue();
4165 Instruction* shlInstr = subtreeRoot->getInstruction();
4167 const Type* opType = argVal1->getType();
4168 assert((opType->isInteger() || isa<PointerType>(opType)) &&
4169 "Shl unsupported for other types");
4170 unsigned opSize = target.getTargetData().getTypeSize(opType);
4172 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
4173 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
4174 argVal1, argVal2, 0, shlInstr, mvec,
4175 MachineCodeForInstruction::get(shlInstr));
4179 case 63: // reg: Shr(reg, reg)
4181 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
4182 assert((opType->isInteger() || isa<PointerType>(opType)) &&
4183 "Shr unsupported for other types");
4184 unsigned opSize = target.getTargetData().getTypeSize(opType);
4185 Add3OperandInstr(opType->isSigned()
4186 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
4187 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
4192 case 64: // reg: Phi(reg,reg)
4193 break; // don't forward the value
4195 case 65: // reg: VANext(reg): the va_next(va_list, type) instruction
4196 { // Increment the va_list pointer register according to the type.
4197 // All LLVM argument types are <= 64 bits, so use one doubleword.
4198 Instruction* vaNextI = subtreeRoot->getInstruction();
4199 assert(target.getTargetData().getTypeSize(vaNextI->getType()) <= 8 &&
4200 "We assumed that all LLVM parameter types <= 8 bytes!");
4201 unsigned argSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4202 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaNextI->getOperand(0)).
4203 addSImm(argSize).addRegDef(vaNextI));
4207 case 66: // reg: VAArg (reg): the va_arg instruction
4208 { // Load argument from stack using current va_list pointer value.
4209 // Use 64-bit load for all non-FP args, and LDDF or double for FP.
4210 Instruction* vaArgI = subtreeRoot->getInstruction();
4211 MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
4212 ? (vaArgI->getType() == Type::FloatTy
4213 ? V9::LDFi : V9::LDDFi)
4215 mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
4216 addSImm(0).addRegDef(vaArgI));
4220 case 71: // reg: VReg
4221 case 72: // reg: Constant
4222 break; // don't forward the value
4225 assert(0 && "Unrecognized BURG rule");
4230 if (forwardOperandNum >= 0) {
4231 // We did not generate a machine instruction but need to use operand.
4232 // If user is in the same tree, replace Value in its machine operand.
4233 // If not, insert a copy instruction which should get coalesced away
4234 // by register allocation.
4235 if (subtreeRoot->parent() != NULL)
4236 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
4238 std::vector<MachineInstr*> minstrVec;
4239 Instruction* instr = subtreeRoot->getInstruction();
4240 CreateCopyInstructionsByType(target,
4241 instr->getParent()->getParent(),
4242 instr->getOperand(forwardOperandNum),
4244 MachineCodeForInstruction::get(instr));
4245 assert(minstrVec.size() > 0);
4246 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4250 if (maskUnsignedResult) {
4251 // If result is unsigned and smaller than int reg size,
4252 // we need to clear high bits of result value.
4253 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
4254 Instruction* dest = subtreeRoot->getInstruction();
4255 if (dest->getType()->isUnsigned()) {
4256 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
4257 if (destSize <= 4) {
4258 // Mask high 64 - N bits, where N = 4*destSize.
4260 // Use a TmpInstruction to represent the
4261 // intermediate result before masking. Since those instructions
4262 // have already been generated, go back and substitute tmpI
4263 // for dest in the result position of each one of them.
4265 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
4266 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
4267 dest, NULL, "maskHi");
4268 Value* srlArgToUse = tmpI;
4270 unsigned numSubst = 0;
4271 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
4273 // Make sure we substitute all occurrences of dest in these instrs.
4274 // Otherwise, we will have bogus code.
4275 bool someArgsWereIgnored = false;
4277 // Make sure not to substitute an upwards-exposed use -- that would
4278 // introduce a use of `tmpI' with no preceding def. Therefore,
4279 // substitute a use or def-and-use operand only if a previous def
4280 // operand has already been substituted (i.e., numSubst > 0).
4282 numSubst += mvec[i]->substituteValue(dest, tmpI,
4283 /*defsOnly*/ numSubst == 0,
4284 /*notDefsAndUses*/ numSubst > 0,
4285 someArgsWereIgnored);
4286 assert(!someArgsWereIgnored &&
4287 "Operand `dest' exists but not replaced: probably bogus!");
4289 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
4291 // Left shift 32-N if size (N) is less than 32 bits.
4292 // Use another tmp. virtual register to represent this result.
4294 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
4295 tmpI, NULL, "maskHi2");
4296 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
4297 .addZImm(8*(4-destSize))
4298 .addReg(srlArgToUse, MachineOperand::Def));
4301 // Logical right shift 32-N to get zero extension in top 64-N bits.
4302 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
4303 .addZImm(8*(4-destSize))
4304 .addReg(dest, MachineOperand::Def));
4306 } else if (destSize < 8) {
4307 assert(0 && "Unsupported type size: 32 < size < 64 bits");
4313 } // End llvm namespace
4315 //==------------------------------------------------------------------------==//
4316 // Class V9ISel Implementation
4317 //==------------------------------------------------------------------------==//
4319 bool V9ISel::runOnFunction(Function &F) {
4320 // First pass - Walk the function, lowering any calls to intrinsic functions
4321 // which the instruction selector cannot handle.
4322 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4323 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
4324 if (CallInst *CI = dyn_cast<CallInst>(I++))
4325 if (Function *F = CI->getCalledFunction())
4326 switch (F->getIntrinsicID()) {
4327 case Intrinsic::not_intrinsic:
4328 case Intrinsic::vastart:
4329 case Intrinsic::vacopy:
4330 case Intrinsic::vaend:
4331 // We directly implement these intrinsics. Note that this knowledge
4332 // is incestuously entangled with the code in
4333 // SparcInstrSelection.cpp and must be updated when it is updated.
4334 // Since ALL of the code in this library is incestuously intertwined
4335 // with it already and sparc specific, we will live with this.
4338 // All other intrinsic calls we must lower.
4339 Instruction *Before = CI->getPrev();
4340 Target.getIntrinsicLowering().LowerIntrinsicCall(CI);
4341 if (Before) { // Move iterator to instruction after call
4348 // Build the instruction trees to be given as inputs to BURG.
4349 InstrForest instrForest(&F);
4350 if (SelectDebugLevel >= Select_DebugInstTrees) {
4351 std::cerr << "\n\n*** Input to instruction selection for function "
4352 << F.getName() << "\n\n" << F
4353 << "\n\n*** Instruction trees for function "
4354 << F.getName() << "\n\n";
4358 // Invoke BURG instruction selection for each tree
4359 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
4360 RI != instrForest.roots_end(); ++RI) {
4361 InstructionNode* basicNode = *RI;
4362 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
4364 // Invoke BURM to label each tree node with a state
4365 burm_label(basicNode);
4366 if (SelectDebugLevel >= Select_DebugBurgTrees) {
4367 printcover(basicNode, 1, 0);
4368 std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
4369 printMatches(basicNode);
4372 // Then recursively walk the tree to select instructions
4373 SelectInstructionsForTree(basicNode, /*goalnt*/1);
4376 // Create the MachineBasicBlocks and add all of the MachineInstrs
4377 // defined in the MachineCodeForInstruction objects to the MachineBasicBlocks.
4378 MachineFunction &MF = MachineFunction::get(&F);
4379 std::map<const BasicBlock *, MachineBasicBlock *> MBBMap;
4380 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
4381 MachineBasicBlock *MBB = new MachineBasicBlock(BI);
4382 MF.getBasicBlockList().push_back(MBB);
4385 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
4386 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
4387 MBB->insert(MBB->end(), mvec.begin(), mvec.end());
4391 // Initialize Machine-CFG for the function.
4392 for (MachineFunction::iterator i = MF.begin (), e = MF.end (); i != e; ++i) {
4393 MachineBasicBlock &MBB = *i;
4394 const BasicBlock *BB = MBB.getBasicBlock ();
4395 // for each successor S of BB, add MBBMap[S] as a successor of MBB.
4396 for (succ_const_iterator si = succ_begin(BB), se = succ_end(BB); si != se;
4398 MachineBasicBlock *succMBB = MBBMap[*si];
4399 assert (succMBB && "Can't find MachineBasicBlock for this successor");
4400 MBB.addSuccessor (succMBB);
4404 // Insert phi elimination code
4405 InsertCodeForPhis(F);
4407 if (SelectDebugLevel >= Select_PrintMachineCode) {
4408 std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
4409 MachineFunction::get(&F).dump();
4415 /// InsertCodeForPhis - This method inserts Phi elimination code for
4416 /// all Phi nodes in the given function. After this method is called,
4417 /// the Phi nodes still exist in the LLVM code, but copies are added to the
4420 void V9ISel::InsertCodeForPhis(Function &F) {
4421 // Iterate over every Phi node PN in F:
4422 MachineFunction &MF = MachineFunction::get(&F);
4423 for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
4424 for (BasicBlock::const_iterator IIt = BB->getBasicBlock()->begin();
4425 const PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
4426 // Create a new temporary register to hold the result of the Phi copy.
4427 // The leak detector shouldn't track these nodes. They are not garbage,
4428 // even though their parent field is never filled in.
4429 Value *PhiCpRes = new PHINode(PN->getType(), PN->getName() + ":PhiCp");
4430 LeakDetector::removeGarbageObject(PhiCpRes);
4432 // For each of PN's incoming values, insert a copy in the corresponding
4433 // predecessor block.
4434 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get (PN);
4435 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
4436 std::vector<MachineInstr*> mvec, CpVec;
4437 Target.getRegInfo()->cpValue2Value(PN->getIncomingValue(i),
4439 for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
4440 MI != mvec.end(); ++MI) {
4441 std::vector<MachineInstr*> CpVec2 =
4442 FixConstantOperandsForInstr(const_cast<PHINode*>(PN), *MI, Target);
4443 CpVec2.push_back(*MI);
4444 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
4446 // Insert the copy instructions into the predecessor BB.
4447 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
4448 MCforPN.insert (MCforPN.end (), CpVec.begin (), CpVec.end ());
4450 // Insert a copy instruction from PhiCpRes to PN.
4451 std::vector<MachineInstr*> mvec;
4452 Target.getRegInfo()->cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
4454 BB->insert(BB->begin(), mvec.begin(), mvec.end());
4455 MCforPN.insert (MCforPN.end (), mvec.begin (), mvec.end ());
4456 } // for each Phi Instr in BB
4457 } // for all BBs in function
4460 /// InsertPhiElimInstructions - Inserts the instructions in CpVec into the
4461 /// MachineBasicBlock corresponding to BB, just before its terminator
4462 /// instruction. This is used by InsertCodeForPhis() to insert copies, above.
4464 void V9ISel::InsertPhiElimInstructions(BasicBlock *BB,
4465 const std::vector<MachineInstr*>& CpVec)
4467 Instruction *TermInst = (Instruction*)BB->getTerminator();
4468 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
4469 MachineInstr *FirstMIOfTerm = MC4Term.front();
4470 assert (FirstMIOfTerm && "No Machine Instrs for terminator");
4472 MachineBasicBlock *MBB = FirstMIOfTerm->getParent();
4473 assert(MBB && "Machine BB for predecessor's terminator not found");
4474 MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
4475 assert(MCIt != MBB->end() && "Start inst of terminator not found");
4477 // Insert the copy instructions just before the first machine instruction
4478 // generated for the terminator.
4479 MBB->insert(MCIt, CpVec.begin(), CpVec.end());
4482 /// SelectInstructionsForTree - Recursively walk the tree to select
4483 /// instructions. Do this top-down so that child instructions can exploit
4484 /// decisions made at the child instructions.
4486 /// E.g., if br(setle(reg,const)) decides the constant is 0 and uses
4487 /// a branch-on-integer-register instruction, then the setle node
4488 /// can use that information to avoid generating the SUBcc instruction.
4490 /// Note that this cannot be done bottom-up because setle must do this
4491 /// only if it is a child of the branch (otherwise, the result of setle
4492 /// may be used by multiple instructions).
4494 void V9ISel::SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt) {
4495 // Get the rule that matches this node.
4496 int ruleForNode = burm_rule(treeRoot->state, goalnt);
4498 if (ruleForNode == 0) {
4499 std::cerr << "Could not match instruction tree for instr selection\n";
4503 // Get this rule's non-terminals and the corresponding child nodes (if any)
4504 short *nts = burm_nts[ruleForNode];
4506 // First, select instructions for the current node and rule.
4507 // (If this is a list node, not an instruction, then skip this step).
4508 // This function is specific to the target architecture.
4509 if (treeRoot->opLabel != VRegListOp) {
4510 std::vector<MachineInstr*> minstrVec;
4511 InstructionNode* instrNode = (InstructionNode*)treeRoot;
4512 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
4513 GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
4514 MachineCodeForInstruction &mvec =
4515 MachineCodeForInstruction::get(instrNode->getInstruction());
4516 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4519 // Then, recursively compile the child nodes, if any.
4522 // i.e., there is at least one kid
4523 InstrTreeNode* kids[2];
4524 int currentRule = ruleForNode;
4525 burm_kids(treeRoot, currentRule, kids);
4527 // First skip over any chain rules so that we don't visit
4528 // the current node again.
4529 while (ThisIsAChainRule(currentRule)) {
4530 currentRule = burm_rule(treeRoot->state, nts[0]);
4531 nts = burm_nts[currentRule];
4532 burm_kids(treeRoot, currentRule, kids);
4535 // Now we have the first non-chain rule so we have found
4536 // the actual child nodes. Recursively compile them.
4537 for (unsigned i = 0; nts[i]; i++) {
4539 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
4540 if (nodeType == InstrTreeNode::NTVRegListNode ||
4541 nodeType == InstrTreeNode::NTInstructionNode)
4542 SelectInstructionsForTree(kids[i], nts[i]);
4546 // Finally, do any post-processing on this node after its children
4547 // have been translated.
4548 if (treeRoot->opLabel != VRegListOp)
4549 PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
4552 /// PostprocessMachineCodeForTree - Apply any final cleanups to
4553 /// machine code for the root of a subtree after selection for all its
4554 /// children has been completed.
4556 void V9ISel::PostprocessMachineCodeForTree(InstructionNode *instrNode,
4557 int ruleForNode, short *nts) {
4558 // Fix up any constant operands in the machine instructions to either
4559 // use an immediate field or to load the constant into a register.
4560 // Walk backwards and use direct indexes to allow insertion before current.
4561 Instruction* vmInstr = instrNode->getInstruction();
4562 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
4563 for (unsigned i = mvec.size(); i != 0; --i) {
4564 std::vector<MachineInstr*> loadConstVec =
4565 FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
4566 mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
4570 /// createSparcV9BurgInstSelector - Creates and returns a new SparcV9
4571 /// BURG-based instruction selection pass.
4573 FunctionPass *llvm::createSparcV9BurgInstSelector(TargetMachine &TM) {
4574 return new V9ISel(TM);