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