We won't use automake
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
index 139320f64033962062eaacf6aad7d24d141b7050..7af9bfe4fa6b6d566bc9f8b478d767d781850c95 100644 (file)
@@ -32,8 +32,9 @@
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/InstVisitor.h"
 #include "llvm/Support/Mangler.h"
-#include "Support/StringExtras.h"
-#include "Config/config.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Config/config.h"
 #include <algorithm>
 #include <iostream>
 #include <sstream>
@@ -46,7 +47,7 @@ namespace {
   /// NameAllUsedStructs - This pass inserts names for any unnamed structure
   /// types that are used by the program.
   ///
-  class CBackendNameAllUsedStructs : public Pass {
+  class CBackendNameAllUsedStructs : public ModulePass {
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<FindUsedTypes>();
     }
@@ -55,7 +56,7 @@ namespace {
       return "C backend type canonicalizer";
     }
 
-    virtual bool run(Module &M);
+    virtual bool runOnModule(Module &M);
   };
   
   /// CWriter - This class is the main chunk of code that converts an LLVM
@@ -173,6 +174,7 @@ namespace {
     void visitUnwindInst(UnwindInst &I) {
       assert(0 && "Lowerinvoke pass didn't work!");
     }
+    void visitUnreachableInst(UnreachableInst &I);
 
     void visitPHINode(PHINode &I);
     void visitBinaryOperator(Instruction &I);
@@ -202,6 +204,8 @@ namespace {
     }
 
     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
+    void printPHICopiesForSuccessor(BasicBlock *CurBlock,
+                                    BasicBlock *Successor, unsigned Indent);
     void printPHICopiesForSuccessors(BasicBlock *CurBlock, 
                                      unsigned Indent);
     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
@@ -215,7 +219,7 @@ namespace {
 /// the program, and removes names from structure types that are not used by the
 /// program.
 ///
-bool CBackendNameAllUsedStructs::run(Module &M) {
+bool CBackendNameAllUsedStructs::runOnModule(Module &M) {
   // Get a set of types that are used by the program...
   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
   
@@ -520,6 +524,11 @@ void CWriter::printConstant(Constant *CPV) {
                 << *CE << "\n";
       abort();
     }
+  } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
+    Out << "((";
+    printType(Out, CPV->getType());
+    Out << ")/*UNDEF*/0)";
+    return;
   }
 
   switch (CPV->getType()->getTypeID()) {
@@ -556,20 +565,56 @@ void CWriter::printConstant(Constant *CPV) {
       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
           << "*)&FPConstant" << I->second << ")";
     } else {
+      if (IsNAN(FPC->getValue())) {
+        // The value is NaN
+        // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
+        // it's 0x7ff4.
+        const unsigned long QuietNaN = 0x7ff8UL;
+        const unsigned long SignalNaN = 0x7ff4UL;
+
+        // We need to grab the first part of the FP #
+        union {
+          double   d;
+          uint64_t ll;
+        } DHex;
+        char Buffer[100];
+
+        DHex.d = FPC->getValue();
+        sprintf(Buffer, "0x%llx", (unsigned long long)DHex.ll);
+
+        std::string Num(&Buffer[0], &Buffer[6]);
+        unsigned long Val = strtoul(Num.c_str(), 0, 16);
+
+        if (FPC->getType() == Type::FloatTy)
+          Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
+              << Buffer << "\") /*nan*/ ";
+        else
+          Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
+              << Buffer << "\") /*nan*/ ";
+      } else if (IsInf(FPC->getValue())) {
+        // The value is Inf
+        if (FPC->getValue() < 0) Out << "-";
+        Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
+            << " /*inf*/ ";
+      } else {
+        std::string Num;
 #if HAVE_PRINTF_A
-      // Print out the constant as a floating point number.
-      char Buffer[100];
-      sprintf(Buffer, "%a", FPC->getValue());
-      Out << Buffer << " /*" << FPC->getValue() << "*/ ";
+        // Print out the constant as a floating point number.
+        char Buffer[100];
+        sprintf(Buffer, "%a", FPC->getValue());
+        Num = Buffer;
 #else
-      Out << ftostr(FPC->getValue());
+        Num = ftostr(FPC->getValue());
 #endif
+        Out << Num;
+      }
     }
     break;
   }
 
   case Type::ArrayTyID:
-    if (isa<ConstantAggregateZero>(CPV)) {
+    if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
       const ArrayType *AT = cast<ArrayType>(CPV->getType());
       Out << "{";
       if (AT->getNumElements()) {
@@ -588,7 +633,7 @@ void CWriter::printConstant(Constant *CPV) {
     break;
 
   case Type::StructTyID:
-    if (isa<ConstantAggregateZero>(CPV)) {
+    if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
       const StructType *ST = cast<StructType>(CPV->getType());
       Out << "{";
       if (ST->getNumElements()) {
@@ -620,8 +665,8 @@ void CWriter::printConstant(Constant *CPV) {
       printType(Out, CPV->getType());
       Out << ")/*NULL*/0)";
       break;
-    } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
-      writeOperand(CPR->getValue());
+    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
+      writeOperand(GV);
       break;
     }
     // FALL THROUGH
@@ -641,7 +686,8 @@ void CWriter::writeOperandInternal(Value *Operand) {
       return;
     }
   
-  if (Constant *CPV = dyn_cast<Constant>(Operand)) {
+  Constant* CPV = dyn_cast<Constant>(Operand);
+  if (CPV && !isa<GlobalValue>(CPV)) {
     printConstant(CPV); 
   } else {
     Out << Mang->getValueName(Operand);
@@ -667,10 +713,10 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#if defined(sun) || defined(__CYGWIN__) || defined(__APPLE__)\n"
       << "extern void *__builtin_alloca(unsigned long);\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
+      << "#elif defined(__FreeBSD__)\n"
+      << "#define alloca(x) __builtin_alloca(x)\n"
       << "#else\n"
-      << "#ifndef __FreeBSD__\n"
       << "#include <alloca.h>\n"
-      << "#endif\n"
       << "#endif\n\n";
 
   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
@@ -699,6 +745,53 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#else\n"
       << "#define __ATTRIBUTE_WEAK__\n"
       << "#endif\n\n";
+
+  // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
+  // From the GCC documentation:
+  // 
+  //   double __builtin_nan (const char *str)
+  //
+  // This is an implementation of the ISO C99 function nan.
+  //
+  // Since ISO C99 defines this function in terms of strtod, which we do
+  // not implement, a description of the parsing is in order. The string is
+  // parsed as by strtol; that is, the base is recognized by leading 0 or
+  // 0x prefixes. The number parsed is placed in the significand such that
+  // the least significant bit of the number is at the least significant
+  // bit of the significand. The number is truncated to fit the significand
+  // field provided. The significand is forced to be a quiet NaN.
+  //
+  // This function, if given a string literal, is evaluated early enough
+  // that it is considered a compile-time constant.
+  //
+  //   float __builtin_nanf (const char *str)
+  //
+  // Similar to __builtin_nan, except the return type is float.
+  //
+  //   double __builtin_inf (void)
+  //
+  // Similar to __builtin_huge_val, except a warning is generated if the
+  // target floating-point format does not support infinities. This
+  // function is suitable for implementing the ISO C99 macro INFINITY.
+  //
+  //   float __builtin_inff (void)
+  //
+  // Similar to __builtin_inf, except the return type is float.
+  Out << "#ifdef __GNUC__\n"
+      << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
+      << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
+      << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
+      << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
+      << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
+      << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
+      << "#else\n"
+      << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
+      << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
+      << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
+      << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
+      << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
+      << "#define LLVM_INFF          0.0F                    /* Float */\n"
+      << "#endif\n";
 }
 
 bool CWriter::doInitialization(Module &M) {
@@ -1120,6 +1213,10 @@ void CWriter::visitSwitchInst(SwitchInst &SI) {
   Out << "  }\n";
 }
 
+void CWriter::visitUnreachableInst(UnreachableInst &I) {
+  Out << "  /*UNREACHABLE*/;\n";
+}
+
 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
   /// FIXME: This should be reenabled, but loop reordering safe!!
   return true;
@@ -1135,18 +1232,38 @@ bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
   return false;
 }
 
-void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock, 
+void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
+                                          BasicBlock *Successor, 
                                           unsigned Indent) {
-  for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
-       SI != E; ++SI)
-    for (BasicBlock::iterator I = SI->begin();
-         PHINode *PN = dyn_cast<PHINode>(I); ++I) {
-      //  now we have to do the printing
+  for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
+    PHINode *PN = cast<PHINode>(I);
+    // Now we have to do the printing.
+    Value *IV = PN->getIncomingValueForBlock(CurBlock);
+    if (!isa<UndefValue>(IV)) {
       Out << std::string(Indent, ' ');
       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
-      writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBlock)));
+      writeOperand(IV);
       Out << ";   /* for PHI node */\n";
     }
+  }
+}
+
+
+void CWriter::printPHICopiesForSuccessors(BasicBlock *CurBlock, 
+                                          unsigned Indent) {
+  for (succ_iterator SI = succ_begin(CurBlock), E = succ_end(CurBlock);
+       SI != E; ++SI)
+    for (BasicBlock::iterator I = SI->begin(); isa<PHINode>(I); ++I) {
+      PHINode *PN = cast<PHINode>(I);
+      // Now we have to do the printing.
+      Value *IV = PN->getIncomingValueForBlock(CurBlock);
+      if (!isa<UndefValue>(IV)) {
+        Out << std::string(Indent, ' ');
+        Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
+        writeOperand(IV);
+        Out << ";   /* for PHI node */\n";
+      }
+    }
 }
 
 
@@ -1163,7 +1280,6 @@ void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
 // that immediately succeeds the current one.
 //
 void CWriter::visitBranchInst(BranchInst &I) {
-  printPHICopiesForSuccessors(I.getParent(), 0);
 
   if (I.isConditional()) {
     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
@@ -1171,10 +1287,12 @@ void CWriter::visitBranchInst(BranchInst &I) {
       writeOperand(I.getCondition());
       Out << ") {\n";
       
+      printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
       
       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
         Out << "  } else {\n";
+        printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
       }
     } else {
@@ -1183,11 +1301,13 @@ void CWriter::visitBranchInst(BranchInst &I) {
       writeOperand(I.getCondition());
       Out << ") {\n";
 
+      printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
     }
 
     Out << "  }\n";
   } else {
+    printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
   }
   Out << "\n";
@@ -1327,9 +1447,13 @@ void CWriter::visitCallInst(CallInst &I) {
         Out << ")";
         return;
       case Intrinsic::vaend:
-        Out << "va_end(*(va_list*)&";
-        writeOperand(I.getOperand(1));
-        Out << ")";
+        if (!isa<ConstantPointerNull>(I.getOperand(1))) {
+          Out << "va_end(*(va_list*)&";
+          writeOperand(I.getOperand(1));
+          Out << ")";
+        } else {
+          Out << "va_end(*(va_list*)0)";
+        }
         return;
       case Intrinsic::vacopy:
         Out << "0;";
@@ -1412,9 +1536,6 @@ void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
   // If accessing a global value with no indexing, avoid *(&GV) syndrome
   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
     HasImplicitAddress = true;
-  } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
-    HasImplicitAddress = true;
-    Ptr = CPR->getValue();         // Get to the global...
   } else if (isDirectAlloca(Ptr)) {
     HasImplicitAddress = true;
   }