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