1 //===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "mcexpr"
11 #include "llvm/MC/MCExpr.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
26 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
30 void MCExpr::print(raw_ostream &OS) const {
33 return cast<MCTargetExpr>(this)->PrintImpl(OS);
34 case MCExpr::Constant:
35 OS << cast<MCConstantExpr>(*this).getValue();
38 case MCExpr::SymbolRef: {
39 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
40 const MCSymbol &Sym = SRE.getSymbol();
41 // Parenthesize names that start with $ so that they don't look like
43 bool UseParens = Sym.getName()[0] == '$';
45 if (SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_HA16 ||
46 SRE.getKind() == MCSymbolRefExpr::VK_PPC_DARWIN_LO16) {
47 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
52 OS << '(' << Sym << ')';
56 if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_PLT ||
57 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TLSGD ||
58 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOT ||
59 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTOFF ||
60 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TPOFF ||
61 SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTTPOFF ||
62 SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET1)
63 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
64 else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
65 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_HA16 &&
66 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_LO16)
67 OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
73 const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
74 switch (UE.getOpcode()) {
75 case MCUnaryExpr::LNot: OS << '!'; break;
76 case MCUnaryExpr::Minus: OS << '-'; break;
77 case MCUnaryExpr::Not: OS << '~'; break;
78 case MCUnaryExpr::Plus: OS << '+'; break;
80 OS << *UE.getSubExpr();
84 case MCExpr::Binary: {
85 const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
87 // Only print parens around the LHS if it is non-trivial.
88 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
91 OS << '(' << *BE.getLHS() << ')';
94 switch (BE.getOpcode()) {
95 case MCBinaryExpr::Add:
96 // Print "X-42" instead of "X+-42".
97 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
98 if (RHSC->getValue() < 0) {
99 OS << RHSC->getValue();
106 case MCBinaryExpr::And: OS << '&'; break;
107 case MCBinaryExpr::Div: OS << '/'; break;
108 case MCBinaryExpr::EQ: OS << "=="; break;
109 case MCBinaryExpr::GT: OS << '>'; break;
110 case MCBinaryExpr::GTE: OS << ">="; break;
111 case MCBinaryExpr::LAnd: OS << "&&"; break;
112 case MCBinaryExpr::LOr: OS << "||"; break;
113 case MCBinaryExpr::LT: OS << '<'; break;
114 case MCBinaryExpr::LTE: OS << "<="; break;
115 case MCBinaryExpr::Mod: OS << '%'; break;
116 case MCBinaryExpr::Mul: OS << '*'; break;
117 case MCBinaryExpr::NE: OS << "!="; break;
118 case MCBinaryExpr::Or: OS << '|'; break;
119 case MCBinaryExpr::Shl: OS << "<<"; break;
120 case MCBinaryExpr::Shr: OS << ">>"; break;
121 case MCBinaryExpr::Sub: OS << '-'; break;
122 case MCBinaryExpr::Xor: OS << '^'; break;
125 // Only print parens around the LHS if it is non-trivial.
126 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
129 OS << '(' << *BE.getRHS() << ')';
135 llvm_unreachable("Invalid expression kind!");
138 void MCExpr::dump() const {
145 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
146 const MCExpr *RHS, MCContext &Ctx) {
147 return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
150 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
152 return new (Ctx) MCUnaryExpr(Opc, Expr);
155 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
156 return new (Ctx) MCConstantExpr(Value);
161 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
164 return new (Ctx) MCSymbolRefExpr(Sym, Kind);
167 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
169 return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
172 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
174 case VK_Invalid: return "<<invalid>>";
175 case VK_None: return "<<none>>";
177 case VK_GOT: return "GOT";
178 case VK_GOTOFF: return "GOTOFF";
179 case VK_GOTPCREL: return "GOTPCREL";
180 case VK_GOTTPOFF: return "GOTTPOFF";
181 case VK_INDNTPOFF: return "INDNTPOFF";
182 case VK_NTPOFF: return "NTPOFF";
183 case VK_GOTNTPOFF: return "GOTNTPOFF";
184 case VK_PLT: return "PLT";
185 case VK_TLSGD: return "TLSGD";
186 case VK_TLSLD: return "TLSLD";
187 case VK_TLSLDM: return "TLSLDM";
188 case VK_TPOFF: return "TPOFF";
189 case VK_DTPOFF: return "DTPOFF";
190 case VK_TLVP: return "TLVP";
191 case VK_SECREL: return "SECREL";
192 case VK_ARM_PLT: return "(PLT)";
193 case VK_ARM_GOT: return "(GOT)";
194 case VK_ARM_GOTOFF: return "(GOTOFF)";
195 case VK_ARM_TPOFF: return "(tpoff)";
196 case VK_ARM_GOTTPOFF: return "(gottpoff)";
197 case VK_ARM_TLSGD: return "(tlsgd)";
198 case VK_ARM_TARGET1: return "(target1)";
199 case VK_PPC_TOC: return "toc";
200 case VK_PPC_DARWIN_HA16: return "ha16";
201 case VK_PPC_DARWIN_LO16: return "lo16";
202 case VK_PPC_GAS_HA16: return "ha";
203 case VK_PPC_GAS_LO16: return "l";
204 case VK_Mips_GPREL: return "GPREL";
205 case VK_Mips_GOT_CALL: return "GOT_CALL";
206 case VK_Mips_GOT16: return "GOT16";
207 case VK_Mips_GOT: return "GOT";
208 case VK_Mips_ABS_HI: return "ABS_HI";
209 case VK_Mips_ABS_LO: return "ABS_LO";
210 case VK_Mips_TLSGD: return "TLSGD";
211 case VK_Mips_TLSLDM: return "TLSLDM";
212 case VK_Mips_DTPREL_HI: return "DTPREL_HI";
213 case VK_Mips_DTPREL_LO: return "DTPREL_LO";
214 case VK_Mips_GOTTPREL: return "GOTTPREL";
215 case VK_Mips_TPREL_HI: return "TPREL_HI";
216 case VK_Mips_TPREL_LO: return "TPREL_LO";
217 case VK_Mips_GPOFF_HI: return "GPOFF_HI";
218 case VK_Mips_GPOFF_LO: return "GPOFF_LO";
219 case VK_Mips_GOT_DISP: return "GOT_DISP";
220 case VK_Mips_GOT_PAGE: return "GOT_PAGE";
221 case VK_Mips_GOT_OFST: return "GOT_OFST";
223 llvm_unreachable("Invalid variant kind");
226 MCSymbolRefExpr::VariantKind
227 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
228 return StringSwitch<VariantKind>(Name)
231 .Case("GOTOFF", VK_GOTOFF)
232 .Case("gotoff", VK_GOTOFF)
233 .Case("GOTPCREL", VK_GOTPCREL)
234 .Case("gotpcrel", VK_GOTPCREL)
235 .Case("GOTTPOFF", VK_GOTTPOFF)
236 .Case("gottpoff", VK_GOTTPOFF)
237 .Case("INDNTPOFF", VK_INDNTPOFF)
238 .Case("indntpoff", VK_INDNTPOFF)
239 .Case("NTPOFF", VK_NTPOFF)
240 .Case("ntpoff", VK_NTPOFF)
241 .Case("GOTNTPOFF", VK_GOTNTPOFF)
242 .Case("gotntpoff", VK_GOTNTPOFF)
245 .Case("TLSGD", VK_TLSGD)
246 .Case("tlsgd", VK_TLSGD)
247 .Case("TLSLD", VK_TLSLD)
248 .Case("tlsld", VK_TLSLD)
249 .Case("TLSLDM", VK_TLSLDM)
250 .Case("tlsldm", VK_TLSLDM)
251 .Case("TPOFF", VK_TPOFF)
252 .Case("tpoff", VK_TPOFF)
253 .Case("DTPOFF", VK_DTPOFF)
254 .Case("dtpoff", VK_DTPOFF)
255 .Case("TLVP", VK_TLVP)
256 .Case("tlvp", VK_TLVP)
257 .Default(VK_Invalid);
262 void MCTargetExpr::Anchor() {}
266 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
267 return EvaluateAsAbsolute(Res, 0, 0, 0);
270 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
271 const MCAsmLayout &Layout) const {
272 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
275 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
276 const MCAsmLayout &Layout,
277 const SectionAddrMap &Addrs) const {
278 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
281 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
282 return EvaluateAsAbsolute(Res, &Asm, 0, 0);
285 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
286 const MCAsmLayout *Layout,
287 const SectionAddrMap *Addrs) const {
290 // Fast path constants.
291 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
292 Res = CE->getValue();
296 // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
297 // absolutize differences across sections and that is what the MachO writer
300 EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
302 // Record the current value.
303 Res = Value.getConstant();
305 return IsRelocatable && Value.isAbsolute();
308 /// \brief Helper method for \see EvaluateSymbolAdd().
309 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
310 const MCAsmLayout *Layout,
311 const SectionAddrMap *Addrs,
313 const MCSymbolRefExpr *&A,
314 const MCSymbolRefExpr *&B,
319 const MCSymbol &SA = A->getSymbol();
320 const MCSymbol &SB = B->getSymbol();
322 if (SA.isUndefined() || SB.isUndefined())
325 if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
328 MCSymbolData &AD = Asm->getSymbolData(SA);
329 MCSymbolData &BD = Asm->getSymbolData(SB);
331 if (AD.getFragment() == BD.getFragment()) {
332 Addend += (AD.getOffset() - BD.getOffset());
334 // Pointers to Thumb symbols need to have their low-bit set to allow
336 if (Asm->isThumbFunc(&SA))
339 // Clear the symbol expr pointers to indicate we have folded these
348 const MCSectionData &SecA = *AD.getFragment()->getParent();
349 const MCSectionData &SecB = *BD.getFragment()->getParent();
351 if ((&SecA != &SecB) && !Addrs)
355 Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
356 Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
357 if (Addrs && (&SecA != &SecB))
358 Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
360 // Pointers to Thumb symbols need to have their low-bit set to allow
362 if (Asm->isThumbFunc(&SA))
365 // Clear the symbol expr pointers to indicate we have folded these
370 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
372 /// This routine conceptually attempts to construct an MCValue:
373 /// Result = (Result_A - Result_B + Result_Cst)
374 /// from two MCValue's LHS and RHS where
375 /// Result = LHS + RHS
377 /// Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
379 /// This routine attempts to aggresively fold the operands such that the result
380 /// is representable in an MCValue, but may not always succeed.
382 /// \returns True on success, false if the result is not representable in an
385 /// NOTE: It is really important to have both the Asm and Layout arguments.
386 /// They might look redundant, but this function can be used before layout
387 /// is done (see the object streamer for example) and having the Asm argument
388 /// lets us avoid relaxations early.
389 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
390 const MCAsmLayout *Layout,
391 const SectionAddrMap *Addrs,
393 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
394 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
396 // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
397 // about dealing with modifiers. This will ultimately bite us, one day.
398 const MCSymbolRefExpr *LHS_A = LHS.getSymA();
399 const MCSymbolRefExpr *LHS_B = LHS.getSymB();
400 int64_t LHS_Cst = LHS.getConstant();
402 // Fold the result constant immediately.
403 int64_t Result_Cst = LHS_Cst + RHS_Cst;
405 assert((!Layout || Asm) &&
406 "Must have an assembler object if layout is given!");
408 // If we have a layout, we can fold resolved differences.
410 // First, fold out any differences which are fully resolved. By
411 // reassociating terms in
412 // Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
413 // we have the four possible differences:
418 // Since we are attempting to be as aggressive as possible about folding, we
419 // attempt to evaluate each possible alternative.
420 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
422 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
424 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
426 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
430 // We can't represent the addition or subtraction of two symbols.
431 if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
434 // At this point, we have at most one additive symbol and one subtractive
435 // symbol -- find them.
436 const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
437 const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
439 // If we have a negated symbol, then we must have also have a non-negated
440 // symbol in order to encode the expression.
444 Res = MCValue::get(A, B, Result_Cst);
448 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
449 const MCAsmLayout &Layout) const {
450 return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
454 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
455 const MCAssembler *Asm,
456 const MCAsmLayout *Layout,
457 const SectionAddrMap *Addrs,
459 ++stats::MCExprEvaluate;
463 return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
466 Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
470 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
471 const MCSymbol &Sym = SRE->getSymbol();
473 // Evaluate recursively if this is a variable.
474 if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
475 bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
479 // If we failed to simplify this to a constant, let the target
481 if (Ret && !Res.getSymA() && !Res.getSymB())
485 Res = MCValue::get(SRE, 0, 0);
490 const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
493 if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
497 switch (AUE->getOpcode()) {
498 case MCUnaryExpr::LNot:
499 if (!Value.isAbsolute())
501 Res = MCValue::get(!Value.getConstant());
503 case MCUnaryExpr::Minus:
504 /// -(a - b + const) ==> (b - a - const)
505 if (Value.getSymA() && !Value.getSymB())
507 Res = MCValue::get(Value.getSymB(), Value.getSymA(),
508 -Value.getConstant());
510 case MCUnaryExpr::Not:
511 if (!Value.isAbsolute())
513 Res = MCValue::get(~Value.getConstant());
515 case MCUnaryExpr::Plus:
524 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
525 MCValue LHSValue, RHSValue;
527 if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
529 !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
533 // We only support a few operations on non-constant expressions, handle
535 if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
536 switch (ABE->getOpcode()) {
539 case MCBinaryExpr::Sub:
540 // Negate RHS and add.
541 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
542 RHSValue.getSymB(), RHSValue.getSymA(),
543 -RHSValue.getConstant(),
546 case MCBinaryExpr::Add:
547 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
548 RHSValue.getSymA(), RHSValue.getSymB(),
549 RHSValue.getConstant(),
554 // FIXME: We need target hooks for the evaluation. It may be limited in
555 // width, and gas defines the result of comparisons and right shifts
556 // differently from Apple as.
557 int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
559 switch (ABE->getOpcode()) {
560 case MCBinaryExpr::Add: Result = LHS + RHS; break;
561 case MCBinaryExpr::And: Result = LHS & RHS; break;
562 case MCBinaryExpr::Div: Result = LHS / RHS; break;
563 case MCBinaryExpr::EQ: Result = LHS == RHS; break;
564 case MCBinaryExpr::GT: Result = LHS > RHS; break;
565 case MCBinaryExpr::GTE: Result = LHS >= RHS; break;
566 case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
567 case MCBinaryExpr::LOr: Result = LHS || RHS; break;
568 case MCBinaryExpr::LT: Result = LHS < RHS; break;
569 case MCBinaryExpr::LTE: Result = LHS <= RHS; break;
570 case MCBinaryExpr::Mod: Result = LHS % RHS; break;
571 case MCBinaryExpr::Mul: Result = LHS * RHS; break;
572 case MCBinaryExpr::NE: Result = LHS != RHS; break;
573 case MCBinaryExpr::Or: Result = LHS | RHS; break;
574 case MCBinaryExpr::Shl: Result = LHS << RHS; break;
575 case MCBinaryExpr::Shr: Result = LHS >> RHS; break;
576 case MCBinaryExpr::Sub: Result = LHS - RHS; break;
577 case MCBinaryExpr::Xor: Result = LHS ^ RHS; break;
580 Res = MCValue::get(Result);
585 llvm_unreachable("Invalid assembly expression kind!");
588 const MCSection *MCExpr::FindAssociatedSection() const {
591 // We never look through target specific expressions.
592 return cast<MCTargetExpr>(this)->FindAssociatedSection();
595 return MCSymbol::AbsolutePseudoSection;
598 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
599 const MCSymbol &Sym = SRE->getSymbol();
602 return &Sym.getSection();
608 return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
611 const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
612 const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
613 const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
615 // If either section is absolute, return the other.
616 if (LHS_S == MCSymbol::AbsolutePseudoSection)
618 if (RHS_S == MCSymbol::AbsolutePseudoSection)
621 // Otherwise, return the first non-null section.
622 return LHS_S ? LHS_S : RHS_S;
626 llvm_unreachable("Invalid assembly expression kind!");