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