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