Turn off "attribute weak" to pacify Mac OS X's system compiler, which prints a
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
index bac088abf7fb9a8757e921ed99bb5a4b5f7dd4b1..3d73493d94acc23406a99f6ccf105669e2361bc8 100644 (file)
 #include "llvm/Intrinsics.h"
 #include "llvm/Analysis/FindUsedTypes.h"
 #include "llvm/Analysis/ConstantsScanner.h"
+#include "llvm/Support/CallSite.h"
+#include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/InstVisitor.h"
 #include "llvm/Support/InstIterator.h"
-#include "llvm/Support/CallSite.h"
 #include "llvm/Support/Mangler.h"
 #include "Support/StringExtras.h"
 #include "Support/STLExtras.h"
@@ -160,8 +161,8 @@ namespace {
     }
     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
                             unsigned Indent);
-    void printIndexingExpression(Value *Ptr, User::op_iterator I,
-                                 User::op_iterator E);
+    void printIndexingExpression(Value *Ptr, gep_type_iterator I,
+                                 gep_type_iterator E);
   };
 
 // Pass the Type* and the variable name and this prints out the variable
@@ -381,8 +382,8 @@ void CWriter::printConstant(Constant *CPV) {
 
     case Instruction::GetElementPtr:
       Out << "(&(";
-      printIndexingExpression(CE->getOperand(0),
-                              CPV->op_begin()+1, CPV->op_end());
+      printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
+                              gep_type_end(CPV));
       Out << "))";
       return;
     case Instruction::Add:
@@ -396,6 +397,8 @@ void CWriter::printConstant(Constant *CPV) {
     case Instruction::SetLE:
     case Instruction::SetGT:
     case Instruction::SetGE:
+    case Instruction::Shl:
+    case Instruction::Shr:
       Out << "(";
       printConstant(CE->getOperand(0));
       switch (CE->getOpcode()) {
@@ -410,6 +413,8 @@ void CWriter::printConstant(Constant *CPV) {
       case Instruction::SetLE: Out << " <= "; break;
       case Instruction::SetGT: Out << " > "; break;
       case Instruction::SetGE: Out << " >= "; break;
+      case Instruction::Shl: Out << " << "; break;
+      case Instruction::Shr: Out << " >> "; break;
       default: assert(0 && "Illegal opcode here!");
       }
       printConstant(CE->getOperand(1));
@@ -564,7 +569,7 @@ bool CWriter::nameAllUsedStructureTypes(Module &M) {
 // generateCompilerSpecificCode - This is where we add conditional compilation
 // directives to cater to specific compilers as need be.
 //
-void generateCompilerSpecificCode(std::ostream& Out) {
+static void generateCompilerSpecificCode(std::ostream& Out) {
   // Alloca is hard to get, and we don't want to include stdlib.h here...
   Out << "/* get a declaration for alloca */\n"
       << "#ifdef sun\n"
@@ -580,9 +585,53 @@ void generateCompilerSpecificCode(std::ostream& Out) {
   // If we aren't being compiled with GCC, just drop these attributes.
   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
       << "#define __attribute__(X)\n"
-      << "#endif\n";
+      << "#endif\n\n";
+
+#if 0
+  // At some point, we should support "external weak" vs. "weak" linkages.
+  // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
+  Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
+      << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
+      << "#elif defined(__GNUC__)\n"
+      << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
+      << "#else\n"
+      << "#define __EXTERNAL_WEAK__\n"
+      << "#endif\n\n";
+#endif
+
+  // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
+  Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
+      << "#define __ATTRIBUTE_WEAK__\n"
+      << "#elif defined(__GNUC__)\n"
+      << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
+      << "#else\n"
+      << "#define __ATTRIBUTE_WEAK__\n"
+      << "#endif\n\n";
+}
+
+// generateProcessorSpecificCode - This is where we add conditional compilation
+// directives to cater to specific processors as need be.
+//
+static void generateProcessorSpecificCode(std::ostream& Out) {
+  // According to ANSI C, longjmp'ing to a setjmp could invalidate any
+  // non-volatile variable in the scope of the setjmp.  For now, we are not
+  // doing analysis to determine which variables need to be marked volatile, so
+  // we just mark them all.
+  //
+  // HOWEVER, many targets implement setjmp by saving and restoring the register
+  // file, so they DON'T need variables to be marked volatile, and this is a
+  // HUGE pessimization for them.  For this reason, on known-good processors, we
+  // do not emit volatile qualifiers.
+  Out << "#if defined(__386__) || defined(__i386__) || \\\n"
+      << "    defined(i386) || defined(WIN32)\n"
+      << "/* setjmp does not require variables to be marked volatile */"
+      << "#define VOLATILE_FOR_SETJMP\n"
+      << "#else\n"
+      << "#define VOLATILE_FOR_SETJMP volatile\n"
+      << "#endif\n\n";
 }
 
+
 void CWriter::printModule(Module *M) {
   // Calculate which global values have names that will collide when we throw
   // away type information.
@@ -605,10 +654,11 @@ void CWriter::printModule(Module *M) {
 
   // get declaration for alloca
   Out << "/* Provide Declarations */\n";
-  Out << "#include <stdarg.h>\n";
-  Out << "#include <setjmp.h>\n";
+  Out << "#include <stdarg.h>\n";      // Varargs support
+  Out << "#include <setjmp.h>\n";      // Unwind support
   generateCompilerSpecificCode(Out);
-  
+  generateProcessorSpecificCode(Out);
+
   // Provide a definition for `bool' if not compiling with a C++ compiler.
   Out << "\n"
       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
@@ -654,7 +704,7 @@ void CWriter::printModule(Module *M) {
       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
           !I->getIntrinsicID()) {
         printFunctionSignature(I, true);
-        if (I->hasWeakLinkage()) Out << " __attribute__((weak))";
+        if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
     }
@@ -677,7 +727,7 @@ void CWriter::printModule(Module *M) {
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
         else if (I->hasWeakLinkage())
-          Out << " __attribute__((weak))";
+          Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
   }
@@ -693,7 +743,7 @@ void CWriter::printModule(Module *M) {
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
         else if (I->hasWeakLinkage())
-          Out << " __attribute__((weak))";
+          Out << " __ATTRIBUTE_WEAK__";
 
         // If the initializer is not null, emit the initializer.  If it is null,
         // we try to avoid emitting large amounts of zeros.  The problem with
@@ -912,6 +962,8 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
     if (FT->getParamTypes().size()) FunctionInnards << ", ";
     FunctionInnards << "...";  // Output varargs portion of signature!
+  } else if (!FT->isVarArg() && FT->getParamTypes().empty()) {
+    FunctionInnards << "void"; // ret() -> ret(void) in C.
   }
   FunctionInnards << ")";
   // Print out the return type and the entire signature for that matter
@@ -924,19 +976,30 @@ void CWriter::printFunction(Function *F) {
   printFunctionSignature(F, false);
   Out << " {\n";
 
+  // Determine whether or not the function contains any invoke instructions.
+  bool HasInvoke = false;
+  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
+    if (isa<InvokeInst>(I->getTerminator())) {
+      HasInvoke = true;
+      break;
+    }
+
   // print local variable information for the function
   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
     if (const AllocaInst *AI = isDirectAlloca(*I)) {
       Out << "  ";
+      if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
       Out << ";    /* Address exposed local */\n";
     } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
       Out << "  ";
+      if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
       printType(Out, (*I)->getType(), Mang->getValueName(*I));
       Out << ";\n";
       
       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
         Out << "  ";
+        if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
         printType(Out, (*I)->getType(),
                   Mang->getValueName(*I)+"__PHI_TEMPORARY");
         Out << ";\n";
@@ -1051,7 +1114,11 @@ void CWriter::visitUnwindInst(UnwindInst &I) {
   // instruction to add an entry to the top of the jmpbuf_list.  Thus, here we
   // just have to longjmp to the specified handler.
   Out << "  if (__llvm_jmpbuf_list == 0) {  /* unwind */\n"
+      << "#ifdef _LP64\n"
+      << "    extern signed long long write();\n"
+      << "#else\n"
       << "    extern write();\n"
+      << "#endif\n"
       << "    ((void (*)(int, void*, unsigned))write)(2,\n"
       << "           \"throw found with no handler!\\n\", 31); abort();\n"
       << "  }\n"
@@ -1297,8 +1364,8 @@ void CWriter::visitFreeInst(FreeInst &I) {
   Out << ")";
 }
 
-void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
-                                      User::op_iterator E) {
+void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
+                                      gep_type_iterator E) {
   bool HasImplicitAddress = false;
   // If accessing a global value with no indexing, avoid *(&GV) syndrome
   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
@@ -1318,7 +1385,7 @@ void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
     return;
   }
 
-  const Constant *CI = dyn_cast<Constant>(I);
+  const Constant *CI = dyn_cast<Constant>(I.getOperand());
   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
     Out << "(&";
 
@@ -1334,22 +1401,24 @@ void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
 
   if (HasImplicitAddress) {
     ++I;
-  } else if (CI && CI->isNullValue() && I+1 != E) {
+  } else if (CI && CI->isNullValue()) {
+    gep_type_iterator TmpI = I; ++TmpI;
+
     // Print out the -> operator if possible...
-    if ((*(I+1))->getType() == Type::UByteTy) {
+    if (TmpI != E && isa<StructType>(*TmpI)) {
       Out << (HasImplicitAddress ? "." : "->");
-      Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
-      I += 2;
-    } 
+      Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
+      I = ++TmpI;
+    }
   }
 
   for (; I != E; ++I)
-    if ((*I)->getType() == Type::LongTy) {
+    if (isa<StructType>(*I)) {
+      Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
+    } else {
       Out << "[";
-      writeOperand(*I);
+      writeOperand(I.getOperand());
       Out << "]";
-    } else {
-      Out << ".field" << cast<ConstantUInt>(*I)->getValue();
     }
 }
 
@@ -1367,7 +1436,8 @@ void CWriter::visitStoreInst(StoreInst &I) {
 
 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
   Out << "&";
-  printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
+  printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
+                          gep_type_end(I));
 }
 
 void CWriter::visitVANextInst(VANextInst &I) {