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