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