What should be the last unnecessary <iostream>s in the library.
[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/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/Statistic.h"
37 #include <queue>
38 #include <set>
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 //                      Pattern Matcher Implementation
43 //===----------------------------------------------------------------------===//
44
45 namespace {
46   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
47   /// SDOperand's instead of register numbers for the leaves of the matched
48   /// tree.
49   struct X86ISelAddressMode {
50     enum {
51       RegBase,
52       FrameIndexBase
53     } BaseType;
54
55     struct {            // This is really a union, discriminated by BaseType!
56       SDOperand Reg;
57       int FrameIndex;
58     } Base;
59
60     bool isRIPRel;     // RIP relative?
61     unsigned Scale;
62     SDOperand IndexReg; 
63     unsigned Disp;
64     GlobalValue *GV;
65     Constant *CP;
66     const char *ES;
67     int JT;
68     unsigned Align;    // CP alignment.
69
70     X86ISelAddressMode()
71       : BaseType(RegBase), isRIPRel(false), Scale(1), IndexReg(), Disp(0),
72         GV(0), CP(0), ES(0), JT(-1), Align(0) {
73     }
74   };
75 }
76
77 namespace {
78   Statistic
79   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
80
81   Statistic
82   NumLoadMoved("x86-codegen", "Number of loads moved below TokenFactor");
83
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     /// FastISel - Enable fast(er) instruction selection.
94     ///
95     bool FastISel;
96
97     /// TM - Keep a reference to X86TargetMachine.
98     ///
99     X86TargetMachine &TM;
100
101     /// X86Lowering - This object fully describes how to lower LLVM code to an
102     /// X86-specific SelectionDAG.
103     X86TargetLowering X86Lowering;
104
105     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
106     /// make the right decision when generating code for different targets.
107     const X86Subtarget *Subtarget;
108
109     /// GlobalBaseReg - keeps track of the virtual register mapped onto global
110     /// base register.
111     unsigned GlobalBaseReg;
112
113   public:
114     X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
115       : SelectionDAGISel(X86Lowering),
116         ContainsFPCode(false), FastISel(fast), 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     /// InstructionSelectBasicBlock - This callback is invoked by
131     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
132     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
133
134     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
135
136     virtual bool CanBeFoldedBy(SDNode *N, SDNode *U, SDNode *Root);
137
138 // Include the pieces autogenerated from the target description.
139 #include "X86GenDAGISel.inc"
140
141   private:
142     SDNode *Select(SDOperand N);
143
144     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM, bool isRoot = true);
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) {
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         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
495           if (I->getOperand(op).isRegister() && I->getOperand(op).isDef() &&
496               MRegisterInfo::isVirtualRegister(I->getOperand(op).getReg()) &&
497               RegMap->getRegClass(I->getOperand(0).getReg()) == 
498                 X86::RFPRegisterClass) {
499             ContainsFPCode = true;
500             break;
501           }
502         }
503       }
504     } while (!ContainsFPCode && &*(MBBI++) != BB);
505     
506     // Check PHI nodes in successor blocks.  These PHI's will be lowered to have
507     // a copy of the input value in this block.
508     if (!ContainsFPCode) {
509       // Final check, check LLVM BB's that are successors to the LLVM BB
510       // corresponding to BB for FP PHI nodes.
511       const BasicBlock *LLVMBB = BB->getBasicBlock();
512       const PHINode *PN;
513       for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
514            !ContainsFPCode && SI != E; ++SI) {
515         for (BasicBlock::const_iterator II = SI->begin();
516              (PN = dyn_cast<PHINode>(II)); ++II) {
517           if (PN->getType()->isFloatingPoint()) {
518             ContainsFPCode = true;
519             break;
520           }
521         }
522       }
523     }
524
525     // Finally, if we found any FP code, emit the FP_REG_KILL instruction.
526     if (ContainsFPCode) {
527       BuildMI(*BB, BB->getFirstTerminator(),
528               TM.getInstrInfo()->get(X86::FP_REG_KILL));
529       ++NumFPKill;
530     }
531   }
532 }
533
534 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
535 /// the main function.
536 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
537                                              MachineFrameInfo *MFI) {
538   const TargetInstrInfo *TII = TM.getInstrInfo();
539   if (Subtarget->isTargetCygwin())
540     BuildMI(BB, TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
541
542   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
543   int CWFrameIdx = MFI->CreateStackObject(2, 2);
544   addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
545
546   // Set the high part to be 64-bit precision.
547   addFrameReference(BuildMI(BB, TII->get(X86::MOV8mi)),
548                     CWFrameIdx, 1).addImm(2);
549
550   // Reload the modified control word now.
551   addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
552 }
553
554 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
555   // If this is main, emit special code for main.
556   MachineBasicBlock *BB = MF.begin();
557   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
558     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
559 }
560
561 /// MatchAddress - Add the specified node to the specified addressing mode,
562 /// returning true if it cannot be done.  This just pattern matches for the
563 /// addressing mode
564 bool X86DAGToDAGISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM,
565                                    bool isRoot) {
566   // RIP relative addressing: %rip + 32-bit displacement!
567   if (AM.isRIPRel) {
568     if (!AM.ES && AM.JT != -1 && N.getOpcode() == ISD::Constant) {
569       int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
570       if (isInt32(AM.Disp + Val)) {
571         AM.Disp += Val;
572         return false;
573       }
574     }
575     return true;
576   }
577
578   int id = N.Val->getNodeId();
579   bool Available = isSelected(id);
580
581   switch (N.getOpcode()) {
582   default: break;
583   case ISD::Constant: {
584     int64_t Val = cast<ConstantSDNode>(N)->getSignExtended();
585     if (isInt32(AM.Disp + Val)) {
586       AM.Disp += Val;
587       return false;
588     }
589     break;
590   }
591
592   case X86ISD::Wrapper: {
593     bool is64Bit = Subtarget->is64Bit();
594     // Under X86-64 non-small code model, GV (and friends) are 64-bits.
595     if (is64Bit && TM.getCodeModel() != CodeModel::Small)
596       break;
597     if (AM.GV != 0 || AM.CP != 0 || AM.ES != 0 || AM.JT != -1)
598       break;
599     // If value is available in a register both base and index components have
600     // been picked, we can't fit the result available in the register in the
601     // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
602     if (!Available || (AM.Base.Reg.Val && AM.IndexReg.Val)) {
603       bool isStatic = TM.getRelocationModel() == Reloc::Static;
604       SDOperand N0 = N.getOperand(0);
605       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
606         GlobalValue *GV = G->getGlobal();
607         bool isAbs32 = !is64Bit ||
608           (isStatic && !(GV->isExternal() || GV->hasWeakLinkage() ||
609                          GV->hasLinkOnceLinkage()));
610         if (isAbs32 || isRoot) {
611           AM.GV = G->getGlobal();
612           AM.Disp += G->getOffset();
613           AM.isRIPRel = !isAbs32;
614           return false;
615         }
616       } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
617         if (!is64Bit || isStatic || isRoot) {
618           AM.CP = CP->getConstVal();
619           AM.Align = CP->getAlignment();
620           AM.Disp += CP->getOffset();
621           AM.isRIPRel = !isStatic;
622           return false;
623         }
624       } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
625         if (isStatic || isRoot) {
626           AM.ES = S->getSymbol();
627           AM.isRIPRel = !isStatic;
628           return false;
629         }
630       } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
631         if (isStatic || isRoot) {
632           AM.JT = J->getIndex();
633           AM.isRIPRel = !isStatic;
634           return false;
635         }
636       }
637     }
638     break;
639   }
640
641   case ISD::FrameIndex:
642     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
643       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
644       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
645       return false;
646     }
647     break;
648
649   case ISD::SHL:
650     if (!Available && AM.IndexReg.Val == 0 && AM.Scale == 1)
651       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
652         unsigned Val = CN->getValue();
653         if (Val == 1 || Val == 2 || Val == 3) {
654           AM.Scale = 1 << Val;
655           SDOperand ShVal = N.Val->getOperand(0);
656
657           // Okay, we know that we have a scale by now.  However, if the scaled
658           // value is an add of something and a constant, we can fold the
659           // constant into the disp field here.
660           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
661               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
662             AM.IndexReg = ShVal.Val->getOperand(0);
663             ConstantSDNode *AddVal =
664               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
665             uint64_t Disp = AM.Disp + (AddVal->getValue() << Val);
666             if (isInt32(Disp))
667               AM.Disp = Disp;
668             else
669               AM.IndexReg = ShVal;
670           } else {
671             AM.IndexReg = ShVal;
672           }
673           return false;
674         }
675       }
676     break;
677
678   case ISD::MUL:
679     // X*[3,5,9] -> X+X*[2,4,8]
680     if (!Available &&
681         AM.BaseType == X86ISelAddressMode::RegBase &&
682         AM.Base.Reg.Val == 0 &&
683         AM.IndexReg.Val == 0)
684       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
685         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
686           AM.Scale = unsigned(CN->getValue())-1;
687
688           SDOperand MulVal = N.Val->getOperand(0);
689           SDOperand Reg;
690
691           // Okay, we know that we have a scale by now.  However, if the scaled
692           // value is an add of something and a constant, we can fold the
693           // constant into the disp field here.
694           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
695               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
696             Reg = MulVal.Val->getOperand(0);
697             ConstantSDNode *AddVal =
698               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
699             uint64_t Disp = AM.Disp + AddVal->getValue() * CN->getValue();
700             if (isInt32(Disp))
701               AM.Disp = Disp;
702             else
703               Reg = N.Val->getOperand(0);
704           } else {
705             Reg = N.Val->getOperand(0);
706           }
707
708           AM.IndexReg = AM.Base.Reg = Reg;
709           return false;
710         }
711     break;
712
713   case ISD::ADD: {
714     if (!Available) {
715       X86ISelAddressMode Backup = AM;
716       if (!MatchAddress(N.Val->getOperand(0), AM, false) &&
717           !MatchAddress(N.Val->getOperand(1), AM, false))
718         return false;
719       AM = Backup;
720       if (!MatchAddress(N.Val->getOperand(1), AM, false) &&
721           !MatchAddress(N.Val->getOperand(0), AM, false))
722         return false;
723       AM = Backup;
724     }
725     break;
726   }
727
728   case ISD::OR: {
729     if (!Available) {
730       X86ISelAddressMode Backup = AM;
731       // Look for (x << c1) | c2 where (c2 < c1)
732       ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(0));
733       if (CN && !MatchAddress(N.Val->getOperand(1), AM, false)) {
734         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
735           AM.Disp = CN->getValue();
736           return false;
737         }
738       }
739       AM = Backup;
740       CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1));
741       if (CN && !MatchAddress(N.Val->getOperand(0), AM, false)) {
742         if (AM.GV == NULL && AM.Disp == 0 && CN->getValue() < AM.Scale) {
743           AM.Disp = CN->getValue();
744           return false;
745         }
746       }
747       AM = Backup;
748     }
749     break;
750   }
751   }
752
753   // Is the base register already occupied?
754   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
755     // If so, check to see if the scale index register is set.
756     if (AM.IndexReg.Val == 0) {
757       AM.IndexReg = N;
758       AM.Scale = 1;
759       return false;
760     }
761
762     // Otherwise, we cannot select it.
763     return true;
764   }
765
766   // Default, generate it as a register.
767   AM.BaseType = X86ISelAddressMode::RegBase;
768   AM.Base.Reg = N;
769   return false;
770 }
771
772 /// SelectAddr - returns true if it is able pattern match an addressing mode.
773 /// It returns the operands which make up the maximal addressing mode it can
774 /// match by reference.
775 bool X86DAGToDAGISel::SelectAddr(SDOperand Op, SDOperand N, SDOperand &Base,
776                                  SDOperand &Scale, SDOperand &Index,
777                                  SDOperand &Disp) {
778   X86ISelAddressMode AM;
779   if (MatchAddress(N, AM))
780     return false;
781
782   MVT::ValueType VT = N.getValueType();
783   if (AM.BaseType == X86ISelAddressMode::RegBase) {
784     if (!AM.Base.Reg.Val)
785       AM.Base.Reg = CurDAG->getRegister(0, VT);
786   }
787
788   if (!AM.IndexReg.Val)
789     AM.IndexReg = CurDAG->getRegister(0, VT);
790
791   getAddressOperands(AM, Base, Scale, Index, Disp);
792   return true;
793 }
794
795 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
796 /// constant +0.0.
797 static inline bool isZeroNode(SDOperand Elt) {
798   return ((isa<ConstantSDNode>(Elt) &&
799   cast<ConstantSDNode>(Elt)->getValue() == 0) ||
800   (isa<ConstantFPSDNode>(Elt) &&
801   cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
802 }
803
804
805 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
806 /// match a load whose top elements are either undef or zeros.  The load flavor
807 /// is derived from the type of N, which is either v4f32 or v2f64.
808 bool X86DAGToDAGISel::SelectScalarSSELoad(SDOperand Op, SDOperand Pred,
809                                           SDOperand N, SDOperand &Base,
810                                           SDOperand &Scale, SDOperand &Index,
811                                           SDOperand &Disp, SDOperand &InChain,
812                                           SDOperand &OutChain) {
813   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
814     InChain = N.getOperand(0).getValue(1);
815     if (ISD::isNON_EXTLoad(InChain.Val) &&
816         InChain.getValue(0).hasOneUse() &&
817         N.hasOneUse() &&
818         CanBeFoldedBy(N.Val, Pred.Val, Op.Val)) {
819       LoadSDNode *LD = cast<LoadSDNode>(InChain);
820       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
821         return false;
822       OutChain = LD->getChain();
823       return true;
824     }
825   }
826
827   // Also handle the case where we explicitly require zeros in the top
828   // elements.  This is a vector shuffle from the zero vector.
829   if (N.getOpcode() == ISD::VECTOR_SHUFFLE && N.Val->hasOneUse() &&
830       N.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
831       N.getOperand(1).getOpcode() == ISD::SCALAR_TO_VECTOR && 
832       N.getOperand(1).Val->hasOneUse() &&
833       ISD::isNON_EXTLoad(N.getOperand(1).getOperand(0).Val) &&
834       N.getOperand(1).getOperand(0).hasOneUse()) {
835     // Check to see if the BUILD_VECTOR is building a zero vector.
836     SDOperand BV = N.getOperand(0);
837     for (unsigned i = 0, e = BV.getNumOperands(); i != e; ++i)
838       if (!isZeroNode(BV.getOperand(i)) &&
839           BV.getOperand(i).getOpcode() != ISD::UNDEF)
840         return false;  // Not a zero/undef vector.
841     // Check to see if the shuffle mask is 4/L/L/L or 2/L, where L is something
842     // from the LHS.
843     unsigned VecWidth = BV.getNumOperands();
844     SDOperand ShufMask = N.getOperand(2);
845     assert(ShufMask.getOpcode() == ISD::BUILD_VECTOR && "Invalid shuf mask!");
846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(ShufMask.getOperand(0))) {
847       if (C->getValue() == VecWidth) {
848         for (unsigned i = 1; i != VecWidth; ++i) {
849           if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF) {
850             // ok.
851           } else {
852             ConstantSDNode *C = cast<ConstantSDNode>(ShufMask.getOperand(i));
853             if (C->getValue() >= VecWidth) return false;
854           }
855         }
856       }
857       
858       // Okay, this is a zero extending load.  Fold it.
859       LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(1).getOperand(0));
860       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp))
861         return false;
862       OutChain = LD->getChain();
863       InChain = SDOperand(LD, 1);
864       return true;
865     }
866   }
867   return false;
868 }
869
870
871 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
872 /// mode it matches can be cost effectively emitted as an LEA instruction.
873 bool X86DAGToDAGISel::SelectLEAAddr(SDOperand Op, SDOperand N,
874                                     SDOperand &Base, SDOperand &Scale,
875                                     SDOperand &Index, SDOperand &Disp) {
876   X86ISelAddressMode AM;
877   if (MatchAddress(N, AM))
878     return false;
879
880   MVT::ValueType VT = N.getValueType();
881   unsigned Complexity = 0;
882   if (AM.BaseType == X86ISelAddressMode::RegBase)
883     if (AM.Base.Reg.Val)
884       Complexity = 1;
885     else
886       AM.Base.Reg = CurDAG->getRegister(0, VT);
887   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
888     Complexity = 4;
889
890   if (AM.IndexReg.Val)
891     Complexity++;
892   else
893     AM.IndexReg = CurDAG->getRegister(0, VT);
894
895   if (AM.Scale > 2) 
896     Complexity += 2;
897   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg
898   else if (AM.Scale > 1)
899     Complexity++;
900
901   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
902   // to a LEA. This is determined with some expermentation but is by no means
903   // optimal (especially for code size consideration). LEA is nice because of
904   // its three-address nature. Tweak the cost function again when we can run
905   // convertToThreeAddress() at register allocation time.
906   if (AM.GV || AM.CP || AM.ES || AM.JT != -1) {
907     // For X86-64, we should always use lea to materialize RIP relative
908     // addresses.
909     if (Subtarget->is64Bit())
910       Complexity = 4;
911     else
912       Complexity += 2;
913   }
914
915   if (AM.Disp && (AM.Base.Reg.Val || AM.IndexReg.Val))
916     Complexity++;
917
918   if (Complexity > 2) {
919     getAddressOperands(AM, Base, Scale, Index, Disp);
920     return true;
921   }
922   return false;
923 }
924
925 bool X86DAGToDAGISel::TryFoldLoad(SDOperand P, SDOperand N,
926                                   SDOperand &Base, SDOperand &Scale,
927                                   SDOperand &Index, SDOperand &Disp) {
928   if (ISD::isNON_EXTLoad(N.Val) &&
929       N.hasOneUse() &&
930       CanBeFoldedBy(N.Val, P.Val, P.Val))
931     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp);
932   return false;
933 }
934
935 /// getGlobalBaseReg - Output the instructions required to put the
936 /// base address to use for accessing globals into a register.
937 ///
938 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
939   assert(!Subtarget->is64Bit() && "X86-64 PIC uses RIP relative addressing");
940   if (!GlobalBaseReg) {
941     // Insert the set of GlobalBaseReg into the first MBB of the function
942     MachineBasicBlock &FirstMBB = BB->getParent()->front();
943     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
944     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
945     GlobalBaseReg = RegMap->createVirtualRegister(X86::GR32RegisterClass);
946     const TargetInstrInfo *TII = TM.getInstrInfo();
947     BuildMI(FirstMBB, MBBI, TII->get(X86::MovePCtoStack));
948     BuildMI(FirstMBB, MBBI, TII->get(X86::POP32r), GlobalBaseReg);
949   }
950   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).Val;
951 }
952
953 static SDNode *FindCallStartFromCall(SDNode *Node) {
954   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
955     assert(Node->getOperand(0).getValueType() == MVT::Other &&
956          "Node doesn't have a token chain argument!");
957   return FindCallStartFromCall(Node->getOperand(0).Val);
958 }
959
960 SDNode *X86DAGToDAGISel::Select(SDOperand N) {
961   SDNode *Node = N.Val;
962   MVT::ValueType NVT = Node->getValueType(0);
963   unsigned Opc, MOpc;
964   unsigned Opcode = Node->getOpcode();
965
966 #ifndef NDEBUG
967   DOUT << std::string(Indent, ' ') << "Selecting: ";
968   DEBUG(Node->dump(CurDAG));
969   DOUT << "\n";
970   Indent += 2;
971 #endif
972
973   if (Opcode >= ISD::BUILTIN_OP_END && Opcode < X86ISD::FIRST_NUMBER) {
974 #ifndef NDEBUG
975     DOUT << std::string(Indent-2, ' ') << "== ";
976     DEBUG(Node->dump(CurDAG));
977     DOUT << "\n";
978     Indent -= 2;
979 #endif
980     return NULL;   // Already selected.
981   }
982
983   switch (Opcode) {
984     default: break;
985     case X86ISD::GlobalBaseReg: 
986       return getGlobalBaseReg();
987
988     case ISD::ADD: {
989       // Turn ADD X, c to MOV32ri X+c. This cannot be done with tblgen'd
990       // code and is matched first so to prevent it from being turned into
991       // LEA32r X+c.
992       // In 64-bit mode, use LEA to take advantage of RIP-relative addressing.
993       MVT::ValueType PtrVT = TLI.getPointerTy();
994       SDOperand N0 = N.getOperand(0);
995       SDOperand N1 = N.getOperand(1);
996       if (N.Val->getValueType(0) == PtrVT &&
997           N0.getOpcode() == X86ISD::Wrapper &&
998           N1.getOpcode() == ISD::Constant) {
999         unsigned Offset = (unsigned)cast<ConstantSDNode>(N1)->getValue();
1000         SDOperand C(0, 0);
1001         // TODO: handle ExternalSymbolSDNode.
1002         if (GlobalAddressSDNode *G =
1003             dyn_cast<GlobalAddressSDNode>(N0.getOperand(0))) {
1004           C = CurDAG->getTargetGlobalAddress(G->getGlobal(), PtrVT,
1005                                              G->getOffset() + Offset);
1006         } else if (ConstantPoolSDNode *CP =
1007                    dyn_cast<ConstantPoolSDNode>(N0.getOperand(0))) {
1008           C = CurDAG->getTargetConstantPool(CP->getConstVal(), PtrVT,
1009                                             CP->getAlignment(),
1010                                             CP->getOffset()+Offset);
1011         }
1012
1013         if (C.Val) {
1014           if (Subtarget->is64Bit()) {
1015             SDOperand Ops[] = { CurDAG->getRegister(0, PtrVT), getI8Imm(1),
1016                                 CurDAG->getRegister(0, PtrVT), C };
1017             return CurDAG->SelectNodeTo(N.Val, X86::LEA64r, MVT::i64, Ops, 4);
1018           } else
1019             return CurDAG->SelectNodeTo(N.Val, X86::MOV32ri, PtrVT, C);
1020         }
1021       }
1022
1023       // Other cases are handled by auto-generated code.
1024       break;
1025     }
1026
1027     case ISD::MULHU:
1028     case ISD::MULHS: {
1029       if (Opcode == ISD::MULHU)
1030         switch (NVT) {
1031         default: assert(0 && "Unsupported VT!");
1032         case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1033         case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1034         case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1035         case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1036         }
1037       else
1038         switch (NVT) {
1039         default: assert(0 && "Unsupported VT!");
1040         case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1041         case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1042         case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1043         case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1044         }
1045
1046       unsigned LoReg, HiReg;
1047       switch (NVT) {
1048       default: assert(0 && "Unsupported VT!");
1049       case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1050       case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1051       case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1052       case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1053       }
1054
1055       SDOperand N0 = Node->getOperand(0);
1056       SDOperand N1 = Node->getOperand(1);
1057
1058       bool foldedLoad = false;
1059       SDOperand Tmp0, Tmp1, Tmp2, Tmp3;
1060       foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1061       // MULHU and MULHS are commmutative
1062       if (!foldedLoad) {
1063         foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3);
1064         if (foldedLoad) {
1065           N0 = Node->getOperand(1);
1066           N1 = Node->getOperand(0);
1067         }
1068       }
1069
1070       SDOperand Chain;
1071       if (foldedLoad) {
1072         Chain = N1.getOperand(0);
1073         AddToISelQueue(Chain);
1074       } else
1075         Chain = CurDAG->getEntryNode();
1076
1077       SDOperand InFlag(0, 0);
1078       AddToISelQueue(N0);
1079       Chain  = CurDAG->getCopyToReg(Chain, CurDAG->getRegister(LoReg, NVT),
1080                                     N0, InFlag);
1081       InFlag = Chain.getValue(1);
1082
1083       if (foldedLoad) {
1084         AddToISelQueue(Tmp0);
1085         AddToISelQueue(Tmp1);
1086         AddToISelQueue(Tmp2);
1087         AddToISelQueue(Tmp3);
1088         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Chain, InFlag };
1089         SDNode *CNode =
1090           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1091         Chain  = SDOperand(CNode, 0);
1092         InFlag = SDOperand(CNode, 1);
1093       } else {
1094         AddToISelQueue(N1);
1095         InFlag =
1096           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1097       }
1098
1099       SDOperand Result = CurDAG->getCopyFromReg(Chain, HiReg, NVT, InFlag);
1100       ReplaceUses(N.getValue(0), Result);
1101       if (foldedLoad)
1102         ReplaceUses(N1.getValue(1), Result.getValue(1));
1103
1104 #ifndef NDEBUG
1105       DOUT << std::string(Indent-2, ' ') << "=> ";
1106       DEBUG(Result.Val->dump(CurDAG));
1107       DOUT << "\n";
1108       Indent -= 2;
1109 #endif
1110       return NULL;
1111     }
1112       
1113     case ISD::SDIV:
1114     case ISD::UDIV:
1115     case ISD::SREM:
1116     case ISD::UREM: {
1117       bool isSigned = Opcode == ISD::SDIV || Opcode == ISD::SREM;
1118       bool isDiv    = Opcode == ISD::SDIV || Opcode == ISD::UDIV;
1119       if (!isSigned)
1120         switch (NVT) {
1121         default: assert(0 && "Unsupported VT!");
1122         case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1123         case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1124         case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1125         case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1126         }
1127       else
1128         switch (NVT) {
1129         default: assert(0 && "Unsupported VT!");
1130         case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1131         case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1132         case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1133         case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1134         }
1135
1136       unsigned LoReg, HiReg;
1137       unsigned ClrOpcode, SExtOpcode;
1138       switch (NVT) {
1139       default: assert(0 && "Unsupported VT!");
1140       case MVT::i8:
1141         LoReg = X86::AL;  HiReg = X86::AH;
1142         ClrOpcode  = 0;
1143         SExtOpcode = X86::CBW;
1144         break;
1145       case MVT::i16:
1146         LoReg = X86::AX;  HiReg = X86::DX;
1147         ClrOpcode  = X86::MOV16r0;
1148         SExtOpcode = X86::CWD;
1149         break;
1150       case MVT::i32:
1151         LoReg = X86::EAX; HiReg = X86::EDX;
1152         ClrOpcode  = X86::MOV32r0;
1153         SExtOpcode = X86::CDQ;
1154         break;
1155       case MVT::i64:
1156         LoReg = X86::RAX; HiReg = X86::RDX;
1157         ClrOpcode  = X86::MOV64r0;
1158         SExtOpcode = X86::CQO;
1159         break;
1160       }
1161
1162       SDOperand N0 = Node->getOperand(0);
1163       SDOperand N1 = Node->getOperand(1);
1164       SDOperand InFlag(0, 0);
1165       if (NVT == MVT::i8 && !isSigned) {
1166         // Special case for div8, just use a move with zero extension to AX to
1167         // clear the upper 8 bits (AH).
1168         SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Move, Chain;
1169         if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3)) {
1170           SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N0.getOperand(0) };
1171           AddToISelQueue(N0.getOperand(0));
1172           AddToISelQueue(Tmp0);
1173           AddToISelQueue(Tmp1);
1174           AddToISelQueue(Tmp2);
1175           AddToISelQueue(Tmp3);
1176           Move =
1177             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rm8, MVT::i16, MVT::Other,
1178                                             Ops, 5), 0);
1179           Chain = Move.getValue(1);
1180           ReplaceUses(N0.getValue(1), Chain);
1181         } else {
1182           AddToISelQueue(N0);
1183           Move =
1184             SDOperand(CurDAG->getTargetNode(X86::MOVZX16rr8, MVT::i16, N0), 0);
1185           Chain = CurDAG->getEntryNode();
1186         }
1187         Chain  = CurDAG->getCopyToReg(Chain, X86::AX, Move, InFlag);
1188         InFlag = Chain.getValue(1);
1189       } else {
1190         AddToISelQueue(N0);
1191         InFlag =
1192           CurDAG->getCopyToReg(CurDAG->getEntryNode(), LoReg, N0,
1193                                InFlag).getValue(1);
1194         if (isSigned) {
1195           // Sign extend the low part into the high part.
1196           InFlag =
1197             SDOperand(CurDAG->getTargetNode(SExtOpcode, MVT::Flag, InFlag), 0);
1198         } else {
1199           // Zero out the high part, effectively zero extending the input.
1200           SDOperand ClrNode = SDOperand(CurDAG->getTargetNode(ClrOpcode, NVT), 0);
1201           InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), HiReg, ClrNode,
1202                                         InFlag).getValue(1);
1203         }
1204       }
1205
1206       SDOperand Tmp0, Tmp1, Tmp2, Tmp3, Chain;
1207       bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3);
1208       if (foldedLoad) {
1209         AddToISelQueue(N1.getOperand(0));
1210         AddToISelQueue(Tmp0);
1211         AddToISelQueue(Tmp1);
1212         AddToISelQueue(Tmp2);
1213         AddToISelQueue(Tmp3);
1214         SDOperand Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, N1.getOperand(0), InFlag };
1215         SDNode *CNode =
1216           CurDAG->getTargetNode(MOpc, MVT::Other, MVT::Flag, Ops, 6);
1217         Chain  = SDOperand(CNode, 0);
1218         InFlag = SDOperand(CNode, 1);
1219       } else {
1220         AddToISelQueue(N1);
1221         Chain = CurDAG->getEntryNode();
1222         InFlag =
1223           SDOperand(CurDAG->getTargetNode(Opc, MVT::Flag, N1, InFlag), 0);
1224       }
1225
1226       SDOperand Result =
1227         CurDAG->getCopyFromReg(Chain, isDiv ? LoReg : HiReg, NVT, InFlag);
1228       ReplaceUses(N.getValue(0), Result);
1229       if (foldedLoad)
1230         ReplaceUses(N1.getValue(1), Result.getValue(1));
1231
1232 #ifndef NDEBUG
1233       DOUT << std::string(Indent-2, ' ') << "=> ";
1234       DEBUG(Result.Val->dump(CurDAG));
1235       DOUT << "\n";
1236       Indent -= 2;
1237 #endif
1238
1239       return NULL;
1240     }
1241
1242     case ISD::TRUNCATE: {
1243       if (!Subtarget->is64Bit() && NVT == MVT::i8) {
1244         unsigned Opc2;
1245         MVT::ValueType VT;
1246         switch (Node->getOperand(0).getValueType()) {
1247         default: assert(0 && "Unknown truncate!");
1248         case MVT::i16:
1249           Opc = X86::MOV16to16_;
1250           VT = MVT::i16;
1251           Opc2 = X86::TRUNC_16_to8;
1252           break;
1253         case MVT::i32:
1254           Opc = X86::MOV32to32_;
1255           VT = MVT::i32;
1256           Opc2 = X86::TRUNC_32_to8;
1257           break;
1258         }
1259
1260         AddToISelQueue(Node->getOperand(0));
1261         SDOperand Tmp =
1262           SDOperand(CurDAG->getTargetNode(Opc, VT, Node->getOperand(0)), 0);
1263         SDNode *ResNode = CurDAG->getTargetNode(Opc2, NVT, Tmp);
1264       
1265 #ifndef NDEBUG
1266         DOUT << std::string(Indent-2, ' ') << "=> ";
1267         DEBUG(ResNode->dump(CurDAG));
1268         DOUT << "\n";
1269         Indent -= 2;
1270 #endif
1271         return ResNode;
1272       }
1273
1274       break;
1275     }
1276   }
1277
1278   SDNode *ResNode = SelectCode(N);
1279
1280 #ifndef NDEBUG
1281   DOUT << std::string(Indent-2, ' ') << "=> ";
1282   if (ResNode == NULL || ResNode == N.Val)
1283     DEBUG(N.Val->dump(CurDAG));
1284   else
1285     DEBUG(ResNode->dump(CurDAG));
1286   DOUT << "\n";
1287   Indent -= 2;
1288 #endif
1289
1290   return ResNode;
1291 }
1292
1293 bool X86DAGToDAGISel::
1294 SelectInlineAsmMemoryOperand(const SDOperand &Op, char ConstraintCode,
1295                              std::vector<SDOperand> &OutOps, SelectionDAG &DAG){
1296   SDOperand Op0, Op1, Op2, Op3;
1297   switch (ConstraintCode) {
1298   case 'o':   // offsetable        ??
1299   case 'v':   // not offsetable    ??
1300   default: return true;
1301   case 'm':   // memory
1302     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3))
1303       return true;
1304     break;
1305   }
1306   
1307   OutOps.push_back(Op0);
1308   OutOps.push_back(Op1);
1309   OutOps.push_back(Op2);
1310   OutOps.push_back(Op3);
1311   AddToISelQueue(Op0);
1312   AddToISelQueue(Op1);
1313   AddToISelQueue(Op2);
1314   AddToISelQueue(Op3);
1315   return false;
1316 }
1317
1318 /// createX86ISelDag - This pass converts a legalized DAG into a 
1319 /// X86-specific DAG, ready for instruction scheduling.
1320 ///
1321 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
1322   return new X86DAGToDAGISel(TM, Fast);
1323 }