Correctly handle an ELF symbol defined with "a = b + expr".
[oota-llvm.git] / lib / MC / MCSymbol.cpp
index f7f9184f03d0a45bd55473ed53b7b76f638ba2bc..d0283a635bef31aa3889cdb23756810657b0db14 100644 (file)
@@ -9,6 +9,7 @@
 
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCValue.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
@@ -26,7 +27,7 @@ static bool isAcceptableChar(char C) {
   return true;
 }
 
-/// NameNeedsQuoting - Return true if the identifier \arg Str needs quotes to be
+/// NameNeedsQuoting - Return true if the identifier \p Str needs quotes to be
 /// syntactically correct.
 static bool NameNeedsQuoting(StringRef Str) {
   assert(!Str.empty() && "Cannot create an empty MCSymbol");
@@ -51,6 +52,22 @@ const MCSymbol &MCSymbol::AliasedSymbol() const {
   return *S;
 }
 
+const MCSymbol *MCSymbol::getBaseSymbol(const MCAsmLayout &Layout) const {
+  if (!isVariable())
+    return this;
+
+  const MCExpr *Expr = getVariableValue();
+  MCValue Value;
+  if (!Expr->EvaluateAsRelocatable(Value, &Layout))
+    return nullptr;
+
+  if (Value.getSymB())
+    return nullptr;
+  if (const MCSymbolRefExpr *A = Value.getSymA())
+    return &A->getSymbol();
+  return nullptr;
+}
+
 void MCSymbol::setVariableValue(const MCExpr *Value) {
   assert(!IsUsed && "Cannot set a variable that has already been used.");
   assert(Value && "Invalid variable value!");
@@ -68,14 +85,27 @@ void MCSymbol::print(raw_ostream &OS) const {
   // The name for this MCSymbol is required to be a valid target name.  However,
   // some targets support quoting names with funny characters.  If the name
   // contains a funny character, then print it quoted.
-  if (!NameNeedsQuoting(getName())) {
-    OS << getName();
+  StringRef Name = getName();
+  if (!NameNeedsQuoting(Name)) {
+    OS << Name;
     return;
   }
 
-  OS << '"' << getName() << '"';
+  OS << '"';
+  for (unsigned I = 0, E = Name.size(); I != E; ++I) {
+    char C = Name[I];
+    if (C == '\n')
+      OS << "\\n";
+    else if (C == '"')
+      OS << "\\\"";
+    else
+      OS << C;
+  }
+  OS << '"';
 }
 
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
 void MCSymbol::dump() const {
   print(dbgs());
 }
+#endif