Breaking up the PowerPC target into 32- and 64-bit subparts, Part I: 32-bit.
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
index d920137f30a10ba2595c4c9ab445e09ebec975a4..5f3b5de7c6c9f0493907ff8bbc99fb8d0d5a2d96 100644 (file)
@@ -1,4 +1,4 @@
-//===-- Printer.cpp - Convert LLVM code to PowerPC assembly ---------------===//
+//===-- PPC32AsmPrinter.cpp - Print machine instrs to PowerPC assembly ----===//
 // 
 //                     The LLVM Compiler Infrastructure
 //
@@ -9,7 +9,7 @@
 //
 // This file contains a printer that converts from our internal representation
 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
-// the output mechanism used by `llc' and `lli -print-machineinstrs'.
+// the output mechanism used by `llc'.
 //
 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
@@ -19,6 +19,7 @@
 #define DEBUG_TYPE "asmprinter"
 #include "PowerPC.h"
 #include "PowerPCInstrInfo.h"
+#include "PPC32TargetMachine.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
@@ -47,7 +48,7 @@ namespace {
     /// Target machine description which we query for reg. names, data
     /// layout, etc.
     ///
-    TargetMachine &TM;
+    PPC32TargetMachine &TM;
 
     /// Name-mangler for global names.
     ///
@@ -55,8 +56,8 @@ namespace {
     std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
     std::set<std::string> Strings;
 
-    Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm), labelNumber(0)
-      }
+    Printer(std::ostream &o, TargetMachine &tm) : O(o),
+      TM(reinterpret_cast<PPC32TargetMachine&>(tm)), LabelNumber(0) {}
 
     /// Cache of mangled name for current function. This is
     /// recalculated at the beginning of each call to
@@ -64,17 +65,17 @@ namespace {
     ///
     std::string CurrentFnName;
 
-    /// Unique incrementer for label values for referencing
-    /// Global values.
+    /// Unique incrementer for label values for referencing Global values.
     ///
-    unsigned int labelNumber;
-
+    unsigned LabelNumber;
+  
     virtual const char *getPassName() const {
-      return "PowerPC Assembly Printer";
+      return "PPC32 Assembly Printer";
     }
 
     void printMachineInstruction(const MachineInstr *MI);
     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
+    void printImmOp(const MachineOperand &MO, unsigned ArgType);
     void printConstantPool(MachineConstantPool *MCP);
     bool runOnMachineFunction(MachineFunction &F);    
     bool doInitialization(Module &M);
@@ -84,12 +85,12 @@ namespace {
   };
 } // end of anonymous namespace
 
-/// createPPCCodePrinterPass - Returns a pass that prints the PPC
+/// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
 /// assembly code for a MachineFunction to the given output stream,
 /// using the given target machine description.  This should work
-/// regardless of whether the function is in SSA form.
+/// regardless of whether the function is in SSA form or not.
 ///
-FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm) {
+FunctionPass *createPPC32AsmPrinter(std::ostream &o,TargetMachine &tm) {
   return new Printer(o, tm);
 }
 
@@ -131,7 +132,7 @@ static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
     } else if (isprint(C)) {
       O << C;
     } else {
-      switch(C) {
+      switch (C) {
       case '\b': O << "\\b"; break;
       case '\f': O << "\\f"; break;
       case '\n': O << "\\n"; break;
@@ -167,7 +168,7 @@ void Printer::emitConstantValueOnly(const Constant *CV) {
     O << Mang->getValueName(GV);
   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
     const TargetData &TD = TM.getTargetData();
-    switch(CE->getOpcode()) {
+    switch (CE->getOpcode()) {
     case Instruction::GetElementPtr: {
       // generate a symbolic expression for the byte address
       const Constant *ptrVal = CE->getOperand(0);
@@ -230,22 +231,20 @@ void Printer::emitGlobalConstant(const Constant *CV) {
       printAsCString(O, CVA);
       O << "\n";
     } else { // Not a string.  Print the values in successive locations
-      const std::vector<Use> &constValues = CVA->getValues();
-      for (unsigned i=0; i < constValues.size(); i++)
-        emitGlobalConstant(cast<Constant>(constValues[i].get()));
+      for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
+        emitGlobalConstant(CVA->getOperand(i));
     }
     return;
   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
     // Print the fields in successive locations. Pad to align if needed!
     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
-    const std::vector<Use>& constValues = CVS->getValues();
     unsigned sizeSoFar = 0;
-    for (unsigned i=0, N = constValues.size(); i < N; i++) {
-      const Constant* field = cast<Constant>(constValues[i].get());
+    for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
+      const Constant* field = CVS->getOperand(i);
 
       // Check if padding is needed and insert one or more 0s.
       unsigned fieldSize = TD.getTypeSize(field->getType());
-      unsigned padSize = ((i == N-1? cvsLayout->StructSize
+      unsigned padSize = ((i == e-1? cvsLayout->StructSize
                            : cvsLayout->MemberOffsets[i+1])
                           - cvsLayout->MemberOffsets[i]) - fieldSize;
       sizeSoFar += fieldSize + padSize;
@@ -293,7 +292,7 @@ void Printer::emitGlobalConstant(const Constant *CV) {
       return;
     }
     }
-  } else if (CV->getType()->getPrimitiveSize() == 64) {
+  } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
       union DU {                            // Abide by C TBAA rules
         int64_t UVal;
@@ -395,6 +394,7 @@ bool Printer::runOnMachineFunction(MachineFunction &MF) {
       printMachineInstruction(II);
     }
   }
+  ++LabelNumber;
 
   // We didn't modify anything.
   return false;
@@ -418,13 +418,11 @@ void Printer::printOp(const MachineOperand &MO,
     return;
 
   case MachineOperand::MO_SignExtendedImmed:
-    O << (short)MO.getImmedValue();
-    return;
-
   case MachineOperand::MO_UnextendedImmed:
-    O << (unsigned short)MO.getImmedValue();
+    std::cerr << "printOp() does not handle immediate values\n";
+    abort();
     return;
-    
+
   case MachineOperand::MO_PCRelativeDisp:
     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
     abort();
@@ -450,20 +448,25 @@ void Printer::printOp(const MachineOperand &MO,
     if (!elideOffsetKeyword) {
       GlobalValue *GV = MO.getGlobal();
       std::string Name = Mang->getValueName(GV);
+
       // Dynamically-resolved functions need a stub for the function
       Function *F = dyn_cast<Function>(GV);
-      if (F && F->isExternal()) {
+      if (F && F->isExternal() &&
+          TM.CalledFunctions.find(F) != TM.CalledFunctions.end()) {
         FnStubs.insert(Name);
         O << "L" << Name << "$stub";
-      } else {
-        GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
-        // External global variables need a non-lazily-resolved stub
-        if (GVar && GVar->isExternal()) {
-          GVStubs.insert(Name);
-          O << "L" << Name << "$non_lazy_ptr";
-        } else 
-          O << Mang->getValueName(GV);
+        return;
+      }
+            
+      // External global variables need a non-lazily-resolved stub
+      if (!GV->hasInternalLinkage() &&
+          TM.AddressTaken.find(GV) != TM.AddressTaken.end()) {
+        GVStubs.insert(Name);
+        O << "L" << Name << "$non_lazy_ptr";
+        return;
       }
+            
+      O << Mang->getValueName(GV);
     }
     return;
     
@@ -473,27 +476,37 @@ void Printer::printOp(const MachineOperand &MO,
   }
 }
 
-/// printMachineInstruction -- Print out a single PPC32 LLVM instruction
+void Printer::printImmOp(const MachineOperand &MO, unsigned ArgType) {
+  int Imm = MO.getImmedValue();
+  if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
+    O << (short)Imm;
+  } else if (ArgType == PPCII::Zimm16) {
+    O << (unsigned short)Imm;
+  } else {
+    O << Imm;
+  }
+}
+
+/// printMachineInstruction -- Print out a single PPC LLVM instruction
 /// MI in Darwin syntax to the current output stream.
 ///
 void Printer::printMachineInstruction(const MachineInstr *MI) {
   unsigned Opcode = MI->getOpcode();
   const TargetInstrInfo &TII = *TM.getInstrInfo();
   const TargetInstrDescriptor &Desc = TII.get(Opcode);
-  unsigned int i;
-
-  unsigned int ArgCount = MI->getNumOperands();
-    //Desc.TSFlags & PPC32II::ArgCountMask;
-  unsigned int ArgType[] = {
-    (Desc.TSFlags >> PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask,
-    (Desc.TSFlags >> PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask,
-    (Desc.TSFlags >> PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask,
-    (Desc.TSFlags >> PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask,
-    (Desc.TSFlags >> PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask
+  unsigned i;
+
+  unsigned ArgCount = MI->getNumOperands();
+  unsigned ArgType[] = {
+    (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
+    (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
+    (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
+    (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
+    (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
   };
-  assert(((Desc.TSFlags & PPC32II::VMX) == 0) &&
+  assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
          "Instruction requires VMX support");
-  assert(((Desc.TSFlags & PPC32II::PPC64) == 0) &&
+  assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
          "Instruction requires 64 bit support");
   ++EmittedInsts;
 
@@ -501,73 +514,85 @@ void Printer::printMachineInstruction(const MachineInstr *MI) {
   // appropriate number of args that the assembler expects.  This is because
   // may have many arguments appended to record the uses of registers that are
   // holding arguments to the called function.
-  if (Opcode == PPC32::IMPLICIT_DEF) {
+  if (Opcode == PPC::COND_BRANCH) {
+    std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
+    abort();
+  } else if (Opcode == PPC::IMPLICIT_DEF) {
     O << "; IMPLICIT DEF ";
     printOp(MI->getOperand(0));
     O << "\n";
     return;
-  } else if (Opcode == PPC32::CALLpcrel) {
-    O << TII.getName(MI->getOpcode()) << " ";
+  } else if (Opcode == PPC::CALLpcrel) {
+    O << TII.getName(Opcode) << " ";
     printOp(MI->getOperand(0));
     O << "\n";
     return;
-  } else if (Opcode == PPC32::CALLindirect) {
-    O << TII.getName(MI->getOpcode()) << " ";
-    printOp(MI->getOperand(0));
+  } else if (Opcode == PPC::CALLindirect) {
+    O << TII.getName(Opcode) << " ";
+    printImmOp(MI->getOperand(0), ArgType[0]);
     O << ", ";
-    printOp(MI->getOperand(1));
+    printImmOp(MI->getOperand(1), ArgType[0]);
     O << "\n";
     return;
-  } else if (Opcode == PPC32::MovePCtoLR) {
+  } else if (Opcode == PPC::MovePCtoLR) {
     // FIXME: should probably be converted to cout.width and cout.fill
-    O << "bl \"L0000" << labelNumber << "$pb\"\n";
-    O << "\"L0000" << labelNumber << "$pb\":\n";
+    O << "bl \"L0000" << LabelNumber << "$pb\"\n";
+    O << "\"L0000" << LabelNumber << "$pb\":\n";
     O << "\tmflr ";
     printOp(MI->getOperand(0));
     O << "\n";
     return;
   }
 
-  O << TII.getName(MI->getOpcode()) << " ";
-  if (Opcode == PPC32::LOADLoDirect || Opcode == PPC32::LOADLoIndirect) {
+  O << TII.getName(Opcode) << " ";
+  if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
     printOp(MI->getOperand(0));
     O << ", lo16(";
     printOp(MI->getOperand(2));
-    O << "-\"L0000" << labelNumber << "$pb\")";
-    labelNumber++;
+    O << "-\"L0000" << LabelNumber << "$pb\")";
     O << "(";
-    if (MI->getOperand(1).getReg() == PPC32::R0)
+    if (MI->getOperand(1).getReg() == PPC::R0)
       O << "0";
     else
       printOp(MI->getOperand(1));
     O << ")\n";
-  } else if (Opcode == PPC32::LOADHiAddr) {
+  } else if (Opcode == PPC::LOADHiAddr) {
     printOp(MI->getOperand(0));
     O << ", ";
-    if (MI->getOperand(1).getReg() == PPC32::R0)
+    if (MI->getOperand(1).getReg() == PPC::R0)
       O << "0";
     else
       printOp(MI->getOperand(1));
     O << ", ha16(" ;
     printOp(MI->getOperand(2));
-     O << "-\"L0000" << labelNumber << "$pb\")\n";
-  } else if (ArgCount == 3 && ArgType[1] == PPC32II::Disimm16) {
+     O << "-\"L0000" << LabelNumber << "$pb\")\n";
+  } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
     printOp(MI->getOperand(0));
     O << ", ";
-    printOp(MI->getOperand(1));
+    printImmOp(MI->getOperand(1), ArgType[1]);
     O << "(";
     if (MI->getOperand(2).hasAllocatedReg() &&
-        MI->getOperand(2).getReg() == PPC32::R0)
+        MI->getOperand(2).getReg() == PPC::R0)
       O << "0";
     else
       printOp(MI->getOperand(2));
     O << ")\n";
   } else {
     for (i = 0; i < ArgCount; ++i) {
-      if (i == 1 && ArgCount == 3 && ArgType[2] == PPC32II::Simm16 &&
+      // addi and friends
+      if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
           MI->getOperand(1).hasAllocatedReg() && 
-          MI->getOperand(1).getReg() == PPC32::R0) {
+          MI->getOperand(1).getReg() == PPC::R0) {
         O << "0";
+      // for long branch support, bc $+8
+      } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
+                 TII.isBranch(MI->getOpcode())) {
+        O << "$+8";
+        assert(8 == MI->getOperand(i).getImmedValue()
+          && "branch off PC not to pc+8?");
+        //printOp(MI->getOperand(i));
+      } else if (MI->getOperand(i).isImmediate()) {
+        printImmOp(MI->getOperand(i), ArgType[i]);
       } else {
         printOp(MI->getOperand(i));
       }
@@ -613,10 +638,10 @@ bool Printer::doFinalization(Module &M) {
           (I->hasInternalLinkage() || I->hasWeakLinkage())) {
         SwitchSection(O, CurSection, ".data");
         if (I->hasInternalLinkage())
-          O << "\t.lcomm " << name << "," << TD.getTypeSize(C->getType())
+          O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
             << "," << (unsigned)TD.getTypeAlignment(C->getType());
         else 
-          O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
+          O << ".comm " << name << "," << TD.getTypeSize(C->getType());
         O << "\t\t; ";
         WriteAsOperand(O, I, true, true, &M);
         O << "\n";
@@ -661,8 +686,7 @@ bool Printer::doFinalization(Module &M) {
   if (LinkOnceStubs.begin() != LinkOnceStubs.end())
     O << ".data\n.align 2\n";
   for (std::set<std::string>::iterator i = LinkOnceStubs.begin(), 
-         e = LinkOnceStubs.end(); i != e; ++i)
-  {
+         e = LinkOnceStubs.end(); i != e; ++i) {
     O << *i << "$non_lazy_ptr:\n"
       << "\t.long\t" << *i << '\n';
   }
@@ -671,31 +695,32 @@ bool Printer::doFinalization(Module &M) {
   for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 
        i != e; ++i)
   {
-    O << "\t.picsymbol_stub\n";
+    O << ".data\n";
+    O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
+    O << "\t.align 2\n";
     O << "L" << *i << "$stub:\n";
     O << "\t.indirect_symbol " << *i << "\n";
     O << "\tmflr r0\n";
-    O << "\tbL0$" << *i << "\n";
+    O << "\tbcl 20,31,L0$" << *i << "\n";
     O << "L0$" << *i << ":\n";
     O << "\tmflr r11\n";
     O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
     O << "\tmtlr r0\n";
-    O << "\tlwz r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
+    O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
     O << "\tmtctr r12\n";
-    O << "\taddi r11,r11,lo16(L" << *i << "$lazy_ptr - L0$" << *i << ")\n";
     O << "\tbctr\n";
     O << ".data\n";
     O << ".lazy_symbol_pointer\n";
     O << "L" << *i << "$lazy_ptr:\n";
-    O << ".indirect_symbol " << *i << "\n";
-    O << ".long dyld_stub_binding_helper\n";
+    O << "\t.indirect_symbol " << *i << "\n";
+    O << "\t.long dyld_stub_binding_helper\n";
   }
 
   O << "\n";
 
   // Output stubs for external global variables
   if (GVStubs.begin() != GVStubs.end())
-    O << ".data\n\t.non_lazy_symbol_pointer\n";
+    O << ".data\n.non_lazy_symbol_pointer\n";
   for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); 
        i != e; ++i) {
     O << "L" << *i << "$non_lazy_ptr:\n";