Skip to content
AsmPrinter.cpp 73.1 KiB
Newer Older
    // integer type.  This promotes constant folding and simplifies this code.
    const TargetData *TD = TM.getTargetData();
    Constant *Op = CE->getOperand(0);
    Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
                                      false/*ZExt*/);
    return EmitConstantValueOnly(Op);
  }
    
  case Instruction::PtrToInt: {
    // Support only foldable casts to/from pointers that can be eliminated by
    // changing the pointer to the appropriately sized integer type.
    Constant *Op = CE->getOperand(0);
    const Type *Ty = CE->getType();
    const TargetData *TD = TM.getTargetData();

    // We can emit the pointer value into this slot if the slot is an
    // integer slot greater or equal to the size of the pointer.
    if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))

    O << "((";
    EmitConstantValueOnly(Op);
    APInt ptrMask =
      APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType()));
    
    SmallString<40> S;
    ptrMask.toStringUnsigned(S);
    O << ") & " << S.str() << ')';
    return;
  }
  case Instruction::Trunc:
    // We emit the value and depend on the assembler to truncate the generated
    // expression properly.  This is important for differences between
    // blockaddress labels.  Since the two labels are in the same function, it
    // is reasonable to treat their delta as a 32-bit value.
    return EmitConstantValueOnly(CE->getOperand(0));
  case Instruction::Add:
  case Instruction::Sub:
  case Instruction::And:
  case Instruction::Or:
  case Instruction::Xor:
    O << '(';
    EmitConstantValueOnly(CE->getOperand(0));
    O << ')';
    switch (CE->getOpcode()) {
    case Instruction::Add:
    O << '(';
    EmitConstantValueOnly(CE->getOperand(1));
    O << ')';
    break;
/// printAsCString - Print the specified array as a C compatible string, only if
/// the predicate isString is true.
///
David Greene's avatar
 
David Greene committed
static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA,
  assert(CVA->isString() && "Array is not string compatible!");

  for (unsigned i = 0; i != LastElt; ++i) {
    unsigned char C =
Reid Spencer's avatar
Reid Spencer committed
        (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue();
/// EmitString - Emit a zero-byte-terminated string constant.
///
void AsmPrinter::EmitString(const ConstantArray *CVA) const {
  unsigned NumElts = CVA->getNumOperands();
  if (MAI->getAscizDirective() && NumElts && 
Reid Spencer's avatar
Reid Spencer committed
      cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) {
void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA,
                                         unsigned AddrSpace) {
  if (CVA->isString()) {
    EmitString(CVA);
  } else { // Not a string.  Print the values in successive locations
    for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
      EmitGlobalConstant(CVA->getOperand(i), AddrSpace);
  }
}

void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) {
  const VectorType *PTy = CP->getType();
  
  for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
    EmitGlobalConstant(CP->getOperand(I));
}

void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
                                          unsigned AddrSpace) {
  // Print the fields in successive locations. Pad to align if needed!
  const TargetData *TD = TM.getTargetData();
  unsigned Size = TD->getTypeAllocSize(CVS->getType());
  const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
  uint64_t sizeSoFar = 0;
  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.
    uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
    uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
                        - cvsLayout->getElementOffset(i)) - fieldSize;
    sizeSoFar += fieldSize + padSize;

    // Now print the actual field value.

    // Insert padding - this may include padding to increase the size of the
    // current field up to the ABI size (if the struct is not packed) as well
    // as padding to ensure that the next field starts at the right offset.
  }
  assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
         "Layout of constant struct may be incorrect!");
}

void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP, 
                                      unsigned AddrSpace) {
  // FP Constants are printed as integer constants to avoid losing
  // precision...
  LLVMContext &Context = CFP->getContext();
  const TargetData *TD = TM.getTargetData();
    double Val = CFP->getValueAPF().convertToDouble();  // for comment only
    uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
    if (MAI->getData64bitsDirective(AddrSpace)) {
      O << MAI->getData64bitsDirective(AddrSpace) << i;
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString() << " double " << Val;
      O << '\n';
    } else if (TD->isBigEndian()) {
      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant word of double " << Val;
      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant word of double " << Val;
      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant word of double " << Val;
      O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant word of double " << Val;
    float Val = CFP->getValueAPF().convertToFloat();  // for comment only
    O << MAI->getData32bitsDirective(AddrSpace)
      << CFP->getValueAPF().bitcastToAPInt().getZExtValue();
      O.PadToColumn(MAI->getCommentColumn());
      O << MAI->getCommentString() << " float " << Val;
    // all long double variants are printed as hex
    // api needed to prevent premature destruction
    APInt api = CFP->getValueAPF().bitcastToAPInt();
    const uint64_t *p = api.getRawData();
    // Convert to double so we can print the approximate val as a comment.
    APFloat DoubleVal = CFP->getValueAPF();
    bool ignored;
    DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
                      &ignored);
    if (TD->isBigEndian()) {
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant halfword of x86_fp80 ~"
          << DoubleVal.convertToDouble();
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString() << " next halfword";
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString() << " next halfword";
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString() << " next halfword";
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant halfword";
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant halfword of x86_fp80 ~"
          << DoubleVal.convertToDouble();
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant halfword";
    EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) -
              TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace);
    // all long double variants are printed as hex
    // api needed to prevent premature destruction
    APInt api = CFP->getValueAPF().bitcastToAPInt();
    const uint64_t *p = api.getRawData();
    if (TD->isBigEndian()) {
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant word of ppc_fp128";
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant word";
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " least significant word of ppc_fp128";
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
      O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32);
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString()
          << " most significant word";
  } else llvm_unreachable("Floating point constant type not handled");
void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
                                            unsigned AddrSpace) {
  const TargetData *TD = TM.getTargetData();
  unsigned BitWidth = CI->getBitWidth();
  assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");

  // We don't expect assemblers to support integer data directives
  // for more than 64 bits, so we emit the data in at most 64-bit
  // quantities at a time.
  const uint64_t *RawData = CI->getValue().getRawData();
  for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
    uint64_t Val;
    if (TD->isBigEndian())
      Val = RawData[e - i - 1];
    else
      Val = RawData[i];

    if (MAI->getData64bitsDirective(AddrSpace)) {
      O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n';

    // Emit two 32-bit chunks, order depends on endianness.
    unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32);
    const char *FirstName = " least", *SecondName = " most";
    if (TD->isBigEndian()) {
      std::swap(FirstChunk, SecondChunk);
      std::swap(FirstName, SecondName);
    }
    
    O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk;
    if (VerboseAsm) {
      O.PadToColumn(MAI->getCommentColumn());
      O << MAI->getCommentString()
        << FirstName << " significant half of i64 " << Val;
    }
    O << '\n';
    
    O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk;
    if (VerboseAsm) {
      O.PadToColumn(MAI->getCommentColumn());
      O << MAI->getCommentString()
        << SecondName << " significant half of i64 " << Val;
    }
    O << '\n';
/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
  const TargetData *TD = TM.getTargetData();
  unsigned Size = TD->getTypeAllocSize(type);
Chris Lattner's avatar
Chris Lattner committed
  if (CV->isNullValue() || isa<UndefValue>(CV)) {
    return;
  }
  
  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
    EmitGlobalConstantArray(CVA , AddrSpace);
    return;
  }
  
  if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
    EmitGlobalConstantStruct(CVS, AddrSpace);
    return;
  }

  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  }
  
  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
    // If we can directly emit an 8-byte constant, do it.
    if (Size == 8)
      if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) {
        O << Data64Dir << CI->getZExtValue() << '\n';
        return;
      }

    // Small integers are handled below; large integers are handled here.
    if (Size > 4) {
      EmitGlobalConstantLargeInt(CI, AddrSpace);
  }
  
  if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
  EmitConstantValueOnly(CV);
  if (VerboseAsm) {
    if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
      SmallString<40> S;
      CI->getValue().toStringUnsigned(S, 16);
      O.PadToColumn(MAI->getCommentColumn());
      O << MAI->getCommentString() << " 0x" << S.str();
Chris Lattner's avatar
Chris Lattner committed

void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
  llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
/// PrintSpecial - Print information related to the specified machine instr
/// that is independent of the operand, and may be independent of the instr
/// itself.  This can be useful for portably encoding the comment character
/// or other bits of target-specific knowledge into the asmstrings.  The
/// syntax used is ${:comment}.  Targets can override this to add support
/// for their own strange codes.
void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const {
  if (!strcmp(Code, "private")) {
    O << MAI->getPrivateGlobalPrefix();
  } else if (!strcmp(Code, "comment")) {
    if (VerboseAsm)
Chris Lattner's avatar
Chris Lattner committed
    // Comparing the address of MI isn't sufficient, because machineinstrs may
    // be allocated to the same address across functions.
    const Function *ThisF = MI->getParent()->getParent()->getFunction();
    
    // If this is a new LastFn instruction, bump the counter.
    if (LastMI != MI || LastFn != ThisF) {
Chris Lattner's avatar
Chris Lattner committed
      ++Counter;
      LastMI = MI;
Chris Lattner's avatar
Chris Lattner committed
    }
    std::string msg;
    raw_string_ostream Msg(msg);
    Msg << "Unknown special formatter '" << Code
    llvm_report_error(Msg.str());
/// processDebugLoc - Processes the debug information of each machine
/// instruction's DebugLoc.
void AsmPrinter::processDebugLoc(const MachineInstr *MI, 
                                 bool BeforePrintingInsn) {
  if (!MAI || !DW || !MAI->doesSupportDebugInformation()
      || !DW->ShouldEmitDwarfDebug())
  DebugLoc DL = MI->getDebugLoc();
  if (DL.isUnknown())
    return;
  DILocation CurDLT = MF->getDILocation(DL);
  if (CurDLT.getScope().isNull())
    return;

  if (BeforePrintingInsn) {
    if (CurDLT.getNode() != PrevDLT.getNode()) {
      unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 
                                        CurDLT.getColumnNumber(),
                                        CurDLT.getScope().getNode());
      DW->BeginScope(MI, L);
  } else {
    // After printing instruction
    DW->EndScope(MI);
Chris Lattner's avatar
Chris Lattner committed
/// printInlineAsm - This method formats and prints the specified machine
/// instruction that is an inline asm.
void AsmPrinter::printInlineAsm(const MachineInstr *MI) const {
  unsigned NumOperands = MI->getNumOperands();
  
  // Count the number of register definitions.
  unsigned NumDefs = 0;
  for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
       ++NumDefs)
    assert(NumDefs != NumOperands-1 && "No asm string?");
  
  assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");

  // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
  const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
  // If this asmstr is empty, just print the #APP/#NOAPP markers.
  // These are useful to see where empty asm's wound up.
  if (AsmStr[0] == 0) {
    O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
    O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n';
  O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t";
Bill Wendling's avatar
Bill Wendling committed
  // The variant of the current asmprinter.
  int AsmPrinterVariant = MAI->getAssemblerDialect();
Bill Wendling's avatar
Bill Wendling committed

  int CurVariant = -1;            // The number of the {.|.|.} region we are in.
  const char *LastEmitted = AsmStr; // One past the last character emitted.
  while (*LastEmitted) {
    switch (*LastEmitted) {
    default: {
      // Not a special case, emit the string section literally.
      const char *LiteralEnd = LastEmitted+1;
      while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
             *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
        ++LiteralEnd;
      if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
        O.write(LastEmitted, LiteralEnd-LastEmitted);
      LastEmitted = LiteralEnd;
      break;
    }
    case '\n':
      ++LastEmitted;   // Consume newline character.
      O << '\n';       // Indent code with newline.
    case '$': {
      ++LastEmitted;   // Consume '$' character.
      bool Done = true;

      // Handle escapes.
      switch (*LastEmitted) {
      default: Done = false; break;
      case '$':     // $$ -> $
        if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
          O << '$';
        ++LastEmitted;  // Consume second '$' character.
        break;
      case '(':             // $( -> same as GCC's { character.
        ++LastEmitted;      // Consume '(' character.
        if (CurVariant != -1) {
          llvm_report_error("Nested variants found in inline asm string: '"
                            + std::string(AsmStr) + "'");
        }
        CurVariant = 0;     // We're in the first variant now.
        break;
      case '|':
        ++LastEmitted;  // consume '|' character.
        if (CurVariant == -1)
          O << '|';       // this is gcc's behavior for | outside a variant
        else
          ++CurVariant;   // We're in the next variant.
        break;
      case ')':         // $) -> same as GCC's } char.
        ++LastEmitted;  // consume ')' character.
        if (CurVariant == -1)
          O << '}';     // this is gcc's behavior for } outside a variant
        else 
          CurVariant = -1;
      
      bool HasCurlyBraces = false;
      if (*LastEmitted == '{') {     // ${variable}
        ++LastEmitted;               // Consume '{' character.
        HasCurlyBraces = true;
      }
      
      // If we have ${:foo}, then this is not a real operand reference, it is a
      // "magic" string reference, just like in .td files.  Arrange to call
      // PrintSpecial.
      if (HasCurlyBraces && *LastEmitted == ':') {
        ++LastEmitted;
        const char *StrStart = LastEmitted;
        const char *StrEnd = strchr(StrStart, '}');
        if (StrEnd == 0) {
          llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 
                            + std::string(AsmStr) + "'");
        }
        
        std::string Val(StrStart, StrEnd);
        PrintSpecial(MI, Val.c_str());
        LastEmitted = StrEnd+1;
        break;
      }
            
      const char *IDStart = LastEmitted;
      char *IDEnd;
      errno = 0;
      long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs.
      if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) {
        llvm_report_error("Bad $ operand number in inline asm string: '" 
                          + std::string(AsmStr) + "'");
        // If we have curly braces, check for a modifier character.  This
        // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
        if (*LastEmitted == ':') {
          ++LastEmitted;    // Consume ':' character.
          if (*LastEmitted == 0) {
            llvm_report_error("Bad ${:} expression in inline asm string: '" 
                              + std::string(AsmStr) + "'");
          }
          
          Modifier[0] = *LastEmitted;
          ++LastEmitted;    // Consume modifier character.
        }
        
          llvm_report_error("Bad ${} expression in inline asm string: '" 
                            + std::string(AsmStr) + "'");
        }
        ++LastEmitted;    // Consume '}' character.
      }
      
      if ((unsigned)Val >= NumOperands-1) {
        llvm_report_error("Invalid $ operand number in inline asm string: '" 
                          + std::string(AsmStr) + "'");
      // Okay, we finally have a value number.  Ask the target to print this
      if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
        unsigned OpNo = 1;
        // Scan to find the machine operand number for the operand.
          if (OpNo >= MI->getNumOperands()) break;
          unsigned OpFlags = MI->getOperand(OpNo).getImm();
          OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;

        if (OpNo >= MI->getNumOperands()) {
          Error = true;
          unsigned OpFlags = MI->getOperand(OpNo).getImm();
          ++OpNo;  // Skip over the ID number.

          if (Modifier[0] == 'l')  // labels are target independent
            O << *GetMBBSymbol(MI->getOperand(OpNo).getMBB()->getNumber());
          else {
            AsmPrinter *AP = const_cast<AsmPrinter*>(this);
            if ((OpFlags & 7) == 4) {
              Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
                                                Modifier[0] ? Modifier : 0);
            } else {
              Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
                                          Modifier[0] ? Modifier : 0);
            }
          std::string msg;
          raw_string_ostream Msg(msg);
          Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n";
          MI->print(Msg);
          llvm_report_error(Msg.str());
  O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd();
/// printImplicitDef - This method prints the specified machine instruction
/// that is an implicit def.
void AsmPrinter::printImplicitDef(const MachineInstr *MI) const {
  if (!VerboseAsm) return;
  O.PadToColumn(MAI->getCommentColumn());
  O << MAI->getCommentString() << " implicit-def: "
    << TRI->getName(MI->getOperand(0).getReg());
void AsmPrinter::printKill(const MachineInstr *MI) const {
  if (!VerboseAsm) return;
  O.PadToColumn(MAI->getCommentColumn());
  O << MAI->getCommentString() << " kill:";
  for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) {
    const MachineOperand &op = MI->getOperand(n);
    assert(op.isReg() && "KILL instruction must have only register operands");
    O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>");
  }
}

Jim Laskey's avatar
Jim Laskey committed
/// printLabel - This method prints a local label used by debug and
/// exception handling tables.
void AsmPrinter::printLabel(const MachineInstr *MI) const {
  printLabel(MI->getOperand(0).getImm());
void AsmPrinter::printLabel(unsigned Id) const {
  O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':';
/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
/// instruction, using the specified assembler variant.  Targets should
Dale Johannesen's avatar
Dale Johannesen committed
/// override this to format as appropriate.
bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
                                 unsigned AsmVariant, const char *ExtraCode) {
  // Target doesn't support this yet!
  return true;
Chris Lattner's avatar
Chris Lattner committed
}

bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
                                       unsigned AsmVariant,
                                       const char *ExtraCode) {
  // Target doesn't support this yet!
  return true;
}
MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA,
                                            const char *Suffix) const {
  return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix);
}

MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F,
                                            const BasicBlock *BB,
                                            const char *Suffix) const {
  assert(BB->hasName() &&
         "Address of anonymous basic block not supported yet!");

  // This code must use the function name itself, and not the function number,
  // since it must be possible to generate the label name from within other
  // functions.
  SmallString<60> FnName;
  Mang->getNameWithPrefix(FnName, F, false);
  // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME!
  Mang->getNameWithPrefix(NameResult,
                          StringRef("BA") + Twine((unsigned)FnName.size()) + 
                          "_" + FnName.str() + "_" + BB->getName() + Suffix, 
                          Mangler::Private);

  return OutContext.GetOrCreateSymbol(NameResult.str());
MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const {
  SmallString<60> Name;
  raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB"
    << getFunctionNumber() << '_' << MBBID;
  
  return OutContext.GetOrCreateSymbol(Name.str());
}

/// GetGlobalValueSymbol - Return the MCSymbol for the specified global
/// value.
MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
  SmallString<60> NameStr;
  Mang->getNameWithPrefix(NameStr, GV, false);
  return OutContext.GetOrCreateSymbol(NameStr.str());
}

/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
Chris Lattner's avatar
Chris Lattner committed
/// global value name as its base, with the specified suffix, and where the
/// symbol is forced to have private linkage if ForcePrivate is true.
MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
                                                   StringRef Suffix,
                                                   bool ForcePrivate) const {
Chris Lattner's avatar
Chris Lattner committed
  SmallString<60> NameStr;
  Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
Chris Lattner's avatar
Chris Lattner committed
  NameStr.append(Suffix.begin(), Suffix.end());
  return OutContext.GetOrCreateSymbol(NameStr.str());
}

/// GetExternalSymbolSymbol - Return the MCSymbol for the specified
/// ExternalSymbol.
MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
  SmallString<60> NameStr;
  Mang->getNameWithPrefix(NameStr, Sym);
  return OutContext.GetOrCreateSymbol(NameStr.str());
}  

/// EmitBasicBlockStart - This method prints the label for the specified
/// MachineBasicBlock, an alignment (if present) and a comment describing
/// it if appropriate.
void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
Dan Gohman's avatar
Dan Gohman committed
  // Emit an alignment directive for this block, if needed.
  if (unsigned Align = MBB->getAlignment())
    EmitAlignment(Log2_32(Align));
Dan Gohman's avatar
Dan Gohman committed
  // If the block has its address taken, emit a special label to satisfy
  // references to the block. This is done so that we don't need to
  // remember the number of this label, and so that we can make
  // forward references to labels without knowing what their numbers
  // will be.
  if (MBB->hasAddressTaken()) {
    O << *GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(),
                                MBB->getBasicBlock());
    O << ':';
    if (VerboseAsm) {
      O.PadToColumn(MAI->getCommentColumn());
      O << MAI->getCommentString() << " Address Taken";
    }
    O << '\n';
  }

Dan Gohman's avatar
Dan Gohman committed
  // Print the main label for the block.
  if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) {
    if (VerboseAsm)
      O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':';
  } else {
    O << *GetMBBSymbol(MBB->getNumber()) << ':';
Dan Gohman's avatar
Dan Gohman committed
  // Print some comments to accompany the label.
    if (const BasicBlock *BB = MBB->getBasicBlock())
      if (BB->hasName()) {
        O.PadToColumn(MAI->getCommentColumn());
        O << MAI->getCommentString() << ' ';
        WriteAsOperand(O, BB, /*PrintType=*/false);
David Greene's avatar
 
David Greene committed

David Greene's avatar
 
David Greene committed
  }
/// printPICJumpTableSetLabel - This method prints a set label for the
/// specified MachineBasicBlock for a jumptable entry.
void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 
                                           const MachineBasicBlock *MBB) const {
  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
    << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','
    << *GetMBBSymbol(MBB->getNumber())
    << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
Evan Cheng's avatar
Evan Cheng committed
    << '_' << uid << '\n';
void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2,
                                           const MachineBasicBlock *MBB) const {
  O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
Evan Cheng's avatar
Evan Cheng committed
    << getFunctionNumber() << '_' << uid << '_' << uid2
    << "_set_" << MBB->getNumber() << ','
    << *GetMBBSymbol(MBB->getNumber())
    << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 
Evan Cheng's avatar
Evan Cheng committed
    << '_' << uid << '_' << uid2 << '\n';
/// printDataDirective - This method prints the asm directive for the
/// specified type.
void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) {
  const TargetData *TD = TM.getTargetData();
  switch (type->getTypeID()) {
Chris Lattner's avatar
Chris Lattner committed
  case Type::FloatTyID: case Type::DoubleTyID:
  case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID:
    assert(0 && "Should have already output floating point constant.");
  default:
    assert(0 && "Can't handle printing this type of thing");
Reid Spencer's avatar
Reid Spencer committed
  case Type::IntegerTyID: {
    unsigned BitWidth = cast<IntegerType>(type)->getBitWidth();
    if (BitWidth <= 8)
      O << MAI->getData8bitsDirective(AddrSpace);
Reid Spencer's avatar
Reid Spencer committed
    else if (BitWidth <= 16)
      O << MAI->getData16bitsDirective(AddrSpace);
Reid Spencer's avatar
Reid Spencer committed
    else if (BitWidth <= 32)
      O << MAI->getData32bitsDirective(AddrSpace);
Reid Spencer's avatar
Reid Spencer committed
    else if (BitWidth <= 64) {
      assert(MAI->getData64bitsDirective(AddrSpace) &&
Reid Spencer's avatar
Reid Spencer committed
             "Target cannot handle 64-bit constant exprs!");
      O << MAI->getData64bitsDirective(AddrSpace);
      llvm_unreachable("Target cannot handle given data directive width!");
Reid Spencer's avatar
Reid Spencer committed
    }
Reid Spencer's avatar
Reid Spencer committed
  }
  case Type::PointerTyID:
    if (TD->getPointerSize() == 8) {
      assert(MAI->getData64bitsDirective(AddrSpace) &&
             "Target cannot handle 64-bit pointer exprs!");
      O << MAI->getData64bitsDirective(AddrSpace);
    } else if (TD->getPointerSize() == 2) {
      O << MAI->getData16bitsDirective(AddrSpace);
    } else if (TD->getPointerSize() == 1) {
      O << MAI->getData8bitsDirective(AddrSpace);
Reid Spencer's avatar
Reid Spencer committed
    } else {
      O << MAI->getData32bitsDirective(AddrSpace);
void AsmPrinter::printVisibility(const MCSymbol *Sym,
                                 unsigned Visibility) const {
  if (Visibility == GlobalValue::HiddenVisibility) {
    if (const char *Directive = MAI->getHiddenDirective())
      O << Directive << *Sym << '\n';
  } else if (Visibility == GlobalValue::ProtectedVisibility) {
    if (const char *Directive = MAI->getProtectedDirective())
      O << Directive << *Sym << '\n';
void AsmPrinter::printOffset(int64_t Offset) const {
  if (Offset > 0)
    O << '+' << Offset;
  else if (Offset < 0)
    O << Offset;
}

GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
  if (!S->usesMetadata())
  gcp_iterator GCPI = GCMetadataPrinters.find(S);
  if (GCPI != GCMetadataPrinters.end())
    return GCPI->second;
  
  const char *Name = S->getName().c_str();
  
  for (GCMetadataPrinterRegistry::iterator
         I = GCMetadataPrinterRegistry::begin(),
         E = GCMetadataPrinterRegistry::end(); I != E; ++I)
    if (strcmp(Name, I->getName()) == 0) {
      GCMetadataPrinter *GMP = I->instantiate();