xref: /llvm-project-15.0.7/llvm/lib/MC/MCExpr.cpp (revision bacf751a)
1 //===- MCExpr.cpp - Assembly Level Expression 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/MCExpr.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/Config/llvm-config.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cassert>
28 #include <cstdint>
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "mcexpr"
33 
34 namespace {
35 namespace stats {
36 
37 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
38 
39 } // end namespace stats
40 } // end anonymous namespace
41 
42 void MCExpr::print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens) const {
43   switch (getKind()) {
44   case MCExpr::Target:
45     return cast<MCTargetExpr>(this)->printImpl(OS, MAI);
46   case MCExpr::Constant:
47     OS << cast<MCConstantExpr>(*this).getValue();
48     return;
49 
50   case MCExpr::SymbolRef: {
51     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
52     const MCSymbol &Sym = SRE.getSymbol();
53     // Parenthesize names that start with $ so that they don't look like
54     // absolute names.
55     bool UseParens =
56         !InParens && !Sym.getName().empty() && Sym.getName()[0] == '$';
57     if (UseParens) {
58       OS << '(';
59       Sym.print(OS, MAI);
60       OS << ')';
61     } else
62       Sym.print(OS, MAI);
63 
64     if (SRE.getKind() != MCSymbolRefExpr::VK_None)
65       SRE.printVariantKind(OS);
66 
67     return;
68   }
69 
70   case MCExpr::Unary: {
71     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
72     switch (UE.getOpcode()) {
73     case MCUnaryExpr::LNot:  OS << '!'; break;
74     case MCUnaryExpr::Minus: OS << '-'; break;
75     case MCUnaryExpr::Not:   OS << '~'; break;
76     case MCUnaryExpr::Plus:  OS << '+'; break;
77     }
78     bool Binary = UE.getSubExpr()->getKind() == MCExpr::Binary;
79     if (Binary) OS << "(";
80     UE.getSubExpr()->print(OS, MAI);
81     if (Binary) OS << ")";
82     return;
83   }
84 
85   case MCExpr::Binary: {
86     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
87 
88     // Only print parens around the LHS if it is non-trivial.
89     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
90       BE.getLHS()->print(OS, MAI);
91     } else {
92       OS << '(';
93       BE.getLHS()->print(OS, MAI);
94       OS << ')';
95     }
96 
97     switch (BE.getOpcode()) {
98     case MCBinaryExpr::Add:
99       // Print "X-42" instead of "X+-42".
100       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
101         if (RHSC->getValue() < 0) {
102           OS << RHSC->getValue();
103           return;
104         }
105       }
106 
107       OS <<  '+';
108       break;
109     case MCBinaryExpr::AShr: OS << ">>"; break;
110     case MCBinaryExpr::And:  OS <<  '&'; break;
111     case MCBinaryExpr::Div:  OS <<  '/'; break;
112     case MCBinaryExpr::EQ:   OS << "=="; break;
113     case MCBinaryExpr::GT:   OS <<  '>'; break;
114     case MCBinaryExpr::GTE:  OS << ">="; break;
115     case MCBinaryExpr::LAnd: OS << "&&"; break;
116     case MCBinaryExpr::LOr:  OS << "||"; break;
117     case MCBinaryExpr::LShr: OS << ">>"; break;
118     case MCBinaryExpr::LT:   OS <<  '<'; break;
119     case MCBinaryExpr::LTE:  OS << "<="; break;
120     case MCBinaryExpr::Mod:  OS <<  '%'; break;
121     case MCBinaryExpr::Mul:  OS <<  '*'; break;
122     case MCBinaryExpr::NE:   OS << "!="; break;
123     case MCBinaryExpr::Or:   OS <<  '|'; break;
124     case MCBinaryExpr::Shl:  OS << "<<"; break;
125     case MCBinaryExpr::Sub:  OS <<  '-'; break;
126     case MCBinaryExpr::Xor:  OS <<  '^'; break;
127     }
128 
129     // Only print parens around the LHS if it is non-trivial.
130     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
131       BE.getRHS()->print(OS, MAI);
132     } else {
133       OS << '(';
134       BE.getRHS()->print(OS, MAI);
135       OS << ')';
136     }
137     return;
138   }
139   }
140 
141   llvm_unreachable("Invalid expression kind!");
142 }
143 
144 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
145 LLVM_DUMP_METHOD void MCExpr::dump() const {
146   dbgs() << *this;
147   dbgs() << '\n';
148 }
149 #endif
150 
151 /* *** */
152 
153 const MCBinaryExpr *MCBinaryExpr::create(Opcode Opc, const MCExpr *LHS,
154                                          const MCExpr *RHS, MCContext &Ctx,
155                                          SMLoc Loc) {
156   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS, Loc);
157 }
158 
159 const MCUnaryExpr *MCUnaryExpr::create(Opcode Opc, const MCExpr *Expr,
160                                        MCContext &Ctx, SMLoc Loc) {
161   return new (Ctx) MCUnaryExpr(Opc, Expr, Loc);
162 }
163 
164 const MCConstantExpr *MCConstantExpr::create(int64_t Value, MCContext &Ctx) {
165   return new (Ctx) MCConstantExpr(Value);
166 }
167 
168 /* *** */
169 
170 MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind,
171                                  const MCAsmInfo *MAI, SMLoc Loc)
172     : MCExpr(MCExpr::SymbolRef, Loc), Kind(Kind),
173       UseParensForSymbolVariant(MAI->useParensForSymbolVariant()),
174       HasSubsectionsViaSymbols(MAI->hasSubsectionsViaSymbols()),
175       Symbol(Symbol) {
176   assert(Symbol);
177 }
178 
179 const MCSymbolRefExpr *MCSymbolRefExpr::create(const MCSymbol *Sym,
180                                                VariantKind Kind,
181                                                MCContext &Ctx, SMLoc Loc) {
182   return new (Ctx) MCSymbolRefExpr(Sym, Kind, Ctx.getAsmInfo(), Loc);
183 }
184 
185 const MCSymbolRefExpr *MCSymbolRefExpr::create(StringRef Name, VariantKind Kind,
186                                                MCContext &Ctx) {
187   return create(Ctx.getOrCreateSymbol(Name), Kind, Ctx);
188 }
189 
190 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
191   switch (Kind) {
192   case VK_Invalid: return "<<invalid>>";
193   case VK_None: return "<<none>>";
194 
195   case VK_DTPOFF: return "DTPOFF";
196   case VK_DTPREL: return "DTPREL";
197   case VK_GOT: return "GOT";
198   case VK_GOTOFF: return "GOTOFF";
199   case VK_GOTREL: return "GOTREL";
200   case VK_GOTPCREL: return "GOTPCREL";
201   case VK_GOTTPOFF: return "GOTTPOFF";
202   case VK_INDNTPOFF: return "INDNTPOFF";
203   case VK_NTPOFF: return "NTPOFF";
204   case VK_GOTNTPOFF: return "GOTNTPOFF";
205   case VK_PLT: return "PLT";
206   case VK_TLSGD: return "TLSGD";
207   case VK_TLSLD: return "TLSLD";
208   case VK_TLSLDM: return "TLSLDM";
209   case VK_TPOFF: return "TPOFF";
210   case VK_TPREL: return "TPREL";
211   case VK_TLSCALL: return "tlscall";
212   case VK_TLSDESC: return "tlsdesc";
213   case VK_TLVP: return "TLVP";
214   case VK_TLVPPAGE: return "TLVPPAGE";
215   case VK_TLVPPAGEOFF: return "TLVPPAGEOFF";
216   case VK_PAGE: return "PAGE";
217   case VK_PAGEOFF: return "PAGEOFF";
218   case VK_GOTPAGE: return "GOTPAGE";
219   case VK_GOTPAGEOFF: return "GOTPAGEOFF";
220   case VK_SECREL: return "SECREL32";
221   case VK_SIZE: return "SIZE";
222   case VK_WEAKREF: return "WEAKREF";
223   case VK_X86_ABS8: return "ABS8";
224   case VK_ARM_NONE: return "none";
225   case VK_ARM_GOT_PREL: return "GOT_PREL";
226   case VK_ARM_TARGET1: return "target1";
227   case VK_ARM_TARGET2: return "target2";
228   case VK_ARM_PREL31: return "prel31";
229   case VK_ARM_SBREL: return "sbrel";
230   case VK_ARM_TLSLDO: return "tlsldo";
231   case VK_ARM_TLSDESCSEQ: return "tlsdescseq";
232   case VK_AVR_NONE: return "none";
233   case VK_AVR_LO8: return "lo8";
234   case VK_AVR_HI8: return "hi8";
235   case VK_AVR_HLO8: return "hlo8";
236   case VK_AVR_DIFF8: return "diff8";
237   case VK_AVR_DIFF16: return "diff16";
238   case VK_AVR_DIFF32: return "diff32";
239   case VK_PPC_LO: return "l";
240   case VK_PPC_HI: return "h";
241   case VK_PPC_HA: return "ha";
242   case VK_PPC_HIGH: return "high";
243   case VK_PPC_HIGHA: return "higha";
244   case VK_PPC_HIGHER: return "higher";
245   case VK_PPC_HIGHERA: return "highera";
246   case VK_PPC_HIGHEST: return "highest";
247   case VK_PPC_HIGHESTA: return "highesta";
248   case VK_PPC_GOT_LO: return "got@l";
249   case VK_PPC_GOT_HI: return "got@h";
250   case VK_PPC_GOT_HA: return "got@ha";
251   case VK_PPC_TOCBASE: return "tocbase";
252   case VK_PPC_TOC: return "toc";
253   case VK_PPC_TOC_LO: return "toc@l";
254   case VK_PPC_TOC_HI: return "toc@h";
255   case VK_PPC_TOC_HA: return "toc@ha";
256   case VK_PPC_DTPMOD: return "dtpmod";
257   case VK_PPC_TPREL_LO: return "tprel@l";
258   case VK_PPC_TPREL_HI: return "tprel@h";
259   case VK_PPC_TPREL_HA: return "tprel@ha";
260   case VK_PPC_TPREL_HIGH: return "tprel@high";
261   case VK_PPC_TPREL_HIGHA: return "tprel@higha";
262   case VK_PPC_TPREL_HIGHER: return "tprel@higher";
263   case VK_PPC_TPREL_HIGHERA: return "tprel@highera";
264   case VK_PPC_TPREL_HIGHEST: return "tprel@highest";
265   case VK_PPC_TPREL_HIGHESTA: return "tprel@highesta";
266   case VK_PPC_DTPREL_LO: return "dtprel@l";
267   case VK_PPC_DTPREL_HI: return "dtprel@h";
268   case VK_PPC_DTPREL_HA: return "dtprel@ha";
269   case VK_PPC_DTPREL_HIGH: return "dtprel@high";
270   case VK_PPC_DTPREL_HIGHA: return "dtprel@higha";
271   case VK_PPC_DTPREL_HIGHER: return "dtprel@higher";
272   case VK_PPC_DTPREL_HIGHERA: return "dtprel@highera";
273   case VK_PPC_DTPREL_HIGHEST: return "dtprel@highest";
274   case VK_PPC_DTPREL_HIGHESTA: return "dtprel@highesta";
275   case VK_PPC_GOT_TPREL: return "got@tprel";
276   case VK_PPC_GOT_TPREL_LO: return "got@tprel@l";
277   case VK_PPC_GOT_TPREL_HI: return "got@tprel@h";
278   case VK_PPC_GOT_TPREL_HA: return "got@tprel@ha";
279   case VK_PPC_GOT_DTPREL: return "got@dtprel";
280   case VK_PPC_GOT_DTPREL_LO: return "got@dtprel@l";
281   case VK_PPC_GOT_DTPREL_HI: return "got@dtprel@h";
282   case VK_PPC_GOT_DTPREL_HA: return "got@dtprel@ha";
283   case VK_PPC_TLS: return "tls";
284   case VK_PPC_GOT_TLSGD: return "got@tlsgd";
285   case VK_PPC_GOT_TLSGD_LO: return "got@tlsgd@l";
286   case VK_PPC_GOT_TLSGD_HI: return "got@tlsgd@h";
287   case VK_PPC_GOT_TLSGD_HA: return "got@tlsgd@ha";
288   case VK_PPC_TLSGD: return "tlsgd";
289   case VK_PPC_GOT_TLSLD: return "got@tlsld";
290   case VK_PPC_GOT_TLSLD_LO: return "got@tlsld@l";
291   case VK_PPC_GOT_TLSLD_HI: return "got@tlsld@h";
292   case VK_PPC_GOT_TLSLD_HA: return "got@tlsld@ha";
293   case VK_PPC_TLSLD: return "tlsld";
294   case VK_PPC_LOCAL: return "local";
295   case VK_COFF_IMGREL32: return "IMGREL";
296   case VK_Hexagon_PCREL: return "PCREL";
297   case VK_Hexagon_LO16: return "LO16";
298   case VK_Hexagon_HI16: return "HI16";
299   case VK_Hexagon_GPREL: return "GPREL";
300   case VK_Hexagon_GD_GOT: return "GDGOT";
301   case VK_Hexagon_LD_GOT: return "LDGOT";
302   case VK_Hexagon_GD_PLT: return "GDPLT";
303   case VK_Hexagon_LD_PLT: return "LDPLT";
304   case VK_Hexagon_IE: return "IE";
305   case VK_Hexagon_IE_GOT: return "IEGOT";
306   case VK_WebAssembly_FUNCTION: return "FUNCTION";
307   case VK_WebAssembly_GLOBAL: return "GLOBAL";
308   case VK_WebAssembly_TYPEINDEX: return "TYPEINDEX";
309   case VK_AMDGPU_GOTPCREL32_LO: return "gotpcrel32@lo";
310   case VK_AMDGPU_GOTPCREL32_HI: return "gotpcrel32@hi";
311   case VK_AMDGPU_REL32_LO: return "rel32@lo";
312   case VK_AMDGPU_REL32_HI: return "rel32@hi";
313   case VK_AMDGPU_REL64: return "rel64";
314   }
315   llvm_unreachable("Invalid variant kind");
316 }
317 
318 MCSymbolRefExpr::VariantKind
319 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
320   return StringSwitch<VariantKind>(Name.lower())
321     .Case("dtprel", VK_DTPREL)
322     .Case("dtpoff", VK_DTPOFF)
323     .Case("got", VK_GOT)
324     .Case("gotoff", VK_GOTOFF)
325     .Case("gotrel", VK_GOTREL)
326     .Case("gotpcrel", VK_GOTPCREL)
327     .Case("gottpoff", VK_GOTTPOFF)
328     .Case("indntpoff", VK_INDNTPOFF)
329     .Case("ntpoff", VK_NTPOFF)
330     .Case("gotntpoff", VK_GOTNTPOFF)
331     .Case("plt", VK_PLT)
332     .Case("tlscall", VK_TLSCALL)
333     .Case("tlsdesc", VK_TLSDESC)
334     .Case("tlsgd", VK_TLSGD)
335     .Case("tlsld", VK_TLSLD)
336     .Case("tlsldm", VK_TLSLDM)
337     .Case("tpoff", VK_TPOFF)
338     .Case("tprel", VK_TPREL)
339     .Case("tlvp", VK_TLVP)
340     .Case("tlvppage", VK_TLVPPAGE)
341     .Case("tlvppageoff", VK_TLVPPAGEOFF)
342     .Case("page", VK_PAGE)
343     .Case("pageoff", VK_PAGEOFF)
344     .Case("gotpage", VK_GOTPAGE)
345     .Case("gotpageoff", VK_GOTPAGEOFF)
346     .Case("imgrel", VK_COFF_IMGREL32)
347     .Case("secrel32", VK_SECREL)
348     .Case("size", VK_SIZE)
349     .Case("abs8", VK_X86_ABS8)
350     .Case("l", VK_PPC_LO)
351     .Case("h", VK_PPC_HI)
352     .Case("ha", VK_PPC_HA)
353     .Case("high", VK_PPC_HIGH)
354     .Case("higha", VK_PPC_HIGHA)
355     .Case("higher", VK_PPC_HIGHER)
356     .Case("highera", VK_PPC_HIGHERA)
357     .Case("highest", VK_PPC_HIGHEST)
358     .Case("highesta", VK_PPC_HIGHESTA)
359     .Case("got@l", VK_PPC_GOT_LO)
360     .Case("got@h", VK_PPC_GOT_HI)
361     .Case("got@ha", VK_PPC_GOT_HA)
362     .Case("local", VK_PPC_LOCAL)
363     .Case("tocbase", VK_PPC_TOCBASE)
364     .Case("toc", VK_PPC_TOC)
365     .Case("toc@l", VK_PPC_TOC_LO)
366     .Case("toc@h", VK_PPC_TOC_HI)
367     .Case("toc@ha", VK_PPC_TOC_HA)
368     .Case("tls", VK_PPC_TLS)
369     .Case("dtpmod", VK_PPC_DTPMOD)
370     .Case("tprel@l", VK_PPC_TPREL_LO)
371     .Case("tprel@h", VK_PPC_TPREL_HI)
372     .Case("tprel@ha", VK_PPC_TPREL_HA)
373     .Case("tprel@high", VK_PPC_TPREL_HIGH)
374     .Case("tprel@higha", VK_PPC_TPREL_HIGHA)
375     .Case("tprel@higher", VK_PPC_TPREL_HIGHER)
376     .Case("tprel@highera", VK_PPC_TPREL_HIGHERA)
377     .Case("tprel@highest", VK_PPC_TPREL_HIGHEST)
378     .Case("tprel@highesta", VK_PPC_TPREL_HIGHESTA)
379     .Case("dtprel@l", VK_PPC_DTPREL_LO)
380     .Case("dtprel@h", VK_PPC_DTPREL_HI)
381     .Case("dtprel@ha", VK_PPC_DTPREL_HA)
382     .Case("dtprel@high", VK_PPC_DTPREL_HIGH)
383     .Case("dtprel@higha", VK_PPC_DTPREL_HIGHA)
384     .Case("dtprel@higher", VK_PPC_DTPREL_HIGHER)
385     .Case("dtprel@highera", VK_PPC_DTPREL_HIGHERA)
386     .Case("dtprel@highest", VK_PPC_DTPREL_HIGHEST)
387     .Case("dtprel@highesta", VK_PPC_DTPREL_HIGHESTA)
388     .Case("got@tprel", VK_PPC_GOT_TPREL)
389     .Case("got@tprel@l", VK_PPC_GOT_TPREL_LO)
390     .Case("got@tprel@h", VK_PPC_GOT_TPREL_HI)
391     .Case("got@tprel@ha", VK_PPC_GOT_TPREL_HA)
392     .Case("got@dtprel", VK_PPC_GOT_DTPREL)
393     .Case("got@dtprel@l", VK_PPC_GOT_DTPREL_LO)
394     .Case("got@dtprel@h", VK_PPC_GOT_DTPREL_HI)
395     .Case("got@dtprel@ha", VK_PPC_GOT_DTPREL_HA)
396     .Case("got@tlsgd", VK_PPC_GOT_TLSGD)
397     .Case("got@tlsgd@l", VK_PPC_GOT_TLSGD_LO)
398     .Case("got@tlsgd@h", VK_PPC_GOT_TLSGD_HI)
399     .Case("got@tlsgd@ha", VK_PPC_GOT_TLSGD_HA)
400     .Case("got@tlsld", VK_PPC_GOT_TLSLD)
401     .Case("got@tlsld@l", VK_PPC_GOT_TLSLD_LO)
402     .Case("got@tlsld@h", VK_PPC_GOT_TLSLD_HI)
403     .Case("got@tlsld@ha", VK_PPC_GOT_TLSLD_HA)
404     .Case("gdgot", VK_Hexagon_GD_GOT)
405     .Case("gdplt", VK_Hexagon_GD_PLT)
406     .Case("iegot", VK_Hexagon_IE_GOT)
407     .Case("ie", VK_Hexagon_IE)
408     .Case("ldgot", VK_Hexagon_LD_GOT)
409     .Case("ldplt", VK_Hexagon_LD_PLT)
410     .Case("pcrel", VK_Hexagon_PCREL)
411     .Case("none", VK_ARM_NONE)
412     .Case("got_prel", VK_ARM_GOT_PREL)
413     .Case("target1", VK_ARM_TARGET1)
414     .Case("target2", VK_ARM_TARGET2)
415     .Case("prel31", VK_ARM_PREL31)
416     .Case("sbrel", VK_ARM_SBREL)
417     .Case("tlsldo", VK_ARM_TLSLDO)
418     .Case("lo8", VK_AVR_LO8)
419     .Case("hi8", VK_AVR_HI8)
420     .Case("hlo8", VK_AVR_HLO8)
421     .Case("function", VK_WebAssembly_FUNCTION)
422     .Case("global", VK_WebAssembly_GLOBAL)
423     .Case("typeindex", VK_WebAssembly_TYPEINDEX)
424     .Case("gotpcrel32@lo", VK_AMDGPU_GOTPCREL32_LO)
425     .Case("gotpcrel32@hi", VK_AMDGPU_GOTPCREL32_HI)
426     .Case("rel32@lo", VK_AMDGPU_REL32_LO)
427     .Case("rel32@hi", VK_AMDGPU_REL32_HI)
428     .Case("rel64", VK_AMDGPU_REL64)
429     .Default(VK_Invalid);
430 }
431 
432 void MCSymbolRefExpr::printVariantKind(raw_ostream &OS) const {
433   if (UseParensForSymbolVariant)
434     OS << '(' << MCSymbolRefExpr::getVariantKindName(getKind()) << ')';
435   else
436     OS << '@' << MCSymbolRefExpr::getVariantKindName(getKind());
437 }
438 
439 /* *** */
440 
441 void MCTargetExpr::anchor() {}
442 
443 /* *** */
444 
445 bool MCExpr::evaluateAsAbsolute(int64_t &Res) const {
446   return evaluateAsAbsolute(Res, nullptr, nullptr, nullptr);
447 }
448 
449 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
450                                 const MCAsmLayout &Layout) const {
451   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr);
452 }
453 
454 bool MCExpr::evaluateAsAbsolute(int64_t &Res,
455                                 const MCAsmLayout &Layout,
456                                 const SectionAddrMap &Addrs) const {
457   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
458 }
459 
460 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
461   return evaluateAsAbsolute(Res, &Asm, nullptr, nullptr);
462 }
463 
464 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm) const {
465   return evaluateAsAbsolute(Res, Asm, nullptr, nullptr);
466 }
467 
468 bool MCExpr::evaluateKnownAbsolute(int64_t &Res,
469                                    const MCAsmLayout &Layout) const {
470   return evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr,
471                             true);
472 }
473 
474 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
475                                 const MCAsmLayout *Layout,
476                                 const SectionAddrMap *Addrs) const {
477   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
478   // absolutize differences across sections and that is what the MachO writer
479   // uses Addrs for.
480   return evaluateAsAbsolute(Res, Asm, Layout, Addrs, Addrs);
481 }
482 
483 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
484                                 const MCAsmLayout *Layout,
485                                 const SectionAddrMap *Addrs, bool InSet) const {
486   MCValue Value;
487 
488   // Fast path constants.
489   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
490     Res = CE->getValue();
491     return true;
492   }
493 
494   bool IsRelocatable =
495       evaluateAsRelocatableImpl(Value, Asm, Layout, nullptr, Addrs, InSet);
496 
497   // Record the current value.
498   Res = Value.getConstant();
499 
500   return IsRelocatable && Value.isAbsolute();
501 }
502 
503 /// Helper method for \see EvaluateSymbolAdd().
504 static void AttemptToFoldSymbolOffsetDifference(
505     const MCAssembler *Asm, const MCAsmLayout *Layout,
506     const SectionAddrMap *Addrs, bool InSet, const MCSymbolRefExpr *&A,
507     const MCSymbolRefExpr *&B, int64_t &Addend) {
508   if (!A || !B)
509     return;
510 
511   const MCSymbol &SA = A->getSymbol();
512   const MCSymbol &SB = B->getSymbol();
513 
514   if (SA.isUndefined() || SB.isUndefined())
515     return;
516 
517   if (!Asm->getWriter().isSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
518     return;
519 
520   if (SA.getFragment() == SB.getFragment() && !SA.isVariable() &&
521       !SA.isUnset() && !SB.isVariable() && !SB.isUnset()) {
522     Addend += (SA.getOffset() - SB.getOffset());
523 
524     // Pointers to Thumb symbols need to have their low-bit set to allow
525     // for interworking.
526     if (Asm->isThumbFunc(&SA))
527       Addend |= 1;
528 
529     // If symbol is labeled as micromips, we set low-bit to ensure
530     // correct offset in .gcc_except_table
531     if (Asm->getBackend().isMicroMips(&SA))
532       Addend |= 1;
533 
534     // Clear the symbol expr pointers to indicate we have folded these
535     // operands.
536     A = B = nullptr;
537     return;
538   }
539 
540   if (!Layout)
541     return;
542 
543   const MCSection &SecA = *SA.getFragment()->getParent();
544   const MCSection &SecB = *SB.getFragment()->getParent();
545 
546   if ((&SecA != &SecB) && !Addrs)
547     return;
548 
549   // Eagerly evaluate.
550   Addend += Layout->getSymbolOffset(A->getSymbol()) -
551             Layout->getSymbolOffset(B->getSymbol());
552   if (Addrs && (&SecA != &SecB))
553     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
554 
555   // Pointers to Thumb symbols need to have their low-bit set to allow
556   // for interworking.
557   if (Asm->isThumbFunc(&SA))
558     Addend |= 1;
559 
560   // Clear the symbol expr pointers to indicate we have folded these
561   // operands.
562   A = B = nullptr;
563 }
564 
565 /// Evaluate the result of an add between (conceptually) two MCValues.
566 ///
567 /// This routine conceptually attempts to construct an MCValue:
568 ///   Result = (Result_A - Result_B + Result_Cst)
569 /// from two MCValue's LHS and RHS where
570 ///   Result = LHS + RHS
571 /// and
572 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
573 ///
574 /// This routine attempts to aggresively fold the operands such that the result
575 /// is representable in an MCValue, but may not always succeed.
576 ///
577 /// \returns True on success, false if the result is not representable in an
578 /// MCValue.
579 
580 /// NOTE: It is really important to have both the Asm and Layout arguments.
581 /// They might look redundant, but this function can be used before layout
582 /// is done (see the object streamer for example) and having the Asm argument
583 /// lets us avoid relaxations early.
584 static bool
585 EvaluateSymbolicAdd(const MCAssembler *Asm, const MCAsmLayout *Layout,
586                     const SectionAddrMap *Addrs, bool InSet, const MCValue &LHS,
587                     const MCSymbolRefExpr *RHS_A, const MCSymbolRefExpr *RHS_B,
588                     int64_t RHS_Cst, MCValue &Res) {
589   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
590   // about dealing with modifiers. This will ultimately bite us, one day.
591   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
592   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
593   int64_t LHS_Cst = LHS.getConstant();
594 
595   // Fold the result constant immediately.
596   int64_t Result_Cst = LHS_Cst + RHS_Cst;
597 
598   assert((!Layout || Asm) &&
599          "Must have an assembler object if layout is given!");
600 
601   // If we have a layout, we can fold resolved differences. Do not do this if
602   // the backend requires this to be emitted as individual relocations, unless
603   // the InSet flag is set to get the current difference anyway (used for
604   // example to calculate symbol sizes).
605   if (Asm &&
606       (InSet || !Asm->getBackend().requiresDiffExpressionRelocations())) {
607     // First, fold out any differences which are fully resolved. By
608     // reassociating terms in
609     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
610     // we have the four possible differences:
611     //   (LHS_A - LHS_B),
612     //   (LHS_A - RHS_B),
613     //   (RHS_A - LHS_B),
614     //   (RHS_A - RHS_B).
615     // Since we are attempting to be as aggressive as possible about folding, we
616     // attempt to evaluate each possible alternative.
617     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
618                                         Result_Cst);
619     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
620                                         Result_Cst);
621     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
622                                         Result_Cst);
623     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
624                                         Result_Cst);
625   }
626 
627   // We can't represent the addition or subtraction of two symbols.
628   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
629     return false;
630 
631   // At this point, we have at most one additive symbol and one subtractive
632   // symbol -- find them.
633   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
634   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
635 
636   Res = MCValue::get(A, B, Result_Cst);
637   return true;
638 }
639 
640 bool MCExpr::evaluateAsRelocatable(MCValue &Res,
641                                    const MCAsmLayout *Layout,
642                                    const MCFixup *Fixup) const {
643   MCAssembler *Assembler = Layout ? &Layout->getAssembler() : nullptr;
644   return evaluateAsRelocatableImpl(Res, Assembler, Layout, Fixup, nullptr,
645                                    false);
646 }
647 
648 bool MCExpr::evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const {
649   MCAssembler *Assembler = &Layout.getAssembler();
650   return evaluateAsRelocatableImpl(Res, Assembler, &Layout, nullptr, nullptr,
651                                    true);
652 }
653 
654 static bool canExpand(const MCSymbol &Sym, bool InSet) {
655   const MCExpr *Expr = Sym.getVariableValue();
656   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
657   if (Inner) {
658     if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
659       return false;
660   }
661 
662   if (InSet)
663     return true;
664   return !Sym.isInSection();
665 }
666 
667 bool MCExpr::evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
668                                        const MCAsmLayout *Layout,
669                                        const MCFixup *Fixup,
670                                        const SectionAddrMap *Addrs,
671                                        bool InSet) const {
672   ++stats::MCExprEvaluate;
673 
674   switch (getKind()) {
675   case Target:
676     return cast<MCTargetExpr>(this)->evaluateAsRelocatableImpl(Res, Layout,
677                                                                Fixup);
678 
679   case Constant:
680     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
681     return true;
682 
683   case SymbolRef: {
684     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
685     const MCSymbol &Sym = SRE->getSymbol();
686 
687     // Evaluate recursively if this is a variable.
688     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None &&
689         canExpand(Sym, InSet)) {
690       bool IsMachO = SRE->hasSubsectionsViaSymbols();
691       if (Sym.getVariableValue()->evaluateAsRelocatableImpl(
692               Res, Asm, Layout, Fixup, Addrs, InSet || IsMachO)) {
693         if (!IsMachO)
694           return true;
695 
696         const MCSymbolRefExpr *A = Res.getSymA();
697         const MCSymbolRefExpr *B = Res.getSymB();
698         // FIXME: This is small hack. Given
699         // a = b + 4
700         // .long a
701         // the OS X assembler will completely drop the 4. We should probably
702         // include it in the relocation or produce an error if that is not
703         // possible.
704         // Allow constant expressions.
705         if (!A && !B)
706           return true;
707         // Allows aliases with zero offset.
708         if (Res.getConstant() == 0 && (!A || !B))
709           return true;
710       }
711     }
712 
713     Res = MCValue::get(SRE, nullptr, 0);
714     return true;
715   }
716 
717   case Unary: {
718     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
719     MCValue Value;
720 
721     if (!AUE->getSubExpr()->evaluateAsRelocatableImpl(Value, Asm, Layout, Fixup,
722                                                       Addrs, InSet))
723       return false;
724 
725     switch (AUE->getOpcode()) {
726     case MCUnaryExpr::LNot:
727       if (!Value.isAbsolute())
728         return false;
729       Res = MCValue::get(!Value.getConstant());
730       break;
731     case MCUnaryExpr::Minus:
732       /// -(a - b + const) ==> (b - a - const)
733       if (Value.getSymA() && !Value.getSymB())
734         return false;
735 
736       // The cast avoids undefined behavior if the constant is INT64_MIN.
737       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
738                          -(uint64_t)Value.getConstant());
739       break;
740     case MCUnaryExpr::Not:
741       if (!Value.isAbsolute())
742         return false;
743       Res = MCValue::get(~Value.getConstant());
744       break;
745     case MCUnaryExpr::Plus:
746       Res = Value;
747       break;
748     }
749 
750     return true;
751   }
752 
753   case Binary: {
754     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
755     MCValue LHSValue, RHSValue;
756 
757     if (!ABE->getLHS()->evaluateAsRelocatableImpl(LHSValue, Asm, Layout, Fixup,
758                                                   Addrs, InSet) ||
759         !ABE->getRHS()->evaluateAsRelocatableImpl(RHSValue, Asm, Layout, Fixup,
760                                                   Addrs, InSet)) {
761       // Check if both are Target Expressions, see if we can compare them.
762       if (const MCTargetExpr *L = dyn_cast<MCTargetExpr>(ABE->getLHS()))
763         if (const MCTargetExpr *R = cast<MCTargetExpr>(ABE->getRHS())) {
764           switch (ABE->getOpcode()) {
765           case MCBinaryExpr::EQ:
766             Res = MCValue::get((L->isEqualTo(R)) ? -1 : 0);
767             return true;
768           case MCBinaryExpr::NE:
769             Res = MCValue::get((R->isEqualTo(R)) ? 0 : -1);
770             return true;
771           default: break;
772           }
773         }
774       return false;
775     }
776 
777     // We only support a few operations on non-constant expressions, handle
778     // those first.
779     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
780       switch (ABE->getOpcode()) {
781       default:
782         return false;
783       case MCBinaryExpr::Sub:
784         // Negate RHS and add.
785         // The cast avoids undefined behavior if the constant is INT64_MIN.
786         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
787                                    RHSValue.getSymB(), RHSValue.getSymA(),
788                                    -(uint64_t)RHSValue.getConstant(), Res);
789 
790       case MCBinaryExpr::Add:
791         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
792                                    RHSValue.getSymA(), RHSValue.getSymB(),
793                                    RHSValue.getConstant(), Res);
794       }
795     }
796 
797     // FIXME: We need target hooks for the evaluation. It may be limited in
798     // width, and gas defines the result of comparisons differently from
799     // Apple as.
800     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
801     int64_t Result = 0;
802     auto Op = ABE->getOpcode();
803     switch (Op) {
804     case MCBinaryExpr::AShr: Result = LHS >> RHS; break;
805     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
806     case MCBinaryExpr::And:  Result = LHS & RHS; break;
807     case MCBinaryExpr::Div:
808     case MCBinaryExpr::Mod:
809       // Handle division by zero. gas just emits a warning and keeps going,
810       // we try to be stricter.
811       // FIXME: Currently the caller of this function has no way to understand
812       // we're bailing out because of 'division by zero'. Therefore, it will
813       // emit a 'expected relocatable expression' error. It would be nice to
814       // change this code to emit a better diagnostic.
815       if (RHS == 0)
816         return false;
817       if (ABE->getOpcode() == MCBinaryExpr::Div)
818         Result = LHS / RHS;
819       else
820         Result = LHS % RHS;
821       break;
822     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
823     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
824     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
825     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
826     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
827     case MCBinaryExpr::LShr: Result = uint64_t(LHS) >> uint64_t(RHS); break;
828     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
829     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
830     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
831     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
832     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
833     case MCBinaryExpr::Shl:  Result = uint64_t(LHS) << uint64_t(RHS); break;
834     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
835     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
836     }
837 
838     switch (Op) {
839     default:
840       Res = MCValue::get(Result);
841       break;
842     case MCBinaryExpr::EQ:
843     case MCBinaryExpr::GT:
844     case MCBinaryExpr::GTE:
845     case MCBinaryExpr::LT:
846     case MCBinaryExpr::LTE:
847     case MCBinaryExpr::NE:
848       // A comparison operator returns a -1 if true and 0 if false.
849       Res = MCValue::get(Result ? -1 : 0);
850       break;
851     }
852 
853     return true;
854   }
855   }
856 
857   llvm_unreachable("Invalid assembly expression kind!");
858 }
859 
860 MCFragment *MCExpr::findAssociatedFragment() const {
861   switch (getKind()) {
862   case Target:
863     // We never look through target specific expressions.
864     return cast<MCTargetExpr>(this)->findAssociatedFragment();
865 
866   case Constant:
867     return MCSymbol::AbsolutePseudoFragment;
868 
869   case SymbolRef: {
870     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
871     const MCSymbol &Sym = SRE->getSymbol();
872     return Sym.getFragment();
873   }
874 
875   case Unary:
876     return cast<MCUnaryExpr>(this)->getSubExpr()->findAssociatedFragment();
877 
878   case Binary: {
879     const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
880     MCFragment *LHS_F = BE->getLHS()->findAssociatedFragment();
881     MCFragment *RHS_F = BE->getRHS()->findAssociatedFragment();
882 
883     // If either is absolute, return the other.
884     if (LHS_F == MCSymbol::AbsolutePseudoFragment)
885       return RHS_F;
886     if (RHS_F == MCSymbol::AbsolutePseudoFragment)
887       return LHS_F;
888 
889     // Not always correct, but probably the best we can do without more context.
890     if (BE->getOpcode() == MCBinaryExpr::Sub)
891       return MCSymbol::AbsolutePseudoFragment;
892 
893     // Otherwise, return the first non-null fragment.
894     return LHS_F ? LHS_F : RHS_F;
895   }
896   }
897 
898   llvm_unreachable("Invalid assembly expression kind!");
899 }
900