[WebAssembly] Use the new offset syntax for memory operands in inline asm.
[oota-llvm.git] / lib / Target / WebAssembly / WebAssemblyAsmPrinter.cpp
index 5c8fe57084714d441545ca404b22d9020dab882e..079c864c7bc1c15e9a7bc5c8d238fad2829ea0af 100644 (file)
 //===----------------------------------------------------------------------===//
 
 #include "WebAssembly.h"
+#include "InstPrinter/WebAssemblyInstPrinter.h"
+#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
+#include "WebAssemblyMCInstLower.h"
 #include "WebAssemblyMachineFunctionInfo.h"
 #include "WebAssemblyRegisterInfo.h"
 #include "WebAssemblySubtarget.h"
-#include "InstPrinter/WebAssemblyInstPrinter.h"
-#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
-
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/CodeGen/Analysis.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/IR/DataLayout.h"
-#include "llvm/IR/DebugInfo.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
-
 using namespace llvm;
 
 #define DEBUG_TYPE "asm-printer"
@@ -41,13 +41,12 @@ using namespace llvm;
 namespace {
 
 class WebAssemblyAsmPrinter final : public AsmPrinter {
-  const WebAssemblyInstrInfo *TII;
   const MachineRegisterInfo *MRI;
-  unsigned NumArgs;
+  const WebAssemblyFunctionInfo *MFI;
 
 public:
   WebAssemblyAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
-      : AsmPrinter(TM, std::move(Streamer)), TII(nullptr), MRI(nullptr) {}
+      : AsmPrinter(TM, std::move(Streamer)), MRI(nullptr), MFI(nullptr) {}
 
 private:
   const char *getPassName() const override {
@@ -58,15 +57,9 @@ private:
   // MachineFunctionPass Implementation.
   //===------------------------------------------------------------------===//
 
-  void getAnalysisUsage(AnalysisUsage &AU) const override {
-    AsmPrinter::getAnalysisUsage(AU);
-  }
-
   bool runOnMachineFunction(MachineFunction &MF) override {
-    const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
-    TII = Subtarget.getInstrInfo();
     MRI = &MF.getRegInfo();
-    NumArgs = MF.getInfo<WebAssemblyFunctionInfo>()->getNumArguments();
+    MFI = MF.getInfo<WebAssemblyFunctionInfo>();
     return AsmPrinter::runOnMachineFunction(MF);
   }
 
@@ -77,14 +70,17 @@ private:
   void EmitJumpTableInfo() override;
   void EmitConstantPool() override;
   void EmitFunctionBodyStart() override;
-
   void EmitInstruction(const MachineInstr *MI) override;
-
-  std::string getRegTypeName(unsigned RegNo) const;
-  static std::string toString(const APFloat &APF);
-  const char *toString(Type *Ty) const;
+  bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
+                       unsigned AsmVariant, const char *ExtraCode,
+                       raw_ostream &OS) override;
+  bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
+                             unsigned AsmVariant, const char *ExtraCode,
+                             raw_ostream &OS) override;
+
+  MVT getRegType(unsigned RegNo) const;
+  const char *toString(MVT VT) const;
   std::string regToString(const MachineOperand &MO);
-  std::string argToString(const MachineOperand &MO);
 };
 
 } // end anonymous namespace
@@ -93,103 +89,28 @@ private:
 // Helpers.
 //===----------------------------------------------------------------------===//
 
-// Operand type (if any), followed by the lower-case version of the opcode's
-// name matching the names WebAssembly opcodes are expected to have. The
-// tablegen names are uppercase and suffixed with their type (after an
-// underscore).
-static std::string OpcodeName(const WebAssemblyInstrInfo *TII,
-                              const MachineInstr *MI) {
-  std::string N(StringRef(TII->getName(MI->getOpcode())).lower());
-  std::string::size_type Len = N.length();
-  std::string::size_type Under = N.rfind('_');
-  bool HasType = std::string::npos != Under;
-  std::string::size_type NameEnd = HasType ? Under : Len;
-  std::string Name(&N[0], &N[NameEnd]);
-  return HasType ? (std::string(&N[NameEnd + 1], &N[Len]) + '.' + Name) : Name;
-}
-
-static std::string toSymbol(StringRef S) { return ("$" + S).str(); }
-
-std::string WebAssemblyAsmPrinter::getRegTypeName(unsigned RegNo) const {
+MVT WebAssemblyAsmPrinter::getRegType(unsigned RegNo) const {
   const TargetRegisterClass *TRC = MRI->getRegClass(RegNo);
   for (MVT T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
     if (TRC->hasType(T))
-      return EVT(T).getEVTString();
+      return T;
   DEBUG(errs() << "Unknown type for register number: " << RegNo);
   llvm_unreachable("Unknown register type");
-  return "?";
-}
-
-std::string WebAssemblyAsmPrinter::toString(const APFloat &FP) {
-  static const size_t BufBytes = 128;
-  char buf[BufBytes];
-  if (FP.isNaN())
-    assert((FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) ||
-            FP.bitwiseIsEqual(
-                APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) &&
-           "convertToHexString handles neither SNaN nor NaN payloads");
-  // Use C99's hexadecimal floating-point representation.
-  auto Written = FP.convertToHexString(
-      buf, /*hexDigits=*/0, /*upperCase=*/false, APFloat::rmNearestTiesToEven);
-  (void)Written;
-  assert(Written != 0);
-  assert(Written < BufBytes);
-  return buf;
+  return MVT::Other;
 }
 
 std::string WebAssemblyAsmPrinter::regToString(const MachineOperand &MO) {
   unsigned RegNo = MO.getReg();
-  if (TargetRegisterInfo::isPhysicalRegister(RegNo))
-    return WebAssemblyInstPrinter::getRegisterName(RegNo);
-
-  // WebAssembly arguments and local variables are in the same index space, and
-  // there are no explicit varargs, so we just add the number of arguments to
-  // the virtual register number to get the local variable number.
-  return utostr(TargetRegisterInfo::virtReg2Index(RegNo) + NumArgs);
+  assert(TargetRegisterInfo::isVirtualRegister(RegNo) &&
+         "Unlowered physical register encountered during assembly printing");
+  assert(!MFI->isVRegStackified(RegNo));
+  unsigned WAReg = MFI->getWAReg(RegNo);
+  assert(WAReg != WebAssemblyFunctionInfo::UnusedReg);
+  return '$' + utostr(WAReg);
 }
 
-std::string WebAssemblyAsmPrinter::argToString(const MachineOperand &MO) {
-  unsigned ArgNo = MO.getImm();
-  // Same as above, but we don't need to add NumArgs here.
-  return utostr(ArgNo);
-}
-
-const char *WebAssemblyAsmPrinter::toString(Type *Ty) const {
-  switch (Ty->getTypeID()) {
-  default:
-    break;
-  // Treat all pointers as the underlying integer into linear memory.
-  case Type::PointerTyID:
-    switch (getPointerSize()) {
-    case 4:
-      return "i32";
-    case 8:
-      return "i64";
-    default:
-      llvm_unreachable("unsupported pointer size");
-    }
-    break;
-  case Type::FloatTyID:
-    return "f32";
-  case Type::DoubleTyID:
-    return "f64";
-  case Type::IntegerTyID:
-    switch (Ty->getIntegerBitWidth()) {
-    case 8:
-      return "i8";
-    case 16:
-      return "i16";
-    case 32:
-      return "i32";
-    case 64:
-      return "i64";
-    default:
-      break;
-    }
-  }
-  DEBUG(dbgs() << "Invalid type "; Ty->print(dbgs()); dbgs() << '\n');
-  llvm_unreachable("invalid type");
-  return "<invalid>";
+const char *WebAssemblyAsmPrinter::toString(MVT VT) const {
+  return WebAssembly::TypeToString(VT);
 }
 
 //===----------------------------------------------------------------------===//
@@ -205,122 +126,147 @@ void WebAssemblyAsmPrinter::EmitJumpTableInfo() {
   // Nothing to do; jump tables are incorporated into the instruction stream.
 }
 
+static void ComputeLegalValueVTs(const Function &F, const TargetMachine &TM,
+                                 Type *Ty, SmallVectorImpl<MVT> &ValueVTs) {
+  const DataLayout &DL(F.getParent()->getDataLayout());
+  const WebAssemblyTargetLowering &TLI =
+      *TM.getSubtarget<WebAssemblySubtarget>(F).getTargetLowering();
+  SmallVector<EVT, 4> VTs;
+  ComputeValueVTs(TLI, DL, Ty, VTs);
+
+  for (EVT VT : VTs) {
+    unsigned NumRegs = TLI.getNumRegisters(F.getContext(), VT);
+    MVT RegisterVT = TLI.getRegisterType(F.getContext(), VT);
+    for (unsigned i = 0; i != NumRegs; ++i)
+      ValueVTs.push_back(RegisterVT);
+  }
+}
+
 void WebAssemblyAsmPrinter::EmitFunctionBodyStart() {
-  const Function *F = MF->getFunction();
-  Type *Rt = F->getReturnType();
-  SmallString<128> Str;
-  raw_svector_ostream OS(Str);
-  bool First = true;
-
-  if (!Rt->isVoidTy() || !F->arg_empty()) {
-    for (const Argument &A : F->args()) {
-      OS << (First ? "" : "\n") << "\t.param " << toString(A.getType());
-      First = false;
-    }
-    if (!Rt->isVoidTy()) {
-      OS << (First ? "" : "\n") << "\t.result " << toString(Rt);
-      First = false;
-    }
+  if (!MFI->getParams().empty()) {
+    MCInst Param;
+    Param.setOpcode(WebAssembly::PARAM);
+    for (MVT VT : MFI->getParams())
+      Param.addOperand(MCOperand::createImm(VT.SimpleTy));
+    EmitToStreamer(*OutStreamer, Param);
   }
 
-  bool FirstVReg = true;
+  SmallVector<MVT, 4> ResultVTs;
+  const Function &F(*MF->getFunction());
+  ComputeLegalValueVTs(F, TM, F.getReturnType(), ResultVTs);
+  // If the return type needs to be legalized it will get converted into
+  // passing a pointer.
+  if (ResultVTs.size() == 1) {
+    MCInst Result;
+    Result.setOpcode(WebAssembly::RESULT);
+    Result.addOperand(MCOperand::createImm(ResultVTs.front().SimpleTy));
+    EmitToStreamer(*OutStreamer, Result);
+  }
+
+  bool AnyWARegs = false;
+  MCInst Local;
+  Local.setOpcode(WebAssembly::LOCAL);
   for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
     unsigned VReg = TargetRegisterInfo::index2VirtReg(Idx);
-    if (!MRI->use_empty(VReg)) {
-      if (FirstVReg) {
-        OS << (First ? "" : "\n") << "\t.local ";
-        First = false;
-      }
-      OS << (FirstVReg ? "" : ", ") << getRegTypeName(VReg);
-      FirstVReg = false;
-    }
+    unsigned WAReg = MFI->getWAReg(VReg);
+    // Don't declare unused registers.
+    if (WAReg == WebAssemblyFunctionInfo::UnusedReg)
+      continue;
+    // Don't redeclare parameters.
+    if (WAReg < MFI->getParams().size())
+      continue;
+    // Don't declare stackified registers.
+    if (int(WAReg) < 0)
+      continue;
+    Local.addOperand(MCOperand::createImm(getRegType(VReg).SimpleTy));
+    AnyWARegs = true;
   }
+  if (AnyWARegs)
+    EmitToStreamer(*OutStreamer, Local);
 
-  if (!First)
-    OutStreamer->EmitRawText(OS.str());
   AsmPrinter::EmitFunctionBodyStart();
 }
 
 void WebAssemblyAsmPrinter::EmitInstruction(const MachineInstr *MI) {
   DEBUG(dbgs() << "EmitInstruction: " << *MI << '\n');
-  SmallString<128> Str;
-  raw_svector_ostream OS(Str);
-
-  unsigned NumDefs = MI->getDesc().getNumDefs();
-  assert(NumDefs <= 1 &&
-         "Instructions with multiple result values not implemented");
-
-  OS << '\t';
 
   switch (MI->getOpcode()) {
-  case TargetOpcode::COPY:
-    OS << "get_local " << regToString(MI->getOperand(1));
-    break;
-  case WebAssembly::GLOBAL:
-    // TODO: wasm64
-    OS << "i32.const " << toSymbol(MI->getOperand(1).getGlobal()->getName());
-    break;
   case WebAssembly::ARGUMENT_I32:
   case WebAssembly::ARGUMENT_I64:
   case WebAssembly::ARGUMENT_F32:
   case WebAssembly::ARGUMENT_F64:
-    OS << "get_local " << argToString(MI->getOperand(1));
+    // These represent values which are live into the function entry, so there's
+    // no instruction to emit.
     break;
-  case WebAssembly::Immediate_I32:
-    OS << "i32.const " << MI->getOperand(1).getImm();
-    break;
-  case WebAssembly::Immediate_I64:
-    OS << "i64.const " << MI->getOperand(1).getImm();
-    break;
-  case WebAssembly::Immediate_F32:
-    OS << "f32.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
-    break;
-  case WebAssembly::Immediate_F64:
-    OS << "f64.const " << toString(MI->getOperand(1).getFPImm()->getValueAPF());
+  case WebAssembly::LOOP_END:
+    // This is a no-op which just exists to tell AsmPrinter.cpp that there's a
+    // fallthrough which nevertheless requires a label for the destination here.
     break;
   default: {
-    OS << OpcodeName(TII, MI);
-    bool NeedComma = false;
-    for (const MachineOperand &MO : MI->uses()) {
-      if (MO.isReg() && MO.isImplicit())
-        continue;
-      if (NeedComma)
-        OS << ',';
-      NeedComma = true;
-      OS << ' ';
-      switch (MO.getType()) {
-      default:
-        llvm_unreachable("unexpected machine operand type");
-      case MachineOperand::MO_Register:
-        OS << "(get_local " << regToString(MO) << ')';
-        break;
-      case MachineOperand::MO_Immediate:
-        OS << MO.getImm();
-        break;
-      case MachineOperand::MO_FPImmediate:
-        OS << toString(MO.getFPImm()->getValueAPF());
-        break;
-      case MachineOperand::MO_GlobalAddress:
-        OS << toSymbol(MO.getGlobal()->getName());
-        break;
-      case MachineOperand::MO_MachineBasicBlock:
-        OS << toSymbol(MO.getMBB()->getSymbol()->getName());
-        break;
-      }
-    }
+    WebAssemblyMCInstLower MCInstLowering(OutContext, *this);
+    MCInst TmpInst;
+    MCInstLowering.Lower(MI, TmpInst);
+    EmitToStreamer(*OutStreamer, TmpInst);
     break;
   }
   }
+}
+
+bool WebAssemblyAsmPrinter::PrintAsmOperand(const MachineInstr *MI,
+                                            unsigned OpNo, unsigned AsmVariant,
+                                            const char *ExtraCode,
+                                            raw_ostream &OS) {
+  if (AsmVariant != 0)
+    report_fatal_error("There are no defined alternate asm variants");
+
+  // First try the generic code, which knows about modifiers like 'c' and 'n'.
+  if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, OS))
+    return false;
+
+  if (!ExtraCode) {
+    const MachineOperand &MO = MI->getOperand(OpNo);
+    switch (MO.getType()) {
+    case MachineOperand::MO_Immediate:
+      OS << MO.getImm();
+      return false;
+    case MachineOperand::MO_Register:
+      OS << regToString(MO);
+      return false;
+    case MachineOperand::MO_GlobalAddress:
+      getSymbol(MO.getGlobal())->print(OS, MAI);
+      printOffset(MO.getOffset(), OS);
+      return false;
+    case MachineOperand::MO_ExternalSymbol:
+      GetExternalSymbolSymbol(MO.getSymbolName())->print(OS, MAI);
+      printOffset(MO.getOffset(), OS);
+      return false;
+    case MachineOperand::MO_MachineBasicBlock:
+      MO.getMBB()->getSymbol()->print(OS, MAI);
+      return false;
+    default:
+      break;
+    }
+  }
 
-  OutStreamer->EmitRawText(OS.str());
+  return true;
+}
 
-  if (NumDefs != 0) {
-    SmallString<128> Str;
-    raw_svector_ostream OS(Str);
-    const MachineOperand &Operand = MI->getOperand(0);
-    OS << "\tset_local " << regToString(Operand) << ", pop";
-    OutStreamer->EmitRawText(OS.str());
+bool WebAssemblyAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
+                                                  unsigned OpNo,
+                                                  unsigned AsmVariant,
+                                                  const char *ExtraCode,
+                                                  raw_ostream &OS) {
+  if (AsmVariant != 0)
+    report_fatal_error("There are no defined alternate asm variants");
+
+  if (!ExtraCode) {
+    // TODO: For now, we just hard-code 0 as the constant offset; teach
+    // SelectInlineAsmMemoryOperand how to do address mode matching.
+    OS << "0(" + regToString(MI->getOperand(OpNo)) + ')';
+    return false;
   }
+
+  return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, AsmVariant, ExtraCode, OS);
 }
 
 // Force static initialization.