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