Align Win64 EH Table sections to 4 bytes.
[oota-llvm.git] / utils / TableGen / TableGen.cpp
index ecce8e0f20bff30aa07924aaaccf69a2226b32cd..d88a2d6a0e26491526573ad52ee84fb1cc6a0217 100644 (file)
@@ -1,10 +1,10 @@
 //===- TableGen.cpp - Top-Level TableGen implementation -------------------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by the LLVM research group and is distributed under
-// the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
 //===----------------------------------------------------------------------===//
 //
 // TableGen is a tool which can be used to build up a description of something,
 //
 //===----------------------------------------------------------------------===//
 
-#include "Record.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/System/Signals.h"
-#include "llvm/Support/FileUtilities.h"
+#include "AsmMatcherEmitter.h"
+#include "AsmWriterEmitter.h"
+#include "CallingConvEmitter.h"
+#include "ClangASTNodesEmitter.h"
+#include "ClangAttrEmitter.h"
+#include "ClangDiagnosticsEmitter.h"
+#include "ClangSACheckersEmitter.h"
 #include "CodeEmitterGen.h"
-#include "RegisterInfoEmitter.h"
+#include "DAGISelEmitter.h"
+#include "DisassemblerEmitter.h"
+#include "EDEmitter.h"
+#include "FastISelEmitter.h"
+#include "InstrEnumEmitter.h"
 #include "InstrInfoEmitter.h"
-#include "AsmWriterEmitter.h"
-#include "InstrSelectorEmitter.h"
+#include "IntrinsicEmitter.h"
+#include "LLVMCConfigurationEmitter.h"
+#include "NeonEmitter.h"
+#include "OptParserEmitter.h"
+#include "Record.h"
+#include "RegisterInfoEmitter.h"
+#include "ARMDecoderEmitter.h"
+#include "SubtargetEmitter.h"
+#include "TGParser.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/system_error.h"
 #include <algorithm>
 #include <cstdio>
-#include <fstream>
 using namespace llvm;
 
 enum ActionType {
   PrintRecords,
   GenEmitter,
   GenRegisterEnums, GenRegister, GenRegisterHeader,
-  GenInstrEnums, GenInstrs, GenAsmWriter, GenInstrSelector,
-  PrintEnums,
-  Parse
+  GenInstrEnums, GenInstrs, GenAsmWriter, GenAsmMatcher,
+  GenARMDecoder,
+  GenDisassembler,
+  GenCallingConv,
+  GenClangAttrClasses,
+  GenClangAttrImpl,
+  GenClangAttrList,
+  GenClangAttrPCHRead,
+  GenClangAttrPCHWrite,
+  GenClangAttrSpellingList,
+  GenClangDiagsDefs,
+  GenClangDiagGroups,
+  GenClangDiagsIndexName,
+  GenClangDeclNodes,
+  GenClangStmtNodes,
+  GenClangSACheckers,
+  GenDAGISel,
+  GenFastISel,
+  GenOptParserDefs, GenOptParserImpl,
+  GenSubtarget,
+  GenIntrinsic,
+  GenTgtIntrinsic,
+  GenLLVMCConf,
+  GenEDInfo,
+  GenArmNeon,
+  GenArmNeonSema,
+  GenArmNeonTest,
+  PrintEnums
 };
 
 namespace {
@@ -55,14 +100,68 @@ namespace {
                                "Generate enum values for instructions"),
                     clEnumValN(GenInstrs, "gen-instr-desc",
                                "Generate instruction descriptions"),
+                    clEnumValN(GenCallingConv, "gen-callingconv",
+                               "Generate calling convention descriptions"),
                     clEnumValN(GenAsmWriter, "gen-asm-writer",
                                "Generate assembly writer"),
-                    clEnumValN(GenInstrSelector, "gen-instr-selector",
-                               "Generate an instruction selector"),
+                    clEnumValN(GenARMDecoder, "gen-arm-decoder",
+                               "Generate decoders for ARM/Thumb"),
+                    clEnumValN(GenDisassembler, "gen-disassembler",
+                               "Generate disassembler"),
+                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
+                               "Generate assembly instruction matcher"),
+                    clEnumValN(GenDAGISel, "gen-dag-isel",
+                               "Generate a DAG instruction selector"),
+                    clEnumValN(GenFastISel, "gen-fast-isel",
+                               "Generate a \"fast\" instruction selector"),
+                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
+                               "Generate option definitions"),
+                    clEnumValN(GenOptParserImpl, "gen-opt-parser-impl",
+                               "Generate option parser implementation"),
+                    clEnumValN(GenSubtarget, "gen-subtarget",
+                               "Generate subtarget enumerations"),
+                    clEnumValN(GenIntrinsic, "gen-intrinsic",
+                               "Generate intrinsic information"),
+                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
+                               "Generate target intrinsic information"),
+                    clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes",
+                               "Generate clang attribute clases"),
+                    clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl",
+                               "Generate clang attribute implementations"),
+                    clEnumValN(GenClangAttrList, "gen-clang-attr-list",
+                               "Generate a clang attribute list"),
+                    clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read",
+                               "Generate clang PCH attribute reader"),
+                    clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write",
+                               "Generate clang PCH attribute writer"),
+                    clEnumValN(GenClangAttrSpellingList,
+                               "gen-clang-attr-spelling-list",
+                               "Generate a clang attribute spelling list"),
+                    clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
+                               "Generate Clang diagnostics definitions"),
+                    clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
+                               "Generate Clang diagnostic groups"),
+                    clEnumValN(GenClangDiagsIndexName,
+                               "gen-clang-diags-index-name",
+                               "Generate Clang diagnostic name index"),
+                    clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes",
+                               "Generate Clang AST declaration nodes"),
+                    clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes",
+                               "Generate Clang AST statement nodes"),
+                    clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers",
+                               "Generate Clang Static Analyzer checkers"),
+                    clEnumValN(GenLLVMCConf, "gen-llvmc",
+                               "Generate LLVMC configuration library"),
+                    clEnumValN(GenEDInfo, "gen-enhanced-disassembly-info",
+                               "Generate enhanced disassembly info"),
+                    clEnumValN(GenArmNeon, "gen-arm-neon",
+                               "Generate arm_neon.h for clang"),
+                    clEnumValN(GenArmNeonSema, "gen-arm-neon-sema",
+                               "Generate ARM NEON sema support for clang"),
+                    clEnumValN(GenArmNeonTest, "gen-arm-neon-test",
+                               "Generate ARM NEON tests for clang"),
                     clEnumValN(PrintEnums, "print-enums",
                                "Print enum values for a class"),
-                    clEnumValN(Parse, "parse",
-                               "Interpret machine code (testing only)"),
                     clEnumValEnd));
 
   cl::opt<std::string>
@@ -76,425 +175,211 @@ namespace {
   cl::opt<std::string>
   InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
 
-  cl::opt<std::string>
-  IncludeDir("I", cl::desc("Directory of include files"),
-                  cl::value_desc("directory"), cl::init(""));
-}
-
-namespace llvm {
-  void ParseFile(const std::string &Filename,
-                 const std::string &IncludeDir);
-}
-
-RecordKeeper llvm::Records;
-
-static Init *getBit(Record *R, unsigned BitNo) {
-  const std::vector<RecordVal> &V = R->getValues();
-  for (unsigned i = 0, e = V.size(); i != e; ++i)
-    if (V[i].getPrefix()) {
-      assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
-            "Can only handle fields of bits<> type!");
-      BitsInit *I = (BitsInit*)V[i].getValue();
-      if (BitNo < I->getNumBits())
-       return I->getBit(BitNo);
-      BitNo -= I->getNumBits();
-    }
-
-  std::cerr << "Cannot find requested bit!\n";
-  exit(1);
-  return 0;
-}
-
-static unsigned getNumBits(Record *R) {
-  const std::vector<RecordVal> &V = R->getValues();
-  unsigned Num = 0;
-  for (unsigned i = 0, e = V.size(); i != e; ++i)
-    if (V[i].getPrefix()) {
-      assert(dynamic_cast<BitsInit*>(V[i].getValue()) &&
-            "Can only handle fields of bits<> type!");
-      Num += ((BitsInit*)V[i].getValue())->getNumBits();
-    }
-  return Num;
-}
-
-static bool BitsAreFixed(Record *I1, Record *I2, unsigned BitNo) {
-  return dynamic_cast<BitInit*>(getBit(I1, BitNo)) &&
-         dynamic_cast<BitInit*>(getBit(I2, BitNo));
-}
-
-static bool BitsAreEqual(Record *I1, Record *I2, unsigned BitNo) {
-  BitInit *Bit1 = dynamic_cast<BitInit*>(getBit(I1, BitNo));
-  BitInit *Bit2 = dynamic_cast<BitInit*>(getBit(I2, BitNo));
-
-  return Bit1 && Bit2 && Bit1->getValue() == Bit2->getValue();
-}
-
-static bool BitRangesEqual(Record *I1, Record *I2,
-                          unsigned Start, unsigned End) {
-  for (unsigned i = Start; i != End; ++i)
-    if (!BitsAreEqual(I1, I2, i))
-      return false;
-  return true;
-}
-
-static unsigned getFirstFixedBit(Record *R, unsigned FirstFixedBit) {
-  // Look for the first bit of the pair that are required to be 0 or 1.
-  while (!dynamic_cast<BitInit*>(getBit(R, FirstFixedBit)))
-    ++FirstFixedBit;
-  return FirstFixedBit;
-}
-
-static void FindInstDifferences(Record *I1, Record *I2,
-                               unsigned FirstFixedBit, unsigned MaxBits,
-                               unsigned &FirstVaryingBitOverall,
-                               unsigned &LastFixedBitOverall) {
-  // Compare the first instruction to the rest of the instructions, looking for
-  // fields that differ.
-  //
-  unsigned FirstVaryingBit = FirstFixedBit;
-  while (FirstVaryingBit < MaxBits && BitsAreEqual(I1, I2, FirstVaryingBit))
-    ++FirstVaryingBit;
+  cl::list<std::string>
+  IncludeDirs("I", cl::desc("Directory of include files"),
+              cl::value_desc("directory"), cl::Prefix);
 
-  unsigned LastFixedBit = FirstVaryingBit;
-  while (LastFixedBit < MaxBits && BitsAreFixed(I1, I2, LastFixedBit))
-    ++LastFixedBit;
-  
-  if (FirstVaryingBit < FirstVaryingBitOverall)
-    FirstVaryingBitOverall = FirstVaryingBit;
-  if (LastFixedBit < LastFixedBitOverall)
-    LastFixedBitOverall = LastFixedBit;
-}
-
-static bool getBitValue(Record *R, unsigned BitNo) {
-  Init *I = getBit(R, BitNo);
-  assert(dynamic_cast<BitInit*>(I) && "Bit should be fixed!");
-  return ((BitInit*)I)->getValue();
+  cl::opt<std::string>
+  ClangComponent("clang-component",
+                 cl::desc("Only use warnings from specified component"),
+                 cl::value_desc("component"), cl::Hidden);
 }
 
-struct BitComparator {
-  unsigned BitBegin, BitEnd;
-  BitComparator(unsigned B, unsigned E) : BitBegin(B), BitEnd(E) {}
 
-  bool operator()(Record *R1, Record *R2) { // Return true if R1 is less than R2
-    for (unsigned i = BitBegin; i != BitEnd; ++i) {
-      bool V1 = getBitValue(R1, i), V2 = getBitValue(R2, i);
-      if (V1 < V2)
-       return true;
-      else if (V2 < V1)
-       return false;
-    }
-    return false;
-  }
-};
+static SourceMgr SrcMgr;
 
-static void PrintRange(std::vector<Record*>::iterator I, 
-                      std::vector<Record*>::iterator E) {
-  while (I != E) std::cerr << **I++;
+void llvm::PrintError(SMLoc ErrorLoc, const Twine &Msg) {
+  SrcMgr.PrintMessage(ErrorLoc, Msg, "error");
 }
 
-static bool getMemoryBit(unsigned char *M, unsigned i) {
-  return (M[i/8] & (1 << (i&7))) != 0;
-}
 
-static unsigned getFirstFixedBitInSequence(std::vector<Record*>::iterator IB,
-                                          std::vector<Record*>::iterator IE,
-                                          unsigned StartBit) {
-  unsigned FirstFixedBit = 0;
-  for (std::vector<Record*>::iterator I = IB; I != IE; ++I)
-    FirstFixedBit = std::max(FirstFixedBit, getFirstFixedBit(*I, StartBit));
-  return FirstFixedBit;
-}
 
-// ParseMachineCode - Try to split the vector of instructions (which is
-// intentionally taken by-copy) in half, narrowing down the possible
-// instructions that we may have found.  Eventually, this list will get pared
-// down to zero or one instruction, in which case we have a match or failure.
-//
-static Record *ParseMachineCode(std::vector<Record*>::iterator InstsB, 
-                               std::vector<Record*>::iterator InstsE,
-                               unsigned char *M) {
-  assert(InstsB != InstsE && "Empty range?");
-  if (InstsB+1 == InstsE) {
-    // Only a single instruction, see if we match it...
-    Record *Inst = *InstsB;
-    for (unsigned i = 0, e = getNumBits(Inst); i != e; ++i)
-      if (BitInit *BI = dynamic_cast<BitInit*>(getBit(Inst, i)))
-       if (getMemoryBit(M, i) != BI->getValue())
-         throw std::string("Parse failed!\n");
-    return Inst;
+/// ParseFile - this function begins the parsing of the specified tablegen
+/// file.
+static bool ParseFile(const std::string &Filename,
+                      const std::vector<std::string> &IncludeDirs,
+                      SourceMgr &SrcMgr,
+                      RecordKeeper &Records) {
+  OwningPtr<MemoryBuffer> File;
+  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), File)) {
+    errs() << "Could not open input file '" << Filename << "': "
+           << ec.message() <<"\n";
+    return true;
   }
+  MemoryBuffer *F = File.take();
 
-  unsigned MaxBits = ~0;
-  for (std::vector<Record*>::iterator I = InstsB; I != InstsE; ++I)
-    MaxBits = std::min(MaxBits, getNumBits(*I));
-
-  unsigned FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, 0);
-  unsigned FirstVaryingBit, LastFixedBit;
-  do {
-    FirstVaryingBit = ~0;
-    LastFixedBit = ~0;
-    for (std::vector<Record*>::iterator I = InstsB+1; I != InstsE; ++I)
-      FindInstDifferences(*InstsB, *I, FirstFixedBit, MaxBits,
-                         FirstVaryingBit, LastFixedBit);
-    if (FirstVaryingBit == MaxBits) {
-      std::cerr << "ERROR: Could not find bit to distinguish between "
-               << "the following entries!\n";
-      PrintRange(InstsB, InstsE);
-    }
-
-#if 0
-    std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
-             << ": " << InstsE-InstsB << "\n";
-#endif
-
-    FirstFixedBit = getFirstFixedBitInSequence(InstsB, InstsE, FirstVaryingBit);
-  } while (FirstVaryingBit != FirstFixedBit);
-
-  //std::cerr << "\n\nXXXXXXXXXXXXXXXXX\n\n";
-  //PrintRange(InstsB, InstsE);
-
-  // Sort the Insts list so that the entries have all of the bits in the range
-  // [FirstVaryingBit,LastFixedBit) sorted.  These bits are all guaranteed to be
-  // set to either 0 or 1 (BitInit values), which simplifies things.
-  //
-  std::sort(InstsB, InstsE, BitComparator(FirstVaryingBit, LastFixedBit));
-
-  // Once the list is sorted by these bits, split the bit list into smaller
-  // lists, and recurse on each one.
-  //
-  std::vector<Record*>::iterator RangeBegin = InstsB;
-  Record *Match = 0;
-  while (RangeBegin != InstsE) {
-    std::vector<Record*>::iterator RangeEnd = RangeBegin+1;
-    while (RangeEnd != InstsE &&
-          BitRangesEqual(*RangeBegin, *RangeEnd, FirstVaryingBit, LastFixedBit))
-      ++RangeEnd;
-    
-    // We just identified a range of equal instructions.  If this range is the
-    // input range, we were not able to distinguish between the instructions in
-    // the set.  Print an error and exit!
-    //
-    if (RangeBegin == InstsB && RangeEnd == InstsE) {
-      std::cerr << "Error: Could not distinguish among the following insts!:\n";
-      PrintRange(InstsB, InstsE);
-      exit(1);
-    }
-    
-#if 0
-    std::cerr << "FVB: " << FirstVaryingBit << " - " << LastFixedBit
-             << ": [" << RangeEnd-RangeBegin << "] - ";
-    for (int i = LastFixedBit-1; i >= (int)FirstVaryingBit; --i)
-      std::cerr << (int)((BitInit*)getBit(*RangeBegin, i))->getValue() << " ";
-    std::cerr << "\n";
-#endif
+  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
+  SrcMgr.AddNewSourceBuffer(F, SMLoc());
 
-    if (Record *R = ParseMachineCode(RangeBegin, RangeEnd, M)) {
-      if (Match) {
-       std::cerr << "Error: Multiple matches found:\n";
-       PrintRange(InstsB, InstsE);
-      }
+  // Record the location of the include directory so that the lexer can find
+  // it later.
+  SrcMgr.setIncludeDirs(IncludeDirs);
 
-      assert(Match == 0 && "Multiple matches??");
-      Match = R;
-    }
-    RangeBegin = RangeEnd;
-  }
+  TGParser Parser(SrcMgr, Records);
 
-  return Match;
-}
-
-static void PrintValue(Record *I, unsigned char *Ptr, const RecordVal &Val) {
-  assert(dynamic_cast<BitsInit*>(Val.getValue()) &&
-        "Can only handle undefined bits<> types!");
-  BitsInit *BI = (BitsInit*)Val.getValue();
-  assert(BI->getNumBits() <= 32 && "Can only handle fields up to 32 bits!");
-
-  unsigned Value = 0;
-  const std::vector<RecordVal> &Vals = I->getValues();
-
-  // Start by filling in fixed values...
-  for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
-    if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(i)))
-      Value |= B->getValue() << i;
-  
-  // Loop over all of the fields in the instruction adding in any
-  // contributions to this value (due to bit references).
-  //
-  unsigned Offset = 0;
-  for (unsigned f = 0, e = Vals.size(); f != e; ++f)
-    if (Vals[f].getPrefix()) {
-      BitsInit *FieldInitializer = (BitsInit*)Vals[f].getValue();
-      if (&Vals[f] == &Val) {
-       // Read the bits directly now...
-       for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
-         Value |= getMemoryBit(Ptr, Offset+i) << i;
-       break;
-      }
-      
-      // Scan through the field looking for bit initializers of the current
-      // variable...
-      for (unsigned i = 0, e = FieldInitializer->getNumBits(); i != e; ++i)
-       if (VarBitInit *VBI =
-           dynamic_cast<VarBitInit*>(FieldInitializer->getBit(i))) {
-          TypedInit *TI = VBI->getVariable();
-          if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
-            if (VI->getName() == Val.getName())
-              Value |= getMemoryBit(Ptr, Offset+i) << VBI->getBitNum();
-          } else if (FieldInit *FI = dynamic_cast<FieldInit*>(TI)) {
-            // FIXME: implement this!
-            std::cerr << "FIELD INIT not implemented yet!\n";
-          }
-       }       
-      Offset += FieldInitializer->getNumBits();
-    }
-
-  std::cout << "0x" << std::hex << Value << std::dec;
-}
-
-static void PrintInstruction(Record *I, unsigned char *Ptr) {
-  std::cout << "Inst " << getNumBits(I)/8 << " bytes: "
-           << "\t" << I->getName() << "\t" << *I->getValue("Name")->getValue()
-           << "\t";
-  
-  const std::vector<RecordVal> &Vals = I->getValues();
-  for (unsigned i = 0, e = Vals.size(); i != e; ++i)
-    if (!Vals[i].getValue()->isComplete()) {
-      std::cout << Vals[i].getName() << "=";
-      PrintValue(I, Ptr, Vals[i]);
-      std::cout << "\t";
-    }
-  
-  std::cout << "\n";// << *I;
-}
-
-static void ParseMachineCode() {
-  // X86 code
-  unsigned char Buffer[] = {
-                             0x55,             // push EBP
-                            0x89, 0xE5,       // mov EBP, ESP
-                            //0x83, 0xEC, 0x08, // sub ESP, 0x8
-                            0xE8, 1, 2, 3, 4, // call +0x04030201
-                            0x89, 0xEC,       // mov ESP, EBP
-                            0x5D,             // pop EBP
-                            0xC3,             // ret
-                            0x90,             // nop
-                            0xC9,             // leave
-                            0x89, 0xF6,       // mov ESI, ESI
-                            0x68, 1, 2, 3, 4, // push 0x04030201
-                            0x5e,             // pop ESI
-                            0xFF, 0xD0,       // call EAX
-                            0xB8, 1, 2, 3, 4, // mov EAX, 0x04030201
-                            0x85, 0xC0,       // test EAX, EAX
-                            0xF4,             // hlt
-  };
-
-#if 0
-  // SparcV9 code
-  unsigned char Buffer[] = { 0xbf, 0xe0, 0x20, 0x1f, 0x1, 0x0, 0x0, 0x1, 
-                             0x0, 0x0, 0x0, 0x0, 0xc1, 0x0, 0x20, 0x1, 0x1,
-                             0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
-                             0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1,
-                             0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
-                             0x0, 0x0, 0xaf, 0xe8, 0x20, 0x17
-  };
-#endif
-
-  std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
-
-  unsigned char *BuffPtr = Buffer;
-  while (1) {
-    Record *R = ParseMachineCode(Insts.begin(), Insts.end(), BuffPtr);
-    PrintInstruction(R, BuffPtr);
-
-    unsigned Bits = getNumBits(R);
-    assert((Bits & 7) == 0 && "Instruction is not an even number of bytes!");
-    BuffPtr += Bits/8;
-  }
+  return Parser.ParseFile();
 }
 
 int main(int argc, char **argv) {
+  RecordKeeper Records;
+
+  sys::PrintStackTraceOnErrorSignal();
+  PrettyStackTraceProgram X(argc, argv);
   cl::ParseCommandLineOptions(argc, argv);
-  ParseFile(InputFilename, IncludeDir);
 
-  std::ostream *Out = &std::cout;
-  if (OutputFilename != "-") {
-    Out = new std::ofstream(OutputFilename.c_str());
 
-    if (!Out->good()) {
-      std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
+  try {
+    // Parse the input file.
+    if (ParseFile(InputFilename, IncludeDirs, SrcMgr, Records))
       return 1;
-    }
 
-    // Make sure the file gets removed if *gasp* tablegen crashes...
-    sys::RemoveFileOnSignal(sys::Path(OutputFilename));
-  }
+    std::string Error;
+    tool_output_file Out(OutputFilename.c_str(), Error);
+    if (!Error.empty()) {
+      errs() << argv[0] << ": error opening " << OutputFilename
+        << ":" << Error << "\n";
+      return 1;
+    }
 
-  try {
     switch (Action) {
     case PrintRecords:
-      *Out << Records;           // No argument, dump all contents
-      break;
-    case Parse:
-      ParseMachineCode();
+      Out.os() << Records;           // No argument, dump all contents
       break;
     case GenEmitter:
-      CodeEmitterGen(Records).run(*Out);
+      CodeEmitterGen(Records).run(Out.os());
       break;
 
     case GenRegisterEnums:
-      RegisterInfoEmitter(Records).runEnums(*Out);
+      RegisterInfoEmitter(Records).runEnums(Out.os());
       break;
     case GenRegister:
-      RegisterInfoEmitter(Records).run(*Out);
+      RegisterInfoEmitter(Records).run(Out.os());
       break;
     case GenRegisterHeader:
-      RegisterInfoEmitter(Records).runHeader(*Out);
+      RegisterInfoEmitter(Records).runHeader(Out.os());
       break;
-
     case GenInstrEnums:
-      InstrInfoEmitter(Records).runEnums(*Out);
+      InstrEnumEmitter(Records).run(Out.os());
       break;
     case GenInstrs:
-      InstrInfoEmitter(Records).run(*Out);
+      InstrInfoEmitter(Records).run(Out.os());
+      break;
+    case GenCallingConv:
+      CallingConvEmitter(Records).run(Out.os());
       break;
-
     case GenAsmWriter:
-      AsmWriterEmitter(Records).run(*Out);
+      AsmWriterEmitter(Records).run(Out.os());
       break;
-
-    case GenInstrSelector:
-      InstrSelectorEmitter(Records).run(*Out);
+    case GenARMDecoder:
+      ARMDecoderEmitter(Records).run(Out.os());
+      break;
+    case GenAsmMatcher:
+      AsmMatcherEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrClasses:
+      ClangAttrClassEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrImpl:
+      ClangAttrImplEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrList:
+      ClangAttrListEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrPCHRead:
+      ClangAttrPCHReadEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrPCHWrite:
+      ClangAttrPCHWriteEmitter(Records).run(Out.os());
+      break;
+    case GenClangAttrSpellingList:
+      ClangAttrSpellingListEmitter(Records).run(Out.os());
+      break;
+    case GenClangDiagsDefs:
+      ClangDiagsDefsEmitter(Records, ClangComponent).run(Out.os());
+      break;
+    case GenClangDiagGroups:
+      ClangDiagGroupsEmitter(Records).run(Out.os());
+      break;
+    case GenClangDiagsIndexName:
+      ClangDiagsIndexNameEmitter(Records).run(Out.os());
+      break;
+    case GenClangDeclNodes:
+      ClangASTNodesEmitter(Records, "Decl", "Decl").run(Out.os());
+      ClangDeclContextEmitter(Records).run(Out.os());
+      break;
+    case GenClangStmtNodes:
+      ClangASTNodesEmitter(Records, "Stmt", "").run(Out.os());
+      break;
+    case GenClangSACheckers:
+      ClangSACheckersEmitter(Records).run(Out.os());
+      break;
+    case GenDisassembler:
+      DisassemblerEmitter(Records).run(Out.os());
+      break;
+    case GenOptParserDefs:
+      OptParserEmitter(Records, true).run(Out.os());
+      break;
+    case GenOptParserImpl:
+      OptParserEmitter(Records, false).run(Out.os());
+      break;
+    case GenDAGISel:
+      DAGISelEmitter(Records).run(Out.os());
+      break;
+    case GenFastISel:
+      FastISelEmitter(Records).run(Out.os());
+      break;
+    case GenSubtarget:
+      SubtargetEmitter(Records).run(Out.os());
+      break;
+    case GenIntrinsic:
+      IntrinsicEmitter(Records).run(Out.os());
+      break;
+    case GenTgtIntrinsic:
+      IntrinsicEmitter(Records, true).run(Out.os());
+      break;
+    case GenLLVMCConf:
+      LLVMCConfigurationEmitter(Records).run(Out.os());
+      break;
+    case GenEDInfo:
+      EDEmitter(Records).run(Out.os());
+      break;
+    case GenArmNeon:
+      NeonEmitter(Records).run(Out.os());
+      break;
+    case GenArmNeonSema:
+      NeonEmitter(Records).runHeader(Out.os());
+      break;
+    case GenArmNeonTest:
+      NeonEmitter(Records).runTests(Out.os());
       break;
     case PrintEnums:
     {
       std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class);
       for (unsigned i = 0, e = Recs.size(); i != e; ++i)
-        *Out << Recs[i]->getName() << ", ";
-      *Out << "\n";
+        Out.os() << Recs[i]->getName() << ", ";
+      Out.os() << "\n";
       break;
     }
     default:
       assert(1 && "Invalid Action");
       return 1;
     }
+
+    // Declare success.
+    Out.keep();
+    return 0;
+
+  } catch (const TGError &Error) {
+    errs() << argv[0] << ": error:\n";
+    PrintError(Error.getLoc(), Error.getMessage());
+
   } catch (const std::string &Error) {
-    std::cerr << argv[0] << ": " << Error << "\n";
-    if (Out != &std::cout) {
-      delete Out;                             // Close the file
-      std::remove(OutputFilename.c_str());    // Remove the file, it's broken
-    }
-    return 1;
+    errs() << argv[0] << ": " << Error << "\n";
+  } catch (const char *Error) {
+    errs() << argv[0] << ": " << Error << "\n";
   } catch (...) {
-    std::cerr << argv[0] << ": Unknown unexpected exception occurred.\n";
-    if (Out != &std::cout) {
-      delete Out;                             // Close the file
-      std::remove(OutputFilename.c_str());    // Remove the file, it's broken
-    }
-    return 2;
+    errs() << argv[0] << ": Unknown unexpected exception occurred.\n";
   }
 
-  if (Out != &std::cout) {
-    delete Out;                               // Close the file
-  }
-  return 0;
+  return 1;
 }