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 OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
63 else if (SRE.getKind() != MCSymbolRefExpr::VK_None &&
64 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_HA16 &&
65 SRE.getKind() != MCSymbolRefExpr::VK_PPC_DARWIN_LO16)
66 OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
72 const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
73 switch (UE.getOpcode()) {
74 case MCUnaryExpr::LNot: OS << '!'; break;
75 case MCUnaryExpr::Minus: OS << '-'; break;
76 case MCUnaryExpr::Not: OS << '~'; break;
77 case MCUnaryExpr::Plus: OS << '+'; break;
79 OS << *UE.getSubExpr();
83 case MCExpr::Binary: {
84 const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
86 // Only print parens around the LHS if it is non-trivial.
87 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
90 OS << '(' << *BE.getLHS() << ')';
93 switch (BE.getOpcode()) {
94 case MCBinaryExpr::Add:
95 // Print "X-42" instead of "X+-42".
96 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
97 if (RHSC->getValue() < 0) {
98 OS << RHSC->getValue();
105 case MCBinaryExpr::And: OS << '&'; break;
106 case MCBinaryExpr::Div: OS << '/'; break;
107 case MCBinaryExpr::EQ: OS << "=="; break;
108 case MCBinaryExpr::GT: OS << '>'; break;
109 case MCBinaryExpr::GTE: OS << ">="; break;
110 case MCBinaryExpr::LAnd: OS << "&&"; break;
111 case MCBinaryExpr::LOr: OS << "||"; break;
112 case MCBinaryExpr::LT: OS << '<'; break;
113 case MCBinaryExpr::LTE: OS << "<="; break;
114 case MCBinaryExpr::Mod: OS << '%'; break;
115 case MCBinaryExpr::Mul: OS << '*'; break;
116 case MCBinaryExpr::NE: OS << "!="; break;
117 case MCBinaryExpr::Or: OS << '|'; break;
118 case MCBinaryExpr::Shl: OS << "<<"; break;
119 case MCBinaryExpr::Shr: OS << ">>"; break;
120 case MCBinaryExpr::Sub: OS << '-'; break;
121 case MCBinaryExpr::Xor: OS << '^'; break;
124 // Only print parens around the LHS if it is non-trivial.
125 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
128 OS << '(' << *BE.getRHS() << ')';
134 assert(0 && "Invalid expression kind!");
137 void MCExpr::dump() const {
144 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
145 const MCExpr *RHS, MCContext &Ctx) {
146 return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
149 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
151 return new (Ctx) MCUnaryExpr(Opc, Expr);
154 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
155 return new (Ctx) MCConstantExpr(Value);
160 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
163 return new (Ctx) MCSymbolRefExpr(Sym, Kind);
166 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
168 return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
171 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
173 case VK_Invalid: return "<<invalid>>";
174 case VK_None: return "<<none>>";
176 case VK_GOT: return "GOT";
177 case VK_GOTOFF: return "GOTOFF";
178 case VK_GOTPCREL: return "GOTPCREL";
179 case VK_GOTTPOFF: return "GOTTPOFF";
180 case VK_INDNTPOFF: return "INDNTPOFF";
181 case VK_NTPOFF: return "NTPOFF";
182 case VK_GOTNTPOFF: return "GOTNTPOFF";
183 case VK_PLT: return "PLT";
184 case VK_TLSGD: return "TLSGD";
185 case VK_TLSLD: return "TLSLD";
186 case VK_TLSLDM: return "TLSLDM";
187 case VK_TPOFF: return "TPOFF";
188 case VK_DTPOFF: return "DTPOFF";
189 case VK_TLVP: return "TLVP";
190 case VK_ARM_PLT: return "(PLT)";
191 case VK_ARM_GOT: return "(GOT)";
192 case VK_ARM_GOTOFF: return "(GOTOFF)";
193 case VK_ARM_TPOFF: return "(tpoff)";
194 case VK_ARM_GOTTPOFF: return "(gottpoff)";
195 case VK_ARM_TLSGD: return "(tlsgd)";
196 case VK_PPC_TOC: return "toc";
197 case VK_PPC_DARWIN_HA16: return "ha16";
198 case VK_PPC_DARWIN_LO16: return "lo16";
199 case VK_PPC_GAS_HA16: return "ha";
200 case VK_PPC_GAS_LO16: return "l";
201 case VK_Mips_GPREL: return "GPREL";
202 case VK_Mips_GOT_CALL: return "GOT_CALL";
203 case VK_Mips_GOT16: return "GOT16";
204 case VK_Mips_GOT: return "GOT";
205 case VK_Mips_ABS_HI: return "ABS_HI";
206 case VK_Mips_ABS_LO: return "ABS_LO";
207 case VK_Mips_TLSGD: return "TLSGD";
208 case VK_Mips_TLSLDM: return "TLSLDM";
209 case VK_Mips_DTPREL_HI: return "DTPREL_HI";
210 case VK_Mips_DTPREL_LO: return "DTPREL_LO";
211 case VK_Mips_GOTTPREL: return "GOTTPREL";
212 case VK_Mips_TPREL_HI: return "TPREL_HI";
213 case VK_Mips_TPREL_LO: return "TPREL_LO";
214 case VK_Mips_GPOFF_HI: return "GPOFF_HI";
215 case VK_Mips_GPOFF_LO: return "GPOFF_LO";
216 case VK_Mips_GOT_DISP: return "GOT_DISP";
217 case VK_Mips_GOT_PAGE: return "GOT_PAGE";
218 case VK_Mips_GOT_OFST: return "GOT_OFST";
220 llvm_unreachable("Invalid variant kind");
223 MCSymbolRefExpr::VariantKind
224 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
225 return StringSwitch<VariantKind>(Name)
228 .Case("GOTOFF", VK_GOTOFF)
229 .Case("gotoff", VK_GOTOFF)
230 .Case("GOTPCREL", VK_GOTPCREL)
231 .Case("gotpcrel", VK_GOTPCREL)
232 .Case("GOTTPOFF", VK_GOTTPOFF)
233 .Case("gottpoff", VK_GOTTPOFF)
234 .Case("INDNTPOFF", VK_INDNTPOFF)
235 .Case("indntpoff", VK_INDNTPOFF)
236 .Case("NTPOFF", VK_NTPOFF)
237 .Case("ntpoff", VK_NTPOFF)
238 .Case("GOTNTPOFF", VK_GOTNTPOFF)
239 .Case("gotntpoff", VK_GOTNTPOFF)
242 .Case("TLSGD", VK_TLSGD)
243 .Case("tlsgd", VK_TLSGD)
244 .Case("TLSLD", VK_TLSLD)
245 .Case("tlsld", VK_TLSLD)
246 .Case("TLSLDM", VK_TLSLDM)
247 .Case("tlsldm", VK_TLSLDM)
248 .Case("TPOFF", VK_TPOFF)
249 .Case("tpoff", VK_TPOFF)
250 .Case("DTPOFF", VK_DTPOFF)
251 .Case("dtpoff", VK_DTPOFF)
252 .Case("TLVP", VK_TLVP)
253 .Case("tlvp", VK_TLVP)
254 .Default(VK_Invalid);
259 void MCTargetExpr::Anchor() {}
263 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
264 return EvaluateAsAbsolute(Res, 0, 0, 0);
267 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
268 const MCAsmLayout &Layout) const {
269 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
272 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
273 const MCAsmLayout &Layout,
274 const SectionAddrMap &Addrs) const {
275 return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
278 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
279 return EvaluateAsAbsolute(Res, &Asm, 0, 0);
282 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
283 const MCAsmLayout *Layout,
284 const SectionAddrMap *Addrs) const {
287 // Fast path constants.
288 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
289 Res = CE->getValue();
293 // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
294 // absolutize differences across sections and that is what the MachO writer
297 EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
299 // Record the current value.
300 Res = Value.getConstant();
302 return IsRelocatable && Value.isAbsolute();
305 /// \brief Helper method for \see EvaluateSymbolAdd().
306 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
307 const MCAsmLayout *Layout,
308 const SectionAddrMap *Addrs,
310 const MCSymbolRefExpr *&A,
311 const MCSymbolRefExpr *&B,
316 const MCSymbol &SA = A->getSymbol();
317 const MCSymbol &SB = B->getSymbol();
319 if (SA.isUndefined() || SB.isUndefined())
322 if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
325 MCSymbolData &AD = Asm->getSymbolData(SA);
326 MCSymbolData &BD = Asm->getSymbolData(SB);
328 if (AD.getFragment() == BD.getFragment()) {
329 Addend += (AD.getOffset() - BD.getOffset());
331 // Pointers to Thumb symbols need to have their low-bit set to allow
333 if (Asm->isThumbFunc(&SA))
336 // Clear the symbol expr pointers to indicate we have folded these
345 const MCSectionData &SecA = *AD.getFragment()->getParent();
346 const MCSectionData &SecB = *BD.getFragment()->getParent();
348 if ((&SecA != &SecB) && !Addrs)
352 Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
353 Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
354 if (Addrs && (&SecA != &SecB))
355 Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
357 // Clear the symbol expr pointers to indicate we have folded these
362 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
364 /// This routine conceptually attempts to construct an MCValue:
365 /// Result = (Result_A - Result_B + Result_Cst)
366 /// from two MCValue's LHS and RHS where
367 /// Result = LHS + RHS
369 /// Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
371 /// This routine attempts to aggresively fold the operands such that the result
372 /// is representable in an MCValue, but may not always succeed.
374 /// \returns True on success, false if the result is not representable in an
377 /// NOTE: It is really important to have both the Asm and Layout arguments.
378 /// They might look redundant, but this function can be used before layout
379 /// is done (see the object streamer for example) and having the Asm argument
380 /// lets us avoid relaxations early.
381 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
382 const MCAsmLayout *Layout,
383 const SectionAddrMap *Addrs,
385 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
386 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
388 // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
389 // about dealing with modifiers. This will ultimately bite us, one day.
390 const MCSymbolRefExpr *LHS_A = LHS.getSymA();
391 const MCSymbolRefExpr *LHS_B = LHS.getSymB();
392 int64_t LHS_Cst = LHS.getConstant();
394 // Fold the result constant immediately.
395 int64_t Result_Cst = LHS_Cst + RHS_Cst;
397 assert((!Layout || Asm) &&
398 "Must have an assembler object if layout is given!");
400 // If we have a layout, we can fold resolved differences.
402 // First, fold out any differences which are fully resolved. By
403 // reassociating terms in
404 // Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
405 // we have the four possible differences:
410 // Since we are attempting to be as aggressive as possible about folding, we
411 // attempt to evaluate each possible alternative.
412 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
414 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
416 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
418 AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
422 // We can't represent the addition or subtraction of two symbols.
423 if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
426 // At this point, we have at most one additive symbol and one subtractive
427 // symbol -- find them.
428 const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
429 const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
431 // If we have a negated symbol, then we must have also have a non-negated
432 // symbol in order to encode the expression.
436 Res = MCValue::get(A, B, Result_Cst);
440 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
441 const MCAsmLayout &Layout) const {
442 return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
446 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
447 const MCAssembler *Asm,
448 const MCAsmLayout *Layout,
449 const SectionAddrMap *Addrs,
451 ++stats::MCExprEvaluate;
455 return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
458 Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
462 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
463 const MCSymbol &Sym = SRE->getSymbol();
465 // Evaluate recursively if this is a variable.
466 if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
467 bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
471 // If we failed to simplify this to a constant, let the target
473 if (Ret && !Res.getSymA() && !Res.getSymB())
477 Res = MCValue::get(SRE, 0, 0);
482 const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
485 if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
489 switch (AUE->getOpcode()) {
490 case MCUnaryExpr::LNot:
491 if (!Value.isAbsolute())
493 Res = MCValue::get(!Value.getConstant());
495 case MCUnaryExpr::Minus:
496 /// -(a - b + const) ==> (b - a - const)
497 if (Value.getSymA() && !Value.getSymB())
499 Res = MCValue::get(Value.getSymB(), Value.getSymA(),
500 -Value.getConstant());
502 case MCUnaryExpr::Not:
503 if (!Value.isAbsolute())
505 Res = MCValue::get(~Value.getConstant());
507 case MCUnaryExpr::Plus:
516 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
517 MCValue LHSValue, RHSValue;
519 if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
521 !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
525 // We only support a few operations on non-constant expressions, handle
527 if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
528 switch (ABE->getOpcode()) {
531 case MCBinaryExpr::Sub:
532 // Negate RHS and add.
533 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
534 RHSValue.getSymB(), RHSValue.getSymA(),
535 -RHSValue.getConstant(),
538 case MCBinaryExpr::Add:
539 return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
540 RHSValue.getSymA(), RHSValue.getSymB(),
541 RHSValue.getConstant(),
546 // FIXME: We need target hooks for the evaluation. It may be limited in
547 // width, and gas defines the result of comparisons and right shifts
548 // differently from Apple as.
549 int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
551 switch (ABE->getOpcode()) {
552 case MCBinaryExpr::Add: Result = LHS + RHS; break;
553 case MCBinaryExpr::And: Result = LHS & RHS; break;
554 case MCBinaryExpr::Div: Result = LHS / RHS; break;
555 case MCBinaryExpr::EQ: Result = LHS == RHS; break;
556 case MCBinaryExpr::GT: Result = LHS > RHS; break;
557 case MCBinaryExpr::GTE: Result = LHS >= RHS; break;
558 case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
559 case MCBinaryExpr::LOr: Result = LHS || RHS; break;
560 case MCBinaryExpr::LT: Result = LHS < RHS; break;
561 case MCBinaryExpr::LTE: Result = LHS <= RHS; break;
562 case MCBinaryExpr::Mod: Result = LHS % RHS; break;
563 case MCBinaryExpr::Mul: Result = LHS * RHS; break;
564 case MCBinaryExpr::NE: Result = LHS != RHS; break;
565 case MCBinaryExpr::Or: Result = LHS | RHS; break;
566 case MCBinaryExpr::Shl: Result = LHS << RHS; break;
567 case MCBinaryExpr::Shr: Result = LHS >> RHS; break;
568 case MCBinaryExpr::Sub: Result = LHS - RHS; break;
569 case MCBinaryExpr::Xor: Result = LHS ^ RHS; break;
572 Res = MCValue::get(Result);
577 assert(0 && "Invalid assembly expression kind!");
581 const MCSection *MCExpr::FindAssociatedSection() const {
584 // We never look through target specific expressions.
585 return cast<MCTargetExpr>(this)->FindAssociatedSection();
588 return MCSymbol::AbsolutePseudoSection;
591 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
592 const MCSymbol &Sym = SRE->getSymbol();
595 return &Sym.getSection();
601 return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
604 const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
605 const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
606 const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
608 // If either section is absolute, return the other.
609 if (LHS_S == MCSymbol::AbsolutePseudoSection)
611 if (RHS_S == MCSymbol::AbsolutePseudoSection)
614 // Otherwise, return the first non-null section.
615 return LHS_S ? LHS_S : RHS_S;
619 assert(0 && "Invalid assembly expression kind!");