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