Added TEST %rAX, $imm instructions to the Intel tables. These are required for the...
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Type.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/Statistic.h"
43 using namespace llvm;
44
45 #include "llvm/Support/CommandLine.h"
46 static cl::opt<bool> AvoidDupAddrCompute("x86-avoid-dup-address", cl::Hidden);
47
48 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
49
50 //===----------------------------------------------------------------------===//
51 //                      Pattern Matcher Implementation
52 //===----------------------------------------------------------------------===//
53
54 namespace {
55   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
56   /// SDValue's instead of register numbers for the leaves of the matched
57   /// tree.
58   struct X86ISelAddressMode {
59     enum {
60       RegBase,
61       FrameIndexBase
62     } BaseType;
63
64     struct {            // This is really a union, discriminated by BaseType!
65       SDValue Reg;
66       int FrameIndex;
67     } Base;
68
69     unsigned Scale;
70     SDValue IndexReg; 
71     int32_t Disp;
72     SDValue Segment;
73     GlobalValue *GV;
74     Constant *CP;
75     const char *ES;
76     int JT;
77     unsigned Align;    // CP alignment.
78     unsigned char SymbolFlags;  // X86II::MO_*
79
80     X86ISelAddressMode()
81       : BaseType(RegBase), Scale(1), IndexReg(), Disp(0),
82         Segment(), GV(0), CP(0), ES(0), JT(-1), Align(0),
83         SymbolFlags(X86II::MO_NO_FLAG) {
84     }
85
86     bool hasSymbolicDisplacement() const {
87       return GV != 0 || CP != 0 || ES != 0 || JT != -1;
88     }
89     
90     bool hasBaseOrIndexReg() const {
91       return IndexReg.getNode() != 0 || Base.Reg.getNode() != 0;
92     }
93     
94     /// isRIPRelative - Return true if this addressing mode is already RIP
95     /// relative.
96     bool isRIPRelative() const {
97       if (BaseType != RegBase) return false;
98       if (RegisterSDNode *RegNode =
99             dyn_cast_or_null<RegisterSDNode>(Base.Reg.getNode()))
100         return RegNode->getReg() == X86::RIP;
101       return false;
102     }
103     
104     void setBaseReg(SDValue Reg) {
105       BaseType = RegBase;
106       Base.Reg = Reg;
107     }
108
109     void dump() {
110       errs() << "X86ISelAddressMode " << this << '\n';
111       errs() << "Base.Reg ";
112       if (Base.Reg.getNode() != 0)
113         Base.Reg.getNode()->dump(); 
114       else
115         errs() << "nul";
116       errs() << " Base.FrameIndex " << Base.FrameIndex << '\n'
117              << " Scale" << Scale << '\n'
118              << "IndexReg ";
119       if (IndexReg.getNode() != 0)
120         IndexReg.getNode()->dump();
121       else
122         errs() << "nul"; 
123       errs() << " Disp " << Disp << '\n'
124              << "GV ";
125       if (GV)
126         GV->dump();
127       else
128         errs() << "nul";
129       errs() << " CP ";
130       if (CP)
131         CP->dump();
132       else
133         errs() << "nul";
134       errs() << '\n'
135              << "ES ";
136       if (ES)
137         errs() << ES;
138       else
139         errs() << "nul";
140       errs() << " JT" << JT << " Align" << Align << '\n';
141     }
142   };
143 }
144
145 namespace {
146   //===--------------------------------------------------------------------===//
147   /// ISel - X86 specific code to select X86 machine instructions for
148   /// SelectionDAG operations.
149   ///
150   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
151     /// X86Lowering - This object fully describes how to lower LLVM code to an
152     /// X86-specific SelectionDAG.
153     X86TargetLowering &X86Lowering;
154
155     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
156     /// make the right decision when generating code for different targets.
157     const X86Subtarget *Subtarget;
158
159     /// OptForSize - If true, selector should try to optimize for code size
160     /// instead of performance.
161     bool OptForSize;
162
163   public:
164     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
165       : SelectionDAGISel(tm, OptLevel),
166         X86Lowering(*tm.getTargetLowering()),
167         Subtarget(&tm.getSubtarget<X86Subtarget>()),
168         OptForSize(false) {}
169
170     virtual const char *getPassName() const {
171       return "X86 DAG->DAG Instruction Selection";
172     }
173
174     /// InstructionSelect - This callback is invoked by
175     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
176     virtual void InstructionSelect();
177
178     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
179
180     virtual
181       bool IsLegalAndProfitableToFold(SDNode *N, SDNode *U, SDNode *Root) const;
182
183 // Include the pieces autogenerated from the target description.
184 #include "X86GenDAGISel.inc"
185
186   private:
187     SDNode *Select(SDValue N);
188     SDNode *SelectAtomic64(SDNode *Node, unsigned Opc);
189     SDNode *SelectAtomicLoadAdd(SDNode *Node, EVT NVT);
190
191     bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
192     bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
193     bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
194     bool MatchAddress(SDValue N, X86ISelAddressMode &AM);
195     bool MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
196                                  unsigned Depth);
197     bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
198     bool SelectAddr(SDValue Op, SDValue N, SDValue &Base,
199                     SDValue &Scale, SDValue &Index, SDValue &Disp,
200                     SDValue &Segment);
201     bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
202                        SDValue &Scale, SDValue &Index, SDValue &Disp);
203     bool SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
204                        SDValue &Scale, SDValue &Index, SDValue &Disp);
205     bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
206                              SDValue N, SDValue &Base, SDValue &Scale,
207                              SDValue &Index, SDValue &Disp,
208                              SDValue &Segment,
209                              SDValue &InChain, SDValue &OutChain);
210     bool TryFoldLoad(SDValue P, SDValue N,
211                      SDValue &Base, SDValue &Scale,
212                      SDValue &Index, SDValue &Disp,
213                      SDValue &Segment);
214     void PreprocessForRMW();
215     void PreprocessForFPConvert();
216
217     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
218     /// inline asm expressions.
219     virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
220                                               char ConstraintCode,
221                                               std::vector<SDValue> &OutOps);
222     
223     void EmitSpecialCodeForMain(MachineBasicBlock *BB, MachineFrameInfo *MFI);
224
225     inline void getAddressOperands(X86ISelAddressMode &AM, SDValue &Base, 
226                                    SDValue &Scale, SDValue &Index,
227                                    SDValue &Disp, SDValue &Segment) {
228       Base  = (AM.BaseType == X86ISelAddressMode::FrameIndexBase) ?
229         CurDAG->getTargetFrameIndex(AM.Base.FrameIndex, TLI.getPointerTy()) :
230         AM.Base.Reg;
231       Scale = getI8Imm(AM.Scale);
232       Index = AM.IndexReg;
233       // These are 32-bit even in 64-bit mode since RIP relative offset
234       // is 32-bit.
235       if (AM.GV)
236         Disp = CurDAG->getTargetGlobalAddress(AM.GV, MVT::i32, AM.Disp,
237                                               AM.SymbolFlags);
238       else if (AM.CP)
239         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
240                                              AM.Align, AM.Disp, AM.SymbolFlags);
241       else if (AM.ES)
242         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
243       else if (AM.JT != -1)
244         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
245       else
246         Disp = CurDAG->getTargetConstant(AM.Disp, MVT::i32);
247
248       if (AM.Segment.getNode())
249         Segment = AM.Segment;
250       else
251         Segment = CurDAG->getRegister(0, MVT::i32);
252     }
253
254     /// getI8Imm - Return a target constant with the specified value, of type
255     /// i8.
256     inline SDValue getI8Imm(unsigned Imm) {
257       return CurDAG->getTargetConstant(Imm, MVT::i8);
258     }
259
260     /// getI16Imm - Return a target constant with the specified value, of type
261     /// i16.
262     inline SDValue getI16Imm(unsigned Imm) {
263       return CurDAG->getTargetConstant(Imm, MVT::i16);
264     }
265
266     /// getI32Imm - Return a target constant with the specified value, of type
267     /// i32.
268     inline SDValue getI32Imm(unsigned Imm) {
269       return CurDAG->getTargetConstant(Imm, MVT::i32);
270     }
271
272     /// getGlobalBaseReg - Return an SDNode that returns the value of
273     /// the global base register. Output instructions required to
274     /// initialize the global base register, if necessary.
275     ///
276     SDNode *getGlobalBaseReg();
277
278     /// getTargetMachine - Return a reference to the TargetMachine, casted
279     /// to the target-specific type.
280     const X86TargetMachine &getTargetMachine() {
281       return static_cast<const X86TargetMachine &>(TM);
282     }
283
284     /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
285     /// to the target-specific type.
286     const X86InstrInfo *getInstrInfo() {
287       return getTargetMachine().getInstrInfo();
288     }
289
290 #ifndef NDEBUG
291     unsigned Indent;
292 #endif
293   };
294 }
295
296
297 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
298                                                  SDNode *Root) const {
299   if (OptLevel == CodeGenOpt::None) return false;
300
301   if (U == Root)
302     switch (U->getOpcode()) {
303     default: break;
304     case ISD::ADD:
305     case ISD::ADDC:
306     case ISD::ADDE:
307     case ISD::AND:
308     case ISD::OR:
309     case ISD::XOR: {
310       SDValue Op1 = U->getOperand(1);
311
312       // If the other operand is a 8-bit immediate we should fold the immediate
313       // instead. This reduces code size.
314       // e.g.
315       // movl 4(%esp), %eax
316       // addl $4, %eax
317       // vs.
318       // movl $4, %eax
319       // addl 4(%esp), %eax
320       // The former is 2 bytes shorter. In case where the increment is 1, then
321       // the saving can be 4 bytes (by using incl %eax).
322       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
323         if (Imm->getAPIntValue().isSignedIntN(8))
324           return false;
325
326       // If the other operand is a TLS address, we should fold it instead.
327       // This produces
328       // movl    %gs:0, %eax
329       // leal    i@NTPOFF(%eax), %eax
330       // instead of
331       // movl    $i@NTPOFF, %eax
332       // addl    %gs:0, %eax
333       // if the block also has an access to a second TLS address this will save
334       // a load.
335       // FIXME: This is probably also true for non TLS addresses.
336       if (Op1.getOpcode() == X86ISD::Wrapper) {
337         SDValue Val = Op1.getOperand(0);
338         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
339           return false;
340       }
341     }
342     }
343
344   // Proceed to 'generic' cycle finder code
345   return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
346 }
347
348 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
349 /// and move load below the TokenFactor. Replace store's chain operand with
350 /// load's chain result.
351 static void MoveBelowTokenFactor(SelectionDAG *CurDAG, SDValue Load,
352                                  SDValue Store, SDValue TF) {
353   SmallVector<SDValue, 4> Ops;
354   for (unsigned i = 0, e = TF.getNode()->getNumOperands(); i != e; ++i)
355     if (Load.getNode() == TF.getOperand(i).getNode())
356       Ops.push_back(Load.getOperand(0));
357     else
358       Ops.push_back(TF.getOperand(i));
359   SDValue NewTF = CurDAG->UpdateNodeOperands(TF, &Ops[0], Ops.size());
360   SDValue NewLoad = CurDAG->UpdateNodeOperands(Load, NewTF,
361                                                Load.getOperand(1),
362                                                Load.getOperand(2));
363   CurDAG->UpdateNodeOperands(Store, NewLoad.getValue(1), Store.getOperand(1),
364                              Store.getOperand(2), Store.getOperand(3));
365 }
366
367 /// isRMWLoad - Return true if N is a load that's part of RMW sub-DAG.
368 /// 
369 static bool isRMWLoad(SDValue N, SDValue Chain, SDValue Address,
370                       SDValue &Load) {
371   if (N.getOpcode() == ISD::BIT_CONVERT)
372     N = N.getOperand(0);
373
374   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
375   if (!LD || LD->isVolatile())
376     return false;
377   if (LD->getAddressingMode() != ISD::UNINDEXED)
378     return false;
379
380   ISD::LoadExtType ExtType = LD->getExtensionType();
381   if (ExtType != ISD::NON_EXTLOAD && ExtType != ISD::EXTLOAD)
382     return false;
383
384   if (N.hasOneUse() &&
385       N.getOperand(1) == Address &&
386       N.getNode()->isOperandOf(Chain.getNode())) {
387     Load = N;
388     return true;
389   }
390   return false;
391 }
392
393 /// MoveBelowCallSeqStart - Replace CALLSEQ_START operand with load's chain
394 /// operand and move load below the call's chain operand.
395 static void MoveBelowCallSeqStart(SelectionDAG *CurDAG, SDValue Load,
396                                   SDValue Call, SDValue CallSeqStart) {
397   SmallVector<SDValue, 8> Ops;
398   SDValue Chain = CallSeqStart.getOperand(0);
399   if (Chain.getNode() == Load.getNode())
400     Ops.push_back(Load.getOperand(0));
401   else {
402     assert(Chain.getOpcode() == ISD::TokenFactor &&
403            "Unexpected CallSeqStart chain operand");
404     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
405       if (Chain.getOperand(i).getNode() == Load.getNode())
406         Ops.push_back(Load.getOperand(0));
407       else
408         Ops.push_back(Chain.getOperand(i));
409     SDValue NewChain =
410       CurDAG->getNode(ISD::TokenFactor, Load.getDebugLoc(),
411                       MVT::Other, &Ops[0], Ops.size());
412     Ops.clear();
413     Ops.push_back(NewChain);
414   }
415   for (unsigned i = 1, e = CallSeqStart.getNumOperands(); i != e; ++i)
416     Ops.push_back(CallSeqStart.getOperand(i));
417   CurDAG->UpdateNodeOperands(CallSeqStart, &Ops[0], Ops.size());
418   CurDAG->UpdateNodeOperands(Load, Call.getOperand(0),
419                              Load.getOperand(1), Load.getOperand(2));
420   Ops.clear();
421   Ops.push_back(SDValue(Load.getNode(), 1));
422   for (unsigned i = 1, e = Call.getNode()->getNumOperands(); i != e; ++i)
423     Ops.push_back(Call.getOperand(i));
424   CurDAG->UpdateNodeOperands(Call, &Ops[0], Ops.size());
425 }
426
427 /// isCalleeLoad - Return true if call address is a load and it can be
428 /// moved below CALLSEQ_START and the chains leading up to the call.
429 /// Return the CALLSEQ_START by reference as a second output.
430 static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
431   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
432     return false;
433   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
434   if (!LD ||
435       LD->isVolatile() ||
436       LD->getAddressingMode() != ISD::UNINDEXED ||
437       LD->getExtensionType() != ISD::NON_EXTLOAD)
438     return false;
439
440   // Now let's find the callseq_start.
441   while (Chain.getOpcode() != ISD::CALLSEQ_START) {
442     if (!Chain.hasOneUse())
443       return false;
444     Chain = Chain.getOperand(0);
445   }
446   
447   if (Chain.getOperand(0).getNode() == Callee.getNode())
448     return true;
449   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
450       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()))
451     return true;
452   return false;
453 }
454
455
456 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
457 /// This is only run if not in -O0 mode.
458 /// This allows the instruction selector to pick more read-modify-write
459 /// instructions. This is a common case:
460 ///
461 ///     [Load chain]
462 ///         ^
463 ///         |
464 ///       [Load]
465 ///       ^    ^
466 ///       |    |
467 ///      /      \-
468 ///     /         |
469 /// [TokenFactor] [Op]
470 ///     ^          ^
471 ///     |          |
472 ///      \        /
473 ///       \      /
474 ///       [Store]
475 ///
476 /// The fact the store's chain operand != load's chain will prevent the
477 /// (store (op (load))) instruction from being selected. We can transform it to:
478 ///
479 ///     [Load chain]
480 ///         ^
481 ///         |
482 ///    [TokenFactor]
483 ///         ^
484 ///         |
485 ///       [Load]
486 ///       ^    ^
487 ///       |    |
488 ///       |     \- 
489 ///       |       | 
490 ///       |     [Op]
491 ///       |       ^
492 ///       |       |
493 ///       \      /
494 ///        \    /
495 ///       [Store]
496 void X86DAGToDAGISel::PreprocessForRMW() {
497   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
498          E = CurDAG->allnodes_end(); I != E; ++I) {
499     if (I->getOpcode() == X86ISD::CALL) {
500       /// Also try moving call address load from outside callseq_start to just
501       /// before the call to allow it to be folded.
502       ///
503       ///     [Load chain]
504       ///         ^
505       ///         |
506       ///       [Load]
507       ///       ^    ^
508       ///       |    |
509       ///      /      \--
510       ///     /          |
511       ///[CALLSEQ_START] |
512       ///     ^          |
513       ///     |          |
514       /// [LOAD/C2Reg]   |
515       ///     |          |
516       ///      \        /
517       ///       \      /
518       ///       [CALL]
519       SDValue Chain = I->getOperand(0);
520       SDValue Load  = I->getOperand(1);
521       if (!isCalleeLoad(Load, Chain))
522         continue;
523       MoveBelowCallSeqStart(CurDAG, Load, SDValue(I, 0), Chain);
524       ++NumLoadMoved;
525       continue;
526     }
527
528     if (!ISD::isNON_TRUNCStore(I))
529       continue;
530     SDValue Chain = I->getOperand(0);
531
532     if (Chain.getNode()->getOpcode() != ISD::TokenFactor)
533       continue;
534
535     SDValue N1 = I->getOperand(1);
536     SDValue N2 = I->getOperand(2);
537     if ((N1.getValueType().isFloatingPoint() &&
538          !N1.getValueType().isVector()) ||
539         !N1.hasOneUse())
540       continue;
541
542     bool RModW = false;
543     SDValue Load;
544     unsigned Opcode = N1.getNode()->getOpcode();
545     switch (Opcode) {
546     case ISD::ADD:
547     case ISD::MUL:
548     case ISD::AND:
549     case ISD::OR:
550     case ISD::XOR:
551     case ISD::ADDC:
552     case ISD::ADDE:
553     case ISD::VECTOR_SHUFFLE: {
554       SDValue N10 = N1.getOperand(0);
555       SDValue N11 = N1.getOperand(1);
556       RModW = isRMWLoad(N10, Chain, N2, Load);
557       if (!RModW)
558         RModW = isRMWLoad(N11, Chain, N2, Load);
559       break;
560     }
561     case ISD::SUB:
562     case ISD::SHL:
563     case ISD::SRA:
564     case ISD::SRL:
565     case ISD::ROTL:
566     case ISD::ROTR:
567     case ISD::SUBC:
568     case ISD::SUBE:
569     case X86ISD::SHLD:
570     case X86ISD::SHRD: {
571       SDValue N10 = N1.getOperand(0);
572       RModW = isRMWLoad(N10, Chain, N2, Load);
573       break;
574     }
575     }
576
577     if (RModW) {
578       MoveBelowTokenFactor(CurDAG, Load, SDValue(I, 0), Chain);
579       ++NumLoadMoved;
580     }
581   }
582 }
583
584
585 /// PreprocessForFPConvert - Walk over the dag lowering fpround and fpextend
586 /// nodes that target the FP stack to be store and load to the stack.  This is a
587 /// gross hack.  We would like to simply mark these as being illegal, but when
588 /// we do that, legalize produces these when it expands calls, then expands
589 /// these in the same legalize pass.  We would like dag combine to be able to
590 /// hack on these between the call expansion and the node legalization.  As such
591 /// this pass basically does "really late" legalization of these inline with the
592 /// X86 isel pass.
593 void X86DAGToDAGISel::PreprocessForFPConvert() {
594   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
595        E = CurDAG->allnodes_end(); I != E; ) {
596     SDNode *N = I++;  // Preincrement iterator to avoid invalidation issues.
597     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
598       continue;
599     
600     // If the source and destination are SSE registers, then this is a legal
601     // conversion that should not be lowered.
602     EVT SrcVT = N->getOperand(0).getValueType();
603     EVT DstVT = N->getValueType(0);
604     bool SrcIsSSE = X86Lowering.isScalarFPTypeInSSEReg(SrcVT);
605     bool DstIsSSE = X86Lowering.isScalarFPTypeInSSEReg(DstVT);
606     if (SrcIsSSE && DstIsSSE)
607       continue;
608
609     if (!SrcIsSSE && !DstIsSSE) {
610       // If this is an FPStack extension, it is a noop.
611       if (N->getOpcode() == ISD::FP_EXTEND)
612         continue;
613       // If this is a value-preserving FPStack truncation, it is a noop.
614       if (N->getConstantOperandVal(1))
615         continue;
616     }
617    
618     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
619     // FPStack has extload and truncstore.  SSE can fold direct loads into other
620     // operations.  Based on this, decide what we want to do.
621     EVT MemVT;
622     if (N->getOpcode() == ISD::FP_ROUND)
623       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
624     else
625       MemVT = SrcIsSSE ? SrcVT : DstVT;
626     
627     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
628     DebugLoc dl = N->getDebugLoc();
629     
630     // FIXME: optimize the case where the src/dest is a load or store?
631     SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
632                                           N->getOperand(0),
633                                           MemTmp, NULL, 0, MemVT);
634     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
635                                         NULL, 0, MemVT);
636
637     // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
638     // extload we created.  This will cause general havok on the dag because
639     // anything below the conversion could be folded into other existing nodes.
640     // To avoid invalidating 'I', back it up to the convert node.
641     --I;
642     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
643     
644     // Now that we did that, the node is dead.  Increment the iterator to the
645     // next node to process, then delete N.
646     ++I;
647     CurDAG->DeleteNode(N);
648   }  
649 }
650
651 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
652 /// when it has created a SelectionDAG for us to codegen.
653 void X86DAGToDAGISel::InstructionSelect() {
654   const Function *F = MF->getFunction();
655   OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
656
657   DEBUG(BB->dump());
658   if (OptLevel != CodeGenOpt::None)
659     PreprocessForRMW();
660
661   // FIXME: This should only happen when not compiled with -O0.
662   PreprocessForFPConvert();
663
664   // Codegen the basic block.
665 #ifndef NDEBUG
666   DEBUG(errs() << "===== Instruction selection begins:\n");
667   Indent = 0;
668 #endif
669   SelectRoot(*CurDAG);
670 #ifndef NDEBUG
671   DEBUG(errs() << "===== Instruction selection ends:\n");
672 #endif
673
674   CurDAG->RemoveDeadNodes();
675 }
676
677 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
678 /// the main function.
679 void X86DAGToDAGISel::EmitSpecialCodeForMain(MachineBasicBlock *BB,
680                                              MachineFrameInfo *MFI) {
681   const TargetInstrInfo *TII = TM.getInstrInfo();
682   if (Subtarget->isTargetCygMing())
683     BuildMI(BB, DebugLoc::getUnknownLoc(),
684             TII->get(X86::CALLpcrel32)).addExternalSymbol("__main");
685 }
686
687 void X86DAGToDAGISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
688   // If this is main, emit special code for main.
689   MachineBasicBlock *BB = MF.begin();
690   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
691     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
692 }
693
694
695 bool X86DAGToDAGISel::MatchSegmentBaseAddress(SDValue N,
696                                               X86ISelAddressMode &AM) {
697   assert(N.getOpcode() == X86ISD::SegmentBaseAddress);
698   SDValue Segment = N.getOperand(0);
699
700   if (AM.Segment.getNode() == 0) {
701     AM.Segment = Segment;
702     return false;
703   }
704
705   return true;
706 }
707
708 bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
709   // This optimization is valid because the GNU TLS model defines that
710   // gs:0 (or fs:0 on X86-64) contains its own address.
711   // For more information see http://people.redhat.com/drepper/tls.pdf
712
713   SDValue Address = N.getOperand(1);
714   if (Address.getOpcode() == X86ISD::SegmentBaseAddress &&
715       !MatchSegmentBaseAddress (Address, AM))
716     return false;
717
718   return true;
719 }
720
721 /// MatchWrapper - Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes
722 /// into an addressing mode.  These wrap things that will resolve down into a
723 /// symbol reference.  If no match is possible, this returns true, otherwise it
724 /// returns false.
725 bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
726   // If the addressing mode already has a symbol as the displacement, we can
727   // never match another symbol.
728   if (AM.hasSymbolicDisplacement())
729     return true;
730
731   SDValue N0 = N.getOperand(0);
732   CodeModel::Model M = TM.getCodeModel();
733
734   // Handle X86-64 rip-relative addresses.  We check this before checking direct
735   // folding because RIP is preferable to non-RIP accesses.
736   if (Subtarget->is64Bit() &&
737       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
738       // they cannot be folded into immediate fields.
739       // FIXME: This can be improved for kernel and other models?
740       (M == CodeModel::Small || M == CodeModel::Kernel) &&
741       // Base and index reg must be 0 in order to use %rip as base and lowering
742       // must allow RIP.
743       !AM.hasBaseOrIndexReg() && N.getOpcode() == X86ISD::WrapperRIP) {
744     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
745       int64_t Offset = AM.Disp + G->getOffset();
746       if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
747       AM.GV = G->getGlobal();
748       AM.Disp = Offset;
749       AM.SymbolFlags = G->getTargetFlags();
750     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
751       int64_t Offset = AM.Disp + CP->getOffset();
752       if (!X86::isOffsetSuitableForCodeModel(Offset, M)) return true;
753       AM.CP = CP->getConstVal();
754       AM.Align = CP->getAlignment();
755       AM.Disp = Offset;
756       AM.SymbolFlags = CP->getTargetFlags();
757     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
758       AM.ES = S->getSymbol();
759       AM.SymbolFlags = S->getTargetFlags();
760     } else {
761       JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
762       AM.JT = J->getIndex();
763       AM.SymbolFlags = J->getTargetFlags();
764     }
765
766     if (N.getOpcode() == X86ISD::WrapperRIP)
767       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
768     return false;
769   }
770
771   // Handle the case when globals fit in our immediate field: This is true for
772   // X86-32 always and X86-64 when in -static -mcmodel=small mode.  In 64-bit
773   // mode, this results in a non-RIP-relative computation.
774   if (!Subtarget->is64Bit() ||
775       ((M == CodeModel::Small || M == CodeModel::Kernel) &&
776        TM.getRelocationModel() == Reloc::Static)) {
777     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
778       AM.GV = G->getGlobal();
779       AM.Disp += G->getOffset();
780       AM.SymbolFlags = G->getTargetFlags();
781     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
782       AM.CP = CP->getConstVal();
783       AM.Align = CP->getAlignment();
784       AM.Disp += CP->getOffset();
785       AM.SymbolFlags = CP->getTargetFlags();
786     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
787       AM.ES = S->getSymbol();
788       AM.SymbolFlags = S->getTargetFlags();
789     } else {
790       JumpTableSDNode *J = cast<JumpTableSDNode>(N0);
791       AM.JT = J->getIndex();
792       AM.SymbolFlags = J->getTargetFlags();
793     }
794     return false;
795   }
796
797   return true;
798 }
799
800 /// MatchAddress - Add the specified node to the specified addressing mode,
801 /// returning true if it cannot be done.  This just pattern matches for the
802 /// addressing mode.
803 bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM) {
804   if (MatchAddressRecursively(N, AM, 0))
805     return true;
806
807   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
808   // a smaller encoding and avoids a scaled-index.
809   if (AM.Scale == 2 &&
810       AM.BaseType == X86ISelAddressMode::RegBase &&
811       AM.Base.Reg.getNode() == 0) {
812     AM.Base.Reg = AM.IndexReg;
813     AM.Scale = 1;
814   }
815
816   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
817   // because it has a smaller encoding.
818   // TODO: Which other code models can use this?
819   if (TM.getCodeModel() == CodeModel::Small &&
820       Subtarget->is64Bit() &&
821       AM.Scale == 1 &&
822       AM.BaseType == X86ISelAddressMode::RegBase &&
823       AM.Base.Reg.getNode() == 0 &&
824       AM.IndexReg.getNode() == 0 &&
825       AM.SymbolFlags == X86II::MO_NO_FLAG &&
826       AM.hasSymbolicDisplacement())
827     AM.Base.Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
828
829   return false;
830 }
831
832 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
833                                               unsigned Depth) {
834   bool is64Bit = Subtarget->is64Bit();
835   DebugLoc dl = N.getDebugLoc();
836   DEBUG({
837       errs() << "MatchAddress: ";
838       AM.dump();
839     });
840   // Limit recursion.
841   if (Depth > 5)
842     return MatchAddressBase(N, AM);
843
844   CodeModel::Model M = TM.getCodeModel();
845
846   // If this is already a %rip relative address, we can only merge immediates
847   // into it.  Instead of handling this in every case, we handle it here.
848   // RIP relative addressing: %rip + 32-bit displacement!
849   if (AM.isRIPRelative()) {
850     // FIXME: JumpTable and ExternalSymbol address currently don't like
851     // displacements.  It isn't very important, but this should be fixed for
852     // consistency.
853     if (!AM.ES && AM.JT != -1) return true;
854
855     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N)) {
856       int64_t Val = AM.Disp + Cst->getSExtValue();
857       if (X86::isOffsetSuitableForCodeModel(Val, M,
858                                             AM.hasSymbolicDisplacement())) {
859         AM.Disp = Val;
860         return false;
861       }
862     }
863     return true;
864   }
865
866   switch (N.getOpcode()) {
867   default: break;
868   case ISD::Constant: {
869     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
870     if (!is64Bit ||
871         X86::isOffsetSuitableForCodeModel(AM.Disp + Val, M,
872                                           AM.hasSymbolicDisplacement())) {
873       AM.Disp += Val;
874       return false;
875     }
876     break;
877   }
878
879   case X86ISD::SegmentBaseAddress:
880     if (!MatchSegmentBaseAddress(N, AM))
881       return false;
882     break;
883
884   case X86ISD::Wrapper:
885   case X86ISD::WrapperRIP:
886     if (!MatchWrapper(N, AM))
887       return false;
888     break;
889
890   case ISD::LOAD:
891     if (!MatchLoad(N, AM))
892       return false;
893     break;
894
895   case ISD::FrameIndex:
896     if (AM.BaseType == X86ISelAddressMode::RegBase
897         && AM.Base.Reg.getNode() == 0) {
898       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
899       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
900       return false;
901     }
902     break;
903
904   case ISD::SHL:
905     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1)
906       break;
907       
908     if (ConstantSDNode
909           *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
910       unsigned Val = CN->getZExtValue();
911       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
912       // that the base operand remains free for further matching. If
913       // the base doesn't end up getting used, a post-processing step
914       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
915       if (Val == 1 || Val == 2 || Val == 3) {
916         AM.Scale = 1 << Val;
917         SDValue ShVal = N.getNode()->getOperand(0);
918
919         // Okay, we know that we have a scale by now.  However, if the scaled
920         // value is an add of something and a constant, we can fold the
921         // constant into the disp field here.
922         if (ShVal.getNode()->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
923             isa<ConstantSDNode>(ShVal.getNode()->getOperand(1))) {
924           AM.IndexReg = ShVal.getNode()->getOperand(0);
925           ConstantSDNode *AddVal =
926             cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
927           uint64_t Disp = AM.Disp + (AddVal->getSExtValue() << Val);
928           if (!is64Bit ||
929               X86::isOffsetSuitableForCodeModel(Disp, M,
930                                                 AM.hasSymbolicDisplacement()))
931             AM.Disp = Disp;
932           else
933             AM.IndexReg = ShVal;
934         } else {
935           AM.IndexReg = ShVal;
936         }
937         return false;
938       }
939     break;
940     }
941
942   case ISD::SMUL_LOHI:
943   case ISD::UMUL_LOHI:
944     // A mul_lohi where we need the low part can be folded as a plain multiply.
945     if (N.getResNo() != 0) break;
946     // FALL THROUGH
947   case ISD::MUL:
948   case X86ISD::MUL_IMM:
949     // X*[3,5,9] -> X+X*[2,4,8]
950     if (AM.BaseType == X86ISelAddressMode::RegBase &&
951         AM.Base.Reg.getNode() == 0 &&
952         AM.IndexReg.getNode() == 0) {
953       if (ConstantSDNode
954             *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
955         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
956             CN->getZExtValue() == 9) {
957           AM.Scale = unsigned(CN->getZExtValue())-1;
958
959           SDValue MulVal = N.getNode()->getOperand(0);
960           SDValue Reg;
961
962           // Okay, we know that we have a scale by now.  However, if the scaled
963           // value is an add of something and a constant, we can fold the
964           // constant into the disp field here.
965           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
966               isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
967             Reg = MulVal.getNode()->getOperand(0);
968             ConstantSDNode *AddVal =
969               cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
970             uint64_t Disp = AM.Disp + AddVal->getSExtValue() *
971                                       CN->getZExtValue();
972             if (!is64Bit ||
973                 X86::isOffsetSuitableForCodeModel(Disp, M,
974                                                   AM.hasSymbolicDisplacement()))
975               AM.Disp = Disp;
976             else
977               Reg = N.getNode()->getOperand(0);
978           } else {
979             Reg = N.getNode()->getOperand(0);
980           }
981
982           AM.IndexReg = AM.Base.Reg = Reg;
983           return false;
984         }
985     }
986     break;
987
988   case ISD::SUB: {
989     // Given A-B, if A can be completely folded into the address and
990     // the index field with the index field unused, use -B as the index.
991     // This is a win if a has multiple parts that can be folded into
992     // the address. Also, this saves a mov if the base register has
993     // other uses, since it avoids a two-address sub instruction, however
994     // it costs an additional mov if the index register has other uses.
995
996     // Test if the LHS of the sub can be folded.
997     X86ISelAddressMode Backup = AM;
998     if (MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
999       AM = Backup;
1000       break;
1001     }
1002     // Test if the index field is free for use.
1003     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1004       AM = Backup;
1005       break;
1006     }
1007     int Cost = 0;
1008     SDValue RHS = N.getNode()->getOperand(1);
1009     // If the RHS involves a register with multiple uses, this
1010     // transformation incurs an extra mov, due to the neg instruction
1011     // clobbering its operand.
1012     if (!RHS.getNode()->hasOneUse() ||
1013         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1014         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1015         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1016         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1017          RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1018       ++Cost;
1019     // If the base is a register with multiple uses, this
1020     // transformation may save a mov.
1021     if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1022          AM.Base.Reg.getNode() &&
1023          !AM.Base.Reg.getNode()->hasOneUse()) ||
1024         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1025       --Cost;
1026     // If the folded LHS was interesting, this transformation saves
1027     // address arithmetic.
1028     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1029         ((AM.Disp != 0) && (Backup.Disp == 0)) +
1030         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1031       --Cost;
1032     // If it doesn't look like it may be an overall win, don't do it.
1033     if (Cost >= 0) {
1034       AM = Backup;
1035       break;
1036     }
1037
1038     // Ok, the transformation is legal and appears profitable. Go for it.
1039     SDValue Zero = CurDAG->getConstant(0, N.getValueType());
1040     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1041     AM.IndexReg = Neg;
1042     AM.Scale = 1;
1043
1044     // Insert the new nodes into the topological ordering.
1045     if (Zero.getNode()->getNodeId() == -1 ||
1046         Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1047       CurDAG->RepositionNode(N.getNode(), Zero.getNode());
1048       Zero.getNode()->setNodeId(N.getNode()->getNodeId());
1049     }
1050     if (Neg.getNode()->getNodeId() == -1 ||
1051         Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1052       CurDAG->RepositionNode(N.getNode(), Neg.getNode());
1053       Neg.getNode()->setNodeId(N.getNode()->getNodeId());
1054     }
1055     return false;
1056   }
1057
1058   case ISD::ADD: {
1059     X86ISelAddressMode Backup = AM;
1060     if (!MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1) &&
1061         !MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1))
1062       return false;
1063     AM = Backup;
1064     if (!MatchAddressRecursively(N.getNode()->getOperand(1), AM, Depth+1) &&
1065         !MatchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1))
1066       return false;
1067     AM = Backup;
1068
1069     // If we couldn't fold both operands into the address at the same time,
1070     // see if we can just put each operand into a register and fold at least
1071     // the add.
1072     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1073         !AM.Base.Reg.getNode() &&
1074         !AM.IndexReg.getNode()) {
1075       AM.Base.Reg = N.getNode()->getOperand(0);
1076       AM.IndexReg = N.getNode()->getOperand(1);
1077       AM.Scale = 1;
1078       return false;
1079     }
1080     break;
1081   }
1082
1083   case ISD::OR:
1084     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
1085     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1086       X86ISelAddressMode Backup = AM;
1087       uint64_t Offset = CN->getSExtValue();
1088       // Start with the LHS as an addr mode.
1089       if (!MatchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1090           // Address could not have picked a GV address for the displacement.
1091           AM.GV == NULL &&
1092           // On x86-64, the resultant disp must fit in 32-bits.
1093           (!is64Bit ||
1094            X86::isOffsetSuitableForCodeModel(AM.Disp + Offset, M,
1095                                              AM.hasSymbolicDisplacement())) &&
1096           // Check to see if the LHS & C is zero.
1097           CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
1098         AM.Disp += Offset;
1099         return false;
1100       }
1101       AM = Backup;
1102     }
1103     break;
1104       
1105   case ISD::AND: {
1106     // Perform some heroic transforms on an and of a constant-count shift
1107     // with a constant to enable use of the scaled offset field.
1108
1109     SDValue Shift = N.getOperand(0);
1110     if (Shift.getNumOperands() != 2) break;
1111
1112     // Scale must not be used already.
1113     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
1114
1115     SDValue X = Shift.getOperand(0);
1116     ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
1117     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
1118     if (!C1 || !C2) break;
1119
1120     // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
1121     // allows us to convert the shift and and into an h-register extract and
1122     // a scaled index.
1123     if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
1124       unsigned ScaleLog = 8 - C1->getZExtValue();
1125       if (ScaleLog > 0 && ScaleLog < 4 &&
1126           C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
1127         SDValue Eight = CurDAG->getConstant(8, MVT::i8);
1128         SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
1129         SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1130                                       X, Eight);
1131         SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
1132                                       Srl, Mask);
1133         SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
1134         SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1135                                       And, ShlCount);
1136
1137         // Insert the new nodes into the topological ordering.
1138         if (Eight.getNode()->getNodeId() == -1 ||
1139             Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1140           CurDAG->RepositionNode(X.getNode(), Eight.getNode());
1141           Eight.getNode()->setNodeId(X.getNode()->getNodeId());
1142         }
1143         if (Mask.getNode()->getNodeId() == -1 ||
1144             Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1145           CurDAG->RepositionNode(X.getNode(), Mask.getNode());
1146           Mask.getNode()->setNodeId(X.getNode()->getNodeId());
1147         }
1148         if (Srl.getNode()->getNodeId() == -1 ||
1149             Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1150           CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
1151           Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
1152         }
1153         if (And.getNode()->getNodeId() == -1 ||
1154             And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1155           CurDAG->RepositionNode(N.getNode(), And.getNode());
1156           And.getNode()->setNodeId(N.getNode()->getNodeId());
1157         }
1158         if (ShlCount.getNode()->getNodeId() == -1 ||
1159             ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1160           CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
1161           ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
1162         }
1163         if (Shl.getNode()->getNodeId() == -1 ||
1164             Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1165           CurDAG->RepositionNode(N.getNode(), Shl.getNode());
1166           Shl.getNode()->setNodeId(N.getNode()->getNodeId());
1167         }
1168         CurDAG->ReplaceAllUsesWith(N, Shl);
1169         AM.IndexReg = And;
1170         AM.Scale = (1 << ScaleLog);
1171         return false;
1172       }
1173     }
1174
1175     // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
1176     // allows us to fold the shift into this addressing mode.
1177     if (Shift.getOpcode() != ISD::SHL) break;
1178
1179     // Not likely to be profitable if either the AND or SHIFT node has more
1180     // than one use (unless all uses are for address computation). Besides,
1181     // isel mechanism requires their node ids to be reused.
1182     if (!N.hasOneUse() || !Shift.hasOneUse())
1183       break;
1184     
1185     // Verify that the shift amount is something we can fold.
1186     unsigned ShiftCst = C1->getZExtValue();
1187     if (ShiftCst != 1 && ShiftCst != 2 && ShiftCst != 3)
1188       break;
1189     
1190     // Get the new AND mask, this folds to a constant.
1191     SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
1192                                          SDValue(C2, 0), SDValue(C1, 0));
1193     SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X, 
1194                                      NewANDMask);
1195     SDValue NewSHIFT = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
1196                                        NewAND, SDValue(C1, 0));
1197
1198     // Insert the new nodes into the topological ordering.
1199     if (C1->getNodeId() > X.getNode()->getNodeId()) {
1200       CurDAG->RepositionNode(X.getNode(), C1);
1201       C1->setNodeId(X.getNode()->getNodeId());
1202     }
1203     if (NewANDMask.getNode()->getNodeId() == -1 ||
1204         NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
1205       CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
1206       NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
1207     }
1208     if (NewAND.getNode()->getNodeId() == -1 ||
1209         NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
1210       CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
1211       NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
1212     }
1213     if (NewSHIFT.getNode()->getNodeId() == -1 ||
1214         NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
1215       CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
1216       NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
1217     }
1218
1219     CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
1220     
1221     AM.Scale = 1 << ShiftCst;
1222     AM.IndexReg = NewAND;
1223     return false;
1224   }
1225   }
1226
1227   return MatchAddressBase(N, AM);
1228 }
1229
1230 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
1231 /// specified addressing mode without any further recursion.
1232 bool X86DAGToDAGISel::MatchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1233   // Is the base register already occupied?
1234   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
1235     // If so, check to see if the scale index register is set.
1236     if (AM.IndexReg.getNode() == 0) {
1237       AM.IndexReg = N;
1238       AM.Scale = 1;
1239       return false;
1240     }
1241
1242     // Otherwise, we cannot select it.
1243     return true;
1244   }
1245
1246   // Default, generate it as a register.
1247   AM.BaseType = X86ISelAddressMode::RegBase;
1248   AM.Base.Reg = N;
1249   return false;
1250 }
1251
1252 /// SelectAddr - returns true if it is able pattern match an addressing mode.
1253 /// It returns the operands which make up the maximal addressing mode it can
1254 /// match by reference.
1255 bool X86DAGToDAGISel::SelectAddr(SDValue Op, SDValue N, SDValue &Base,
1256                                  SDValue &Scale, SDValue &Index,
1257                                  SDValue &Disp, SDValue &Segment) {
1258   X86ISelAddressMode AM;
1259   bool Done = false;
1260   if (AvoidDupAddrCompute && !N.hasOneUse()) {
1261     unsigned Opcode = N.getOpcode();
1262     if (Opcode != ISD::Constant && Opcode != ISD::FrameIndex &&
1263         Opcode != X86ISD::Wrapper && Opcode != X86ISD::WrapperRIP) {
1264       // If we are able to fold N into addressing mode, then we'll allow it even
1265       // if N has multiple uses. In general, addressing computation is used as
1266       // addresses by all of its uses. But watch out for CopyToReg uses, that
1267       // means the address computation is liveout. It will be computed by a LEA
1268       // so we want to avoid computing the address twice.
1269       for (SDNode::use_iterator UI = N.getNode()->use_begin(),
1270              UE = N.getNode()->use_end(); UI != UE; ++UI) {
1271         if (UI->getOpcode() == ISD::CopyToReg) {
1272           MatchAddressBase(N, AM);
1273           Done = true;
1274           break;
1275         }
1276       }
1277     }
1278   }
1279
1280   if (!Done && MatchAddress(N, AM))
1281     return false;
1282
1283   EVT VT = N.getValueType();
1284   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1285     if (!AM.Base.Reg.getNode())
1286       AM.Base.Reg = CurDAG->getRegister(0, VT);
1287   }
1288
1289   if (!AM.IndexReg.getNode())
1290     AM.IndexReg = CurDAG->getRegister(0, VT);
1291
1292   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1293   return true;
1294 }
1295
1296 /// SelectScalarSSELoad - Match a scalar SSE load.  In particular, we want to
1297 /// match a load whose top elements are either undef or zeros.  The load flavor
1298 /// is derived from the type of N, which is either v4f32 or v2f64.
1299 bool X86DAGToDAGISel::SelectScalarSSELoad(SDValue Op, SDValue Pred,
1300                                           SDValue N, SDValue &Base,
1301                                           SDValue &Scale, SDValue &Index,
1302                                           SDValue &Disp, SDValue &Segment,
1303                                           SDValue &InChain,
1304                                           SDValue &OutChain) {
1305   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1306     InChain = N.getOperand(0).getValue(1);
1307     if (ISD::isNON_EXTLoad(InChain.getNode()) &&
1308         InChain.getValue(0).hasOneUse() &&
1309         N.hasOneUse() &&
1310         IsLegalAndProfitableToFold(N.getNode(), Pred.getNode(), Op.getNode())) {
1311       LoadSDNode *LD = cast<LoadSDNode>(InChain);
1312       if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1313         return false;
1314       OutChain = LD->getChain();
1315       return true;
1316     }
1317   }
1318
1319   // Also handle the case where we explicitly require zeros in the top
1320   // elements.  This is a vector shuffle from the zero vector.
1321   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1322       // Check to see if the top elements are all zeros (or bitcast of zeros).
1323       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 
1324       N.getOperand(0).getNode()->hasOneUse() &&
1325       ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1326       N.getOperand(0).getOperand(0).hasOneUse()) {
1327     // Okay, this is a zero extending load.  Fold it.
1328     LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1329     if (!SelectAddr(Op, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1330       return false;
1331     OutChain = LD->getChain();
1332     InChain = SDValue(LD, 1);
1333     return true;
1334   }
1335   return false;
1336 }
1337
1338
1339 /// SelectLEAAddr - it calls SelectAddr and determines if the maximal addressing
1340 /// mode it matches can be cost effectively emitted as an LEA instruction.
1341 bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
1342                                     SDValue &Base, SDValue &Scale,
1343                                     SDValue &Index, SDValue &Disp) {
1344   X86ISelAddressMode AM;
1345
1346   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1347   // segments.
1348   SDValue Copy = AM.Segment;
1349   SDValue T = CurDAG->getRegister(0, MVT::i32);
1350   AM.Segment = T;
1351   if (MatchAddress(N, AM))
1352     return false;
1353   assert (T == AM.Segment);
1354   AM.Segment = Copy;
1355
1356   EVT VT = N.getValueType();
1357   unsigned Complexity = 0;
1358   if (AM.BaseType == X86ISelAddressMode::RegBase)
1359     if (AM.Base.Reg.getNode())
1360       Complexity = 1;
1361     else
1362       AM.Base.Reg = CurDAG->getRegister(0, VT);
1363   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1364     Complexity = 4;
1365
1366   if (AM.IndexReg.getNode())
1367     Complexity++;
1368   else
1369     AM.IndexReg = CurDAG->getRegister(0, VT);
1370
1371   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1372   // a simple shift.
1373   if (AM.Scale > 1)
1374     Complexity++;
1375
1376   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1377   // to a LEA. This is determined with some expermentation but is by no means
1378   // optimal (especially for code size consideration). LEA is nice because of
1379   // its three-address nature. Tweak the cost function again when we can run
1380   // convertToThreeAddress() at register allocation time.
1381   if (AM.hasSymbolicDisplacement()) {
1382     // For X86-64, we should always use lea to materialize RIP relative
1383     // addresses.
1384     if (Subtarget->is64Bit())
1385       Complexity = 4;
1386     else
1387       Complexity += 2;
1388   }
1389
1390   if (AM.Disp && (AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
1391     Complexity++;
1392
1393   // If it isn't worth using an LEA, reject it.
1394   if (Complexity <= 2)
1395     return false;
1396   
1397   SDValue Segment;
1398   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1399   return true;
1400 }
1401
1402 /// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
1403 bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
1404                                         SDValue &Scale, SDValue &Index,
1405                                         SDValue &Disp) {
1406   assert(Op.getOpcode() == X86ISD::TLSADDR);
1407   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1408   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1409   
1410   X86ISelAddressMode AM;
1411   AM.GV = GA->getGlobal();
1412   AM.Disp += GA->getOffset();
1413   AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
1414   AM.SymbolFlags = GA->getTargetFlags();
1415
1416   if (N.getValueType() == MVT::i32) {
1417     AM.Scale = 1;
1418     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1419   } else {
1420     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1421   }
1422   
1423   SDValue Segment;
1424   getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
1425   return true;
1426 }
1427
1428
1429 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
1430                                   SDValue &Base, SDValue &Scale,
1431                                   SDValue &Index, SDValue &Disp,
1432                                   SDValue &Segment) {
1433   if (ISD::isNON_EXTLoad(N.getNode()) &&
1434       N.hasOneUse() &&
1435       IsLegalAndProfitableToFold(N.getNode(), P.getNode(), P.getNode()))
1436     return SelectAddr(P, N.getOperand(1), Base, Scale, Index, Disp, Segment);
1437   return false;
1438 }
1439
1440 /// getGlobalBaseReg - Return an SDNode that returns the value of
1441 /// the global base register. Output instructions required to
1442 /// initialize the global base register, if necessary.
1443 ///
1444 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1445   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1446   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
1447 }
1448
1449 static SDNode *FindCallStartFromCall(SDNode *Node) {
1450   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
1451     assert(Node->getOperand(0).getValueType() == MVT::Other &&
1452          "Node doesn't have a token chain argument!");
1453   return FindCallStartFromCall(Node->getOperand(0).getNode());
1454 }
1455
1456 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
1457   SDValue Chain = Node->getOperand(0);
1458   SDValue In1 = Node->getOperand(1);
1459   SDValue In2L = Node->getOperand(2);
1460   SDValue In2H = Node->getOperand(3);
1461   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1462   if (!SelectAddr(In1, In1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1463     return NULL;
1464   SDValue LSI = Node->getOperand(4);    // MemOperand
1465   const SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, In2L, In2H, LSI, Chain};
1466   return CurDAG->getTargetNode(Opc, Node->getDebugLoc(),
1467                                MVT::i32, MVT::i32, MVT::Other, Ops,
1468                                array_lengthof(Ops));
1469 }
1470
1471 SDNode *X86DAGToDAGISel::SelectAtomicLoadAdd(SDNode *Node, EVT NVT) {
1472   if (Node->hasAnyUseOfValue(0))
1473     return 0;
1474
1475   // Optimize common patterns for __sync_add_and_fetch and
1476   // __sync_sub_and_fetch where the result is not used. This allows us
1477   // to use "lock" version of add, sub, inc, dec instructions.
1478   // FIXME: Do not use special instructions but instead add the "lock"
1479   // prefix to the target node somehow. The extra information will then be
1480   // transferred to machine instruction and it denotes the prefix.
1481   SDValue Chain = Node->getOperand(0);
1482   SDValue Ptr = Node->getOperand(1);
1483   SDValue Val = Node->getOperand(2);
1484   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1485   if (!SelectAddr(Ptr, Ptr, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4))
1486     return 0;
1487
1488   bool isInc = false, isDec = false, isSub = false, isCN = false;
1489   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val);
1490   if (CN) {
1491     isCN = true;
1492     int64_t CNVal = CN->getSExtValue();
1493     if (CNVal == 1)
1494       isInc = true;
1495     else if (CNVal == -1)
1496       isDec = true;
1497     else if (CNVal >= 0)
1498       Val = CurDAG->getTargetConstant(CNVal, NVT);
1499     else {
1500       isSub = true;
1501       Val = CurDAG->getTargetConstant(-CNVal, NVT);
1502     }
1503   } else if (Val.hasOneUse() &&
1504              Val.getOpcode() == ISD::SUB &&
1505              X86::isZeroNode(Val.getOperand(0))) {
1506     isSub = true;
1507     Val = Val.getOperand(1);
1508   }
1509
1510   unsigned Opc = 0;
1511   switch (NVT.getSimpleVT().SimpleTy) {
1512   default: return 0;
1513   case MVT::i8:
1514     if (isInc)
1515       Opc = X86::LOCK_INC8m;
1516     else if (isDec)
1517       Opc = X86::LOCK_DEC8m;
1518     else if (isSub) {
1519       if (isCN)
1520         Opc = X86::LOCK_SUB8mi;
1521       else
1522         Opc = X86::LOCK_SUB8mr;
1523     } else {
1524       if (isCN)
1525         Opc = X86::LOCK_ADD8mi;
1526       else
1527         Opc = X86::LOCK_ADD8mr;
1528     }
1529     break;
1530   case MVT::i16:
1531     if (isInc)
1532       Opc = X86::LOCK_INC16m;
1533     else if (isDec)
1534       Opc = X86::LOCK_DEC16m;
1535     else if (isSub) {
1536       if (isCN) {
1537         if (Predicate_i16immSExt8(Val.getNode()))
1538           Opc = X86::LOCK_SUB16mi8;
1539         else
1540           Opc = X86::LOCK_SUB16mi;
1541       } else
1542         Opc = X86::LOCK_SUB16mr;
1543     } else {
1544       if (isCN) {
1545         if (Predicate_i16immSExt8(Val.getNode()))
1546           Opc = X86::LOCK_ADD16mi8;
1547         else
1548           Opc = X86::LOCK_ADD16mi;
1549       } else
1550         Opc = X86::LOCK_ADD16mr;
1551     }
1552     break;
1553   case MVT::i32:
1554     if (isInc)
1555       Opc = X86::LOCK_INC32m;
1556     else if (isDec)
1557       Opc = X86::LOCK_DEC32m;
1558     else if (isSub) {
1559       if (isCN) {
1560         if (Predicate_i32immSExt8(Val.getNode()))
1561           Opc = X86::LOCK_SUB32mi8;
1562         else
1563           Opc = X86::LOCK_SUB32mi;
1564       } else
1565         Opc = X86::LOCK_SUB32mr;
1566     } else {
1567       if (isCN) {
1568         if (Predicate_i32immSExt8(Val.getNode()))
1569           Opc = X86::LOCK_ADD32mi8;
1570         else
1571           Opc = X86::LOCK_ADD32mi;
1572       } else
1573         Opc = X86::LOCK_ADD32mr;
1574     }
1575     break;
1576   case MVT::i64:
1577     if (isInc)
1578       Opc = X86::LOCK_INC64m;
1579     else if (isDec)
1580       Opc = X86::LOCK_DEC64m;
1581     else if (isSub) {
1582       Opc = X86::LOCK_SUB64mr;
1583       if (isCN) {
1584         if (Predicate_i64immSExt8(Val.getNode()))
1585           Opc = X86::LOCK_SUB64mi8;
1586         else if (Predicate_i64immSExt32(Val.getNode()))
1587           Opc = X86::LOCK_SUB64mi32;
1588       }
1589     } else {
1590       Opc = X86::LOCK_ADD64mr;
1591       if (isCN) {
1592         if (Predicate_i64immSExt8(Val.getNode()))
1593           Opc = X86::LOCK_ADD64mi8;
1594         else if (Predicate_i64immSExt32(Val.getNode()))
1595           Opc = X86::LOCK_ADD64mi32;
1596       }
1597     }
1598     break;
1599   }
1600
1601   DebugLoc dl = Node->getDebugLoc();
1602   SDValue Undef = SDValue(CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
1603                                                 dl, NVT), 0);
1604   SDValue MemOp = CurDAG->getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
1605   if (isInc || isDec) {
1606     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, MemOp, Chain };
1607     SDValue Ret = SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Other, Ops, 7), 0);
1608     SDValue RetVals[] = { Undef, Ret };
1609     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1610   } else {
1611     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Val, MemOp, Chain };
1612     SDValue Ret = SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Other, Ops, 8), 0);
1613     SDValue RetVals[] = { Undef, Ret };
1614     return CurDAG->getMergeValues(RetVals, 2, dl).getNode();
1615   }
1616 }
1617
1618 SDNode *X86DAGToDAGISel::Select(SDValue N) {
1619   SDNode *Node = N.getNode();
1620   EVT NVT = Node->getValueType(0);
1621   unsigned Opc, MOpc;
1622   unsigned Opcode = Node->getOpcode();
1623   DebugLoc dl = Node->getDebugLoc();
1624   
1625 #ifndef NDEBUG
1626   DEBUG({
1627       errs() << std::string(Indent, ' ') << "Selecting: ";
1628       Node->dump(CurDAG);
1629       errs() << '\n';
1630     });
1631   Indent += 2;
1632 #endif
1633
1634   if (Node->isMachineOpcode()) {
1635 #ifndef NDEBUG
1636     DEBUG({
1637         errs() << std::string(Indent-2, ' ') << "== ";
1638         Node->dump(CurDAG);
1639         errs() << '\n';
1640       });
1641     Indent -= 2;
1642 #endif
1643     return NULL;   // Already selected.
1644   }
1645
1646   switch (Opcode) {
1647   default: break;
1648   case X86ISD::GlobalBaseReg:
1649     return getGlobalBaseReg();
1650
1651   case X86ISD::ATOMOR64_DAG:
1652     return SelectAtomic64(Node, X86::ATOMOR6432);
1653   case X86ISD::ATOMXOR64_DAG:
1654     return SelectAtomic64(Node, X86::ATOMXOR6432);
1655   case X86ISD::ATOMADD64_DAG:
1656     return SelectAtomic64(Node, X86::ATOMADD6432);
1657   case X86ISD::ATOMSUB64_DAG:
1658     return SelectAtomic64(Node, X86::ATOMSUB6432);
1659   case X86ISD::ATOMNAND64_DAG:
1660     return SelectAtomic64(Node, X86::ATOMNAND6432);
1661   case X86ISD::ATOMAND64_DAG:
1662     return SelectAtomic64(Node, X86::ATOMAND6432);
1663   case X86ISD::ATOMSWAP64_DAG:
1664     return SelectAtomic64(Node, X86::ATOMSWAP6432);
1665
1666   case ISD::ATOMIC_LOAD_ADD: {
1667     SDNode *RetVal = SelectAtomicLoadAdd(Node, NVT);
1668     if (RetVal)
1669       return RetVal;
1670     break;
1671   }
1672
1673   case ISD::SMUL_LOHI:
1674   case ISD::UMUL_LOHI: {
1675     SDValue N0 = Node->getOperand(0);
1676     SDValue N1 = Node->getOperand(1);
1677
1678     bool isSigned = Opcode == ISD::SMUL_LOHI;
1679     if (!isSigned) {
1680       switch (NVT.getSimpleVT().SimpleTy) {
1681       default: llvm_unreachable("Unsupported VT!");
1682       case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
1683       case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
1684       case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
1685       case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
1686       }
1687     } else {
1688       switch (NVT.getSimpleVT().SimpleTy) {
1689       default: llvm_unreachable("Unsupported VT!");
1690       case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
1691       case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
1692       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
1693       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
1694       }
1695     }
1696
1697     unsigned LoReg, HiReg;
1698     switch (NVT.getSimpleVT().SimpleTy) {
1699     default: llvm_unreachable("Unsupported VT!");
1700     case MVT::i8:  LoReg = X86::AL;  HiReg = X86::AH;  break;
1701     case MVT::i16: LoReg = X86::AX;  HiReg = X86::DX;  break;
1702     case MVT::i32: LoReg = X86::EAX; HiReg = X86::EDX; break;
1703     case MVT::i64: LoReg = X86::RAX; HiReg = X86::RDX; break;
1704     }
1705
1706     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1707     bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1708     // Multiply is commmutative.
1709     if (!foldedLoad) {
1710       foldedLoad = TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1711       if (foldedLoad)
1712         std::swap(N0, N1);
1713     }
1714
1715     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
1716                                             N0, SDValue()).getValue(1);
1717
1718     if (foldedLoad) {
1719       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1720                         InFlag };
1721       SDNode *CNode =
1722         CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1723                               array_lengthof(Ops));
1724       InFlag = SDValue(CNode, 1);
1725       // Update the chain.
1726       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1727     } else {
1728       InFlag =
1729         SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1730     }
1731
1732     // Copy the low half of the result, if it is needed.
1733     if (!N.getValue(0).use_empty()) {
1734       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1735                                                 LoReg, NVT, InFlag);
1736       InFlag = Result.getValue(2);
1737       ReplaceUses(N.getValue(0), Result);
1738 #ifndef NDEBUG
1739       DEBUG({
1740           errs() << std::string(Indent-2, ' ') << "=> ";
1741           Result.getNode()->dump(CurDAG);
1742           errs() << '\n';
1743         });
1744 #endif
1745     }
1746     // Copy the high half of the result, if it is needed.
1747     if (!N.getValue(1).use_empty()) {
1748       SDValue Result;
1749       if (HiReg == X86::AH && Subtarget->is64Bit()) {
1750         // Prevent use of AH in a REX instruction by referencing AX instead.
1751         // Shift it down 8 bits.
1752         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1753                                         X86::AX, MVT::i16, InFlag);
1754         InFlag = Result.getValue(2);
1755         Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1756                                                Result,
1757                                    CurDAG->getTargetConstant(8, MVT::i8)), 0);
1758         // Then truncate it down to i8.
1759         Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1760                                                 MVT::i8, Result);
1761       } else {
1762         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1763                                         HiReg, NVT, InFlag);
1764         InFlag = Result.getValue(2);
1765       }
1766       ReplaceUses(N.getValue(1), Result);
1767 #ifndef NDEBUG
1768       DEBUG({
1769           errs() << std::string(Indent-2, ' ') << "=> ";
1770           Result.getNode()->dump(CurDAG);
1771           errs() << '\n';
1772         });
1773 #endif
1774     }
1775
1776 #ifndef NDEBUG
1777     Indent -= 2;
1778 #endif
1779
1780     return NULL;
1781   }
1782
1783   case ISD::SDIVREM:
1784   case ISD::UDIVREM: {
1785     SDValue N0 = Node->getOperand(0);
1786     SDValue N1 = Node->getOperand(1);
1787
1788     bool isSigned = Opcode == ISD::SDIVREM;
1789     if (!isSigned) {
1790       switch (NVT.getSimpleVT().SimpleTy) {
1791       default: llvm_unreachable("Unsupported VT!");
1792       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
1793       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
1794       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
1795       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
1796       }
1797     } else {
1798       switch (NVT.getSimpleVT().SimpleTy) {
1799       default: llvm_unreachable("Unsupported VT!");
1800       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
1801       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
1802       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
1803       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
1804       }
1805     }
1806
1807     unsigned LoReg, HiReg;
1808     unsigned ClrOpcode, SExtOpcode;
1809     switch (NVT.getSimpleVT().SimpleTy) {
1810     default: llvm_unreachable("Unsupported VT!");
1811     case MVT::i8:
1812       LoReg = X86::AL;  HiReg = X86::AH;
1813       ClrOpcode  = 0;
1814       SExtOpcode = X86::CBW;
1815       break;
1816     case MVT::i16:
1817       LoReg = X86::AX;  HiReg = X86::DX;
1818       ClrOpcode  = X86::MOV16r0;
1819       SExtOpcode = X86::CWD;
1820       break;
1821     case MVT::i32:
1822       LoReg = X86::EAX; HiReg = X86::EDX;
1823       ClrOpcode  = X86::MOV32r0;
1824       SExtOpcode = X86::CDQ;
1825       break;
1826     case MVT::i64:
1827       LoReg = X86::RAX; HiReg = X86::RDX;
1828       ClrOpcode  = ~0U; // NOT USED.
1829       SExtOpcode = X86::CQO;
1830       break;
1831     }
1832
1833     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
1834     bool foldedLoad = TryFoldLoad(N, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
1835     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
1836
1837     SDValue InFlag;
1838     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
1839       // Special case for div8, just use a move with zero extension to AX to
1840       // clear the upper 8 bits (AH).
1841       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
1842       if (TryFoldLoad(N, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
1843         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
1844         Move =
1845           SDValue(CurDAG->getTargetNode(X86::MOVZX16rm8, dl, MVT::i16,
1846                                         MVT::Other, Ops,
1847                                         array_lengthof(Ops)), 0);
1848         Chain = Move.getValue(1);
1849         ReplaceUses(N0.getValue(1), Chain);
1850       } else {
1851         Move =
1852           SDValue(CurDAG->getTargetNode(X86::MOVZX16rr8, dl, MVT::i16, N0),0);
1853         Chain = CurDAG->getEntryNode();
1854       }
1855       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, Move, SDValue());
1856       InFlag = Chain.getValue(1);
1857     } else {
1858       InFlag =
1859         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
1860                              LoReg, N0, SDValue()).getValue(1);
1861       if (isSigned && !signBitIsZero) {
1862         // Sign extend the low part into the high part.
1863         InFlag =
1864           SDValue(CurDAG->getTargetNode(SExtOpcode, dl, MVT::Flag, InFlag),0);
1865       } else {
1866         // Zero out the high part, effectively zero extending the input.
1867         SDValue ClrNode;
1868
1869         if (NVT.getSimpleVT() == MVT::i64) {
1870           ClrNode = SDValue(CurDAG->getTargetNode(X86::MOV32r0, dl, MVT::i32),
1871                             0);
1872           // We just did a 32-bit clear, insert it into a 64-bit register to
1873           // clear the whole 64-bit reg.
1874           SDValue Undef =
1875             SDValue(CurDAG->getTargetNode(TargetInstrInfo::IMPLICIT_DEF,
1876                                           dl, MVT::i64), 0);
1877           SDValue SubRegNo =
1878             CurDAG->getTargetConstant(X86::SUBREG_32BIT, MVT::i32);
1879           ClrNode =
1880             SDValue(CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG, dl,
1881                                           MVT::i64, Undef, ClrNode, SubRegNo),
1882                     0);
1883         } else {
1884           ClrNode = SDValue(CurDAG->getTargetNode(ClrOpcode, dl, NVT), 0);
1885         }
1886
1887         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, HiReg,
1888                                       ClrNode, InFlag).getValue(1);
1889       }
1890     }
1891
1892     if (foldedLoad) {
1893       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
1894                         InFlag };
1895       SDNode *CNode =
1896         CurDAG->getTargetNode(MOpc, dl, MVT::Other, MVT::Flag, Ops,
1897                               array_lengthof(Ops));
1898       InFlag = SDValue(CNode, 1);
1899       // Update the chain.
1900       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
1901     } else {
1902       InFlag =
1903         SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Flag, N1, InFlag), 0);
1904     }
1905
1906     // Copy the division (low) result, if it is needed.
1907     if (!N.getValue(0).use_empty()) {
1908       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1909                                                 LoReg, NVT, InFlag);
1910       InFlag = Result.getValue(2);
1911       ReplaceUses(N.getValue(0), Result);
1912 #ifndef NDEBUG
1913       DEBUG({
1914           errs() << std::string(Indent-2, ' ') << "=> ";
1915           Result.getNode()->dump(CurDAG);
1916           errs() << '\n';
1917         });
1918 #endif
1919     }
1920     // Copy the remainder (high) result, if it is needed.
1921     if (!N.getValue(1).use_empty()) {
1922       SDValue Result;
1923       if (HiReg == X86::AH && Subtarget->is64Bit()) {
1924         // Prevent use of AH in a REX instruction by referencing AX instead.
1925         // Shift it down 8 bits.
1926         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1927                                         X86::AX, MVT::i16, InFlag);
1928         InFlag = Result.getValue(2);
1929         Result = SDValue(CurDAG->getTargetNode(X86::SHR16ri, dl, MVT::i16,
1930                                       Result,
1931                                       CurDAG->getTargetConstant(8, MVT::i8)),
1932                          0);
1933         // Then truncate it down to i8.
1934         Result = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1935                                                 MVT::i8, Result);
1936       } else {
1937         Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
1938                                         HiReg, NVT, InFlag);
1939         InFlag = Result.getValue(2);
1940       }
1941       ReplaceUses(N.getValue(1), Result);
1942 #ifndef NDEBUG
1943       DEBUG({
1944           errs() << std::string(Indent-2, ' ') << "=> ";
1945           Result.getNode()->dump(CurDAG);
1946           errs() << '\n';
1947         });
1948 #endif
1949     }
1950
1951 #ifndef NDEBUG
1952     Indent -= 2;
1953 #endif
1954
1955     return NULL;
1956   }
1957
1958   case X86ISD::CMP: {
1959     SDValue N0 = Node->getOperand(0);
1960     SDValue N1 = Node->getOperand(1);
1961
1962     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
1963     // use a smaller encoding.
1964     if (N0.getNode()->getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1965         N0.getValueType() != MVT::i8 &&
1966         X86::isZeroNode(N1)) {
1967       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
1968       if (!C) break;
1969
1970       // For example, convert "testl %eax, $8" to "testb %al, $8"
1971       if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0) {
1972         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i8);
1973         SDValue Reg = N0.getNode()->getOperand(0);
1974
1975         // On x86-32, only the ABCD registers have 8-bit subregisters.
1976         if (!Subtarget->is64Bit()) {
1977           TargetRegisterClass *TRC = 0;
1978           switch (N0.getValueType().getSimpleVT().SimpleTy) {
1979           case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
1980           case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
1981           default: llvm_unreachable("Unsupported TEST operand type!");
1982           }
1983           SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
1984           Reg = SDValue(CurDAG->getTargetNode(X86::COPY_TO_REGCLASS, dl,
1985                                               Reg.getValueType(), Reg, RC), 0);
1986         }
1987
1988         // Extract the l-register.
1989         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT, dl,
1990                                                         MVT::i8, Reg);
1991
1992         // Emit a testb.
1993         return CurDAG->getTargetNode(X86::TEST8ri, dl, MVT::i32, Subreg, Imm);
1994       }
1995
1996       // For example, "testl %eax, $2048" to "testb %ah, $8".
1997       if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0) {
1998         // Shift the immediate right by 8 bits.
1999         SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2000                                                        MVT::i8);
2001         SDValue Reg = N0.getNode()->getOperand(0);
2002
2003         // Put the value in an ABCD register.
2004         TargetRegisterClass *TRC = 0;
2005         switch (N0.getValueType().getSimpleVT().SimpleTy) {
2006         case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2007         case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2008         case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2009         default: llvm_unreachable("Unsupported TEST operand type!");
2010         }
2011         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
2012         Reg = SDValue(CurDAG->getTargetNode(X86::COPY_TO_REGCLASS, dl,
2013                                             Reg.getValueType(), Reg, RC), 0);
2014
2015         // Extract the h-register.
2016         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_8BIT_HI, dl,
2017                                                         MVT::i8, Reg);
2018
2019         // Emit a testb. No special NOREX tricks are needed since there's
2020         // only one GPR operand!
2021         return CurDAG->getTargetNode(X86::TEST8ri, dl, MVT::i32,
2022                                      Subreg, ShiftedImm);
2023       }
2024
2025       // For example, "testl %eax, $32776" to "testw %ax, $32776".
2026       if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2027           N0.getValueType() != MVT::i16) {
2028         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i16);
2029         SDValue Reg = N0.getNode()->getOperand(0);
2030
2031         // Extract the 16-bit subregister.
2032         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_16BIT, dl,
2033                                                         MVT::i16, Reg);
2034
2035         // Emit a testw.
2036         return CurDAG->getTargetNode(X86::TEST16ri, dl, MVT::i32, Subreg, Imm);
2037       }
2038
2039       // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2040       if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2041           N0.getValueType() == MVT::i64) {
2042         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
2043         SDValue Reg = N0.getNode()->getOperand(0);
2044
2045         // Extract the 32-bit subregister.
2046         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::SUBREG_32BIT, dl,
2047                                                         MVT::i32, Reg);
2048
2049         // Emit a testl.
2050         return CurDAG->getTargetNode(X86::TEST32ri, dl, MVT::i32, Subreg, Imm);
2051       }
2052     }
2053     break;
2054   }
2055   }
2056
2057   SDNode *ResNode = SelectCode(N);
2058
2059 #ifndef NDEBUG
2060   DEBUG({
2061       errs() << std::string(Indent-2, ' ') << "=> ";
2062       if (ResNode == NULL || ResNode == N.getNode())
2063         N.getNode()->dump(CurDAG);
2064       else
2065         ResNode->dump(CurDAG);
2066       errs() << '\n';
2067     });
2068   Indent -= 2;
2069 #endif
2070
2071   return ResNode;
2072 }
2073
2074 bool X86DAGToDAGISel::
2075 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
2076                              std::vector<SDValue> &OutOps) {
2077   SDValue Op0, Op1, Op2, Op3, Op4;
2078   switch (ConstraintCode) {
2079   case 'o':   // offsetable        ??
2080   case 'v':   // not offsetable    ??
2081   default: return true;
2082   case 'm':   // memory
2083     if (!SelectAddr(Op, Op, Op0, Op1, Op2, Op3, Op4))
2084       return true;
2085     break;
2086   }
2087   
2088   OutOps.push_back(Op0);
2089   OutOps.push_back(Op1);
2090   OutOps.push_back(Op2);
2091   OutOps.push_back(Op3);
2092   OutOps.push_back(Op4);
2093   return false;
2094 }
2095
2096 /// createX86ISelDag - This pass converts a legalized DAG into a 
2097 /// X86-specific DAG, ready for instruction scheduling.
2098 ///
2099 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2100                                      llvm::CodeGenOpt::Level OptLevel) {
2101   return new X86DAGToDAGISel(TM, OptLevel);
2102 }