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