1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86RegisterInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86ISelLowering.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/Statistic.h"
36 //===----------------------------------------------------------------------===//
37 // Pattern Matcher Implementation
38 //===----------------------------------------------------------------------===//
41 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
42 /// SDOperand's instead of register numbers for the leaves of the matched
44 struct X86ISelAddressMode {
51 struct { // This is really a union, discriminated by BaseType!
62 : BaseType(RegBase), Scale(1), IndexReg(), Disp(0), GV(0) {
69 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
71 //===--------------------------------------------------------------------===//
72 /// ISel - X86 specific code to select X86 machine instructions for
73 /// SelectionDAG operations.
75 class X86DAGToDAGISel : public SelectionDAGISel {
76 /// ContainsFPCode - Every instruction we select that uses or defines a FP
77 /// register should set this to true.
80 /// X86Lowering - This object fully describes how to lower LLVM code to an
81 /// X86-specific SelectionDAG.
82 X86TargetLowering X86Lowering;
84 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
85 /// make the right decision when generating code for different targets.
86 const X86Subtarget *Subtarget;
88 X86DAGToDAGISel(TargetMachine &TM)
89 : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
90 Subtarget = &TM.getSubtarget<X86Subtarget>();
93 virtual const char *getPassName() const {
94 return "X86 DAG->DAG Instruction Selection";
97 /// InstructionSelectBasicBlock - This callback is invoked by
98 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
99 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
101 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
103 // Include the pieces autogenerated from the target description.
104 #include "X86GenDAGISel.inc"
107 void Select(SDOperand &Result, SDOperand N);
109 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
110 bool SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
111 SDOperand &Index, SDOperand &Disp);
112 bool SelectLEAAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
113 SDOperand &Index, SDOperand &Disp);
114 bool TryFoldLoad(SDOperand P, SDOperand N,
115 SDOperand &Base, SDOperand &Scale,
116 SDOperand &Index, SDOperand &Disp);
118 inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base,
119 SDOperand &Scale, SDOperand &Index,
121 Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
122 CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, MVT::i32) : AM.Base.Reg;
123 Scale = getI8Imm(AM.Scale);
125 Disp = AM.GV ? CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp)
126 : getI32Imm(AM.Disp);
129 /// getI8Imm - Return a target constant with the specified value, of type
131 inline SDOperand getI8Imm(unsigned Imm) {
132 return CurDAG->getTargetConstant(Imm, MVT::i8);
135 /// getI16Imm - Return a target constant with the specified value, of type
137 inline SDOperand getI16Imm(unsigned Imm) {
138 return CurDAG->getTargetConstant(Imm, MVT::i16);
141 /// getI32Imm - Return a target constant with the specified value, of type
143 inline SDOperand getI32Imm(unsigned Imm) {
144 return CurDAG->getTargetConstant(Imm, MVT::i32);
149 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
150 /// when it has created a SelectionDAG for us to codegen.
151 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
153 MachineFunction::iterator FirstMBB = BB;
155 // Codegen the basic block.
156 DAG.setRoot(SelectRoot(DAG.getRoot()));
158 DAG.RemoveDeadNodes();
160 // Emit machine code to BB.
161 ScheduleAndEmitDAG(DAG);
163 // If we are emitting FP stack code, scan the basic block to determine if this
164 // block defines any FP values. If so, put an FP_REG_KILL instruction before
165 // the terminator of the block.
166 if (!Subtarget->hasSSE2()) {
167 // Note that FP stack instructions *are* used in SSE code when returning
168 // values, but these are not live out of the basic block, so we don't need
169 // an FP_REG_KILL in this case either.
170 bool ContainsFPCode = false;
172 // Scan all of the machine instructions in these MBBs, checking for FP
174 MachineFunction::iterator MBBI = FirstMBB;
176 for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
177 !ContainsFPCode && I != E; ++I) {
178 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
179 if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
180 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
181 RegMap->getRegClass(I->getOperand(0).getReg()) ==
182 X86::RFPRegisterClass) {
183 ContainsFPCode = true;
188 } while (!ContainsFPCode && &*(MBBI++) != BB);
190 // Check PHI nodes in successor blocks. These PHI's will be lowered to have
191 // a copy of the input value in this block.
192 if (!ContainsFPCode) {
193 // Final check, check LLVM BB's that are successors to the LLVM BB
194 // corresponding to BB for FP PHI nodes.
195 const BasicBlock *LLVMBB = BB->getBasicBlock();
197 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
198 !ContainsFPCode && SI != E; ++SI) {
199 for (BasicBlock::const_iterator II = SI->begin();
200 (PN = dyn_cast<PHINode>(II)); ++II) {
201 if (PN->getType()->isFloatingPoint()) {
202 ContainsFPCode = true;
209 // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
210 if (ContainsFPCode) {
211 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
217 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
218 /// the main function.
219 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
220 MachineFrameInfo *MFI) {
221 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
222 int CWFrameIdx = MFI->CreateStackObject(2, 2);
223 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
225 // Set the high part to be 64-bit precision.
226 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
227 CWFrameIdx, 1).addImm(2);
229 // Reload the modified control word now.
230 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
233 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
234 // If this is main, emit special code for main.
235 MachineBasicBlock *BB = MF.begin();
236 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
237 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
240 /// MatchAddress - Add the specified node to the specified addressing mode,
241 /// returning true if it cannot be done. This just pattern matches for the
243 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
244 switch (N.getOpcode()) {
246 case ISD::FrameIndex:
247 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
248 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
249 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
254 case ISD::ConstantPool:
255 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
256 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N)) {
257 AM.BaseType = X86ISelAddressMode::ConstantPoolBase;
258 AM.Base.Reg = CurDAG->getTargetConstantPool(CP->get(), MVT::i32,
265 case ISD::GlobalAddress:
266 case ISD::TargetGlobalAddress:
268 AM.GV = cast<GlobalAddressSDNode>(N)->getGlobal();
274 AM.Disp += cast<ConstantSDNode>(N)->getValue();
278 if (AM.IndexReg.Val == 0 && AM.Scale == 1)
279 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
280 unsigned Val = CN->getValue();
281 if (Val == 1 || Val == 2 || Val == 3) {
283 SDOperand ShVal = N.Val->getOperand(0);
285 // Okay, we know that we have a scale by now. However, if the scaled
286 // value is an add of something and a constant, we can fold the
287 // constant into the disp field here.
288 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
289 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
290 AM.IndexReg = ShVal.Val->getOperand(0);
291 ConstantSDNode *AddVal =
292 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
293 AM.Disp += AddVal->getValue() << Val;
303 // X*[3,5,9] -> X+X*[2,4,8]
304 if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
305 AM.Base.Reg.Val == 0)
306 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
307 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
308 AM.Scale = unsigned(CN->getValue())-1;
310 SDOperand MulVal = N.Val->getOperand(0);
313 // Okay, we know that we have a scale by now. However, if the scaled
314 // value is an add of something and a constant, we can fold the
315 // constant into the disp field here.
316 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
317 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
318 Reg = MulVal.Val->getOperand(0);
319 ConstantSDNode *AddVal =
320 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
321 AM.Disp += AddVal->getValue() * CN->getValue();
323 Reg = N.Val->getOperand(0);
326 AM.IndexReg = AM.Base.Reg = Reg;
332 X86ISelAddressMode Backup = AM;
333 if (!MatchAddress(N.Val->getOperand(0), AM) &&
334 !MatchAddress(N.Val->getOperand(1), AM))
337 if (!MatchAddress(N.Val->getOperand(1), AM) &&
338 !MatchAddress(N.Val->getOperand(0), AM))
345 // Is the base register already occupied?
346 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
347 // If so, check to see if the scale index register is set.
348 if (AM.IndexReg.Val == 0) {
354 // Otherwise, we cannot select it.
358 // Default, generate it as a register.
359 AM.BaseType = X86ISelAddressMode::RegBase;
364 /// SelectAddr - returns true if it is able pattern match an addressing mode.
365 /// It returns the operands which make up the maximal addressing mode it can
366 /// match by reference.
367 bool X86DAGToDAGISel::SelectAddr(SDOperand N, SDOperand &Base, SDOperand &Scale,
368 SDOperand &Index, SDOperand &Disp) {
369 X86ISelAddressMode AM;
370 if (MatchAddress(N, AM))
373 if (AM.BaseType == X86ISelAddressMode::RegBase) {
374 if (!AM.Base.Reg.Val)
375 AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
378 if (!AM.IndexReg.Val)
379 AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
381 getAddressOperands(AM, Base, Scale, Index, Disp);
385 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
386 SDOperand &Base, SDOperand &Scale,
387 SDOperand &Index, SDOperand &Disp) {
388 if (N.getOpcode() == ISD::LOAD &&
390 !CodeGenMap.count(N.getValue(0)) &&
391 (P.getNumOperands() == 1 || !isNonImmUse(P.Val, N.Val)))
392 return SelectAddr(N.getOperand(1), Base, Scale, Index, Disp);
396 static bool isRegister0(SDOperand Op) {
397 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op))
398 return (R->getReg() == 0);
402 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
403 /// mode it matches can be cost effectively emitted as an LEA instruction.
404 /// For X86, it always is unless it's just a (Reg + const).
405 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand N, SDOperand &Base,
407 SDOperand &Index, SDOperand &Disp) {
408 X86ISelAddressMode AM;
409 if (!MatchAddress(N, AM)) {
410 bool SelectBase = false;
411 bool SelectIndex = false;
413 if (AM.BaseType == X86ISelAddressMode::RegBase) {
414 if (AM.Base.Reg.Val) {
418 AM.Base.Reg = CurDAG->getRegister(0, MVT::i32);
422 if (AM.IndexReg.Val) {
425 AM.IndexReg = CurDAG->getRegister(0, MVT::i32);
429 unsigned Complexity = 0;
436 else if (AM.Disp > 1)
442 getAddressOperands(AM, Base, Scale, Index, Disp);
448 void X86DAGToDAGISel::Select(SDOperand &Result, SDOperand N) {
449 SDNode *Node = N.Val;
450 MVT::ValueType NVT = Node->getValueType(0);
452 unsigned Opcode = Node->getOpcode();
454 if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
456 return; // Already selected.
459 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);
460 if (CGMI != CodeGenMap.end()) {
461 Result = CGMI->second;
469 if (Opcode == ISD::MULHU)
471 default: assert(0 && "Unsupported VT!");
472 case MVT::i8: Opc = X86::MUL8r; MOpc = X86::MUL8m; break;
473 case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
474 case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
478 default: assert(0 && "Unsupported VT!");
479 case MVT::i8: Opc = X86::IMUL8r; MOpc = X86::IMUL8m; break;
480 case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
481 case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
484 unsigned LoReg, HiReg;
486 default: assert(0 && "Unsupported VT!");
487 case MVT::i8: LoReg = X86::AL; HiReg = X86::AH; break;
488 case MVT::i16: LoReg = X86::AX; HiReg = X86::DX; break;
489 case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
492 SDOperand N0 = Node->getOperand(0);
493 SDOperand N1 = Node->getOperand(1);
495 bool foldedLoad = false;
496 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
497 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
498 // MULHU and MULHS are commmutative
500 foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
502 N0 = Node->getOperand(1);
503 N1 = Node->getOperand(0);
509 Select(Chain, N1.getOperand(0));
511 Chain = CurDAG->getEntryNode();
513 SDOperand InFlag(0, 0);
515 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
517 InFlag = Chain.getValue(1);
524 Chain = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
525 Tmp2, Tmp3, Chain, InFlag);
526 InFlag = Chain.getValue(1);
529 InFlag = CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag);
532 Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
533 CodeGenMap[N.getValue(0)] = Result;
535 CodeGenMap[N1.getValue(1)] = Result.getValue(1);
536 AddHandleReplacement(N1.getValue(1), Result.getValue(1));
546 bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
547 bool isDiv = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
550 default: assert(0 && "Unsupported VT!");
551 case MVT::i8: Opc = X86::DIV8r; MOpc = X86::DIV8m; break;
552 case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
553 case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
557 default: assert(0 && "Unsupported VT!");
558 case MVT::i8: Opc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
559 case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
560 case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
563 unsigned LoReg, HiReg;
564 unsigned ClrOpcode, SExtOpcode;
566 default: assert(0 && "Unsupported VT!");
568 LoReg = X86::AL; HiReg = X86::AH;
569 ClrOpcode = X86::MOV8ri;
570 SExtOpcode = X86::CBW;
573 LoReg = X86::AX; HiReg = X86::DX;
574 ClrOpcode = X86::MOV16ri;
575 SExtOpcode = X86::CWD;
578 LoReg = X86::EAX; HiReg = X86::EDX;
579 ClrOpcode = X86::MOV32ri;
580 SExtOpcode = X86::CDQ;
584 SDOperand N0 = Node->getOperand(0);
585 SDOperand N1 = Node->getOperand(1);
587 bool foldedLoad = false;
588 SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
589 foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
592 Select(Chain, N1.getOperand(0));
594 Chain = CurDAG->getEntryNode();
596 SDOperand InFlag(0, 0);
598 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
600 InFlag = Chain.getValue(1);
603 // Sign extend the low part into the high part.
604 InFlag = CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag);
606 // Zero out the high part, effectively zero extending the input.
608 CurDAG->getTargetNode(ClrOpcode, NVT,
609 CurDAG->getTargetConstant(0, NVT));
610 Chain = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(HiReg, NVT),
612 InFlag = Chain.getValue(1);
620 Chain = CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Tmp0, Tmp1,
621 Tmp2, Tmp3, Chain, InFlag);
622 InFlag = Chain.getValue(1);
625 InFlag = CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag);
628 Result = CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg,
630 CodeGenMap[N.getValue(0)] = Result;
632 CodeGenMap[N1.getValue(1)] = Result.getValue(1);
633 AddHandleReplacement(N1.getValue(1), Result.getValue(1));
638 case ISD::TRUNCATE: {
641 switch (Node->getOperand(0).getValueType()) {
642 default: assert(0 && "Unknown truncate!");
643 case MVT::i16: Reg = X86::AX; Opc = X86::MOV16rr; VT = MVT::i16; break;
644 case MVT::i32: Reg = X86::EAX; Opc = X86::MOV32rr; VT = MVT::i32; break;
646 SDOperand Tmp0, Tmp1;
647 Select(Tmp0, Node->getOperand(0));
648 Select(Tmp1, CurDAG->getTargetNode(Opc, VT, Tmp0));
649 SDOperand InFlag = SDOperand(0,0);
650 Result = CurDAG->getCopyToReg(CurDAG->getEntryNode(), Reg, Tmp1, InFlag);
651 SDOperand Chain = Result.getValue(0);
652 InFlag = Result.getValue(1);
655 default: assert(0 && "Unknown truncate!");
656 case MVT::i8: Reg = X86::AL; Opc = X86::MOV8rr; VT = MVT::i8; break;
657 case MVT::i16: Reg = X86::AX; Opc = X86::MOV16rr; VT = MVT::i16; break;
660 Result = CurDAG->getCopyFromReg(Chain, Reg, VT, InFlag);
661 if (N.Val->hasOneUse())
662 Result =CurDAG->SelectNodeTo(N.Val, Opc, VT, Result);
664 Result = CodeGenMap[N] = CurDAG->getTargetNode(Opc, VT, Result);
669 SelectCode(Result, N);
672 /// createX86ISelDag - This pass converts a legalized DAG into a
673 /// X86-specific DAG, ready for instruction scheduling.
675 FunctionPass *llvm::createX86ISelDag(TargetMachine &TM) {
676 return new X86DAGToDAGISel(TM);