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