Revert 74164. We'll want to use this method later.
[oota-llvm.git] / lib / Target / X86 / X86ISelDAGToDAG.cpp
index 2cd6f74f27e0ce18b4d56ff6ed8f8abe4fd09fee..9cedafc8d9348780e03bd45e980c5afa0174c0c3 100644 (file)
@@ -113,10 +113,6 @@ namespace {
   /// SelectionDAG operations.
   ///
   class VISIBILITY_HIDDEN X86DAGToDAGISel : public SelectionDAGISel {
-    /// TM - Keep a reference to X86TargetMachine.
-    ///
-    X86TargetMachine &TM;
-
     /// X86Lowering - This object fully describes how to lower LLVM code to an
     /// X86-specific SelectionDAG.
     X86TargetLowering &X86Lowering;
@@ -134,10 +130,10 @@ namespace {
     bool OptForSize;
 
   public:
-    X86DAGToDAGISel(X86TargetMachine &tm, bool fast)
-      : SelectionDAGISel(tm, fast),
-        TM(tm), X86Lowering(*TM.getTargetLowering()),
-        Subtarget(&TM.getSubtarget<X86Subtarget>()),
+    explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
+      : SelectionDAGISel(tm, OptLevel),
+        X86Lowering(*tm.getTargetLowering()),
+        Subtarget(&tm.getSubtarget<X86Subtarget>()),
         OptForSize(false) {}
 
     virtual const char *getPassName() const {
@@ -162,6 +158,7 @@ namespace {
 
     bool MatchSegmentBaseAddress(SDValue N, X86ISelAddressMode &AM);
     bool MatchLoad(SDValue N, X86ISelAddressMode &AM);
+    bool MatchWrapper(SDValue N, X86ISelAddressMode &AM);
     bool MatchAddress(SDValue N, X86ISelAddressMode &AM,
                       unsigned Depth = 0);
     bool MatchAddressBase(SDValue N, X86ISelAddressMode &AM);
@@ -170,6 +167,8 @@ namespace {
                     SDValue &Segment);
     bool SelectLEAAddr(SDValue Op, SDValue N, SDValue &Base,
                        SDValue &Scale, SDValue &Index, SDValue &Disp);
+    bool SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
+                       SDValue &Scale, SDValue &Index, SDValue &Disp);
     bool SelectScalarSSELoad(SDValue Op, SDValue Pred,
                              SDValue N, SDValue &Base, SDValue &Scale,
                              SDValue &Index, SDValue &Disp,
@@ -242,11 +241,17 @@ namespace {
     ///
     SDNode *getGlobalBaseReg();
 
-    /// getTruncateTo8Bit - return an SDNode that implements a subreg based
-    /// truncate of the specified operand to i8. This can be done with tablegen,
-    /// except that this code uses MVT::Flag in a tricky way that happens to
-    /// improve scheduling in some cases.
-    SDNode *getTruncateTo8Bit(SDValue N0);
+    /// getTargetMachine - Return a reference to the TargetMachine, casted
+    /// to the target-specific type.
+    const X86TargetMachine &getTargetMachine() {
+      return static_cast<const X86TargetMachine &>(TM);
+    }
+
+    /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
+    /// to the target-specific type.
+    const X86InstrInfo *getInstrInfo() {
+      return getTargetMachine().getInstrInfo();
+    }
 
 #ifndef NDEBUG
     unsigned Indent;
@@ -254,64 +259,10 @@ namespace {
   };
 }
 
-/// findFlagUse - Return use of MVT::Flag value produced by the specified
-/// SDNode.
-///
-static SDNode *findFlagUse(SDNode *N) {
-  unsigned FlagResNo = N->getNumValues()-1;
-  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
-    SDUse &Use = I.getUse();
-    if (Use.getResNo() == FlagResNo)
-      return Use.getUser();
-  }
-  return NULL;
-}
-
-/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
-/// This function recursively traverses up the operand chain, ignoring
-/// certain nodes.
-static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
-                          SDNode *Root,
-                          SmallPtrSet<SDNode*, 16> &Visited) {
-  if (Use->getNodeId() < Def->getNodeId() ||
-      !Visited.insert(Use))
-    return false;
-
-  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
-    SDNode *N = Use->getOperand(i).getNode();
-    if (N == Def) {
-      if (Use == ImmedUse || Use == Root)
-        continue;  // We are not looking for immediate use.
-      assert(N != Root);
-      return true;
-    }
-
-    // Traverse up the operand chain.
-    if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
-      return true;
-  }
-  return false;
-}
-
-/// isNonImmUse - Start searching from Root up the DAG to check is Def can
-/// be reached. Return true if that's the case. However, ignore direct uses
-/// by ImmedUse (which would be U in the example illustrated in
-/// IsLegalAndProfitableToFold) and by Root (which can happen in the store
-/// case).
-/// FIXME: to be really generic, we should allow direct use by any node
-/// that is being folded. But realisticly since we only fold loads which
-/// have one non-chain use, we only need to watch out for load/op/store
-/// and load/op/cmp case where the root (store / cmp) may reach the load via
-/// its chain operand.
-static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
-  SmallPtrSet<SDNode*, 16> Visited;
-  return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
-}
-
 
 bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
                                                  SDNode *Root) const {
-  if (Fast) return false;
+  if (OptLevel == CodeGenOpt::None) return false;
 
   if (U == Root)
     switch (U->getOpcode()) {
@@ -322,6 +273,8 @@ bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
     case ISD::AND:
     case ISD::OR:
     case ISD::XOR: {
+      SDValue Op1 = U->getOperand(1);
+
       // If the other operand is a 8-bit immediate we should fold the immediate
       // instead. This reduces code size.
       // e.g.
@@ -332,64 +285,30 @@ bool X86DAGToDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
       // addl 4(%esp), %eax
       // The former is 2 bytes shorter. In case where the increment is 1, then
       // the saving can be 4 bytes (by using incl %eax).
-      if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(U->getOperand(1)))
+      if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
         if (Imm->getAPIntValue().isSignedIntN(8))
           return false;
+
+      // If the other operand is a TLS address, we should fold it instead.
+      // This produces
+      // movl    %gs:0, %eax
+      // leal    i@NTPOFF(%eax), %eax
+      // instead of
+      // movl    $i@NTPOFF, %eax
+      // addl    %gs:0, %eax
+      // if the block also has an access to a second TLS address this will save
+      // a load.
+      // FIXME: This is probably also true for non TLS addresses.
+      if (Op1.getOpcode() == X86ISD::Wrapper) {
+        SDValue Val = Op1.getOperand(0);
+        if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
+          return false;
+      }
     }
     }
 
-  // If Root use can somehow reach N through a path that that doesn't contain
-  // U then folding N would create a cycle. e.g. In the following
-  // diagram, Root can reach N through X. If N is folded into into Root, then
-  // X is both a predecessor and a successor of U.
-  //
-  //          [N*]           //
-  //         ^   ^           //
-  //        /     \          //
-  //      [U*]    [X]?       //
-  //        ^     ^          //
-  //         \   /           //
-  //          \ /            //
-  //         [Root*]         //
-  //
-  // * indicates nodes to be folded together.
-  //
-  // If Root produces a flag, then it gets (even more) interesting. Since it
-  // will be "glued" together with its flag use in the scheduler, we need to
-  // check if it might reach N.
-  //
-  //          [N*]           //
-  //         ^   ^           //
-  //        /     \          //
-  //      [U*]    [X]?       //
-  //        ^       ^        //
-  //         \       \       //
-  //          \      |       //
-  //         [Root*] |       //
-  //          ^      |       //
-  //          f      |       //
-  //          |      /       //
-  //         [Y]    /        //
-  //           ^   /         //
-  //           f  /          //
-  //           | /           //
-  //          [FU]           //
-  //
-  // If FU (flag use) indirectly reaches N (the load), and Root folds N
-  // (call it Fold), then X is a predecessor of FU and a successor of
-  // Fold. But since Fold and FU are flagged together, this will create
-  // a cycle in the scheduling graph.
-
-  MVT VT = Root->getValueType(Root->getNumValues()-1);
-  while (VT == MVT::Flag) {
-    SDNode *FU = findFlagUse(Root);
-    if (FU == NULL)
-      break;
-    Root = FU;
-    VT = Root->getValueType(Root->getNumValues()-1);
-  }
-
-  return !isNonImmUse(Root, N, U);
+  // Proceed to 'generic' cycle finder code
+  return SelectionDAGISel::IsLegalAndProfitableToFold(N, U, Root);
 }
 
 /// MoveBelowTokenFactor - Replace TokenFactor operand with load's chain operand
@@ -499,7 +418,7 @@ static bool isCalleeLoad(SDValue Callee, SDValue &Chain) {
 
 
 /// PreprocessForRMW - Preprocess the DAG to make instruction selection better.
-/// This is only run if not in -fast mode (aka -O0).
+/// This is only run if not in -O0 mode.
 /// This allows the instruction selector to pick more read-modify-write
 /// instructions. This is a common case:
 ///
@@ -701,10 +620,10 @@ void X86DAGToDAGISel::InstructionSelect() {
   OptForSize = F->hasFnAttr(Attribute::OptimizeForSize);
 
   DEBUG(BB->dump());
-  if (!Fast)
+  if (OptLevel != CodeGenOpt::None)
     PreprocessForRMW();
 
-  // FIXME: This should only happen when not -fast.
+  // FIXME: This should only happen when not compiled with -O0.
   PreprocessForFPConvert();
 
   // Codegen the basic block.
@@ -764,6 +683,67 @@ bool X86DAGToDAGISel::MatchLoad(SDValue N, X86ISelAddressMode &AM) {
   return true;
 }
 
+bool X86DAGToDAGISel::MatchWrapper(SDValue N, X86ISelAddressMode &AM) {
+  bool SymbolicAddressesAreRIPRel =
+    getTargetMachine().symbolicAddressesAreRIPRel();
+  bool is64Bit = Subtarget->is64Bit();
+  DOUT << "Wrapper: 64bit " << is64Bit;
+  DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
+
+  // Under X86-64 non-small code model, GV (and friends) are 64-bits.
+  if (is64Bit && (TM.getCodeModel() != CodeModel::Small))
+    return true;
+
+  // Base and index reg must be 0 in order to use rip as base.
+  bool canUsePICRel = !AM.Base.Reg.getNode() && !AM.IndexReg.getNode();
+  if (is64Bit && !canUsePICRel && SymbolicAddressesAreRIPRel)
+    return true;
+
+  if (AM.hasSymbolicDisplacement())
+    return true;
+  // If value is available in a register both base and index components have
+  // been picked, we can't fit the result available in the register in the
+  // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
+
+  SDValue N0 = N.getOperand(0);
+  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
+    uint64_t Offset = G->getOffset();
+    if (!is64Bit || isInt32(AM.Disp + Offset)) {
+      GlobalValue *GV = G->getGlobal();
+      bool isRIPRel = SymbolicAddressesAreRIPRel;
+      if (N0.getOpcode() == llvm::ISD::TargetGlobalTLSAddress) {
+        TLSModel::Model model =
+          getTLSModel (GV, TM.getRelocationModel());
+        if (is64Bit && model == TLSModel::InitialExec)
+          isRIPRel = true;
+      }
+      AM.GV = GV;
+      AM.Disp += Offset;
+      AM.isRIPRel = isRIPRel;
+      return false;
+    }
+  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
+    uint64_t Offset = CP->getOffset();
+    if (!is64Bit || isInt32(AM.Disp + Offset)) {
+      AM.CP = CP->getConstVal();
+      AM.Align = CP->getAlignment();
+      AM.Disp += Offset;
+      AM.isRIPRel = SymbolicAddressesAreRIPRel;
+      return false;
+    }
+  } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
+    AM.ES = S->getSymbol();
+    AM.isRIPRel = SymbolicAddressesAreRIPRel;
+    return false;
+  } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
+    AM.JT = J->getIndex();
+    AM.isRIPRel = SymbolicAddressesAreRIPRel;
+    return false;
+  }
+
+  return true;
+}
+
 /// MatchAddress - Add the specified node to the specified addressing mode,
 /// returning true if it cannot be done.  This just pattern matches for the
 /// addressing mode.
@@ -804,51 +784,10 @@ bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
       return false;
     break;
 
-  case X86ISD::Wrapper: {
-    DOUT << "Wrapper: 64bit " << is64Bit;
-    DOUT << " AM "; DEBUG(AM.dump()); DOUT << "\n";
-    // Under X86-64 non-small code model, GV (and friends) are 64-bits.
-    // Also, base and index reg must be 0 in order to use rip as base.
-    if (is64Bit && (TM.getCodeModel() != CodeModel::Small ||
-                    AM.Base.Reg.getNode() || AM.IndexReg.getNode()))
-      break;
-    if (AM.hasSymbolicDisplacement())
-      break;
-    // If value is available in a register both base and index components have
-    // been picked, we can't fit the result available in the register in the
-    // addressing mode. Duplicate GlobalAddress or ConstantPool as displacement.
-    {
-      SDValue N0 = N.getOperand(0);
-      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
-        uint64_t Offset = G->getOffset();
-        if (!is64Bit || isInt32(AM.Disp + Offset)) {
-          GlobalValue *GV = G->getGlobal();
-          AM.GV = GV;
-          AM.Disp += Offset;
-          AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
-          return false;
-        }
-      } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
-        uint64_t Offset = CP->getOffset();
-        if (!is64Bit || isInt32(AM.Disp + Offset)) {
-          AM.CP = CP->getConstVal();
-          AM.Align = CP->getAlignment();
-          AM.Disp += Offset;
-          AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
-          return false;
-        }
-      } else if (ExternalSymbolSDNode *S =dyn_cast<ExternalSymbolSDNode>(N0)) {
-        AM.ES = S->getSymbol();
-        AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
-        return false;
-      } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
-        AM.JT = J->getIndex();
-        AM.isRIPRel = TM.symbolicAddressesAreRIPRel();
-        return false;
-      }
-    }
+  case X86ISD::Wrapper:
+    if (!MatchWrapper(N, AM))
+      return false;
     break;
-  }
 
   case ISD::LOAD:
     if (!MatchLoad(N, AM))
@@ -941,6 +880,76 @@ bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
     }
     break;
 
+  case ISD::SUB: {
+    // Given A-B, if A can be completely folded into the address and
+    // the index field with the index field unused, use -B as the index.
+    // This is a win if a has multiple parts that can be folded into
+    // the address. Also, this saves a mov if the base register has
+    // other uses, since it avoids a two-address sub instruction, however
+    // it costs an additional mov if the index register has other uses.
+
+    // Test if the LHS of the sub can be folded.
+    X86ISelAddressMode Backup = AM;
+    if (MatchAddress(N.getNode()->getOperand(0), AM, Depth+1)) {
+      AM = Backup;
+      break;
+    }
+    // Test if the index field is free for use.
+    if (AM.IndexReg.getNode() || AM.isRIPRel) {
+      AM = Backup;
+      break;
+    }
+    int Cost = 0;
+    SDValue RHS = N.getNode()->getOperand(1);
+    // If the RHS involves a register with multiple uses, this
+    // transformation incurs an extra mov, due to the neg instruction
+    // clobbering its operand.
+    if (!RHS.getNode()->hasOneUse() ||
+        RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
+        RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
+        RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
+        (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
+         RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
+      ++Cost;
+    // If the base is a register with multiple uses, this
+    // transformation may save a mov.
+    if ((AM.BaseType == X86ISelAddressMode::RegBase &&
+         AM.Base.Reg.getNode() &&
+         !AM.Base.Reg.getNode()->hasOneUse()) ||
+        AM.BaseType == X86ISelAddressMode::FrameIndexBase)
+      --Cost;
+    // If the folded LHS was interesting, this transformation saves
+    // address arithmetic.
+    if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
+        ((AM.Disp != 0) && (Backup.Disp == 0)) +
+        (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
+      --Cost;
+    // If it doesn't look like it may be an overall win, don't do it.
+    if (Cost >= 0) {
+      AM = Backup;
+      break;
+    }
+
+    // Ok, the transformation is legal and appears profitable. Go for it.
+    SDValue Zero = CurDAG->getConstant(0, N.getValueType());
+    SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
+    AM.IndexReg = Neg;
+    AM.Scale = 1;
+
+    // Insert the new nodes into the topological ordering.
+    if (Zero.getNode()->getNodeId() == -1 ||
+        Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
+      CurDAG->RepositionNode(N.getNode(), Zero.getNode());
+      Zero.getNode()->setNodeId(N.getNode()->getNodeId());
+    }
+    if (Neg.getNode()->getNodeId() == -1 ||
+        Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
+      CurDAG->RepositionNode(N.getNode(), Neg.getNode());
+      Neg.getNode()->setNodeId(N.getNode()->getNodeId());
+    }
+    return false;
+  }
+
   case ISD::ADD: {
     X86ISelAddressMode Backup = AM;
     if (!MatchAddress(N.getNode()->getOperand(0), AM, Depth+1) &&
@@ -988,21 +997,82 @@ bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
     break;
       
   case ISD::AND: {
-    // Handle "(x << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
-    // allows us to fold the shift into this addressing mode.
+    // Perform some heroic transforms on an and of a constant-count shift
+    // with a constant to enable use of the scaled offset field.
+
     SDValue Shift = N.getOperand(0);
-    if (Shift.getOpcode() != ISD::SHL) break;
+    if (Shift.getNumOperands() != 2) break;
 
     // Scale must not be used already.
     if (AM.IndexReg.getNode() != 0 || AM.Scale != 1) break;
 
     // Not when RIP is used as the base.
     if (AM.isRIPRel) break;
-      
+
+    SDValue X = Shift.getOperand(0);
     ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N.getOperand(1));
     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
     if (!C1 || !C2) break;
 
+    // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
+    // allows us to convert the shift and and into an h-register extract and
+    // a scaled index.
+    if (Shift.getOpcode() == ISD::SRL && Shift.hasOneUse()) {
+      unsigned ScaleLog = 8 - C1->getZExtValue();
+      if (ScaleLog > 0 && ScaleLog < 4 &&
+          C2->getZExtValue() == (UINT64_C(0xff) << ScaleLog)) {
+        SDValue Eight = CurDAG->getConstant(8, MVT::i8);
+        SDValue Mask = CurDAG->getConstant(0xff, N.getValueType());
+        SDValue Srl = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
+                                      X, Eight);
+        SDValue And = CurDAG->getNode(ISD::AND, dl, N.getValueType(),
+                                      Srl, Mask);
+        SDValue ShlCount = CurDAG->getConstant(ScaleLog, MVT::i8);
+        SDValue Shl = CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
+                                      And, ShlCount);
+
+        // Insert the new nodes into the topological ordering.
+        if (Eight.getNode()->getNodeId() == -1 ||
+            Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(X.getNode(), Eight.getNode());
+          Eight.getNode()->setNodeId(X.getNode()->getNodeId());
+        }
+        if (Mask.getNode()->getNodeId() == -1 ||
+            Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(X.getNode(), Mask.getNode());
+          Mask.getNode()->setNodeId(X.getNode()->getNodeId());
+        }
+        if (Srl.getNode()->getNodeId() == -1 ||
+            Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
+          Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
+        }
+        if (And.getNode()->getNodeId() == -1 ||
+            And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(N.getNode(), And.getNode());
+          And.getNode()->setNodeId(N.getNode()->getNodeId());
+        }
+        if (ShlCount.getNode()->getNodeId() == -1 ||
+            ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
+          ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
+        }
+        if (Shl.getNode()->getNodeId() == -1 ||
+            Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
+          CurDAG->RepositionNode(N.getNode(), Shl.getNode());
+          Shl.getNode()->setNodeId(N.getNode()->getNodeId());
+        }
+        CurDAG->ReplaceAllUsesWith(N, Shl);
+        AM.IndexReg = And;
+        AM.Scale = (1 << ScaleLog);
+        return false;
+      }
+    }
+
+    // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if this
+    // allows us to fold the shift into this addressing mode.
+    if (Shift.getOpcode() != ISD::SHL) break;
+
     // Not likely to be profitable if either the AND or SHIFT node has more
     // than one use (unless all uses are for address computation). Besides,
     // isel mechanism requires their node ids to be reused.
@@ -1015,7 +1085,6 @@ bool X86DAGToDAGISel::MatchAddress(SDValue N, X86ISelAddressMode &AM,
       break;
     
     // Get the new AND mask, this folds to a constant.
-    SDValue X = Shift.getOperand(0);
     SDValue NewANDMask = CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
                                          SDValue(C2, 0), SDValue(C1, 0));
     SDValue NewAND = CurDAG->getNode(ISD::AND, dl, N.getValueType(), X, 
@@ -1170,13 +1239,16 @@ bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
                                     SDValue &Base, SDValue &Scale,
                                     SDValue &Index, SDValue &Disp) {
   X86ISelAddressMode AM;
-  if (MatchAddress(N, AM))
-    return false;
 
-  //Is it better to set AM.Segment before calling MatchAddress to
-  //prevent it from adding a segment?
-  if (AM.Segment.getNode())
+  // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
+  // segments.
+  SDValue Copy = AM.Segment;
+  SDValue T = CurDAG->getRegister(0, MVT::i32);
+  AM.Segment = T;
+  if (MatchAddress(N, AM))
     return false;
+  assert (T == AM.Segment);
+  AM.Segment = Copy;
 
   MVT VT = N.getValueType();
   unsigned Complexity = 0;
@@ -1223,6 +1295,32 @@ bool X86DAGToDAGISel::SelectLEAAddr(SDValue Op, SDValue N,
   return false;
 }
 
+/// SelectTLSADDRAddr - This is only run on TargetGlobalTLSAddress nodes.
+bool X86DAGToDAGISel::SelectTLSADDRAddr(SDValue Op, SDValue N, SDValue &Base,
+                                        SDValue &Scale, SDValue &Index,
+                                        SDValue &Disp) {
+  assert(Op.getOpcode() == X86ISD::TLSADDR);
+  assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
+  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
+  
+  X86ISelAddressMode AM;
+  AM.GV = GA->getGlobal();
+  AM.Disp += GA->getOffset();
+  AM.Base.Reg = CurDAG->getRegister(0, N.getValueType());
+  
+  if (N.getValueType() == MVT::i32) {
+    AM.Scale = 1;
+    AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
+  } else {
+    AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
+  }
+  
+  SDValue Segment;
+  getAddressOperands(AM, Base, Scale, Index, Disp, Segment);
+  return true;
+}
+
+
 bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
                                   SDValue &Base, SDValue &Scale,
                                   SDValue &Index, SDValue &Disp,
@@ -1240,7 +1338,7 @@ bool X86DAGToDAGISel::TryFoldLoad(SDValue P, SDValue N,
 ///
 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
   MachineFunction *MF = CurBB->getParent();
-  unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF);
+  unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
 }
 
@@ -1251,36 +1349,6 @@ static SDNode *FindCallStartFromCall(SDNode *Node) {
   return FindCallStartFromCall(Node->getOperand(0).getNode());
 }
 
-/// getTruncateTo8Bit - return an SDNode that implements a subreg based
-/// truncate of the specified operand to i8. This can be done with tablegen,
-/// except that this code uses MVT::Flag in a tricky way that happens to
-/// improve scheduling in some cases.
-SDNode *X86DAGToDAGISel::getTruncateTo8Bit(SDValue N0) {
-  assert(!Subtarget->is64Bit() &&
-         "getTruncateTo8Bit is only needed on x86-32!");
-  SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
-  DebugLoc dl = N0.getDebugLoc();
-
-  // Ensure that the source register has an 8-bit subreg on 32-bit targets
-  unsigned Opc;
-  MVT N0VT = N0.getValueType();
-  switch (N0VT.getSimpleVT()) {
-  default: assert(0 && "Unknown truncate!");
-  case MVT::i16:
-    Opc = X86::MOV16to16_;
-    break;
-  case MVT::i32:
-    Opc = X86::MOV32to32_;
-    break;
-  }
-
-  // The use of MVT::Flag here is not strictly accurate, but it helps
-  // scheduling in some cases.
-  N0 = SDValue(CurDAG->getTargetNode(Opc, dl, N0VT, MVT::Flag, N0), 0);
-  return CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
-                               MVT::i8, N0, SRIdx, N0.getValue(1));
-}
-
 SDNode *X86DAGToDAGISel::SelectAtomic64(SDNode *Node, unsigned Opc) {
   SDValue Chain = Node->getOperand(0);
   SDValue In1 = Node->getOperand(1);
@@ -1423,7 +1491,7 @@ SDNode *X86DAGToDAGISel::Select(SDValue N) {
                                                  Result,
                                      CurDAG->getTargetConstant(8, MVT::i8)), 0);
           // Then truncate it down to i8.
-          SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
+          SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
           Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
                                                    MVT::i8, Result, SRIdx), 0);
         } else {
@@ -1576,7 +1644,7 @@ SDNode *X86DAGToDAGISel::Select(SDValue N) {
                                         CurDAG->getTargetConstant(8, MVT::i8)), 
                            0);
           // Then truncate it down to i8.
-          SDValue SRIdx = CurDAG->getTargetConstant(1, MVT::i32); // SubRegSet 1
+          SDValue SRIdx = CurDAG->getTargetConstant(X86::SUBREG_8BIT, MVT::i32);
           Result = SDValue(CurDAG->getTargetNode(X86::EXTRACT_SUBREG, dl,
                                                    MVT::i8, Result, SRIdx), 0);
         } else {
@@ -1599,55 +1667,6 @@ SDNode *X86DAGToDAGISel::Select(SDValue N) {
       return NULL;
     }
 
-    case ISD::SIGN_EXTEND_INREG: {
-      MVT SVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
-      if (SVT == MVT::i8 && !Subtarget->is64Bit()) {
-        SDValue N0 = Node->getOperand(0);
-      
-        SDValue TruncOp = SDValue(getTruncateTo8Bit(N0), 0);
-        unsigned Opc = 0;
-        switch (NVT.getSimpleVT()) {
-        default: assert(0 && "Unknown sign_extend_inreg!");
-        case MVT::i16:
-          Opc = X86::MOVSX16rr8;
-          break;
-        case MVT::i32:
-          Opc = X86::MOVSX32rr8; 
-          break;
-        }
-      
-        SDNode *ResNode = CurDAG->getTargetNode(Opc, dl, NVT, TruncOp);
-      
-#ifndef NDEBUG
-        DOUT << std::string(Indent-2, ' ') << "=> ";
-        DEBUG(TruncOp.getNode()->dump(CurDAG));
-        DOUT << "\n";
-        DOUT << std::string(Indent-2, ' ') << "=> ";
-        DEBUG(ResNode->dump(CurDAG));
-        DOUT << "\n";
-        Indent -= 2;
-#endif
-        return ResNode;
-      }
-      break;
-    }
-    
-    case ISD::TRUNCATE: {
-      if (NVT == MVT::i8 && !Subtarget->is64Bit()) {
-        SDValue Input = Node->getOperand(0);
-        SDNode *ResNode = getTruncateTo8Bit(Input);
-      
-#ifndef NDEBUG
-        DOUT << std::string(Indent-2, ' ') << "=> ";
-        DEBUG(ResNode->dump(CurDAG));
-        DOUT << "\n";
-        Indent -= 2;
-#endif
-        return ResNode;
-      }
-      break;
-    }
-
     case ISD::DECLARE: {
       // Handle DECLARE nodes here because the second operand may have been
       // wrapped in X86ISD::Wrapper.
@@ -1729,6 +1748,7 @@ SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
 /// createX86ISelDag - This pass converts a legalized DAG into a 
 /// X86-specific DAG, ready for instruction scheduling.
 ///
-FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, bool Fast) {
-  return new X86DAGToDAGISel(TM, Fast);
+FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
+                                     llvm::CodeGenOpt::Level OptLevel) {
+  return new X86DAGToDAGISel(TM, OptLevel);
 }