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