eliminate PreprocessForRMW now that isel handles it.
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Type.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
42 using namespace llvm;
43
44 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
45
46 //===----------------------------------------------------------------------===//
47 //                      Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
49
50 namespace {
51   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52   /// SDValue's instead of register numbers for the leaves of the matched
53   /// tree.
54   struct X86ISelAddressMode {
55     enum {
56       RegBase,
57       FrameIndexBase
58     } BaseType;
59
60     struct {            // This is really a union, discriminated by BaseType!
61       SDValue Reg;
62       int FrameIndex;
63     } Base;
64
65     unsigned Scale;
66     SDValue IndexReg; 
67     int32_t Disp;
68     SDValue Segment;
69     GlobalValue *GV;
70     Constant *CP;
71     BlockAddress *BlockAddr;
72     const char *ES;
73     int JT;
74     unsigned Align;    // CP alignment.
75     unsigned char SymbolFlags;  // X86II::MO_*
76
77     X86ISelAddressMode()
78       : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
79         Segment(), GV(0), CP(0), BlockAddr(0), ES(0), JT(-1), Align(0),
80         SymbolFlags(X86II::MO_NO_FLAG) {
81     }
82
83     bool hasSymbolicDisplacement() const {
84       return GV != 0 || CP != 0 || ES != 0 || JT != -1 || BlockAddr != 0;
85     }
86     
87     bool hasBaseOrIndexReg() const {
88       return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
89     }
90     
91     /// isRIPRelative - Return true if this addressing mode is already RIP
92     /// relative.
93     bool isRIPRelative() const {
94       if (BaseType != RegBase) return false;
95       if (RegisterSDNode *RegNode =
96             dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
97         return RegNode->getReg() == X86::RIP;
98       return false;
99     }
100     
101     void setBaseReg(SDValue Reg) {
102       BaseType = RegBase;
103       Base.Reg = Reg;
104     }
105
106     void dump() {
107       dbgs() << "X86ISelAddressMode " << this << '\n';
108       dbgs() << "Base.Reg ";
109       if (Base.Reg.getNode() != 0)
110         Base.Reg.getNode()->dump(); 
111       else
112         dbgs() << "nul";
113       dbgs() << " Base.FrameIndex " << Base.FrameIndex << '\n'
114              << " Scale" << Scale << '\n'
115              << "IndexReg ";
116       if (IndexReg.getNode() != 0)
117         IndexReg.getNode()->dump();
118       else
119         dbgs() << "nul"; 
120       dbgs() << " Disp " << Disp << '\n'
121              << "GV ";
122       if (GV)
123         GV->dump();
124       else
125         dbgs() << "nul";
126       dbgs() << " CP ";
127       if (CP)
128         CP->dump();
129       else
130         dbgs() << "nul";
131       dbgs() << '\n'
132              << "ES ";
133       if (ES)
134         dbgs() << ES;
135       else
136         dbgs() << "nul";
137       dbgs() << " JT" << JT << " Align" << Align << '\n';
138     }
139   };
140 }
141
142 namespace {
143   //===--------------------------------------------------------------------===//
144   /// ISel - X86 specific code to select X86 machine instructions for
145   /// SelectionDAG operations.
146   ///
147   class X86DAGToDAGISel : public SelectionDAGISel {
148     /// X86Lowering - This object fully describes how to lower LLVM code to an
149     /// X86-specific SelectionDAG.
150     X86TargetLowering &X86Lowering;
151
152     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
153     /// make the right decision when generating code for different targets.
154     const X86Subtarget *Subtarget;
155
156     /// OptForSize - If true, selector should try to optimize for code size
157     /// instead of performance.
158     bool OptForSize;
159
160   public:
161     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
162       : SelectionDAGISel(tm, OptLevel),
163         X86Lowering(*tm.getTargetLowering()),
164         Subtarget(&tm.getSubtarget<X86Subtarget>()),
165         OptForSize(false) {}
166
167     virtual const char *getPassName() const {
168       return "X86 DAG->DAG Instruction Selection";
169     }
170
171     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
172
173     virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
174
175     virtual void PreprocessISelDAG();
176
177 // Include the pieces autogenerated from the target description.
178 #include "X86GenDAGISel.inc"
179
180   private:
181     SDNode *Select(SDNode *N);
182     SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
183     SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
184
185     bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
186     bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
187     bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
188     bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
189     bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
190                                  unsigned Depth);
191     bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
192     bool SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
193                     SDValue &Scale, SDValue &Index, SDValue &Disp,
194                     SDValue &Segment);
195     bool SelectLEAAddr(SDNode *Op, SDValue N, SDValue &Base,
196                        SDValue &Scale, SDValue &Index, SDValue &Disp);
197     bool SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
198                        SDValue &Scale, SDValue &Index, SDValue &Disp);
199     bool SelectScalarSSELoad(SDNode *Root, SDValue N,
200                              SDValue &Base, SDValue &Scale,
201                              SDValue &Index, SDValue &Disp,
202                              SDValue &Segment,
203                              SDValue &NodeWithChain);
204     
205     bool TryFoldLoad(SDNode *P, SDValue N,
206                      SDValue &Base, SDValue &Scale,
207                      SDValue &Index, SDValue &Disp,
208                      SDValue &Segment);
209     
210     void PreprocessForCallLoads();
211     void PreprocessForFPConvert();
212
213     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
214     /// inline asm expressions.
215     virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
216                                               char ConstraintCode,
217                                               std::vector<SDValue> &OutOps);
218     
219     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
220
221     inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base, 
222                                    SDValue &Scale, SDValue &Index,
223                                    SDValue &Disp, SDValue &Segment) {
224       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
225         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
226         AM.Base.Reg;
227       Scale = getI8Imm(AM.Scale);
228       Index = AM.IndexReg;
229       // These are 32-bit even in 64-bit mode since RIP relative offset
230       // is 32-bit.
231       if (AM.GV)
232         Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
233                                               AM.SymbolFlags);
234       else if (AM.CP)
235         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
236                                              AM.Align, AM.Disp, AM.SymbolFlags);
237       else if (AM.ES)
238         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
239       else if (AM.JT != -1)
240         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
241       else if (AM.BlockAddr)
242         Disp = CurDAG->getBlockAddress(AM.BlockAddr, MVT::i32,
243                                        true, AM.SymbolFlags);
244       else
245         Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
246
247       if (AM.Segment.getNode())
248         Segment = AM.Segment;
249       else
250         Segment = CurDAG->getRegister(0, MVT::i32);
251     }
252
253     /// getI8Imm - Return a target constant with the specified value, of type
254     /// i8.
255     inline SDValue getI8Imm(unsigned Imm) {
256       return CurDAG->getTargetConstant(Imm, MVT::i8);
257     }
258
259     /// getI16Imm - Return a target constant with the specified value, of type
260     /// i16.
261     inline SDValue getI16Imm(unsigned Imm) {
262       return CurDAG->getTargetConstant(Imm, MVT::i16);
263     }
264
265     /// getI32Imm - Return a target constant with the specified value, of type
266     /// i32.
267     inline SDValue getI32Imm(unsigned Imm) {
268       return CurDAG->getTargetConstant(Imm, MVT::i32);
269     }
270
271     /// getGlobalBaseReg - Return an SDNode that returns the value of
272     /// the global base register. Output instructions required to
273     /// initialize the global base register, if necessary.
274     ///
275     SDNode *getGlobalBaseReg();
276
277     /// getTargetMachine - Return a reference to the TargetMachine, casted
278     /// to the target-specific type.
279     const X86TargetMachine &getTargetMachine() {
280       return static_cast<const X86TargetMachine &>(TM);
281     }
282
283     /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
284     /// to the target-specific type.
285     const X86InstrInfo *getInstrInfo() {
286       return getTargetMachine().getInstrInfo();
287     }
288   };
289 }
290
291
292 bool
293 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
294   if (OptLevel == CodeGenOpt::None) return false;
295
296   if (!N.hasOneUse())
297     return false;
298
299   if (N.getOpcode() != ISD::LOAD)
300     return true;
301
302   // If N is a load, do additional profitability checks.
303   if (U == Root) {
304     switch (U->getOpcode()) {
305     default: break;
306     case X86ISD::ADD:
307     case X86ISD::SUB:
308     case X86ISD::AND:
309     case X86ISD::XOR:
310     case X86ISD::OR:
311     case ISD::ADD:
312     case ISD::ADDC:
313     case ISD::ADDE:
314     case ISD::AND:
315     case ISD::OR:
316     case ISD::XOR: {
317       SDValue Op1 = U->getOperand(1);
318
319       // If the other operand is a 8-bit immediate we should fold the immediate
320       // instead. This reduces code size.
321       // e.g.
322       // movl 4(%esp), %eax
323       // addl $4, %eax
324       // vs.
325       // movl $4, %eax
326       // addl 4(%esp), %eax
327       // The former is 2 bytes shorter. In case where the increment is 1, then
328       // the saving can be 4 bytes (by using incl %eax).
329       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
330         if (Imm->getAPIntValue().isSignedIntN(8))
331           return false;
332
333       // If the other operand is a TLS address, we should fold it instead.
334       // This produces
335       // movl    %gs:0, %eax
336       // leal    i@NTPOFF(%eax), %eax
337       // instead of
338       // movl    $i@NTPOFF, %eax
339       // addl    %gs:0, %eax
340       // if the block also has an access to a second TLS address this will save
341       // a load.
342       // FIXME: This is probably also true for non TLS addresses.
343       if (Op1.getOpcode() == X86ISD::Wrapper) {
344         SDValue Val = Op1.getOperand(0);
345         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
346           return false;
347       }
348     }
349     }
350   }
351
352   return true;
353 }
354
355 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
356 /// operand and move load below the call's chain operand.
357 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
358                                   SDValue Call, SDValue CallSeqStart) {
359   SmallVector<SDValue, 8> Ops;
360   SDValue Chain = CallSeqStart.getOperand(0);
361   if (Chain.getNode() == Load.getNode())
362     Ops.push_back(Load.getOperand(0));
363   else {
364     assert(Chain.getOpcode() == ISD::TokenFactor &&
365            "Unexpected CallSeqStart chain operand");
366     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
367       if (Chain.getOperand(i).getNode() == Load.getNode())
368         Ops.push_back(Load.getOperand(0));
369       else
370         Ops.push_back(Chain.getOperand(i));
371     SDValue NewChain =
372       CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
373                       MVT::Other, &Ops[0], Ops.size());
374     Ops.clear();
375     Ops.push_back(NewChain);
376   }
377   for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
378     Ops.push_back(CallSeqStart.getOperand(i));
379   CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
380   CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
381                              Load.getOperand(1), Load.getOperand(2));
382   Ops.clear();
383   Ops.push_back(SDValue(Load.getNode(), 1));
384   for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
385     Ops.push_back(Call.getOperand(i));
386   CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
387 }
388
389 /// isCalleeLoad - Return true if call address is a load and it can be
390 /// moved below CALLSEQ_START and the chains leading up to the call.
391 /// Return the CALLSEQ_START by reference as a second output.
392 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
393   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
394     return false;
395   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
396   if (!LD ||
397       LD->isVolatile() ||
398       LD->getAddressingMode() != ISD::UNINDEXED ||
399       LD->getExtensionType() != ISD::NON_EXTLOAD)
400     return false;
401
402   // Now let's find the callseq_start.
403   while (Chain.getOpcode() != ISD::CALLSEQ_START) {
404     if (!Chain.hasOneUse())
405       return false;
406     Chain = Chain.getOperand(0);
407   }
408   
409   if (Chain.getOperand(0).getNode() == Callee.getNode())
410     return true;
411   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
412       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
413       Callee.getValue(1).hasOneUse())
414     return true;
415   return false;
416 }
417
418
419 void X86DAGToDAGISel::PreprocessForCallLoads() {
420   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
421          E = CurDAG->allnodes_end(); I != E; ++I) {
422     if (I->getOpcode() != X86ISD::CALL)
423       continue;
424     
425     /// Also try moving call address load from outside callseq_start to just
426     /// before the call to allow it to be folded.
427     ///
428     ///     [Load chain]
429     ///         ^
430     ///         |
431     ///       [Load]
432     ///       ^    ^
433     ///       |    |
434     ///      /      \--
435     ///     /          |
436     ///[CALLSEQ_START] |
437     ///     ^          |
438     ///     |          |
439     /// [LOAD/C2Reg]   |
440     ///     |          |
441     ///      \        /
442     ///       \      /
443     ///       [CALL]
444     SDValue Chain = I->getOperand(0);
445     SDValue Load  = I->getOperand(1);
446     if (!isCalleeLoad(Load, Chain))
447       continue;
448     MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
449     ++NumLoadMoved;
450   }
451 }
452
453
454 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
455 /// nodes that target the FP stack to be store and load to the stack.  This is a
456 /// gross hack.  We would like to simply mark these as being illegal, but when
457 /// we do that, legalize produces these when it expands calls, then expands
458 /// these in the same legalize pass.  We would like dag combine to be able to
459 /// hack on these between the call expansion and the node legalization.  As such
460 /// this pass basically does "really late" legalization of these inline with the
461 /// X86 isel pass.
462 void X86DAGToDAGISel::PreprocessForFPConvert() {
463   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
464        E = CurDAG->allnodes_end(); I != E; ) {
465     SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
466     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
467       continue;
468     
469     // If the source and destination are SSE registers, then this is a legal
470     // conversion that should not be lowered.
471     EVT SrcVT = N->getOperand(0).getValueType();
472     EVT DstVT = N->getValueType(0);
473     bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
474     bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
475     if (SrcIsSSE && DstIsSSE)
476       continue;
477
478     if (!SrcIsSSE && !DstIsSSE) {
479       // If this is an FPStack extension, it is a noop.
480       if (N->getOpcode() == ISD::FP_EXTEND)
481         continue;
482       // If this is a value-preserving FPStack truncation, it is a noop.
483       if (N->getConstantOperandVal(1))
484         continue;
485     }
486    
487     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
488     // FPStack has extload and truncstore.  SSE can fold direct loads into other
489     // operations.  Based on this, decide what we want to do.
490     EVT MemVT;
491     if (N->getOpcode() == ISD::FP_ROUND)
492       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
493     else
494       MemVT = SrcIsSSE ? SrcVT : DstVT;
495     
496     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
497     DebugLoc dl = N->getDebugLoc();
498     
499     // FIXME: optimize the case where the src/dest is a load or store?
500     SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
501                                           N->getOperand(0),
502                                           MemTmp, NULL, 0, MemVT,
503                                           false, false, 0);
504     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
505                                         NULL, 0, MemVT, false, false, 0);
506
507     // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
508     // extload we created.  This will cause general havok on the dag because
509     // anything below the conversion could be folded into other existing nodes.
510     // To avoid invalidating 'I', back it up to the convert node.
511     --I;
512     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
513     
514     // Now that we did that, the node is dead.  Increment the iterator to the
515     // next node to process, then delete N.
516     ++I;
517     CurDAG->DeleteNode(N);
518   }  
519 }
520
521 void X86DAGToDAGISel::PreprocessISelDAG() {
522   OptForSize = MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize);
523
524   if (OptLevel != CodeGenOpt::None)
525     PreprocessForCallLoads();
526
527   // FIXME: This should only happen when not compiled with -O0.
528   PreprocessForFPConvert();
529 }
530
531 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
532 /// the main function.
533 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
534                                              MachineFrameInfo *MFI) {
535   const TargetInstrInfo *TII = TM.getInstrInfo();
536   if (Subtarget->isTargetCygMing())
537     BuildMI(BB, DebugLoc::getUnknownLoc(),
538             TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
539 }
540
541 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
542   // If this is main, emit special code for main.
543   MachineBasicBlock *BB = MF.begin();
544   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
545     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
546 }
547
548
549 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
550                                               X86ISelAddressMode &AM) {
551   assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
552   SDValue Segment = N.getOperand(0);
553
554   if (AM.Segment.getNode() == 0) {
555     AM.Segment = Segment;
556     return false;
557   }
558
559   return true;
560 }
561
562 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
563   // This optimization is valid because the GNU TLS model defines that
564   // gs:0 (or fs:0 on X86-64) contains its own address.
565   // For more information see http://people.redhat.com/drepper/tls.pdf
566
567   SDValue Address = N.getOperand(1);
568   if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
569       !MatchSegmentBaseAddress (Address, AM))
570     return false;
571
572   return true;
573 }
574
575 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
576 /// into an addressing mode.  These wrap things that will resolve down into a
577 /// symbol reference.  If no match is possible, this returns true, otherwise it
578 /// returns false.
579 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
580   // If the addressing mode already has a symbol as the displacement, we can
581   // never match another symbol.
582   if (AM.hasSymbolicDisplacement())
583     return true;
584
585   SDValue N0 = N.getOperand(0);
586   CodeModel::Model M = TM.getCodeModel();
587
588   // Handle X86-64 rip-relative addresses.  We check this before checking direct
589   // folding because RIP is preferable to non-RIP accesses.
590   if (Subtarget->is64Bit() &&
591       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
592       // they cannot be folded into immediate fields.
593       // FIXME: This can be improved for kernel and other models?
594       (M == CodeModel::Small || M == CodeModel::Kernel) &&
595       // Base and index reg must be 0 in order to use %rip as base and lowering
596       // must allow RIP.
597       !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
598     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
599       int64_t Offset = AM.Disp + G->getOffset();
600       if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
601       AM.GV = G->getGlobal();
602       AM.Disp = Offset;
603       AM.SymbolFlags = G->getTargetFlags();
604     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
605       int64_t Offset = AM.Disp + CP->getOffset();
606       if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
607       AM.CP = CP->getConstVal();
608       AM.Align = CP->getAlignment();
609       AM.Disp = Offset;
610       AM.SymbolFlags = CP->getTargetFlags();
611     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
612       AM.ES = S->getSymbol();
613       AM.SymbolFlags = S->getTargetFlags();
614     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
615       AM.JT = J->getIndex();
616       AM.SymbolFlags = J->getTargetFlags();
617     } else {
618       AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
619       AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
620     }
621
622     if (N.getOpcode() == X86ISD::WrapperRIP)
623       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
624     return false;
625   }
626
627   // Handle the case when globals fit in our immediate field: This is true for
628   // X86-32 always and X86-64 when in -static -mcmodel=small mode.  In 64-bit
629   // mode, this results in a non-RIP-relative computation.
630   if (!Subtarget->is64Bit() ||
631       ((M == CodeModel::Small || M == CodeModel::Kernel) &&
632        TM.getRelocationModel() == Reloc::Static)) {
633     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
634       AM.GV = G->getGlobal();
635       AM.Disp += G->getOffset();
636       AM.SymbolFlags = G->getTargetFlags();
637     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
638       AM.CP = CP->getConstVal();
639       AM.Align = CP->getAlignment();
640       AM.Disp += CP->getOffset();
641       AM.SymbolFlags = CP->getTargetFlags();
642     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
643       AM.ES = S->getSymbol();
644       AM.SymbolFlags = S->getTargetFlags();
645     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
646       AM.JT = J->getIndex();
647       AM.SymbolFlags = J->getTargetFlags();
648     } else {
649       AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
650       AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
651     }
652     return false;
653   }
654
655   return true;
656 }
657
658 /// MatchAddress - Add the specified node to the specified addressing mode,
659 /// returning true if it cannot be done.  This just pattern matches for the
660 /// addressing mode.
661 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
662   if (MatchAddressRecursively(N, AM, 0))
663     return true;
664
665   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
666   // a smaller encoding and avoids a scaled-index.
667   if (AM.Scale == 2 &&
668       AM.BaseType == X86ISelAddressMode::RegBase &&
669       AM.Base.Reg.getNode() == 0) {
670     AM.Base.Reg = AM.IndexReg;
671     AM.Scale = 1;
672   }
673
674   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
675   // because it has a smaller encoding.
676   // TODO: Which other code models can use this?
677   if (TM.getCodeModel() == CodeModel::Small &&
678       Subtarget->is64Bit() &&
679       AM.Scale == 1 &&
680       AM.BaseType == X86ISelAddressMode::RegBase &&
681       AM.Base.Reg.getNode() == 0 &&
682       AM.IndexReg.getNode() == 0 &&
683       AM.SymbolFlags == X86II::MO_NO_FLAG &&
684       AM.hasSymbolicDisplacement())
685     AM.Base.Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
686
687   return false;
688 }
689
690 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
691                                               unsigned Depth) {
692   bool is64Bit = Subtarget->is64Bit();
693   DebugLoc dl = N.getDebugLoc();
694   DEBUG({
695       dbgs() << "MatchAddress: ";
696       AM.dump();
697     });
698   // Limit recursion.
699   if (Depth > 5)
700     return MatchAddressBase(N, AM);
701
702   CodeModel::Model M = TM.getCodeModel();
703
704   // If this is already a %rip relative address, we can only merge immediates
705   // into it.  Instead of handling this in every case, we handle it here.
706   // RIP relative addressing: %rip + 32-bit displacement!
707   if (AM.isRIPRelative()) {
708     // FIXME: JumpTable and ExternalSymbol address currently don't like
709     // displacements.  It isn't very important, but this should be fixed for
710     // consistency.
711     if (!AM.ES && AM.JT != -1) return true;
712
713     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
714       int64_t Val = AM.Disp + Cst->getSExtValue();
715       if (X86::isOffsetSuitableForCodeModel(Val, M,
716                                             AM.hasSymbolicDisplacement())) {
717         AM.Disp = Val;
718         return false;
719       }
720     }
721     return true;
722   }
723
724   switch (N.getOpcode()) {
725   default: break;
726   case ISD::Constant: {
727     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
728     if (!is64Bit ||
729         X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
730                                           AM.hasSymbolicDisplacement())) {
731       AM.Disp += Val;
732       return false;
733     }
734     break;
735   }
736
737   case X86ISD::SegmentBaseAddress:
738     if (!MatchSegmentBaseAddress(N, AM))
739       return false;
740     break;
741
742   case X86ISD::Wrapper:
743   case X86ISD::WrapperRIP:
744     if (!MatchWrapper(N, AM))
745       return false;
746     break;
747
748   case ISD::LOAD:
749     if (!MatchLoad(N, AM))
750       return false;
751     break;
752
753   case ISD::FrameIndex:
754     if (AM.BaseType == X86ISelAddressMode::RegBase
755         && AM.Base.Reg.getNode() == 0) {
756       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
757       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
758       return false;
759     }
760     break;
761
762   case ISD::SHL:
763     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
764       break;
765       
766     if (ConstantSDNode
767           *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
768       unsigned Val = CN->getZExtValue();
769       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
770       // that the base operand remains free for further matching. If
771       // the base doesn't end up getting used, a post-processing step
772       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
773       if (Val == 1 || Val == 2 || Val == 3) {
774         AM.Scale = 1 << Val;
775         SDValue ShVal = N.getNode()->getOperand(0);
776
777         // Okay, we know that we have a scale by now.  However, if the scaled
778         // value is an add of something and a constant, we can fold the
779         // constant into the disp field here.
780         if (ShVal.getNode()->getOpcode() == ISD::ADD &&
781             isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
782           AM.IndexReg = ShVal.getNode()->getOperand(0);
783           ConstantSDNode *AddVal =
784             cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
785           uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
786           if (!is64Bit ||
787               X86::isOffsetSuitableForCodeModel(Disp, M,
788                                                 AM.hasSymbolicDisplacement()))
789             AM.Disp = Disp;
790           else
791             AM.IndexReg = ShVal;
792         } else {
793           AM.IndexReg = ShVal;
794         }
795         return false;
796       }
797     break;
798     }
799
800   case ISD::SMUL_LOHI:
801   case ISD::UMUL_LOHI:
802     // A mul_lohi where we need the low part can be folded as a plain multiply.
803     if (N.getResNo() != 0) break;
804     // FALL THROUGH
805   case ISD::MUL:
806   case X86ISD::MUL_IMM:
807     // X*[3,5,9] -> X+X*[2,4,8]
808     if (AM.BaseType == X86ISelAddressMode::RegBase &&
809         AM.Base.Reg.getNode() == 0 &&
810         AM.IndexReg.getNode() == 0) {
811       if (ConstantSDNode
812             *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
813         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
814             CN->getZExtValue() == 9) {
815           AM.Scale = unsigned(CN->getZExtValue())-1;
816
817           SDValue MulVal = N.getNode()->getOperand(0);
818           SDValue Reg;
819
820           // Okay, we know that we have a scale by now.  However, if the scaled
821           // value is an add of something and a constant, we can fold the
822           // constant into the disp field here.
823           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
824               isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
825             Reg = MulVal.getNode()->getOperand(0);
826             ConstantSDNode *AddVal =
827               cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
828             uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
829                                       CN->getZExtValue();
830             if (!is64Bit ||
831                 X86::isOffsetSuitableForCodeModel(Disp, M,
832                                                   AM.hasSymbolicDisplacement()))
833               AM.Disp = Disp;
834             else
835               Reg = N.getNode()->getOperand(0);
836           } else {
837             Reg = N.getNode()->getOperand(0);
838           }
839
840           AM.IndexReg = AM.Base.Reg = Reg;
841           return false;
842         }
843     }
844     break;
845
846   case ISD::SUB: {
847     // Given A-B, if A can be completely folded into the address and
848     // the index field with the index field unused, use -B as the index.
849     // This is a win if a has multiple parts that can be folded into
850     // the address. Also, this saves a mov if the base register has
851     // other uses, since it avoids a two-address sub instruction, however
852     // it costs an additional mov if the index register has other uses.
853
854     // Test if the LHS of the sub can be folded.
855     X86ISelAddressMode Backup = AM;
856     if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
857       AM = Backup;
858       break;
859     }
860     // Test if the index field is free for use.
861     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
862       AM = Backup;
863       break;
864     }
865     int Cost = 0;
866     SDValue RHS = N.getNode()->getOperand(1);
867     // If the RHS involves a register with multiple uses, this
868     // transformation incurs an extra mov, due to the neg instruction
869     // clobbering its operand.
870     if (!RHS.getNode()->hasOneUse() ||
871         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
872         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
873         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
874         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
875          RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
876       ++Cost;
877     // If the base is a register with multiple uses, this
878     // transformation may save a mov.
879     if ((AM.BaseType == X86ISelAddressMode::RegBase &&
880          AM.Base.Reg.getNode() &&
881          !AM.Base.Reg.getNode()->hasOneUse()) ||
882         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
883       --Cost;
884     // If the folded LHS was interesting, this transformation saves
885     // address arithmetic.
886     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
887         ((AM.Disp != 0) && (Backup.Disp == 0)) +
888         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
889       --Cost;
890     // If it doesn't look like it may be an overall win, don't do it.
891     if (Cost >= 0) {
892       AM = Backup;
893       break;
894     }
895
896     // Ok, the transformation is legal and appears profitable. Go for it.
897     SDValue Zero = CurDAG->getConstant(0, N.getValueType());
898     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
899     AM.IndexReg = Neg;
900     AM.Scale = 1;
901
902     // Insert the new nodes into the topological ordering.
903     if (Zero.getNode()->getNodeId() == -1 ||
904         Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
905       CurDAG->RepositionNode(N.getNode(), Zero.getNode());
906       Zero.getNode()->setNodeId(N.getNode()->getNodeId());
907     }
908     if (Neg.getNode()->getNodeId() == -1 ||
909         Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
910       CurDAG->RepositionNode(N.getNode(), Neg.getNode());
911       Neg.getNode()->setNodeId(N.getNode()->getNodeId());
912     }
913     return false;
914   }
915
916   case ISD::ADD: {
917     X86ISelAddressMode Backup = AM;
918     if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1) &&
919         !MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1))
920       return false;
921     AM = Backup;
922     if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1) &&
923         !MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1))
924       return false;
925     AM = Backup;
926
927     // If we couldn't fold both operands into the address at the same time,
928     // see if we can just put each operand into a register and fold at least
929     // the add.
930     if (AM.BaseType == X86ISelAddressMode::RegBase &&
931         !AM.Base.Reg.getNode() &&
932         !AM.IndexReg.getNode()) {
933       AM.Base.Reg = N.getNode()->getOperand(0);
934       AM.IndexReg = N.getNode()->getOperand(1);
935       AM.Scale = 1;
936       return false;
937     }
938     break;
939   }
940
941   case ISD::OR:
942     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
943     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
944       X86ISelAddressMode Backup = AM;
945       uint64_t Offset = CN->getSExtValue();
946       // Start with the LHS as an addr mode.
947       if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
948           // Address could not have picked a GV address for the displacement.
949           AM.GV == NULL &&
950           // On x86-64, the resultant disp must fit in 32-bits.
951           (!is64Bit ||
952            X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
953                                              AM.hasSymbolicDisplacement())) &&
954           // Check to see if the LHS & C is zero.
955           CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
956         AM.Disp += Offset;
957         return false;
958       }
959       AM = Backup;
960     }
961     break;
962       
963   case ISD::AND: {
964     // Perform some heroic transforms on an and of a constant-count shift
965     // with a constant to enable use of the scaled offset field.
966
967     SDValue Shift = N.getOperand(0);
968     if (Shift.getNumOperands() != 2) break;
969
970     // Scale must not be used already.
971     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
972
973     SDValue X = Shift.getOperand(0);
974     ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
975     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
976     if (!C1 || !C2) break;
977
978     // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
979     // allows us to convert the shift and and into an h-register extract and
980     // a scaled index.
981     if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
982       unsigned ScaleLog = 8 - C1->getZExtValue();
983       if (ScaleLog > 0 && ScaleLog < 4 &&
984           C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
985         SDValue Eight = CurDAG->getConstant(8, MVT::i8);
986         SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
987         SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
988                                       X, Eight);
989         SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
990                                       Srl, Mask);
991         SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
992         SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
993                                       And, ShlCount);
994
995         // Insert the new nodes into the topological ordering.
996         if (Eight.getNode()->getNodeId() == -1 ||
997             Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
998           CurDAG->RepositionNode(X.getNode(), Eight.getNode());
999           Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1000         }
1001         if (Mask.getNode()->getNodeId() == -1 ||
1002             Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1003           CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1004           Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1005         }
1006         if (Srl.getNode()->getNodeId() == -1 ||
1007             Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1008           CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1009           Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1010         }
1011         if (And.getNode()->getNodeId() == -1 ||
1012             And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1013           CurDAG->RepositionNode(N.getNode(), And.getNode());
1014           And.getNode()->setNodeId(N.getNode()->getNodeId());
1015         }
1016         if (ShlCount.getNode()->getNodeId() == -1 ||
1017             ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1018           CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1019           ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1020         }
1021         if (Shl.getNode()->getNodeId() == -1 ||
1022             Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1023           CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1024           Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1025         }
1026         CurDAG->ReplaceAllUsesWith(N, Shl);
1027         AM.IndexReg = And;
1028         AM.Scale = (1 << ScaleLog);
1029         return false;
1030       }
1031     }
1032
1033     // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1034     // allows us to fold the shift into this addressing mode.
1035     if (Shift.getOpcode() != ISD::SHL) break;
1036
1037     // Not likely to be profitable if either the AND or SHIFT node has more
1038     // than one use (unless all uses are for address computation). Besides,
1039     // isel mechanism requires their node ids to be reused.
1040     if (!N.hasOneUse() || !Shift.hasOneUse())
1041       break;
1042     
1043     // Verify that the shift amount is something we can fold.
1044     unsigned ShiftCst = C1->getZExtValue();
1045     if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1046       break;
1047     
1048     // Get the new AND mask, this folds to a constant.
1049     SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1050                                          SDValue(C2, 0), SDValue(C1, 0));
1051     SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X, 
1052                                      NewANDMask);
1053     SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1054                                        NewAND, SDValue(C1, 0));
1055
1056     // Insert the new nodes into the topological ordering.
1057     if (C1->getNodeId() > X.getNode()->getNodeId()) {
1058       CurDAG->RepositionNode(X.getNode(), C1);
1059       C1->setNodeId(X.getNode()->getNodeId());
1060     }
1061     if (NewANDMask.getNode()->getNodeId() == -1 ||
1062         NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1063       CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1064       NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1065     }
1066     if (NewAND.getNode()->getNodeId() == -1 ||
1067         NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1068       CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1069       NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1070     }
1071     if (NewSHIFT.getNode()->getNodeId() == -1 ||
1072         NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1073       CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1074       NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1075     }
1076
1077     CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1078     
1079     AM.Scale = 1 << ShiftCst;
1080     AM.IndexReg = NewAND;
1081     return false;
1082   }
1083   }
1084
1085   return MatchAddressBase(N, AM);
1086 }
1087
1088 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1089 /// specified addressing mode without any further recursion.
1090 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1091   // Is the base register already occupied?
1092   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1093     // If so, check to see if the scale index register is set.
1094     if (AM.IndexReg.getNode() == 0) {
1095       AM.IndexReg = N;
1096       AM.Scale = 1;
1097       return false;
1098     }
1099
1100     // Otherwise, we cannot select it.
1101     return true;
1102   }
1103
1104   // Default, generate it as a register.
1105   AM.BaseType = X86ISelAddressMode::RegBase;
1106   AM.Base.Reg = N;
1107   return false;
1108 }
1109
1110 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1111 /// It returns the operands which make up the maximal addressing mode it can
1112 /// match by reference.
1113 bool X86DAGToDAGISel::SelectAddr(SDNode *Op, SDValue N, SDValue &Base,
1114                                  SDValue &Scale, SDValue &Index,
1115                                  SDValue &Disp, SDValue &Segment) {
1116   X86ISelAddressMode AM;
1117   if (MatchAddress(N, AM))
1118     return false;
1119
1120   EVT VT = N.getValueType();
1121   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1122     if (!AM.Base.Reg.getNode())
1123       AM.Base.Reg = CurDAG->getRegister(0, VT);
1124   }
1125
1126   if (!AM.IndexReg.getNode())
1127     AM.IndexReg = CurDAG->getRegister(0, VT);
1128
1129   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1130   return true;
1131 }
1132
1133 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
1134 /// match a load whose top elements are either undef or zeros.  The load flavor
1135 /// is derived from the type of N, which is either v4f32 or v2f64.
1136 ///
1137 /// We also return:
1138 ///   PatternChainNode: this is the matched node that has a chain input and
1139 ///   output.
1140 bool X86DAGToDAGISel::SelectScalarSSELoad(SDNode *Root,
1141                                           SDValue N, SDValue &Base,
1142                                           SDValue &Scale, SDValue &Index,
1143                                           SDValue &Disp, SDValue &Segment,
1144                                           SDValue &PatternNodeWithChain) {
1145   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1146     PatternNodeWithChain = N.getOperand(0);
1147     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1148         PatternNodeWithChain.hasOneUse() &&
1149         IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1150         IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1151       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1152       if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp,Segment))
1153         return false;
1154       return true;
1155     }
1156   }
1157
1158   // Also handle the case where we explicitly require zeros in the top
1159   // elements.  This is a vector shuffle from the zero vector.
1160   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1161       // Check to see if the top elements are all zeros (or bitcast of zeros).
1162       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 
1163       N.getOperand(0).getNode()->hasOneUse() &&
1164       ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1165       N.getOperand(0).getOperand(0).hasOneUse() &&
1166       IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1167       IsLegalToFold(N.getOperand(0), N.getNode(), Root)) {
1168     // Okay, this is a zero extending load.  Fold it.
1169     LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1170     if (!SelectAddr(Root, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1171       return false;
1172     PatternNodeWithChain = SDValue(LD, 0);
1173     return true;
1174   }
1175   return false;
1176 }
1177
1178
1179 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1180 /// mode it matches can be cost effectively emitted as an LEA instruction.
1181 bool X86DAGToDAGISel::SelectLEAAddr(SDNode *Op, SDValue N,
1182                                     SDValue &Base, SDValue &Scale,
1183                                     SDValue &Index, SDValue &Disp) {
1184   X86ISelAddressMode AM;
1185
1186   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1187   // segments.
1188   SDValue Copy = AM.Segment;
1189   SDValue T = CurDAG->getRegister(0, MVT::i32);
1190   AM.Segment = T;
1191   if (MatchAddress(N, AM))
1192     return false;
1193   assert (T == AM.Segment);
1194   AM.Segment = Copy;
1195
1196   EVT VT = N.getValueType();
1197   unsigned Complexity = 0;
1198   if (AM.BaseType == X86ISelAddressMode::RegBase)
1199     if (AM.Base.Reg.getNode())
1200       Complexity = 1;
1201     else
1202       AM.Base.Reg = CurDAG->getRegister(0, VT);
1203   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1204     Complexity = 4;
1205
1206   if (AM.IndexReg.getNode())
1207     Complexity++;
1208   else
1209     AM.IndexReg = CurDAG->getRegister(0, VT);
1210
1211   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1212   // a simple shift.
1213   if (AM.Scale > 1)
1214     Complexity++;
1215
1216   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1217   // to a LEA. This is determined with some expermentation but is by no means
1218   // optimal (especially for code size consideration). LEA is nice because of
1219   // its three-address nature. Tweak the cost function again when we can run
1220   // convertToThreeAddress() at register allocation time.
1221   if (AM.hasSymbolicDisplacement()) {
1222     // For X86-64, we should always use lea to materialize RIP relative
1223     // addresses.
1224     if (Subtarget->is64Bit())
1225       Complexity = 4;
1226     else
1227       Complexity += 2;
1228   }
1229
1230   if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1231     Complexity++;
1232
1233   // If it isn't worth using an LEA, reject it.
1234   if (Complexity <= 2)
1235     return false;
1236   
1237   SDValue Segment;
1238   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1239   return true;
1240 }
1241
1242 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1243 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDNode *Op, SDValue N, SDValue &Base,
1244                                         SDValue &Scale, SDValue &Index,
1245                                         SDValue &Disp) {
1246   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1247   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1248   
1249   X86ISelAddressMode AM;
1250   AM.GV = GA->getGlobal();
1251   AM.Disp += GA->getOffset();
1252   AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1253   AM.SymbolFlags = GA->getTargetFlags();
1254
1255   if (N.getValueType() == MVT::i32) {
1256     AM.Scale = 1;
1257     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1258   } else {
1259     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1260   }
1261   
1262   SDValue Segment;
1263   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1264   return true;
1265 }
1266
1267
1268 bool X86DAGToDAGISel::TryFoldLoad(SDNode *P, SDValue N,
1269                                   SDValue &Base, SDValue &Scale,
1270                                   SDValue &Index, SDValue &Disp,
1271                                   SDValue &Segment) {
1272   if (!ISD::isNON_EXTLoad(N.getNode()) ||
1273       !IsProfitableToFold(N, P, P) ||
1274       !IsLegalToFold(N, P, P))
1275     return false;
1276   
1277   return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1278 }
1279
1280 /// getGlobalBaseReg - Return an SDNode that returns the value of
1281 /// the global base register. Output instructions required to
1282 /// initialize the global base register, if necessary.
1283 ///
1284 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1285   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1286   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1287 }
1288
1289 static SDNode *FindCallStartFromCall(SDNode *Node) {
1290   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1291     assert(Node->getOperand(0).getValueType() == MVT::Other &&
1292          "Node doesn't have a token chain argument!");
1293   return FindCallStartFromCall(Node->getOperand(0).getNode());
1294 }
1295
1296 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1297   SDValue Chain = Node->getOperand(0);
1298   SDValue In1 = Node->getOperand(1);
1299   SDValue In2L = Node->getOperand(2);
1300   SDValue In2H = Node->getOperand(3);
1301   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1302   if (!SelectAddr(In1.getNode(), In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1303     return NULL;
1304   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1305   MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1306   const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, Chain};
1307   SDNode *ResNode = CurDAG->getMachineNode(Opc, Node->getDebugLoc(),
1308                                            MVT::i32, MVT::i32, MVT::Other, Ops,
1309                                            array_lengthof(Ops));
1310   cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp + 1);
1311   return ResNode;
1312 }
1313
1314 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1315   if (Node->hasAnyUseOfValue(0))
1316     return 0;
1317
1318   // Optimize common patterns for __sync_add_and_fetch and
1319   // __sync_sub_and_fetch where the result is not used. This allows us
1320   // to use "lock" version of add, sub, inc, dec instructions.
1321   // FIXME: Do not use special instructions but instead add the "lock"
1322   // prefix to the target node somehow. The extra information will then be
1323   // transferred to machine instruction and it denotes the prefix.
1324   SDValue Chain = Node->getOperand(0);
1325   SDValue Ptr = Node->getOperand(1);
1326   SDValue Val = Node->getOperand(2);
1327   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1328   if (!SelectAddr(Ptr.getNode(), Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1329     return 0;
1330
1331   bool isInc = false, isDec = false, isSub = false, isCN = false;
1332   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1333   if (CN) {
1334     isCN = true;
1335     int64_t CNVal = CN->getSExtValue();
1336     if (CNVal == 1)
1337       isInc = true;
1338     else if (CNVal == -1)
1339       isDec = true;
1340     else if (CNVal >= 0)
1341       Val = CurDAG->getTargetConstant(CNVal, NVT);
1342     else {
1343       isSub = true;
1344       Val = CurDAG->getTargetConstant(-CNVal, NVT);
1345     }
1346   } else if (Val.hasOneUse() &&
1347              Val.getOpcode() == ISD::SUB &&
1348              X86::isZeroNode(Val.getOperand(0))) {
1349     isSub = true;
1350     Val = Val.getOperand(1);
1351   }
1352
1353   unsigned Opc = 0;
1354   switch (NVT.getSimpleVT().SimpleTy) {
1355   default: return 0;
1356   case MVT::i8:
1357     if (isInc)
1358       Opc = X86::LOCK_INC8m;
1359     else if (isDec)
1360       Opc = X86::LOCK_DEC8m;
1361     else if (isSub) {
1362       if (isCN)
1363         Opc = X86::LOCK_SUB8mi;
1364       else
1365         Opc = X86::LOCK_SUB8mr;
1366     } else {
1367       if (isCN)
1368         Opc = X86::LOCK_ADD8mi;
1369       else
1370         Opc = X86::LOCK_ADD8mr;
1371     }
1372     break;
1373   case MVT::i16:
1374     if (isInc)
1375       Opc = X86::LOCK_INC16m;
1376     else if (isDec)
1377       Opc = X86::LOCK_DEC16m;
1378     else if (isSub) {
1379       if (isCN) {
1380         if (Predicate_i16immSExt8(Val.getNode()))
1381           Opc = X86::LOCK_SUB16mi8;
1382         else
1383           Opc = X86::LOCK_SUB16mi;
1384       } else
1385         Opc = X86::LOCK_SUB16mr;
1386     } else {
1387       if (isCN) {
1388         if (Predicate_i16immSExt8(Val.getNode()))
1389           Opc = X86::LOCK_ADD16mi8;
1390         else
1391           Opc = X86::LOCK_ADD16mi;
1392       } else
1393         Opc = X86::LOCK_ADD16mr;
1394     }
1395     break;
1396   case MVT::i32:
1397     if (isInc)
1398       Opc = X86::LOCK_INC32m;
1399     else if (isDec)
1400       Opc = X86::LOCK_DEC32m;
1401     else if (isSub) {
1402       if (isCN) {
1403         if (Predicate_i32immSExt8(Val.getNode()))
1404           Opc = X86::LOCK_SUB32mi8;
1405         else
1406           Opc = X86::LOCK_SUB32mi;
1407       } else
1408         Opc = X86::LOCK_SUB32mr;
1409     } else {
1410       if (isCN) {
1411         if (Predicate_i32immSExt8(Val.getNode()))
1412           Opc = X86::LOCK_ADD32mi8;
1413         else
1414           Opc = X86::LOCK_ADD32mi;
1415       } else
1416         Opc = X86::LOCK_ADD32mr;
1417     }
1418     break;
1419   case MVT::i64:
1420     if (isInc)
1421       Opc = X86::LOCK_INC64m;
1422     else if (isDec)
1423       Opc = X86::LOCK_DEC64m;
1424     else if (isSub) {
1425       Opc = X86::LOCK_SUB64mr;
1426       if (isCN) {
1427         if (Predicate_i64immSExt8(Val.getNode()))
1428           Opc = X86::LOCK_SUB64mi8;
1429         else if (Predicate_i64immSExt32(Val.getNode()))
1430           Opc = X86::LOCK_SUB64mi32;
1431       }
1432     } else {
1433       Opc = X86::LOCK_ADD64mr;
1434       if (isCN) {
1435         if (Predicate_i64immSExt8(Val.getNode()))
1436           Opc = X86::LOCK_ADD64mi8;
1437         else if (Predicate_i64immSExt32(Val.getNode()))
1438           Opc = X86::LOCK_ADD64mi32;
1439       }
1440     }
1441     break;
1442   }
1443
1444   DebugLoc dl = Node->getDebugLoc();
1445   SDValue Undef = SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
1446                                                  dl, NVT), 0);
1447   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1448   MemOp[0] = cast<MemSDNode>(Node)->getMemOperand();
1449   if (isInc || isDec) {
1450     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain };
1451     SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 6), 0);
1452     cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1453     SDValue RetVals[] = { Undef, Ret };
1454     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1455   } else {
1456     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, Chain };
1457     SDValue Ret = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops, 7), 0);
1458     cast<MachineSDNode>(Ret)->setMemRefs(MemOp, MemOp + 1);
1459     SDValue RetVals[] = { Undef, Ret };
1460     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1461   }
1462 }
1463
1464 /// HasNoSignedComparisonUses - Test whether the given X86ISD::CMP node has
1465 /// any uses which require the SF or OF bits to be accurate.
1466 static bool HasNoSignedComparisonUses(SDNode *N) {
1467   // Examine each user of the node.
1468   for (SDNode::use_iterator UI = N->use_begin(),
1469          UE = N->use_end(); UI != UE; ++UI) {
1470     // Only examine CopyToReg uses.
1471     if (UI->getOpcode() != ISD::CopyToReg)
1472       return false;
1473     // Only examine CopyToReg uses that copy to EFLAGS.
1474     if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1475           X86::EFLAGS)
1476       return false;
1477     // Examine each user of the CopyToReg use.
1478     for (SDNode::use_iterator FlagUI = UI->use_begin(),
1479            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1480       // Only examine the Flag result.
1481       if (FlagUI.getUse().getResNo() != 1) continue;
1482       // Anything unusual: assume conservatively.
1483       if (!FlagUI->isMachineOpcode()) return false;
1484       // Examine the opcode of the user.
1485       switch (FlagUI->getMachineOpcode()) {
1486       // These comparisons don't treat the most significant bit specially.
1487       case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1488       case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1489       case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1490       case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1491       case X86::JA_4: case X86::JAE_4: case X86::JB_4: case X86::JBE_4:
1492       case X86::JE_4: case X86::JNE_4: case X86::JP_4: case X86::JNP_4:
1493       case X86::CMOVA16rr: case X86::CMOVA16rm:
1494       case X86::CMOVA32rr: case X86::CMOVA32rm:
1495       case X86::CMOVA64rr: case X86::CMOVA64rm:
1496       case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1497       case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1498       case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1499       case X86::CMOVB16rr: case X86::CMOVB16rm:
1500       case X86::CMOVB32rr: case X86::CMOVB32rm:
1501       case X86::CMOVB64rr: case X86::CMOVB64rm:
1502       case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1503       case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1504       case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1505       case X86::CMOVE16rr: case X86::CMOVE16rm:
1506       case X86::CMOVE32rr: case X86::CMOVE32rm:
1507       case X86::CMOVE64rr: case X86::CMOVE64rm:
1508       case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1509       case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1510       case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1511       case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1512       case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1513       case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1514       case X86::CMOVP16rr: case X86::CMOVP16rm:
1515       case X86::CMOVP32rr: case X86::CMOVP32rm:
1516       case X86::CMOVP64rr: case X86::CMOVP64rm:
1517         continue;
1518       // Anything else: assume conservatively.
1519       default: return false;
1520       }
1521     }
1522   }
1523   return true;
1524 }
1525
1526 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1527   EVT NVT = Node->getValueType(0);
1528   unsigned Opc, MOpc;
1529   unsigned Opcode = Node->getOpcode();
1530   DebugLoc dl = Node->getDebugLoc();
1531   
1532   DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1533
1534   if (Node->isMachineOpcode()) {
1535     DEBUG(dbgs() << "== ";  Node->dump(CurDAG); dbgs() << '\n');
1536     return NULL;   // Already selected.
1537   }
1538
1539   switch (Opcode) {
1540   default: break;
1541   case X86ISD::GlobalBaseReg:
1542     return getGlobalBaseReg();
1543
1544   case X86ISD::ATOMOR64_DAG:
1545     return SelectAtomic64(Node, X86::ATOMOR6432);
1546   case X86ISD::ATOMXOR64_DAG:
1547     return SelectAtomic64(Node, X86::ATOMXOR6432);
1548   case X86ISD::ATOMADD64_DAG:
1549     return SelectAtomic64(Node, X86::ATOMADD6432);
1550   case X86ISD::ATOMSUB64_DAG:
1551     return SelectAtomic64(Node, X86::ATOMSUB6432);
1552   case X86ISD::ATOMNAND64_DAG:
1553     return SelectAtomic64(Node, X86::ATOMNAND6432);
1554   case X86ISD::ATOMAND64_DAG:
1555     return SelectAtomic64(Node, X86::ATOMAND6432);
1556   case X86ISD::ATOMSWAP64_DAG:
1557     return SelectAtomic64(Node, X86::ATOMSWAP6432);
1558
1559   case ISD::ATOMIC_LOAD_ADD: {
1560     SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1561     if (RetVal)
1562       return RetVal;
1563     break;
1564   }
1565
1566   case ISD::SMUL_LOHI:
1567   case ISD::UMUL_LOHI: {
1568     SDValue N0 = Node->getOperand(0);
1569     SDValue N1 = Node->getOperand(1);
1570
1571     bool isSigned = Opcode == ISD::SMUL_LOHI;
1572     if (!isSigned) {
1573       switch (NVT.getSimpleVT().SimpleTy) {
1574       default: llvm_unreachable("Unsupported VT!");
1575       case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1576       case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1577       case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1578       case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1579       }
1580     } else {
1581       switch (NVT.getSimpleVT().SimpleTy) {
1582       default: llvm_unreachable("Unsupported VT!");
1583       case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1584       case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1585       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1586       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1587       }
1588     }
1589
1590     unsigned LoReg, HiReg;
1591     switch (NVT.getSimpleVT().SimpleTy) {
1592     default: llvm_unreachable("Unsupported VT!");
1593     case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1594     case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1595     case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1596     case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1597     }
1598
1599     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1600     bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1601     // Multiply is commmutative.
1602     if (!foldedLoad) {
1603       foldedLoad = TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1604       if (foldedLoad)
1605         std::swap(N0, N1);
1606     }
1607
1608     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1609                                             N0, SDValue()).getValue(1);
1610
1611     if (foldedLoad) {
1612       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1613                         InFlag };
1614       SDNode *CNode =
1615         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1616                                array_lengthof(Ops));
1617       InFlag = SDValue(CNode, 1);
1618       // Update the chain.
1619       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1620     } else {
1621       InFlag =
1622         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1623     }
1624
1625     // Copy the low half of the result, if it is needed.
1626     if (!SDValue(Node, 0).use_empty()) {
1627       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1628                                                 LoReg, NVT, InFlag);
1629       InFlag = Result.getValue(2);
1630       ReplaceUses(SDValue(Node, 0), Result);
1631       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1632     }
1633     // Copy the high half of the result, if it is needed.
1634     if (!SDValue(Node, 1).use_empty()) {
1635       SDValue Result;
1636       if (HiReg == X86::AH && Subtarget->is64Bit()) {
1637         // Prevent use of AH in a REX instruction by referencing AX instead.
1638         // Shift it down 8 bits.
1639         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1640                                         X86::AX, MVT::i16, InFlag);
1641         InFlag = Result.getValue(2);
1642         Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1643                                                 Result,
1644                                    CurDAG->getTargetConstant(8, MVT::i8)), 0);
1645         // Then truncate it down to i8.
1646         Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1647                                                 MVT::i8, Result);
1648       } else {
1649         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1650                                         HiReg, NVT, InFlag);
1651         InFlag = Result.getValue(2);
1652       }
1653       ReplaceUses(SDValue(Node, 1), Result);
1654       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1655     }
1656
1657     return NULL;
1658   }
1659
1660   case ISD::SDIVREM:
1661   case ISD::UDIVREM: {
1662     SDValue N0 = Node->getOperand(0);
1663     SDValue N1 = Node->getOperand(1);
1664
1665     bool isSigned = Opcode == ISD::SDIVREM;
1666     if (!isSigned) {
1667       switch (NVT.getSimpleVT().SimpleTy) {
1668       default: llvm_unreachable("Unsupported VT!");
1669       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1670       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1671       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1672       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1673       }
1674     } else {
1675       switch (NVT.getSimpleVT().SimpleTy) {
1676       default: llvm_unreachable("Unsupported VT!");
1677       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1678       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1679       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1680       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1681       }
1682     }
1683
1684     unsigned LoReg, HiReg, ClrReg;
1685     unsigned ClrOpcode, SExtOpcode;
1686     switch (NVT.getSimpleVT().SimpleTy) {
1687     default: llvm_unreachable("Unsupported VT!");
1688     case MVT::i8:
1689       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
1690       ClrOpcode  = 0;
1691       SExtOpcode = X86::CBW;
1692       break;
1693     case MVT::i16:
1694       LoReg = X86::AX;  HiReg = X86::DX;
1695       ClrOpcode  = X86::MOV16r0; ClrReg = X86::DX;
1696       SExtOpcode = X86::CWD;
1697       break;
1698     case MVT::i32:
1699       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
1700       ClrOpcode  = X86::MOV32r0;
1701       SExtOpcode = X86::CDQ;
1702       break;
1703     case MVT::i64:
1704       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
1705       ClrOpcode  = X86::MOV64r0;
1706       SExtOpcode = X86::CQO;
1707       break;
1708     }
1709
1710     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1711     bool foldedLoad = TryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1712     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1713
1714     SDValue InFlag;
1715     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1716       // Special case for div8, just use a move with zero extension to AX to
1717       // clear the upper 8 bits (AH).
1718       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1719       if (TryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1720         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1721         Move =
1722           SDValue(CurDAG->getMachineNode(X86::MOVZX16rm8, dl, MVT::i16,
1723                                          MVT::Other, Ops,
1724                                          array_lengthof(Ops)), 0);
1725         Chain = Move.getValue(1);
1726         ReplaceUses(N0.getValue(1), Chain);
1727       } else {
1728         Move =
1729           SDValue(CurDAG->getMachineNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1730         Chain = CurDAG->getEntryNode();
1731       }
1732       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1733       InFlag = Chain.getValue(1);
1734     } else {
1735       InFlag =
1736         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1737                              LoReg, N0, SDValue()).getValue(1);
1738       if (isSigned && !signBitIsZero) {
1739         // Sign extend the low part into the high part.
1740         InFlag =
1741           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1742       } else {
1743         // Zero out the high part, effectively zero extending the input.
1744         SDValue ClrNode =
1745           SDValue(CurDAG->getMachineNode(ClrOpcode, dl, NVT), 0);
1746         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
1747                                       ClrNode, InFlag).getValue(1);
1748       }
1749     }
1750
1751     if (foldedLoad) {
1752       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1753                         InFlag };
1754       SDNode *CNode =
1755         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1756                                array_lengthof(Ops));
1757       InFlag = SDValue(CNode, 1);
1758       // Update the chain.
1759       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1760     } else {
1761       InFlag =
1762         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1763     }
1764
1765     // Copy the division (low) result, if it is needed.
1766     if (!SDValue(Node, 0).use_empty()) {
1767       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1768                                                 LoReg, NVT, InFlag);
1769       InFlag = Result.getValue(2);
1770       ReplaceUses(SDValue(Node, 0), Result);
1771       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1772     }
1773     // Copy the remainder (high) result, if it is needed.
1774     if (!SDValue(Node, 1).use_empty()) {
1775       SDValue Result;
1776       if (HiReg == X86::AH && Subtarget->is64Bit()) {
1777         // Prevent use of AH in a REX instruction by referencing AX instead.
1778         // Shift it down 8 bits.
1779         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1780                                         X86::AX, MVT::i16, InFlag);
1781         InFlag = Result.getValue(2);
1782         Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
1783                                       Result,
1784                                       CurDAG->getTargetConstant(8, MVT::i8)),
1785                          0);
1786         // Then truncate it down to i8.
1787         Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1788                                                 MVT::i8, Result);
1789       } else {
1790         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1791                                         HiReg, NVT, InFlag);
1792         InFlag = Result.getValue(2);
1793       }
1794       ReplaceUses(SDValue(Node, 1), Result);
1795       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
1796     }
1797     return NULL;
1798   }
1799
1800   case X86ISD::CMP: {
1801     SDValue N0 = Node->getOperand(0);
1802     SDValue N1 = Node->getOperand(1);
1803
1804     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
1805     // use a smaller encoding.
1806     if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1807         N0.getValueType() != MVT::i8 &&
1808         X86::isZeroNode(N1)) {
1809       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
1810       if (!C) break;
1811
1812       // For example, convert "testl %eax, $8" to "testb %al, $8"
1813       if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
1814           (!(C->getZExtValue() & 0x80) ||
1815            HasNoSignedComparisonUses(Node))) {
1816         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
1817         SDValue Reg = N0.getNode()->getOperand(0);
1818
1819         // On x86-32, only the ABCD registers have 8-bit subregisters.
1820         if (!Subtarget->is64Bit()) {
1821           TargetRegisterClass *TRC = 0;
1822           switch (N0.getValueType().getSimpleVT().SimpleTy) {
1823           case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1824           case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1825           default: llvm_unreachable("Unsupported TEST operand type!");
1826           }
1827           SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1828           Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1829                                                Reg.getValueType(), Reg, RC), 0);
1830         }
1831
1832         // Extract the l-register.
1833         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1834                                                         MVT::i8, Reg);
1835
1836         // Emit a testb.
1837         return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
1838       }
1839
1840       // For example, "testl %eax, $2048" to "testb %ah, $8".
1841       if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
1842           (!(C->getZExtValue() & 0x8000) ||
1843            HasNoSignedComparisonUses(Node))) {
1844         // Shift the immediate right by 8 bits.
1845         SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
1846                                                        MVT::i8);
1847         SDValue Reg = N0.getNode()->getOperand(0);
1848
1849         // Put the value in an ABCD register.
1850         TargetRegisterClass *TRC = 0;
1851         switch (N0.getValueType().getSimpleVT().SimpleTy) {
1852         case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
1853         case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1854         case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1855         default: llvm_unreachable("Unsupported TEST operand type!");
1856         }
1857         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1858         Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
1859                                              Reg.getValueType(), Reg, RC), 0);
1860
1861         // Extract the h-register.
1862         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
1863                                                         MVT::i8, Reg);
1864
1865         // Emit a testb. No special NOREX tricks are needed since there's
1866         // only one GPR operand!
1867         return CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
1868                                       Subreg, ShiftedImm);
1869       }
1870
1871       // For example, "testl %eax, $32776" to "testw %ax, $32776".
1872       if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
1873           N0.getValueType() != MVT::i16 &&
1874           (!(C->getZExtValue() & 0x8000) ||
1875            HasNoSignedComparisonUses(Node))) {
1876         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
1877         SDValue Reg = N0.getNode()->getOperand(0);
1878
1879         // Extract the 16-bit subregister.
1880         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
1881                                                         MVT::i16, Reg);
1882
1883         // Emit a testw.
1884         return CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
1885       }
1886
1887       // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
1888       if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
1889           N0.getValueType() == MVT::i64 &&
1890           (!(C->getZExtValue() & 0x80000000) ||
1891            HasNoSignedComparisonUses(Node))) {
1892         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
1893         SDValue Reg = N0.getNode()->getOperand(0);
1894
1895         // Extract the 32-bit subregister.
1896         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
1897                                                         MVT::i32, Reg);
1898
1899         // Emit a testl.
1900         return CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
1901       }
1902     }
1903     break;
1904   }
1905   }
1906
1907   SDNode *ResNode = SelectCode(Node);
1908
1909   DEBUG(dbgs() << "=> ";
1910         if (ResNode == NULL || ResNode == Node)
1911           Node->dump(CurDAG);
1912         else
1913           ResNode->dump(CurDAG);
1914         dbgs() << '\n');
1915
1916   return ResNode;
1917 }
1918
1919 bool X86DAGToDAGISel::
1920 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1921                              std::vector<SDValue> &OutOps) {
1922   SDValue Op0, Op1, Op2, Op3, Op4;
1923   switch (ConstraintCode) {
1924   case 'o':   // offsetable        ??
1925   case 'v':   // not offsetable    ??
1926   default: return true;
1927   case 'm':   // memory
1928     if (!SelectAddr(Op.getNode(), Op, Op0, Op1, Op2, Op3, Op4))
1929       return true;
1930     break;
1931   }
1932   
1933   OutOps.push_back(Op0);
1934   OutOps.push_back(Op1);
1935   OutOps.push_back(Op2);
1936   OutOps.push_back(Op3);
1937   OutOps.push_back(Op4);
1938   return false;
1939 }
1940
1941 /// createX86ISelDag - This pass converts a legalized DAG into a 
1942 /// X86-specific DAG, ready for instruction scheduling.
1943 ///
1944 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
1945                                      llvm::CodeGenOpt::Level OptLevel) {
1946   return new X86DAGToDAGISel(TM, OptLevel);
1947 }