Switch some multiplication instructions over to the new scheme for testing.
[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 was developed by the Evan Cheng and is distributed under
6 // the University of Illinois Open Source 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 "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/ADT/Statistic.h"
38 #include <queue>
39 #include <set>
40 using namespace llvm;
41
42 STATISTIC(NumFPKill   , "Number of FP_REG_KILL instructions added");
43 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
44
45
46 //===----------------------------------------------------------------------===//
47 //                      Pattern Matcher Implementation
48 //===----------------------------------------------------------------------===//
49
50 namespace {
51   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
52   /// SDOperand's instead of register numbers for the leaves of the matched
53   /// tree.
54   struct X86ISelAddressMode {
55     enum {
56       RegBase,
57       FrameIndexBase
58     } BaseType;
59
60     struct {            // This is really a union, discriminated by BaseType!
61       SDOperand Reg;
62       int FrameIndex;
63     } Base;
64
65     bool isRIPRel;     // RIP relative?
66     unsigned Scale;
67     SDOperand IndexReg; 
68     unsigned Disp;
69     GlobalValue *GV;
70     Constant *CP;
71     const char *ES;
72     int JT;
73     unsigned Align;    // CP alignment.
74
75     X86ISelAddressMode()
76       : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
77         GV(0), CP(0), ES(0), JT(-1), Align(0) {
78     }
79   };
80 }
81
82 namespace {
83   //===--------------------------------------------------------------------===//
84   /// ISel - X86 specific code to select X86 machine instructions for
85   /// SelectionDAG operations.
86   ///
87   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
88     /// ContainsFPCode - Every instruction we select that uses or defines a FP
89     /// register should set this to true.
90     bool ContainsFPCode;
91
92     /// FastISel - Enable fast(er) instruction selection.
93     ///
94     bool FastISel;
95
96     /// TM - Keep a reference to X86TargetMachine.
97     ///
98     X86TargetMachine &TM;
99
100     /// X86Lowering - This object fully describes how to lower LLVM code to an
101     /// X86-specific SelectionDAG.
102     X86TargetLowering X86Lowering;
103
104     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
105     /// make the right decision when generating code for different targets.
106     const X86Subtarget *Subtarget;
107
108     /// GlobalBaseReg - keeps track of the virtual register mapped onto global
109     /// base register.
110     unsigned GlobalBaseReg;
111
112   public:
113     X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
114       : SelectionDAGISel(X86Lowering),
115         ContainsFPCode(false), FastISel(fast), TM(tm),
116         X86Lowering(*TM.getTargetLowering()),
117         Subtarget(&TM.getSubtarget<X86Subtarget>()) {}
118
119     virtual bool runOnFunction(Function &Fn) {
120       // Make sure we re-emit a set of the global base reg if necessary
121       GlobalBaseReg = 0;
122       return SelectionDAGISel::runOnFunction(Fn);
123     }
124    
125     virtual const char *getPassName() const {
126       return "X86 DAG->DAG Instruction Selection";
127     }
128
129     /// InstructionSelectBasicBlock - This callback is invoked by
130     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
131     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
132
133     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
134
135     virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const;
136
137 // Include the pieces autogenerated from the target description.
138 #include "X86GenDAGISel.inc"
139
140   private:
141     SDNode *Select(SDOperand N);
142
143     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM,
144                       bool isRoot = true, unsigned Depth = 0);
145     bool SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
146                     SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
147     bool SelectLEAAddr(SDOperand Op, SDOperand N, SDOperand &Base,
148                        SDOperand &Scale, SDOperand &Index, SDOperand &Disp);
149     bool SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
150                              SDOperand N, SDOperand &Base, SDOperand &Scale,
151                              SDOperand &Index, SDOperand &Disp,
152                              SDOperand &InChain, SDOperand &OutChain);
153     bool TryFoldLoad(SDOperand P, SDOperand N,
154                      SDOperand &Base, SDOperand &Scale,
155                      SDOperand &Index, SDOperand &Disp);
156     void InstructionSelectPreprocess(SelectionDAG &DAG);
157
158     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
159     /// inline asm expressions.
160     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
161                                               char ConstraintCode,
162                                               std::vector<SDOperand> &OutOps,
163                                               SelectionDAG &DAG);
164     
165     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
166
167     inline void getAddressOperands(X86ISelAddressMode &AM, SDOperand &Base, 
168                                    SDOperand &Scale, SDOperand &Index,
169                                    SDOperand &Disp) {
170       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
171         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
172         AM.Base.Reg;
173       Scale = getI8Imm(AM.Scale);
174       Index = AM.IndexReg;
175       // These are 32-bit even in 64-bit mode since RIP relative offset
176       // is 32-bit.
177       if (AM.GV)
178         Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp);
179       else if (AM.CP)
180         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Align, AM.Disp);
181       else if (AM.ES)
182         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32);
183       else if (AM.JT != -1)
184         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32);
185       else
186         Disp = getI32Imm(AM.Disp);
187     }
188
189     /// getI8Imm - Return a target constant with the specified value, of type
190     /// i8.
191     inline SDOperand getI8Imm(unsigned Imm) {
192       return CurDAG->getTargetConstant(Imm, MVT::i8);
193     }
194
195     /// getI16Imm - Return a target constant with the specified value, of type
196     /// i16.
197     inline SDOperand getI16Imm(unsigned Imm) {
198       return CurDAG->getTargetConstant(Imm, MVT::i16);
199     }
200
201     /// getI32Imm - Return a target constant with the specified value, of type
202     /// i32.
203     inline SDOperand getI32Imm(unsigned Imm) {
204       return CurDAG->getTargetConstant(Imm, MVT::i32);
205     }
206
207     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
208     /// base register.  Return the virtual register that holds this value.
209     SDNode *getGlobalBaseReg();
210
211 #ifndef NDEBUG
212     unsigned Indent;
213 #endif
214   };
215 }
216
217 static SDNode *findFlagUse(SDNode *N) {
218   unsigned FlagResNo = N->getNumValues()-1;
219   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
220     SDNode *User = *I;
221     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
222       SDOperand Op = User->getOperand(i);
223       if (Op.Val == N && Op.ResNo == FlagResNo)
224         return User;
225     }
226   }
227   return NULL;
228 }
229
230 static void findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
231                           SDNode *Root, SDNode *Skip, bool &found,
232                           std::set<SDNode *> &Visited) {
233   if (found ||
234       Use->getNodeId() > Def->getNodeId() ||
235       !Visited.insert(Use).second)
236     return;
237
238   for (unsigned i = 0, e = Use->getNumOperands(); !found && i != e; ++i) {
239     SDNode *N = Use->getOperand(i).Val;
240     if (N == Skip)
241       continue;
242     if (N == Def) {
243       if (Use == ImmedUse)
244         continue; // Immediate use is ok.
245       if (Use == Root) {
246         assert(Use->getOpcode() == ISD::STORE ||
247                Use->getOpcode() == X86ISD::CMP);
248         continue;
249       }
250       found = true;
251       break;
252     }
253     findNonImmUse(N, Def, ImmedUse, Root, Skip, found, Visited);
254   }
255 }
256
257 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
258 /// be reached. Return true if that's the case. However, ignore direct uses
259 /// by ImmedUse (which would be U in the example illustrated in
260 /// CanBeFoldedBy) and by Root (which can happen in the store case).
261 /// FIXME: to be really generic, we should allow direct use by any node
262 /// that is being folded. But realisticly since we only fold loads which
263 /// have one non-chain use, we only need to watch out for load/op/store
264 /// and load/op/cmp case where the root (store / cmp) may reach the load via
265 /// its chain operand.
266 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
267                                SDNode *Skip = NULL) {
268   std::set<SDNode *> Visited;
269   bool found = false;
270   findNonImmUse(Root, Def, ImmedUse, Root, Skip, found, Visited);
271   return found;
272 }
273
274
275 bool X86DAGToDAGISel::CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root) const {
276   if (FastISel) return false;
277
278   // If U use can somehow reach N through another path then U can't fold N or
279   // it will create a cycle. e.g. In the following diagram, U can reach N
280   // through X. If N is folded into into U, then X is both a predecessor and
281   // a successor of U.
282   //
283   //         [ N ]
284   //         ^  ^
285   //         |  |
286   //        /   \---
287   //      /        [X]
288   //      |         ^
289   //     [U]--------|
290
291   if (isNonImmUse(Root, N, U))
292     return false;
293
294   // If U produces a flag, then it gets (even more) interesting. Since it
295   // would have been "glued" together with its flag use, we need to check if
296   // it might reach N:
297   //
298   //       [ N ]
299   //        ^ ^
300   //        | |
301   //       [U] \--
302   //        ^   [TF]
303   //        |    ^
304   //        |    |
305   //         \  /
306   //          [FU]
307   //
308   // If FU (flag use) indirectly reach N (the load), and U fold N (call it
309   // NU), then TF is a predecessor of FU and a successor of NU. But since
310   // NU and FU are flagged together, this effectively creates a cycle.
311   bool HasFlagUse = false;
312   MVT::ValueType VT = Root->getValueType(Root->getNumValues()-1);
313   while ((VT == MVT::Flag && !Root->use_empty())) {
314     SDNode *FU = findFlagUse(Root);
315     if (FU == NULL)
316       break;
317     else {
318       Root = FU;
319       HasFlagUse = true;
320     }
321     VT = Root->getValueType(Root->getNumValues()-1);
322   }
323
324   if (HasFlagUse)
325     return !isNonImmUse(Root, N, Root, U);
326   return true;
327 }
328
329 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
330 /// and move load below the TokenFactor. Replace store's chain operand with
331 /// load's chain result.
332 static void MoveBelowTokenFactor(SelectionDAG &DAG, SDOperand Load,
333                                  SDOperand Store, SDOperand TF) {
334   std::vector<SDOperand> Ops;
335   for (unsigned i = 0, e = TF.Val->getNumOperands(); i != e; ++i)
336     if (Load.Val == TF.Val->getOperand(i).Val)
337       Ops.push_back(Load.Val->getOperand(0));
338     else
339       Ops.push_back(TF.Val->getOperand(i));
340   DAG.UpdateNodeOperands(TF, &Ops[0], Ops.size());
341   DAG.UpdateNodeOperands(Load, TF, Load.getOperand(1), Load.getOperand(2));
342   DAG.UpdateNodeOperands(Store, Load.getValue(1), Store.getOperand(1),
343                          Store.getOperand(2), Store.getOperand(3));
344 }
345
346 /// InstructionSelectPreprocess - Preprocess the DAG to allow the instruction
347 /// selector to pick more load-modify-store instructions. This is a common
348 /// case:
349 ///
350 ///     [Load chain]
351 ///         ^
352 ///         |
353 ///       [Load]
354 ///       ^    ^
355 ///       |    |
356 ///      /      \-
357 ///     /         |
358 /// [TokenFactor] [Op]
359 ///     ^          ^
360 ///     |          |
361 ///      \        /
362 ///       \      /
363 ///       [Store]
364 ///
365 /// The fact the store's chain operand != load's chain will prevent the
366 /// (store (op (load))) instruction from being selected. We can transform it to:
367 ///
368 ///     [Load chain]
369 ///         ^
370 ///         |
371 ///    [TokenFactor]
372 ///         ^
373 ///         |
374 ///       [Load]
375 ///       ^    ^
376 ///       |    |
377 ///       |     \- 
378 ///       |       | 
379 ///       |     [Op]
380 ///       |       ^
381 ///       |       |
382 ///       \      /
383 ///        \    /
384 ///       [Store]
385 void X86DAGToDAGISel::InstructionSelectPreprocess(SelectionDAG &DAG) {
386   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
387          E = DAG.allnodes_end(); I != E; ++I) {
388     if (!ISD::isNON_TRUNCStore(I))
389       continue;
390     SDOperand Chain = I->getOperand(0);
391     if (Chain.Val->getOpcode() != ISD::TokenFactor)
392       continue;
393
394     SDOperand N1 = I->getOperand(1);
395     SDOperand N2 = I->getOperand(2);
396     if (MVT::isFloatingPoint(N1.getValueType()) ||
397         MVT::isVector(N1.getValueType()) ||
398         !N1.hasOneUse())
399       continue;
400
401     bool RModW = false;
402     SDOperand Load;
403     unsigned Opcode = N1.Val->getOpcode();
404     switch (Opcode) {
405       case ISD::ADD:
406       case ISD::MUL:
407       case ISD::AND:
408       case ISD::OR:
409       case ISD::XOR:
410       case ISD::ADDC:
411       case ISD::ADDE: {
412         SDOperand N10 = N1.getOperand(0);
413         SDOperand N11 = N1.getOperand(1);
414         if (ISD::isNON_EXTLoad(N10.Val))
415           RModW = true;
416         else if (ISD::isNON_EXTLoad(N11.Val)) {
417           RModW = true;
418           std::swap(N10, N11);
419         }
420         RModW = RModW && N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
421           (N10.getOperand(1) == N2) &&
422           (N10.Val->getValueType(0) == N1.getValueType());
423         if (RModW)
424           Load = N10;
425         break;
426       }
427       case ISD::SUB:
428       case ISD::SHL:
429       case ISD::SRA:
430       case ISD::SRL:
431       case ISD::ROTL:
432       case ISD::ROTR:
433       case ISD::SUBC:
434       case ISD::SUBE:
435       case X86ISD::SHLD:
436       case X86ISD::SHRD: {
437         SDOperand N10 = N1.getOperand(0);
438         if (ISD::isNON_EXTLoad(N10.Val))
439           RModW = N10.Val->isOperand(Chain.Val) && N10.hasOneUse() &&
440             (N10.getOperand(1) == N2) &&
441             (N10.Val->getValueType(0) == N1.getValueType());
442         if (RModW)
443           Load = N10;
444         break;
445       }
446     }
447
448     if (RModW) {
449       MoveBelowTokenFactor(DAG, Load, SDOperand(I, 0), Chain);
450       ++NumLoadMoved;
451     }
452   }
453 }
454
455 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
456 /// when it has created a SelectionDAG for us to codegen.
457 void X86DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
458   DEBUG(BB->dump());
459   MachineFunction::iterator FirstMBB = BB;
460
461   if (!FastISel)
462     InstructionSelectPreprocess(DAG);
463
464   // Codegen the basic block.
465 #ifndef NDEBUG
466   DOUT << "===== Instruction selection begins:\n";
467   Indent = 0;
468 #endif
469   DAG.setRoot(SelectRoot(DAG.getRoot()));
470 #ifndef NDEBUG
471   DOUT << "===== Instruction selection ends:\n";
472 #endif
473
474   DAG.RemoveDeadNodes();
475
476   // Emit machine code to BB. 
477   ScheduleAndEmitDAG(DAG);
478   
479   // If we are emitting FP stack code, scan the basic block to determine if this
480   // block defines any FP values.  If so, put an FP_REG_KILL instruction before
481   // the terminator of the block.
482   if (!Subtarget->hasSSE2()) {
483     // Note that FP stack instructions *are* used in SSE code when returning
484     // values, but these are not live out of the basic block, so we don't need
485     // an FP_REG_KILL in this case either.
486     bool ContainsFPCode = false;
487     
488     // Scan all of the machine instructions in these MBBs, checking for FP
489     // stores.
490     MachineFunction::iterator MBBI = FirstMBB;
491     do {
492       for (MachineBasicBlock::iterator I = MBBI->begin(), E = MBBI->end();
493            !ContainsFPCode && I != E; ++I) {
494         if (I->getNumOperands() != 0 && I->getOperand(0).isRegister()) {
495           const TargetRegisterClass *clas;
496           for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
497             if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
498                 MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
499                 ((clas = RegMap->getRegClass(I->getOperand(0).getReg())) == 
500                    X86::RFP32RegisterClass ||
501                  clas == X86::RFP64RegisterClass)) {
502               ContainsFPCode = true;
503               break;
504             }
505           }
506         }
507       }
508     } while (!ContainsFPCode && &*(MBBI++) != BB);
509     
510     // Check PHI nodes in successor blocks.  These PHI's will be lowered to have
511     // a copy of the input value in this block.
512     if (!ContainsFPCode) {
513       // Final check, check LLVM BB's that are successors to the LLVM BB
514       // corresponding to BB for FP PHI nodes.
515       const BasicBlock *LLVMBB = BB->getBasicBlock();
516       const PHINode *PN;
517       for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
518            !ContainsFPCode && SI != E; ++SI) {
519         for (BasicBlock::const_iterator II = SI->begin();
520              (PN = dyn_cast<PHINode>(II)); ++II) {
521           if (PN->getType()->isFloatingPoint()) {
522             ContainsFPCode = true;
523             break;
524           }
525         }
526       }
527     }
528
529     // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
530     if (ContainsFPCode) {
531       BuildMI(*BB, BB->getFirstTerminator(),
532               TM.getInstrInfo()->get(X86::FP_REG_KILL));
533       ++NumFPKill;
534     }
535   }
536 }
537
538 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
539 /// the main function.
540 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
541                                              MachineFrameInfo *MFI) {
542   const TargetInstrInfo *TII = TM.getInstrInfo();
543   if (Subtarget->isTargetCygMing())
544     BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
545
546   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
547   int CWFrameIdx = MFI->CreateStackObject(2, 2);
548   addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
549
550   // Set the high part to be 64-bit precision.
551   addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
552                     CWFrameIdx, 1).addImm(2);
553
554   // Reload the modified control word now.
555   addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
556 }
557
558 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
559   // If this is main, emit special code for main.
560   MachineBasicBlock *BB = MF.begin();
561   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
562     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
563 }
564
565 /// MatchAddress - Add the specified node to the specified addressing mode,
566 /// returning true if it cannot be done.  This just pattern matches for the
567 /// addressing mode
568 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
569                                    bool isRoot, unsigned Depth) {
570   if (Depth > 5) {
571     // Default, generate it as a register.
572     AM.BaseType = X86ISelAddressMode::RegBase;
573     AM.Base.Reg = N;
574     return false;
575   }
576   
577   // RIP relative addressing: %rip + 32-bit displacement!
578   if (AM.isRIPRel) {
579     if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
580       int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
581       if (isInt32(AM.Disp + Val)) {
582         AM.Disp += Val;
583         return false;
584       }
585     }
586     return true;
587   }
588
589   int id = N.Val->getNodeId();
590   bool Available = isSelected(id);
591
592   switch (N.getOpcode()) {
593   default: break;
594   case ISD::Constant: {
595     int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
596     if (isInt32(AM.Disp + Val)) {
597       AM.Disp += Val;
598       return false;
599     }
600     break;
601   }
602
603   case X86ISD::Wrapper: {
604     bool is64Bit = Subtarget->is64Bit();
605     // Under X86-64 non-small code model, GV (and friends) are 64-bits.
606     if (is64Bit && TM.getCodeModel() != CodeModel::Small)
607       break;
608     if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
609       break;
610     // If value is available in a register both base and index components have
611     // been picked, we can't fit the result available in the register in the
612     // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
613     if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
614       bool isStatic = TM.getRelocationModel() == Reloc::Static;
615       SDOperand N0 = N.getOperand(0);
616       // Mac OS X X86-64 lower 4G address is not available.
617       bool isAbs32 = !is64Bit ||
618         (isStatic && Subtarget->hasLow4GUserSpaceAddress());
619       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
620         GlobalValue *GV = G->getGlobal();
621         if (isAbs32 || isRoot) {
622           AM.GV = GV;
623           AM.Disp += G->getOffset();
624           AM.isRIPRel = !isAbs32;
625           return false;
626         }
627       } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
628         if (isAbs32 || isRoot) {
629           AM.CP = CP->getConstVal();
630           AM.Align = CP->getAlignment();
631           AM.Disp += CP->getOffset();
632           AM.isRIPRel = !isAbs32;
633           return false;
634         }
635       } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
636         if (isAbs32 || isRoot) {
637           AM.ES = S->getSymbol();
638           AM.isRIPRel = !isAbs32;
639           return false;
640         }
641       } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
642         if (isAbs32 || isRoot) {
643           AM.JT = J->getIndex();
644           AM.isRIPRel = !isAbs32;
645           return false;
646         }
647       }
648     }
649     break;
650   }
651
652   case ISD::FrameIndex:
653     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
654       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
655       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
656       return false;
657     }
658     break;
659
660   case ISD::SHL:
661     if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
662       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
663         unsigned Val = CN->getValue();
664         if (Val == 1 || Val == 2 || Val == 3) {
665           AM.Scale = 1 << Val;
666           SDOperand ShVal = N.Val->getOperand(0);
667
668           // Okay, we know that we have a scale by now.  However, if the scaled
669           // value is an add of something and a constant, we can fold the
670           // constant into the disp field here.
671           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
672               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
673             AM.IndexReg = ShVal.Val->getOperand(0);
674             ConstantSDNode *AddVal =
675               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
676             uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
677             if (isInt32(Disp))
678               AM.Disp = Disp;
679             else
680               AM.IndexReg = ShVal;
681           } else {
682             AM.IndexReg = ShVal;
683           }
684           return false;
685         }
686       }
687     break;
688
689   case ISD::MUL:
690     // X*[3,5,9] -> X+X*[2,4,8]
691     if (!Available &&
692         AM.BaseType == X86ISelAddressMode::RegBase &&
693         AM.Base.Reg.Val == 0 &&
694         AM.IndexReg.Val == 0) {
695       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
696         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
697           AM.Scale = unsigned(CN->getValue())-1;
698
699           SDOperand MulVal = N.Val->getOperand(0);
700           SDOperand Reg;
701
702           // Okay, we know that we have a scale by now.  However, if the scaled
703           // value is an add of something and a constant, we can fold the
704           // constant into the disp field here.
705           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
706               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
707             Reg = MulVal.Val->getOperand(0);
708             ConstantSDNode *AddVal =
709               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
710             uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
711             if (isInt32(Disp))
712               AM.Disp = Disp;
713             else
714               Reg = N.Val->getOperand(0);
715           } else {
716             Reg = N.Val->getOperand(0);
717           }
718
719           AM.IndexReg = AM.Base.Reg = Reg;
720           return false;
721         }
722     }
723     break;
724
725   case ISD::ADD:
726     if (!Available) {
727       X86ISelAddressMode Backup = AM;
728       if (!MatchAddress(N.Val->getOperand(0), AM, false, Depth+1) &&
729           !MatchAddress(N.Val->getOperand(1), AM, false, Depth+1))
730         return false;
731       AM = Backup;
732       if (!MatchAddress(N.Val->getOperand(1), AM, false, Depth+1) &&
733           !MatchAddress(N.Val->getOperand(0), AM, false, Depth+1))
734         return false;
735       AM = Backup;
736     }
737     break;
738
739   case ISD::OR:
740     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
741     if (!Available) {
742       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
743         X86ISelAddressMode Backup = AM;
744         // Start with the LHS as an addr mode.
745         if (!MatchAddress(N.getOperand(0), AM, false) &&
746             // Address could not have picked a GV address for the displacement.
747             AM.GV == NULL &&
748             // On x86-64, the resultant disp must fit in 32-bits.
749             isInt32(AM.Disp + CN->getSignExtended()) &&
750             // Check to see if the LHS & C is zero.
751             CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getValue())) {
752           AM.Disp += CN->getValue();
753           return false;
754         }
755         AM = Backup;
756       }
757     }
758     break;
759   }
760
761   // Is the base register already occupied?
762   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
763     // If so, check to see if the scale index register is set.
764     if (AM.IndexReg.Val == 0) {
765       AM.IndexReg = N;
766       AM.Scale = 1;
767       return false;
768     }
769
770     // Otherwise, we cannot select it.
771     return true;
772   }
773
774   // Default, generate it as a register.
775   AM.BaseType = X86ISelAddressMode::RegBase;
776   AM.Base.Reg = N;
777   return false;
778 }
779
780 /// SelectAddr - returns true if it is able pattern match an addressing mode.
781 /// It returns the operands which make up the maximal addressing mode it can
782 /// match by reference.
783 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
784                                  SDOperand &Scale, SDOperand &Index,
785                                  SDOperand &Disp) {
786   X86ISelAddressMode AM;
787   if (MatchAddress(N, AM))
788     return false;
789
790   MVT::ValueType VT = N.getValueType();
791   if (AM.BaseType == X86ISelAddressMode::RegBase) {
792     if (!AM.Base.Reg.Val)
793       AM.Base.Reg = CurDAG->getRegister(0, VT);
794   }
795
796   if (!AM.IndexReg.Val)
797     AM.IndexReg = CurDAG->getRegister(0, VT);
798
799   getAddressOperands(AM, Base, Scale, Index, Disp);
800   return true;
801 }
802
803 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
804 /// constant +0.0.
805 static inline bool isZeroNode(SDOperand Elt) {
806   return ((isa<ConstantSDNode>(Elt) &&
807   cast<ConstantSDNode>(Elt)->getValue() == 0) ||
808   (isa<ConstantFPSDNode>(Elt) &&
809   cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
810 }
811
812
813 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
814 /// match a load whose top elements are either undef or zeros.  The load flavor
815 /// is derived from the type of N, which is either v4f32 or v2f64.
816 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
817                                           SDOperand N, SDOperand &Base,
818                                           SDOperand &Scale, SDOperand &Index,
819                                           SDOperand &Disp, SDOperand &InChain,
820                                           SDOperand &OutChain) {
821   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
822     InChain = N.getOperand(0).getValue(1);
823     if (ISD::isNON_EXTLoad(InChain.Val) &&
824         InChain.getValue(0).hasOneUse() &&
825         N.hasOneUse() &&
826         CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
827       LoadSDNode *LD = cast<LoadSDNode>(InChain);
828       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
829         return false;
830       OutChain = LD->getChain();
831       return true;
832     }
833   }
834
835   // Also handle the case where we explicitly require zeros in the top
836   // elements.  This is a vector shuffle from the zero vector.
837   if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
838       N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
839       N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR && 
840       N.getOperand(1).Val->hasOneUse() &&
841       ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
842       N.getOperand(1).getOperand(0).hasOneUse()) {
843     // Check to see if the BUILD_VECTOR is building a zero vector.
844     SDOperand BV = N.getOperand(0);
845     for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
846       if (!isZeroNode(BV.getOperand(i)) &&
847           BV.getOperand(i).getOpcode() != ISD::UNDEF)
848         return false;  // Not a zero/undef vector.
849     // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
850     // from the LHS.
851     unsigned VecWidth = BV.getNumOperands();
852     SDOperand ShufMask = N.getOperand(2);
853     assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
855       if (C->getValue() == VecWidth) {
856         for (unsigned i = 1; i != VecWidth; ++i) {
857           if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
858             // ok.
859           } else {
860             ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
861             if (C->getValue() >= VecWidth) return false;
862           }
863         }
864       }
865       
866       // Okay, this is a zero extending load.  Fold it.
867       LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
868       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
869         return false;
870       OutChain = LD->getChain();
871       InChain = SDOperand(LD, 1);
872       return true;
873     }
874   }
875   return false;
876 }
877
878
879 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
880 /// mode it matches can be cost effectively emitted as an LEA instruction.
881 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
882                                     SDOperand &Base, SDOperand &Scale,
883                                     SDOperand &Index, SDOperand &Disp) {
884   X86ISelAddressMode AM;
885   if (MatchAddress(N, AM))
886     return false;
887
888   MVT::ValueType VT = N.getValueType();
889   unsigned Complexity = 0;
890   if (AM.BaseType == X86ISelAddressMode::RegBase)
891     if (AM.Base.Reg.Val)
892       Complexity = 1;
893     else
894       AM.Base.Reg = CurDAG->getRegister(0, VT);
895   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
896     Complexity = 4;
897
898   if (AM.IndexReg.Val)
899     Complexity++;
900   else
901     AM.IndexReg = CurDAG->getRegister(0, VT);
902
903   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
904   // a simple shift.
905   if (AM.Scale > 1)
906     Complexity++;
907
908   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
909   // to a LEA. This is determined with some expermentation but is by no means
910   // optimal (especially for code size consideration). LEA is nice because of
911   // its three-address nature. Tweak the cost function again when we can run
912   // convertToThreeAddress() at register allocation time.
913   if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
914     // For X86-64, we should always use lea to materialize RIP relative
915     // addresses.
916     if (Subtarget->is64Bit())
917       Complexity = 4;
918     else
919       Complexity += 2;
920   }
921
922   if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
923     Complexity++;
924
925   if (Complexity > 2) {
926     getAddressOperands(AM, Base, Scale, Index, Disp);
927     return true;
928   }
929   return false;
930 }
931
932 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
933                                   SDOperand &Base, SDOperand &Scale,
934                                   SDOperand &Index, SDOperand &Disp) {
935   if (ISD::isNON_EXTLoad(N.Val) &&
936       N.hasOneUse() &&
937       CanBeFoldedBy(N.Val, P.Val, P.Val))
938     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
939   return false;
940 }
941
942 /// getGlobalBaseReg - Output the instructions required to put the
943 /// base address to use for accessing globals into a register.
944 ///
945 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
946   assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
947   if (!GlobalBaseReg) {
948     // Insert the set of GlobalBaseReg into the first MBB of the function
949     MachineBasicBlock &FirstMBB = BB->getParent()->front();
950     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
951     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
952     unsigned PC = RegMap->createVirtualRegister(X86::GR32RegisterClass);
953     
954     const TargetInstrInfo *TII = TM.getInstrInfo();
955     BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
956     BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), PC);
957     
958     // If we're using vanilla 'GOT' PIC style, we should use relative addressing
959     // not to pc, but to _GLOBAL_ADDRESS_TABLE_ external
960     if (TM.getRelocationModel() == Reloc::PIC_ &&
961         Subtarget->isPICStyleGOT()) {
962       GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
963       BuildMI(FirstMBB, MBBI, TII->get(X86::ADD32ri), GlobalBaseReg).
964         addReg(PC).
965         addExternalSymbol("_GLOBAL_OFFSET_TABLE_");
966     } else {
967       GlobalBaseReg = PC;
968     }
969     
970   }
971   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
972 }
973
974 static SDNode *FindCallStartFromCall(SDNode *Node) {
975   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
976     assert(Node->getOperand(0).getValueType() == MVT::Other &&
977          "Node doesn't have a token chain argument!");
978   return FindCallStartFromCall(Node->getOperand(0).Val);
979 }
980
981 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
982   SDNode *Node = N.Val;
983   MVT::ValueType NVT = Node->getValueType(0);
984   unsigned Opc, MOpc;
985   unsigned Opcode = Node->getOpcode();
986
987 #ifndef NDEBUG
988   DOUT << std::string(Indent, ' ') << "Selecting: ";
989   DEBUG(Node->dump(CurDAG));
990   DOUT << "\n";
991   Indent += 2;
992 #endif
993
994   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
995 #ifndef NDEBUG
996     DOUT << std::string(Indent-2, ' ') << "== ";
997     DEBUG(Node->dump(CurDAG));
998     DOUT << "\n";
999     Indent -= 2;
1000 #endif
1001     return NULL;   // Already selected.
1002   }
1003
1004   switch (Opcode) {
1005     default: break;
1006     case X86ISD::GlobalBaseReg: 
1007       return getGlobalBaseReg();
1008
1009     case ISD::ADD: {
1010       // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
1011       // code and is matched first so to prevent it from being turned into
1012       // LEA32r X+c.
1013       // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
1014       MVT::ValueType PtrVT = TLI.getPointerTy();
1015       SDOperand N0 = N.getOperand(0);
1016       SDOperand N1 = N.getOperand(1);
1017       if (N.Val->getValueType(0) == PtrVT &&
1018           N0.getOpcode() == X86ISD::Wrapper &&
1019           N1.getOpcode() == ISD::Constant) {
1020         unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1021         SDOperand C(0, 0);
1022         // TODO: handle ExternalSymbolSDNode.
1023         if (GlobalAddressSDNode *G =
1024             dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1025           C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1026                                              G->getOffset() + Offset);
1027         } else if (ConstantPoolSDNode *CP =
1028                    dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1029           C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1030                                             CP->getAlignment(),
1031                                             CP->getOffset()+Offset);
1032         }
1033
1034         if (C.Val) {
1035           if (Subtarget->is64Bit()) {
1036             SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1037                                 CurDAG->getRegister(0, PtrVT), C };
1038             return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1039           } else
1040             return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1041         }
1042       }
1043
1044       // Other cases are handled by auto-generated code.
1045       break;
1046     }
1047
1048     case ISD::MUL: {
1049       if (NVT == MVT::i8) {
1050         SDOperand N0 = Node->getOperand(0);
1051         SDOperand N1 = Node->getOperand(1);
1052         SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1053         bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1054         if (!foldedLoad) {
1055           foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1056           if (foldedLoad)
1057             std::swap(N0, N1);
1058         }
1059
1060         SDNode *ResNode;
1061         if (foldedLoad) {
1062           SDOperand Chain = N1.getOperand(0);
1063           AddToISelQueue(N0);
1064           AddToISelQueue(Chain);
1065           AddToISelQueue(Tmp0);
1066           AddToISelQueue(Tmp1);
1067           AddToISelQueue(Tmp2);
1068           AddToISelQueue(Tmp3);
1069           SDOperand InFlag(0, 0);
1070           Chain = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag);
1071           InFlag = Chain.getValue(1);
1072           SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1073           ResNode = CurDAG->getTargetNode(X86::MUL8m, MVT::i8, MVT::i8,
1074                                           MVT::Other, Ops, 6);
1075           ReplaceUses(N1.getValue(1), SDOperand(ResNode, 2));
1076         } else {
1077           SDOperand Chain = CurDAG->getEntryNode();
1078           AddToISelQueue(N0);
1079           AddToISelQueue(N1);
1080           SDOperand InFlag(0, 0);
1081           InFlag = CurDAG->getCopyToReg(Chain, X86::AL, N0, InFlag).getValue(1);
1082           ResNode = CurDAG->getTargetNode(X86::MUL8r, MVT::i8, MVT::i8,
1083                                           N1, InFlag);
1084         }
1085
1086         ReplaceUses(N.getValue(0), SDOperand(ResNode, 0));
1087         return NULL;
1088       }
1089       break;
1090     }
1091
1092     case ISD::MULHU:
1093     case ISD::MULHS: {
1094       if (Opcode == ISD::MULHU)
1095         switch (NVT) {
1096         default: assert(0 && "Unsupported VT!");
1097         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1098         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1099         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1100         case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1101         }
1102       else
1103         switch (NVT) {
1104         default: assert(0 && "Unsupported VT!");
1105         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1106         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1107         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1108         case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1109         }
1110
1111       unsigned LoReg, HiReg;
1112       switch (NVT) {
1113       default: assert(0 && "Unsupported VT!");
1114       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1115       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1116       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1117       case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1118       }
1119
1120       SDOperand N0 = Node->getOperand(0);
1121       SDOperand N1 = Node->getOperand(1);
1122
1123       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1124       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1125       // MULHU and MULHS are commmutative
1126       if (!foldedLoad) {
1127         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1128         if (foldedLoad)
1129           std::swap(N0, N1);
1130       }
1131
1132       SDOperand Chain;
1133       if (foldedLoad) {
1134         Chain = N1.getOperand(0);
1135         AddToISelQueue(Chain);
1136       } else
1137         Chain = CurDAG->getEntryNode();
1138
1139       SDOperand InFlag(0, 0);
1140       AddToISelQueue(N0);
1141       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1142                                     N0, InFlag);
1143       InFlag = Chain.getValue(1);
1144
1145       if (foldedLoad) {
1146         AddToISelQueue(Tmp0);
1147         AddToISelQueue(Tmp1);
1148         AddToISelQueue(Tmp2);
1149         AddToISelQueue(Tmp3);
1150         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1151         SDNode *CNode =
1152           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1153         Chain  = SDOperand(CNode, 0);
1154         InFlag = SDOperand(CNode, 1);
1155       } else {
1156         AddToISelQueue(N1);
1157         InFlag =
1158           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1159       }
1160
1161       SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1162       ReplaceUses(N.getValue(0), Result);
1163       if (foldedLoad)
1164         ReplaceUses(N1.getValue(1), Result.getValue(1));
1165
1166 #ifndef NDEBUG
1167       DOUT << std::string(Indent-2, ' ') << "=> ";
1168       DEBUG(Result.Val->dump(CurDAG));
1169       DOUT << "\n";
1170       Indent -= 2;
1171 #endif
1172       return NULL;
1173     }
1174       
1175     case ISD::SDIV:
1176     case ISD::UDIV:
1177     case ISD::SREM:
1178     case ISD::UREM: {
1179       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1180       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1181       if (!isSigned)
1182         switch (NVT) {
1183         default: assert(0 && "Unsupported VT!");
1184         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1185         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1186         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1187         case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1188         }
1189       else
1190         switch (NVT) {
1191         default: assert(0 && "Unsupported VT!");
1192         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1193         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1194         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1195         case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1196         }
1197
1198       unsigned LoReg, HiReg;
1199       unsigned ClrOpcode, SExtOpcode;
1200       switch (NVT) {
1201       default: assert(0 && "Unsupported VT!");
1202       case MVT::i8:
1203         LoReg = X86::AL;  HiReg = X86::AH;
1204         ClrOpcode  = 0;
1205         SExtOpcode = X86::CBW;
1206         break;
1207       case MVT::i16:
1208         LoReg = X86::AX;  HiReg = X86::DX;
1209         ClrOpcode  = X86::MOV16r0;
1210         SExtOpcode = X86::CWD;
1211         break;
1212       case MVT::i32:
1213         LoReg = X86::EAX; HiReg = X86::EDX;
1214         ClrOpcode  = X86::MOV32r0;
1215         SExtOpcode = X86::CDQ;
1216         break;
1217       case MVT::i64:
1218         LoReg = X86::RAX; HiReg = X86::RDX;
1219         ClrOpcode  = X86::MOV64r0;
1220         SExtOpcode = X86::CQO;
1221         break;
1222       }
1223
1224       SDOperand N0 = Node->getOperand(0);
1225       SDOperand N1 = Node->getOperand(1);
1226       SDOperand InFlag(0, 0);
1227       if (NVT == MVT::i8 && !isSigned) {
1228         // Special case for div8, just use a move with zero extension to AX to
1229         // clear the upper 8 bits (AH).
1230         SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1231         if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1232           SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1233           AddToISelQueue(N0.getOperand(0));
1234           AddToISelQueue(Tmp0);
1235           AddToISelQueue(Tmp1);
1236           AddToISelQueue(Tmp2);
1237           AddToISelQueue(Tmp3);
1238           Move =
1239             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1240                                             Ops, 5), 0);
1241           Chain = Move.getValue(1);
1242           ReplaceUses(N0.getValue(1), Chain);
1243         } else {
1244           AddToISelQueue(N0);
1245           Move =
1246             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1247           Chain = CurDAG->getEntryNode();
1248         }
1249         Chain  = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1250         InFlag = Chain.getValue(1);
1251       } else {
1252         AddToISelQueue(N0);
1253         InFlag =
1254           CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1255                                InFlag).getValue(1);
1256         if (isSigned) {
1257           // Sign extend the low part into the high part.
1258           InFlag =
1259             SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1260         } else {
1261           // Zero out the high part, effectively zero extending the input.
1262           SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1263           InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1264                                         InFlag).getValue(1);
1265         }
1266       }
1267
1268       SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1269       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1270       if (foldedLoad) {
1271         AddToISelQueue(N1.getOperand(0));
1272         AddToISelQueue(Tmp0);
1273         AddToISelQueue(Tmp1);
1274         AddToISelQueue(Tmp2);
1275         AddToISelQueue(Tmp3);
1276         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1277         SDNode *CNode =
1278           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1279         Chain  = SDOperand(CNode, 0);
1280         InFlag = SDOperand(CNode, 1);
1281       } else {
1282         AddToISelQueue(N1);
1283         Chain = CurDAG->getEntryNode();
1284         InFlag =
1285           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1286       }
1287
1288       SDOperand Result =
1289         CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1290       ReplaceUses(N.getValue(0), Result);
1291       if (foldedLoad)
1292         ReplaceUses(N1.getValue(1), Result.getValue(1));
1293
1294 #ifndef NDEBUG
1295       DOUT << std::string(Indent-2, ' ') << "=> ";
1296       DEBUG(Result.Val->dump(CurDAG));
1297       DOUT << "\n";
1298       Indent -= 2;
1299 #endif
1300
1301       return NULL;
1302     }
1303       
1304     case ISD::TRUNCATE: {
1305       SDOperand Tmp;
1306       SDOperand Input = Node->getOperand(0);
1307       AddToISelQueue(Node->getOperand(0));
1308       switch (NVT) {
1309       case MVT::i8:
1310         Tmp = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
1311         // Ensure that the source register has an 8-bit subreg on 32-bit targets
1312         if (!Subtarget->is64Bit()) { 
1313           unsigned Opc;
1314           MVT::ValueType VT;
1315           switch (Node->getOperand(0).getValueType()) {
1316           default: assert(0 && "Unknown truncate!");
1317           case MVT::i16:
1318             Opc = X86::MOV16to16_;
1319             VT = MVT::i16;
1320             break;
1321           case MVT::i32:
1322             Opc = X86::MOV32to32_;
1323             VT = MVT::i32;
1324             break;
1325           }
1326           Input = 
1327             SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1328         }
1329         break;
1330       case MVT::i16:
1331         Tmp = CurDAG->getTargetConstant(2, MVT::i32); // SubRegSet 2
1332         break;
1333       case MVT::i32:
1334         Tmp = CurDAG->getTargetConstant(3, MVT::i32); // SubRegSet 3
1335         break;
1336       default: assert(0 && "Unknown truncate!");
1337       }
1338       SDNode *ResNode = CurDAG->getTargetNode(X86::EXTRACT_SUBREG, 
1339                                               NVT, 
1340                                               Input, Tmp);
1341 #ifndef NDEBUG
1342         DOUT << std::string(Indent-2, ' ') << "=> ";
1343         DEBUG(ResNode->dump(CurDAG));
1344         DOUT << "\n";
1345         Indent -= 2;
1346 #endif
1347       return ResNode;
1348       break;
1349     }
1350   }
1351
1352   SDNode *ResNode = SelectCode(N);
1353
1354 #ifndef NDEBUG
1355   DOUT << std::string(Indent-2, ' ') << "=> ";
1356   if (ResNode == NULL || ResNode == N.Val)
1357     DEBUG(N.Val->dump(CurDAG));
1358   else
1359     DEBUG(ResNode->dump(CurDAG));
1360   DOUT << "\n";
1361   Indent -= 2;
1362 #endif
1363
1364   return ResNode;
1365 }
1366
1367 bool X86DAGToDAGISel::
1368 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1369                              std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1370   SDOperand Op0, Op1, Op2, Op3;
1371   switch (ConstraintCode) {
1372   case 'o':   // offsetable        ??
1373   case 'v':   // not offsetable    ??
1374   default: return true;
1375   case 'm':   // memory
1376     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1377       return true;
1378     break;
1379   }
1380   
1381   OutOps.push_back(Op0);
1382   OutOps.push_back(Op1);
1383   OutOps.push_back(Op2);
1384   OutOps.push_back(Op3);
1385   AddToISelQueue(Op0);
1386   AddToISelQueue(Op1);
1387   AddToISelQueue(Op2);
1388   AddToISelQueue(Op3);
1389   return false;
1390 }
1391
1392 /// createX86ISelDag - This pass converts a legalized DAG into a 
1393 /// X86-specific DAG, ready for instruction scheduling.
1394 ///
1395 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1396   return new X86DAGToDAGISel(TM, Fast);
1397 }