MCSymbol: Make print() robust against empty names
[oota-llvm.git] / lib / MC / MCSymbol.cpp
1 //===- lib/MC/MCSymbol.cpp - MCSymbol implementation ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCSymbol.h"
11 #include "llvm/MC/MCExpr.h"
12 #include "llvm/Support/Debug.h"
13 #include "llvm/Support/raw_ostream.h"
14 using namespace llvm;
15
16 // Sentinel value for the absolute pseudo section.
17 MCSection *MCSymbol::AbsolutePseudoSection = reinterpret_cast<MCSection *>(1);
18
19 static bool isAcceptableChar(char C) {
20   if ((C < 'a' || C > 'z') &&
21       (C < 'A' || C > 'Z') &&
22       (C < '0' || C > '9') &&
23       C != '_' && C != '$' && C != '.' && C != '@')
24     return false;
25   return true;
26 }
27
28 /// NameNeedsQuoting - Return true if the identifier \p Str needs quotes to be
29 /// syntactically correct.
30 static bool NameNeedsQuoting(StringRef Str) {
31   assert(!Str.empty() && "Cannot create an empty MCSymbol");
32
33   // If any of the characters in the string is an unacceptable character, force
34   // quotes.
35   for (unsigned i = 0, e = Str.size(); i != e; ++i)
36     if (!isAcceptableChar(Str[i]))
37       return true;
38   return false;
39 }
40
41 void MCSymbol::setVariableValue(const MCExpr *Value) {
42   assert(!IsUsed && "Cannot set a variable that has already been used.");
43   assert(Value && "Invalid variable value!");
44   this->Value = Value;
45   this->Section = nullptr;
46 }
47
48 void MCSymbol::print(raw_ostream &OS) const {
49   // The name for this MCSymbol is required to be a valid target name.  However,
50   // some targets support quoting names with funny characters.  If the name
51   // contains a funny character, then print it quoted.
52   StringRef Name = getName();
53   if (Name.empty()) {
54     OS << "\"\"";
55     return;
56   }
57   if (!NameNeedsQuoting(Name)) {
58     OS << Name;
59     return;
60   }
61
62   OS << '"';
63   for (unsigned I = 0, E = Name.size(); I != E; ++I) {
64     char C = Name[I];
65     if (C == '\n')
66       OS << "\\n";
67     else if (C == '"')
68       OS << "\\\"";
69     else
70       OS << C;
71   }
72   OS << '"';
73 }
74
75 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
76 void MCSymbol::dump() const {
77   print(dbgs());
78 }
79 #endif