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