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