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