Fix 80 column violations.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
index a2cf6a1b568fd40a2086561a66aff605d14c958b..7702b3d5e90c096be026cec9fe6d076195458616 100644 (file)
@@ -25,7 +25,6 @@
 #include "llvm/Instructions.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/IntrinsicInst.h"
-#include "llvm/ParameterAttributes.h"
 #include "llvm/CodeGen/FastISel.h"
 #include "llvm/CodeGen/GCStrategy.h"
 #include "llvm/CodeGen/GCMetadata.h"
@@ -55,14 +54,23 @@ using namespace llvm;
 static cl::opt<bool>
 EnableValueProp("enable-value-prop", cl::Hidden);
 static cl::opt<bool>
-EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
+DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
+#ifndef NDEBUG
+static cl::opt<bool>
+EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
+          cl::desc("Enable verbose messages in the \"fast\" "
+                   "instruction selector"));
 static cl::opt<bool>
-EnableFastISel("fast-isel", cl::Hidden,
-          cl::desc("Enable the experimental \"fast\" instruction selector"));
+EnableFastISelAbort("fast-isel-abort", cl::Hidden,
+          cl::desc("Enable abort calls when \"fast\" instruction fails"));
+#else
+static const bool EnableFastISelVerbose = false,
+                  EnableFastISelAbort = false;
+#endif
 static cl::opt<bool>
-DisableFastISelAbort("fast-isel-no-abort", cl::Hidden,
-          cl::desc("Use the SelectionDAGISel when \"fast\" instruction "
-                   "selection fails"));
+SchedLiveInCopies("schedule-livein-copies",
+                  cl::desc("Schedule copies of livein registers"),
+                  cl::init(false));
 
 #ifndef NDEBUG
 static cl::opt<bool>
@@ -116,7 +124,7 @@ ISHeuristic("pre-RA-sched",
                      " allocation):"));
 
 static RegisterScheduler
-defaultListDAGScheduler("default", "  Best scheduler for the target",
+defaultListDAGScheduler("default", "Best scheduler for the target",
                         createDefaultScheduler);
 
 namespace llvm {
@@ -153,12 +161,107 @@ MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
   return 0;  
 }
 
+/// EmitLiveInCopy - Emit a copy for a live in physical register. If the
+/// physical register has only a single copy use, then coalesced the copy
+/// if possible.
+static void EmitLiveInCopy(MachineBasicBlock *MBB,
+                           MachineBasicBlock::iterator &InsertPos,
+                           unsigned VirtReg, unsigned PhysReg,
+                           const TargetRegisterClass *RC,
+                           DenseMap<MachineInstr*, unsigned> &CopyRegMap,
+                           const MachineRegisterInfo &MRI,
+                           const TargetRegisterInfo &TRI,
+                           const TargetInstrInfo &TII) {
+  unsigned NumUses = 0;
+  MachineInstr *UseMI = NULL;
+  for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
+         UE = MRI.use_end(); UI != UE; ++UI) {
+    UseMI = &*UI;
+    if (++NumUses > 1)
+      break;
+  }
+
+  // If the number of uses is not one, or the use is not a move instruction,
+  // don't coalesce. Also, only coalesce away a virtual register to virtual
+  // register copy.
+  bool Coalesced = false;
+  unsigned SrcReg, DstReg;
+  if (NumUses == 1 &&
+      TII.isMoveInstr(*UseMI, SrcReg, DstReg) &&
+      TargetRegisterInfo::isVirtualRegister(DstReg)) {
+    VirtReg = DstReg;
+    Coalesced = true;
+  }
+
+  // Now find an ideal location to insert the copy.
+  MachineBasicBlock::iterator Pos = InsertPos;
+  while (Pos != MBB->begin()) {
+    MachineInstr *PrevMI = prior(Pos);
+    DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
+    // copyRegToReg might emit multiple instructions to do a copy.
+    unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
+    if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
+      // This is what the BB looks like right now:
+      // r1024 = mov r0
+      // ...
+      // r1    = mov r1024
+      //
+      // We want to insert "r1025 = mov r1". Inserting this copy below the
+      // move to r1024 makes it impossible for that move to be coalesced.
+      //
+      // r1025 = mov r1
+      // r1024 = mov r0
+      // ...
+      // r1    = mov 1024
+      // r2    = mov 1025
+      break; // Woot! Found a good location.
+    --Pos;
+  }
+
+  TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
+  CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
+  if (Coalesced) {
+    if (&*InsertPos == UseMI) ++InsertPos;
+    MBB->erase(UseMI);
+  }
+}
+
+/// EmitLiveInCopies - If this is the first basic block in the function,
+/// and if it has live ins that need to be copied into vregs, emit the
+/// copies into the block.
+static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
+                             const MachineRegisterInfo &MRI,
+                             const TargetRegisterInfo &TRI,
+                             const TargetInstrInfo &TII) {
+  if (SchedLiveInCopies) {
+    // Emit the copies at a heuristically-determined location in the block.
+    DenseMap<MachineInstr*, unsigned> CopyRegMap;
+    MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
+    for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
+           E = MRI.livein_end(); LI != E; ++LI)
+      if (LI->second) {
+        const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
+        EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
+                       RC, CopyRegMap, MRI, TRI, TII);
+      }
+  } else {
+    // Emit the copies into the top of the block.
+    for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
+           E = MRI.livein_end(); LI != E; ++LI)
+      if (LI->second) {
+        const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
+        TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
+                         LI->second, LI->first, RC, RC);
+      }
+  }
+}
+
 //===----------------------------------------------------------------------===//
 // SelectionDAGISel code
 //===----------------------------------------------------------------------===//
 
 SelectionDAGISel::SelectionDAGISel(TargetLowering &tli, bool fast) :
-  FunctionPass((intptr_t)&ID), TLI(tli),
+  FunctionPass(&ID), TLI(tli),
   FuncInfo(new FunctionLoweringInfo(TLI)),
   CurDAG(new SelectionDAG(TLI, *FuncInfo)),
   SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
@@ -184,10 +287,21 @@ void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
 }
 
 bool SelectionDAGISel::runOnFunction(Function &Fn) {
+  // Do some sanity-checking on the command-line options.
+  assert((!EnableFastISelVerbose || EnableFastISel) &&
+         "-fast-isel-verbose requires -fast-isel");
+  assert((!EnableFastISelAbort || EnableFastISel) &&
+         "-fast-isel-abort requires -fast-isel");
+
   // Get alias analysis for load/store combining.
   AA = &getAnalysis<AliasAnalysis>();
 
-  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
+  TargetMachine &TM = TLI.getTargetMachine();
+  MachineFunction &MF = MachineFunction::construct(&Fn, TM);
+  const MachineRegisterInfo &MRI = MF.getRegInfo();
+  const TargetInstrInfo &TII = *TM.getInstrInfo();
+  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
+
   if (MF.getFunction()->hasGC())
     GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
   else
@@ -196,7 +310,8 @@ bool SelectionDAGISel::runOnFunction(Function &Fn) {
   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
 
   FuncInfo->set(Fn, MF, EnableFastISel);
-  CurDAG->init(MF, getAnalysisToUpdate<MachineModuleInfo>());
+  MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
+  CurDAG->init(MF, MMI);
   SDL->init(GFI, *AA);
 
   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
@@ -204,15 +319,17 @@ bool SelectionDAGISel::runOnFunction(Function &Fn) {
       // Mark landing pad.
       FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
 
-  SelectAllBasicBlocks(Fn, MF);
+  SelectAllBasicBlocks(Fn, MF, MMI, TII);
+
+  // If the first basic block in the function has live ins that need to be
+  // copied into vregs, emit the copies into the top of the block before
+  // emitting the code for the block.
+  EmitLiveInCopies(MF.begin(), MRI, TRI, TII);
 
   // Add function live-ins to entry block live-in set.
-  BasicBlock *EntryBB = &Fn.getEntryBlock();
-  BB = FuncInfo->MBBMap[EntryBB];
-  if (!RegInfo->livein_empty())
-    for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
-           E = RegInfo->livein_end(); I != E; ++I)
-      BB->addLiveIn(I->first);
+  for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
+         E = RegInfo->livein_end(); I != E; ++I)
+    MF.begin()->addLiveIn(I->first);
 
 #ifndef NDEBUG
   assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
@@ -287,56 +404,45 @@ static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
   for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
          BI = DAG.allnodes_end(); BI != BE; ) {
     --BI;
-    if (BI->getOpcode() == ISD::CALL) {
+    if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
       SDValue OpRet(Ret, 0);
       SDValue OpCall(BI, 0);
-      bool isMarkedTailCall = 
-        cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
+      bool isMarkedTailCall = TheCall->isTailCall();
       // If CALL node has tail call attribute set to true and the call is not
       // eligible (no RET or the target rejects) the attribute is fixed to
       // false. The TargetLowering::IsEligibleForTailCallOptimization function
       // must correctly identify tail call optimizable calls.
       if (!isMarkedTailCall) continue;
       if (Ret==NULL ||
-          !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
-        // Not eligible. Mark CALL node as non tail call.
-        SmallVector<SDValue, 32> Ops;
-        unsigned idx=0;
-        for(SDNode::op_iterator I =OpCall.getNode()->op_begin(),
-              E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
-          if (idx!=3)
-            Ops.push_back(*I);
-          else
-            Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
-        }
-        DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
+          !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
+        // Not eligible. Mark CALL node as non tail call. Note that we
+        // can modify the call node in place since calls are not CSE'd.
+        TheCall->setNotTailCall();
       } else {
         // Look for tail call clobbered arguments. Emit a series of
         // copyto/copyfrom virtual register nodes to protect them.
         SmallVector<SDValue, 32> Ops;
-        SDValue Chain = OpCall.getOperand(0), InFlag;
-        unsigned idx=0;
-        for(SDNode::op_iterator I = OpCall.getNode()->op_begin(),
-              E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
-          SDValue Arg = *I;
-          if (idx > 4 && (idx % 2)) {
-            bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
-              getArgFlags().isByVal();
-            MachineFunction &MF = DAG.getMachineFunction();
-            MachineFrameInfo *MFI = MF.getFrameInfo();
-            if (!isByVal &&
-                IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
-              MVT VT = Arg.getValueType();
-              unsigned VReg = MF.getRegInfo().
-                createVirtualRegister(TLI.getRegClassFor(VT));
-              Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
-              InFlag = Chain.getValue(1);
-              Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
-              Chain = Arg.getValue(1);
-              InFlag = Arg.getValue(2);
-            }
+        SDValue Chain = TheCall->getChain(), InFlag;
+        Ops.push_back(Chain);
+        Ops.push_back(TheCall->getCallee());
+        for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
+          SDValue Arg = TheCall->getArg(i);
+          bool isByVal = TheCall->getArgFlags(i).isByVal();
+          MachineFunction &MF = DAG.getMachineFunction();
+          MachineFrameInfo *MFI = MF.getFrameInfo();
+          if (!isByVal &&
+              IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
+            MVT VT = Arg.getValueType();
+            unsigned VReg = MF.getRegInfo().
+              createVirtualRegister(TLI.getRegClassFor(VT));
+            Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
+            InFlag = Chain.getValue(1);
+            Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
+            Chain = Arg.getValue(1);
+            InFlag = Arg.getValue(2);
           }
           Ops.push_back(Arg);
+          Ops.push_back(TheCall->getArgFlagsVal(i));
         }
         // Link in chain of CopyTo/CopyFromReg.
         Ops[0] = Chain;
@@ -351,48 +457,6 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
                                         BasicBlock::iterator End) {
   SDL->setCurrentBasicBlock(BB);
 
-  MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
-
-  if (MMI && BB->isLandingPad()) {
-    // Add a label to mark the beginning of the landing pad.  Deletion of the
-    // landing pad can thus be detected via the MachineModuleInfo.
-    unsigned LabelID = MMI->addLandingPad(BB);
-    CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
-                                     CurDAG->getEntryNode(), LabelID));
-
-    // Mark exception register as live in.
-    unsigned Reg = TLI.getExceptionAddressRegister();
-    if (Reg) BB->addLiveIn(Reg);
-
-    // Mark exception selector register as live in.
-    Reg = TLI.getExceptionSelectorRegister();
-    if (Reg) BB->addLiveIn(Reg);
-
-    // FIXME: Hack around an exception handling flaw (PR1508): the personality
-    // function and list of typeids logically belong to the invoke (or, if you
-    // like, the basic block containing the invoke), and need to be associated
-    // with it in the dwarf exception handling tables.  Currently however the
-    // information is provided by an intrinsic (eh.selector) that can be moved
-    // to unexpected places by the optimizers: if the unwind edge is critical,
-    // then breaking it can result in the intrinsics being in the successor of
-    // the landing pad, not the landing pad itself.  This results in exceptions
-    // not being caught because no typeids are associated with the invoke.
-    // This may not be the only way things can go wrong, but it is the only way
-    // we try to work around for the moment.
-    BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
-
-    if (Br && Br->isUnconditional()) { // Critical edge?
-      BasicBlock::iterator I, E;
-      for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
-        if (isa<EHSelectorInst>(I))
-          break;
-
-      if (I == E)
-        // No catch info found - try to extract some from the successor.
-        copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
-    }
-  }
-
   // Lower all of the non-terminator instructions.
   for (BasicBlock::iterator I = Begin; I != End; ++I)
     if (!isa<TerminatorInst>(I))
@@ -408,8 +472,12 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
     }
 
   // Handle PHI nodes in successor blocks.
-  if (End == LLVMBB->end())
+  if (End == LLVMBB->end()) {
     HandlePHINodesInSuccessorBlocks(LLVMBB);
+
+    // Lower the terminator after the copies are emitted.
+    SDL->visit(*LLVMBB->getTerminator());
+  }
     
   // Make sure the root of the DAG is up-to-date.
   CurDAG->setRoot(SDL->getControlRoot());
@@ -418,7 +486,8 @@ void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
   // with correct tailcall attribute so that the target can rely on the tailcall
   // attribute indicating whether the call is really eligible for tail call
   // optimization.
-  CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
+  if (PerformTailCallOpt)
+    CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
 
   // Final step, emit the lowered DAG as machine code.
   CodeGenAndEmitDAG();
@@ -508,7 +577,7 @@ void SelectionDAGISel::CodeGenAndEmitDAG() {
   
   // Second step, hack on the DAG until it only uses operations and types that
   // the target supports.
-  if (EnableLegalizeTypes) {// Enable this some day.
+  if (!DisableLegalizeTypes) {
     if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
                                                  BlockName);
 
@@ -601,88 +670,170 @@ void SelectionDAGISel::CodeGenAndEmitDAG() {
   DEBUG(BB->dump());
 }  
 
-void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF) {
+void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
+                                            MachineModuleInfo *MMI,
+                                            const TargetInstrInfo &TII) {
+  // Initialize the Fast-ISel state, if needed.
+  FastISel *FastIS = 0;
+  if (EnableFastISel)
+    FastIS = TLI.createFastISel(*FuncInfo->MF, MMI,
+                                FuncInfo->ValueMap,
+                                FuncInfo->MBBMap,
+                                FuncInfo->StaticAllocaMap
+#ifndef NDEBUG
+                                , FuncInfo->CatchInfoLost
+#endif
+                                );
+
+  // Iterate over all basic blocks in the function.
   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
     BasicBlock *LLVMBB = &*I;
     BB = FuncInfo->MBBMap[LLVMBB];
 
-    BasicBlock::iterator Begin = LLVMBB->begin();
-    BasicBlock::iterator End = LLVMBB->end();
+    BasicBlock::iterator const Begin = LLVMBB->begin();
+    BasicBlock::iterator const End = LLVMBB->end();
+    BasicBlock::iterator BI = Begin;
 
     // Lower any arguments needed in this block if this is the entry block.
-    if (LLVMBB == &Fn.getEntryBlock())
+    bool SuppressFastISel = false;
+    if (LLVMBB == &Fn.getEntryBlock()) {
       LowerArguments(LLVMBB);
 
-    // Before doing SelectionDAG ISel, see if FastISel has been requested.
-    // FastISel doesn't support EH landing pads, which require special handling.
-    if (EnableFastISel && !BB->isLandingPad()) {
-      if (FastISel *F = TLI.createFastISel(*FuncInfo->MF)) {
-        // Emit code for any incoming arguments. This must happen before
-        // beginning FastISel on the entry block.
-        if (LLVMBB == &Fn.getEntryBlock()) {
-          CurDAG->setRoot(SDL->getControlRoot());
-          CodeGenAndEmitDAG();
-          SDL->clear();
-        }
-        // Do FastISel on as many instructions as possible.
-        while (Begin != End) {
-          Begin = F->SelectInstructions(Begin, End, FuncInfo->ValueMap,
-                                        FuncInfo->MBBMap, BB);
+      // If any of the arguments has the byval attribute, forgo
+      // fast-isel in the entry block.
+      if (FastIS) {
+        unsigned j = 1;
+        for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
+             I != E; ++I, ++j)
+          if (Fn.paramHasAttr(j, Attribute::ByVal)) {
+            if (EnableFastISelVerbose || EnableFastISelAbort)
+              cerr << "FastISel skips entry block due to byval argument\n";
+            SuppressFastISel = true;
+            break;
+          }
+      }
+    }
 
-          // If the "fast" selector selected the entire block, we're done.
-          if (Begin == End)
+    if (MMI && BB->isLandingPad()) {
+      // Add a label to mark the beginning of the landing pad.  Deletion of the
+      // landing pad can thus be detected via the MachineModuleInfo.
+      unsigned LabelID = MMI->addLandingPad(BB);
+
+      const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
+      BuildMI(BB, II).addImm(LabelID);
+
+      // Mark exception register as live in.
+      unsigned Reg = TLI.getExceptionAddressRegister();
+      if (Reg) BB->addLiveIn(Reg);
+
+      // Mark exception selector register as live in.
+      Reg = TLI.getExceptionSelectorRegister();
+      if (Reg) BB->addLiveIn(Reg);
+
+      // FIXME: Hack around an exception handling flaw (PR1508): the personality
+      // function and list of typeids logically belong to the invoke (or, if you
+      // like, the basic block containing the invoke), and need to be associated
+      // with it in the dwarf exception handling tables.  Currently however the
+      // information is provided by an intrinsic (eh.selector) that can be moved
+      // to unexpected places by the optimizers: if the unwind edge is critical,
+      // then breaking it can result in the intrinsics being in the successor of
+      // the landing pad, not the landing pad itself.  This results in exceptions
+      // not being caught because no typeids are associated with the invoke.
+      // This may not be the only way things can go wrong, but it is the only way
+      // we try to work around for the moment.
+      BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
+
+      if (Br && Br->isUnconditional()) { // Critical edge?
+        BasicBlock::iterator I, E;
+        for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
+          if (isa<EHSelectorInst>(I))
             break;
 
-          // Next, try calling the target to attempt to handle the instruction.
-          if (F->TargetSelectInstruction(Begin, FuncInfo->ValueMap,
-                                         FuncInfo->MBBMap, BB)) {
-            ++Begin;
-            continue;
-          }
+        if (I == E)
+          // No catch info found - try to extract some from the successor.
+          copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
+      }
+    }
 
-          // Handle certain instructions as single-LLVM-Instruction blocks.
-          if (isa<CallInst>(Begin) || isa<LoadInst>(Begin) ||
-              isa<StoreInst>(Begin)) {
-            if (Begin->getType() != Type::VoidTy) {
-              unsigned &R = FuncInfo->ValueMap[Begin];
-              if (!R)
-                R = FuncInfo->CreateRegForValue(Begin);
+    // Before doing SelectionDAG ISel, see if FastISel has been requested.
+    if (FastIS && !SuppressFastISel) {
+      // Emit code for any incoming arguments. This must happen before
+      // beginning FastISel on the entry block.
+      if (LLVMBB == &Fn.getEntryBlock()) {
+        CurDAG->setRoot(SDL->getControlRoot());
+        CodeGenAndEmitDAG();
+        SDL->clear();
+      }
+      FastIS->startNewBlock(BB);
+      // Do FastISel on as many instructions as possible.
+      for (; BI != End; ++BI) {
+        // Just before the terminator instruction, insert instructions to
+        // feed PHI nodes in successor blocks.
+        if (isa<TerminatorInst>(BI))
+          if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
+            if (EnableFastISelVerbose || EnableFastISelAbort) {
+              cerr << "FastISel miss: ";
+              BI->dump();
             }
+            if (EnableFastISelAbort)
+              assert(0 && "FastISel didn't handle a PHI in a successor");
+            break;
+          }
+
+        // First try normal tablegen-generated "fast" selection.
+        if (FastIS->SelectInstruction(BI))
+          continue;
+
+        // Next, try calling the target to attempt to handle the instruction.
+        if (FastIS->TargetSelectInstruction(BI))
+          continue;
+
+        // Then handle certain instructions as single-LLVM-Instruction blocks.
+        if (isa<CallInst>(BI)) {
+          if (EnableFastISelVerbose || EnableFastISelAbort) {
+            cerr << "FastISel missed call: ";
+            BI->dump();
+          }
 
-            SelectBasicBlock(LLVMBB, Begin, next(Begin));
-            ++Begin;
-            continue;
+          if (BI->getType() != Type::VoidTy) {
+            unsigned &R = FuncInfo->ValueMap[BI];
+            if (!R)
+              R = FuncInfo->CreateRegForValue(BI);
           }
 
-          if (!DisableFastISelAbort &&
-              // For now, don't abort on non-conditional-branch terminators.
-              (!isa<TerminatorInst>(Begin) ||
-               (isa<BranchInst>(Begin) &&
-                cast<BranchInst>(Begin)->isUnconditional()))) {
+          SelectBasicBlock(LLVMBB, BI, next(BI));
+          // If the instruction was codegen'd with multiple blocks,
+          // inform the FastISel object where to resume inserting.
+          FastIS->setCurrentBlock(BB);
+          continue;
+        }
+
+        // Otherwise, give up on FastISel for the rest of the block.
+        // For now, be a little lenient about non-branch terminators.
+        if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
+          if (EnableFastISelVerbose || EnableFastISelAbort) {
+            cerr << "FastISel miss: ";
+            BI->dump();
+          }
+          if (EnableFastISelAbort)
             // The "fast" selector couldn't handle something and bailed.
             // For the purpose of debugging, just abort.
-#ifndef NDEBUG
-            Begin->dump();
-#endif
             assert(0 && "FastISel didn't select the entire block");
-          }
-          break;
         }
-        delete F;
+        break;
       }
     }
 
     // Run SelectionDAG instruction selection on the remainder of the block
     // not handled by FastISel. If FastISel is not run, this is the entire
-    // block. If FastISel is run and happens to handle all of the
-    // LLVM Instructions in the block, [Begin,End) will be an empty range,
-    // but we still need to run this so that
-    // HandlePHINodesInSuccessorBlocks is called and any resulting code
-    // is emitted.
-    SelectBasicBlock(LLVMBB, Begin, End);
+    // block.
+    if (BI != End)
+      SelectBasicBlock(LLVMBB, BI, End);
 
     FinishBasicBlock();
   }
+
+  delete FastIS;
 }
 
 void
@@ -997,7 +1148,7 @@ SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
     --e;  // Don't process a flag operand if it is here.
   
   while (i != e) {
-    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
+    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
     if ((Flags & 7) != 4 /*MEM*/) {
       // Just skip over this operand, copying the operands verbatim.
       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
@@ -1013,7 +1164,7 @@ SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
       
       // Add this to the output node.
       MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
-      Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
+      Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
                                               IntPtrTy));
       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
       i += 2;