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