<commit_before>//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Expr constant evaluator.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using llvm::APSInt;

#define USE_NEW_EVALUATOR 0

static bool CalcFakeICEVal(const Expr *Expr,
                           llvm::APSInt &Result,
                           ASTContext &Context) {
  // Calculate the value of an expression that has a calculatable
  // value, but isn't an ICE. Currently, this only supports
  // a very narrow set of extensions, but it can be expanded if needed.
  if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
    return CalcFakeICEVal(PE->getSubExpr(), Result, Context);

  if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
    QualType CETy = CE->getType();
    if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
        CETy->isPointerType()) {
      if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
        Result.extOrTrunc(Context.getTypeSize(CETy));
        // FIXME: This assumes pointers are signed.
        Result.setIsSigned(CETy->isSignedIntegerType() ||
                           CETy->isPointerType());
        return true;
      }
    }
  }

  if (Expr->getType()->isIntegralType())
    return Expr->isIntegerConstantExpr(Result, Context);

  return false;
}

static bool EvaluatePointer(const Expr *E, APValue &Result, ASTContext &Ctx);
static bool EvaluateInteger(const Expr *E, APSInt  &Result, ASTContext &Ctx);

//===----------------------------------------------------------------------===//
// Pointer Evaluation
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN PointerExprEvaluator
  : public StmtVisitor<PointerExprEvaluator, APValue> {
  ASTContext &Ctx;
public:

  PointerExprEvaluator(ASTContext &ctx) : Ctx(ctx) {}

  APValue VisitStmt(Stmt *S) {
    // FIXME: Remove this when we support more expressions.
    printf("Unhandled pointer statement\n");
    S->dump();
    return APValue();
  }

  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }

  APValue VisitBinaryOperator(const BinaryOperator *E);
  APValue VisitCastExpr(const CastExpr* E);
};
} // end anonymous namespace

static bool EvaluatePointer(const Expr* E, APValue& Result, ASTContext &Ctx) {
  if (!E->getType()->isPointerType())
    return false;
  Result = PointerExprEvaluator(Ctx).Visit(const_cast<Expr*>(E));
  return Result.isLValue();
}

APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  if (E->getOpcode() != BinaryOperator::Add &&
      E->getOpcode() != BinaryOperator::Sub)
    return APValue();

  const Expr *PExp = E->getLHS();
  const Expr *IExp = E->getRHS();
  if (IExp->getType()->isPointerType())
    std::swap(PExp, IExp);

  APValue ResultLValue;
  if (!EvaluatePointer(PExp, ResultLValue, Ctx))
    return APValue();

  llvm::APSInt AdditionalOffset(32);
  if (!EvaluateInteger(IExp, AdditionalOffset, Ctx))
    return APValue();

  uint64_t Offset = ResultLValue.getLValueOffset();
  if (E->getOpcode() == BinaryOperator::Add)
    Offset += AdditionalOffset.getZExtValue();
  else
    Offset -= AdditionalOffset.getZExtValue();

  return APValue(ResultLValue.getLValueBase(), Offset);
}

APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  const Expr* SubExpr = E->getSubExpr();

   // Check for pointer->pointer cast
  if (SubExpr->getType()->isPointerType()) {
    APValue Result;
    if (EvaluatePointer(SubExpr, Result, Ctx))
      return Result;
    return APValue();
  }

  if (SubExpr->getType()->isArithmeticType()) {
    llvm::APSInt Result(32);
    if (EvaluateInteger(SubExpr, Result, Ctx)) {
      Result.extOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType())));
      return APValue(0, Result.getZExtValue());
    }
  }

  assert(0 && "Unhandled cast");
  return APValue();
}

//===----------------------------------------------------------------------===//
// Integer Evaluation
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN IntExprEvaluator
  : public StmtVisitor<IntExprEvaluator, bool> {
  ASTContext &Ctx;
  APSInt &Result;
public:
  IntExprEvaluator(ASTContext &ctx, APSInt &result) : Ctx(ctx), Result(result){}

  //===--------------------------------------------------------------------===//
  //                            Visitor Methods
  //===--------------------------------------------------------------------===//
  bool VisitStmt(Stmt *S) {
    // FIXME: Remove this when we support more expressions.
    printf("unhandled int expression");
    S->dump();
    return false;
  }

  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }

  bool VisitBinaryOperator(const BinaryOperator *E);
  bool VisitUnaryOperator(const UnaryOperator *E);

  bool HandleCast(const Expr* SubExpr, QualType DestType);
  bool VisitCastExpr(const CastExpr* E) {
    return HandleCast(E->getSubExpr(), E->getType());
  }
  bool VisitImplicitCastExpr(const ImplicitCastExpr* E) {
    return HandleCast(E->getSubExpr(), E->getType());
  }
  bool VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E);

  bool VisitIntegerLiteral(const IntegerLiteral *E) {
    Result = E->getValue();
    return true;
  }
};
} // end anonymous namespace

static bool EvaluateInteger(const Expr* E, APSInt &Result, ASTContext &Ctx) {
  return IntExprEvaluator(Ctx, Result).Visit(const_cast<Expr*>(E));
}

bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  // The LHS of a constant expr is always evaluated and needed.
  if (!Visit(E->getLHS()))
    return false;

  llvm::APSInt RHS(32);
  if (!EvaluateInteger(E->getRHS(), RHS, Ctx))
    return false;

  switch (E->getOpcode()) {
  default:
    return false;
  case BinaryOperator::Mul:
    Result *= RHS;
    break;
  case BinaryOperator::Div:
    if (RHS == 0)
      return false;
    Result /= RHS;
    break;
  case BinaryOperator::Rem:
    if (RHS == 0)
      return false;
    Result %= RHS;
    break;
  case BinaryOperator::Add: Result += RHS; break;
  case BinaryOperator::Sub: Result -= RHS; break;
  case BinaryOperator::Shl:
    Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
    break;
  case BinaryOperator::Shr:
    Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
    break;

  // FIXME: Need to set the result width?
  case BinaryOperator::LT:  Result = Result < RHS; break;
  case BinaryOperator::GT:  Result = Result > RHS; break;
  case BinaryOperator::LE:  Result = Result <= RHS; break;
  case BinaryOperator::GE:  Result = Result >= RHS; break;
  case BinaryOperator::EQ:  Result = Result == RHS; break;
  case BinaryOperator::NE:  Result = Result != RHS; break;
  case BinaryOperator::And: Result &= RHS; break;
  case BinaryOperator::Xor: Result ^= RHS; break;
  case BinaryOperator::Or:  Result |= RHS; break;

  case BinaryOperator::Comma:
    // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
    // *except* when they are contained within a subexpression that is not
    // evaluated".  Note that Assignment can never happen due to constraints
    // on the LHS subexpr, so we don't need to check it here.
    // FIXME: Need to come up with an efficient way to deal with the C99
    // rules on evaluation while still evaluating this.  Maybe a
    // "evaluated comma" out parameter?
    return false;
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  if (E->isOffsetOfOp())
    Result = E->evaluateOffsetOf(Ctx);
  else if (E->isSizeOfAlignOfOp()) {
    // Return the result in the right width.
    Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType())));

    // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
    if (E->getSubExpr()->getType()->isVoidType())
      Result = 1;

    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
    if (!E->getSubExpr()->getType()->isConstantSizeType()) {
      // FIXME: Should we attempt to evaluate this?
      return false;
    }

    // Get information about the size or align.
    if (E->getSubExpr()->getType()->isFunctionType()) {
      // GCC extension: sizeof(function) = 1.
      // FIXME: AlignOf shouldn't be unconditionally 4!
      Result = E->getOpcode() == UnaryOperator::AlignOf ? 4 : 1;
    } else {
      unsigned CharSize = Ctx.Target.getCharWidth();
      if (E->getOpcode() == UnaryOperator::AlignOf)
        Result = Ctx.getTypeAlign(E->getSubExpr()->getType()) / CharSize;
      else
        Result = Ctx.getTypeSize(E->getSubExpr()->getType()) / CharSize;
    }
  } else {
    // Get the operand value.  If this is sizeof/alignof, do not evalute the
    // operand.  This affects C99 6.6p3.
    if (!EvaluateInteger(E->getSubExpr(), Result, Ctx))
      return false;

    switch (E->getOpcode()) {
      // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
      // See C99 6.6p3.
    default:
      return false;
    case UnaryOperator::Extension:
      assert(0 && "Handle UnaryOperator::Extension");
        return false;
    case UnaryOperator::LNot: {
      bool Val = Result == 0;
      uint32_t typeSize = Ctx.getTypeSize(E->getType());
      Result.zextOrTrunc(typeSize);
      Result = Val;
      break;
    }
    case UnaryOperator::Plus:
      break;
    case UnaryOperator::Minus:
      Result = -Result;
      break;
    case UnaryOperator::Not:
      Result = ~Result;
      break;
    }
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::HandleCast(const Expr* SubExpr, QualType DestType) {
  llvm::APSInt Result(32);

  uint32_t DestWidth = static_cast<uint32_t>(Ctx.getTypeSize(DestType));

  // Handle simple integer->integer casts.
  if (SubExpr->getType()->isIntegerType()) {
    if (!EvaluateInteger(SubExpr, Result, Ctx))
      return false;

    // Figure out if this is a truncate, extend or noop cast.
    // If the input is signed, do a sign extend, noop, or truncate.
    if (DestType->isBooleanType()) {
      // Conversion to bool compares against zero.
      Result = Result != 0;
      Result.zextOrTrunc(DestWidth);
    }
    else
      Result.extOrTrunc(DestWidth);
  } else if (SubExpr->getType()->isPointerType()) {
    APValue LV;
    if (!EvaluatePointer(SubExpr, LV, Ctx))
      return false;
    if (LV.getLValueBase())
      return false;

    Result.extOrTrunc(DestWidth);
    Result = LV.getLValueOffset();
  } else {
    assert(0 && "Unhandled cast!");
  }

  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::
VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
  // Return the result in the right width.
  Result.zextOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType())));

  // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
  if (E->getArgumentType()->isVoidType()) {
    Result = 1;
    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
    return true;
  }

  // alignof always evaluates to a constant, sizeof does if arg is not VLA.
  if (E->isSizeOf() && !E->getArgumentType()->isConstantSizeType())
    return false;

  // Get information about the size or align.
  if (E->getArgumentType()->isFunctionType()) {
    // GCC extension: sizeof(function) = 1.
    Result = E->isSizeOf() ? 1 : 4;
  } else {
    unsigned CharSize = Ctx.Target.getCharWidth();
    if (E->isSizeOf())
      Result = Ctx.getTypeSize(E->getArgumentType()) / CharSize;
    else
      Result = Ctx.getTypeAlign(E->getArgumentType()) / CharSize;
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

//===----------------------------------------------------------------------===//
// Top level TryEvaluate.
//===----------------------------------------------------------------------===//

bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
  llvm::APSInt sInt(32);
#if USE_NEW_EVALUATOR
  if (getType()->isIntegerType()) {
    if (EvaluateInteger(this, sInt, Ctx)) {
      Result = APValue(sInt);
      return true;
    }
  } else
    return false;

#else
  if (CalcFakeICEVal(this, sInt, Ctx)) {
    Result = APValue(sInt);
    return true;
  }
#endif

  return false;
}
<commit_msg>add a new getIntTypeSizeInBits method.<commit_after>//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Expr constant evaluator.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using llvm::APSInt;

#define USE_NEW_EVALUATOR 0

static bool CalcFakeICEVal(const Expr *Expr,
                           llvm::APSInt &Result,
                           ASTContext &Context) {
  // Calculate the value of an expression that has a calculatable
  // value, but isn't an ICE. Currently, this only supports
  // a very narrow set of extensions, but it can be expanded if needed.
  if (const ParenExpr *PE = dyn_cast<ParenExpr>(Expr))
    return CalcFakeICEVal(PE->getSubExpr(), Result, Context);

  if (const CastExpr *CE = dyn_cast<CastExpr>(Expr)) {
    QualType CETy = CE->getType();
    if ((CETy->isIntegralType() && !CETy->isBooleanType()) ||
        CETy->isPointerType()) {
      if (CalcFakeICEVal(CE->getSubExpr(), Result, Context)) {
        Result.extOrTrunc(Context.getTypeSize(CETy));
        // FIXME: This assumes pointers are signed.
        Result.setIsSigned(CETy->isSignedIntegerType() ||
                           CETy->isPointerType());
        return true;
      }
    }
  }

  if (Expr->getType()->isIntegralType())
    return Expr->isIntegerConstantExpr(Result, Context);

  return false;
}

static bool EvaluatePointer(const Expr *E, APValue &Result, ASTContext &Ctx);
static bool EvaluateInteger(const Expr *E, APSInt  &Result, ASTContext &Ctx);

//===----------------------------------------------------------------------===//
// Pointer Evaluation
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN PointerExprEvaluator
  : public StmtVisitor<PointerExprEvaluator, APValue> {
  ASTContext &Ctx;
public:

  PointerExprEvaluator(ASTContext &ctx) : Ctx(ctx) {}

  APValue VisitStmt(Stmt *S) {
    // FIXME: Remove this when we support more expressions.
    printf("Unhandled pointer statement\n");
    S->dump();
    return APValue();
  }

  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }

  APValue VisitBinaryOperator(const BinaryOperator *E);
  APValue VisitCastExpr(const CastExpr* E);
};
} // end anonymous namespace

static bool EvaluatePointer(const Expr* E, APValue& Result, ASTContext &Ctx) {
  if (!E->getType()->isPointerType())
    return false;
  Result = PointerExprEvaluator(Ctx).Visit(const_cast<Expr*>(E));
  return Result.isLValue();
}

APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  if (E->getOpcode() != BinaryOperator::Add &&
      E->getOpcode() != BinaryOperator::Sub)
    return APValue();

  const Expr *PExp = E->getLHS();
  const Expr *IExp = E->getRHS();
  if (IExp->getType()->isPointerType())
    std::swap(PExp, IExp);

  APValue ResultLValue;
  if (!EvaluatePointer(PExp, ResultLValue, Ctx))
    return APValue();

  llvm::APSInt AdditionalOffset(32);
  if (!EvaluateInteger(IExp, AdditionalOffset, Ctx))
    return APValue();

  uint64_t Offset = ResultLValue.getLValueOffset();
  if (E->getOpcode() == BinaryOperator::Add)
    Offset += AdditionalOffset.getZExtValue();
  else
    Offset -= AdditionalOffset.getZExtValue();

  return APValue(ResultLValue.getLValueBase(), Offset);
}

APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
  const Expr* SubExpr = E->getSubExpr();

   // Check for pointer->pointer cast
  if (SubExpr->getType()->isPointerType()) {
    APValue Result;
    if (EvaluatePointer(SubExpr, Result, Ctx))
      return Result;
    return APValue();
  }

  if (SubExpr->getType()->isArithmeticType()) {
    llvm::APSInt Result(32);
    if (EvaluateInteger(SubExpr, Result, Ctx)) {
      Result.extOrTrunc(static_cast<uint32_t>(Ctx.getTypeSize(E->getType())));
      return APValue(0, Result.getZExtValue());
    }
  }

  assert(0 && "Unhandled cast");
  return APValue();
}

//===----------------------------------------------------------------------===//
// Integer Evaluation
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN IntExprEvaluator
  : public StmtVisitor<IntExprEvaluator, bool> {
  ASTContext &Ctx;
  APSInt &Result;
public:
  IntExprEvaluator(ASTContext &ctx, APSInt &result) : Ctx(ctx), Result(result){}

  unsigned getIntTypeSizeInBits(QualType T) const {
    return (unsigned)Ctx.getTypeSize(T);
  }

  //===--------------------------------------------------------------------===//
  //                            Visitor Methods
  //===--------------------------------------------------------------------===//

  bool VisitStmt(Stmt *S) {
    // FIXME: Remove this when we support more expressions.
    printf("unhandled int expression");
    S->dump();
    return false;
  }

  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }

  bool VisitBinaryOperator(const BinaryOperator *E);
  bool VisitUnaryOperator(const UnaryOperator *E);

  bool HandleCast(const Expr* SubExpr, QualType DestType);
  bool VisitCastExpr(const CastExpr* E) {
    return HandleCast(E->getSubExpr(), E->getType());
  }
  bool VisitImplicitCastExpr(const ImplicitCastExpr* E) {
    return HandleCast(E->getSubExpr(), E->getType());
  }
  bool VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E);

  bool VisitIntegerLiteral(const IntegerLiteral *E) {
    Result = E->getValue();
    return true;
  }
};
} // end anonymous namespace

static bool EvaluateInteger(const Expr* E, APSInt &Result, ASTContext &Ctx) {
  return IntExprEvaluator(Ctx, Result).Visit(const_cast<Expr*>(E));
}

bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
  // The LHS of a constant expr is always evaluated and needed.
  if (!Visit(E->getLHS()))
    return false;

  llvm::APSInt RHS(32);
  if (!EvaluateInteger(E->getRHS(), RHS, Ctx))
    return false;

  switch (E->getOpcode()) {
  default:
    return false;
  case BinaryOperator::Mul:
    Result *= RHS;
    break;
  case BinaryOperator::Div:
    if (RHS == 0)
      return false;
    Result /= RHS;
    break;
  case BinaryOperator::Rem:
    if (RHS == 0)
      return false;
    Result %= RHS;
    break;
  case BinaryOperator::Add: Result += RHS; break;
  case BinaryOperator::Sub: Result -= RHS; break;
  case BinaryOperator::Shl:
    Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
    break;
  case BinaryOperator::Shr:
    Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
    break;

  // FIXME: Need to set the result width?
  case BinaryOperator::LT:  Result = Result < RHS; break;
  case BinaryOperator::GT:  Result = Result > RHS; break;
  case BinaryOperator::LE:  Result = Result <= RHS; break;
  case BinaryOperator::GE:  Result = Result >= RHS; break;
  case BinaryOperator::EQ:  Result = Result == RHS; break;
  case BinaryOperator::NE:  Result = Result != RHS; break;
  case BinaryOperator::And: Result &= RHS; break;
  case BinaryOperator::Xor: Result ^= RHS; break;
  case BinaryOperator::Or:  Result |= RHS; break;

  case BinaryOperator::Comma:
    // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
    // *except* when they are contained within a subexpression that is not
    // evaluated".  Note that Assignment can never happen due to constraints
    // on the LHS subexpr, so we don't need to check it here.
    // FIXME: Need to come up with an efficient way to deal with the C99
    // rules on evaluation while still evaluating this.  Maybe a
    // "evaluated comma" out parameter?
    return false;
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
  if (E->isOffsetOfOp())
    Result = E->evaluateOffsetOf(Ctx);
  else if (E->isSizeOfAlignOfOp()) {
    // Return the result in the right width.
    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));

    // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
    if (E->getSubExpr()->getType()->isVoidType())
      Result = 1;

    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
    if (!E->getSubExpr()->getType()->isConstantSizeType()) {
      // FIXME: Should we attempt to evaluate this?
      return false;
    }

    // Get information about the size or align.
    if (E->getSubExpr()->getType()->isFunctionType()) {
      // GCC extension: sizeof(function) = 1.
      // FIXME: AlignOf shouldn't be unconditionally 4!
      Result = E->getOpcode() == UnaryOperator::AlignOf ? 4 : 1;
    } else {
      unsigned CharSize = Ctx.Target.getCharWidth();
      if (E->getOpcode() == UnaryOperator::AlignOf)
        Result = Ctx.getTypeAlign(E->getSubExpr()->getType()) / CharSize;
      else
        Result = getIntTypeSizeInBits(E->getSubExpr()->getType()) / CharSize;
    }
  } else {
    // Get the operand value.  If this is sizeof/alignof, do not evalute the
    // operand.  This affects C99 6.6p3.
    if (!EvaluateInteger(E->getSubExpr(), Result, Ctx))
      return false;

    switch (E->getOpcode()) {
      // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
      // See C99 6.6p3.
    default:
      return false;
    case UnaryOperator::Extension:
      assert(0 && "Handle UnaryOperator::Extension");
        return false;
    case UnaryOperator::LNot: {
      bool Val = Result == 0;
      Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
      Result = Val;
      break;
    }
    case UnaryOperator::Plus:
      break;
    case UnaryOperator::Minus:
      Result = -Result;
      break;
    case UnaryOperator::Not:
      Result = ~Result;
      break;
    }
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::HandleCast(const Expr* SubExpr, QualType DestType) {
  unsigned DestWidth = getIntTypeSizeInBits(DestType);

  // Handle simple integer->integer casts.
  if (SubExpr->getType()->isIntegerType()) {
    if (!EvaluateInteger(SubExpr, Result, Ctx))
      return false;

    // Figure out if this is a truncate, extend or noop cast.
    // If the input is signed, do a sign extend, noop, or truncate.
    if (DestType->isBooleanType()) {
      // Conversion to bool compares against zero.
      Result = Result != 0;
      Result.zextOrTrunc(DestWidth);
    } else
      Result.extOrTrunc(DestWidth);
  } else if (SubExpr->getType()->isPointerType()) {
    APValue LV;
    if (!EvaluatePointer(SubExpr, LV, Ctx))
      return false;
    if (LV.getLValueBase())
      return false;

    Result.extOrTrunc(DestWidth);
    Result = LV.getLValueOffset();
  } else {
    assert(0 && "Unhandled cast!");
  }

  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
  return true;
}

bool IntExprEvaluator::
VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
  // Return the result in the right width.
  Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));

  // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
  if (E->getArgumentType()->isVoidType()) {
    Result = 1;
    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
    return true;
  }

  // alignof always evaluates to a constant, sizeof does if arg is not VLA.
  if (E->isSizeOf() && !E->getArgumentType()->isConstantSizeType())
    return false;

  // Get information about the size or align.
  if (E->getArgumentType()->isFunctionType()) {
    // GCC extension: sizeof(function) = 1.
    Result = E->isSizeOf() ? 1 : 4;
  } else {
    unsigned CharSize = Ctx.Target.getCharWidth();
    if (E->isSizeOf())
      Result = getIntTypeSizeInBits(E->getArgumentType()) / CharSize;
    else
      Result = Ctx.getTypeAlign(E->getArgumentType()) / CharSize;
  }

  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
  return true;
}

//===----------------------------------------------------------------------===//
// Top level TryEvaluate.
//===----------------------------------------------------------------------===//

bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
  llvm::APSInt sInt(32);
#if USE_NEW_EVALUATOR
  if (getType()->isIntegerType()) {
    if (EvaluateInteger(this, sInt, Ctx)) {
      Result = APValue(sInt);
      return true;
    }
  } else
    return false;

#else
  if (CalcFakeICEVal(this, sInt, Ctx)) {
    Result = APValue(sInt);
    return true;
  }
#endif

  return false;
}
<|endoftext|>


<commit_before>//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/SymbolTable.h"
#include "lld/Core/AbsoluteAtom.h"
#include "lld/Core/Atom.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "lld/Core/UndefinedAtom.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <vector>

namespace lld {
bool SymbolTable::add(const UndefinedAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const SharedLibraryAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const AbsoluteAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const DefinedAtom &atom) {
  if (!atom.name().empty() &&
      atom.scope() != DefinedAtom::scopeTranslationUnit) {
    // Named atoms cannot be merged by content.
    assert(atom.merge() != DefinedAtom::mergeByContent);
    // Track named atoms that are not scoped to file (static).
    return addByName(atom);
  }
  if (atom.merge() == DefinedAtom::mergeByContent) {
    // Named atoms cannot be merged by content.
    assert(atom.name().empty());
    // Currently only read-only constants can be merged.
    if (atom.permissions() == DefinedAtom::permR__)
      return addByContent(atom);
    // TODO: support mergeByContent of data atoms by comparing content & fixups.
  }
  return false;
}

enum NameCollisionResolution {
  NCR_First,
  NCR_Second,
  NCR_DupDef,
  NCR_DupUndef,
  NCR_DupShLib,
  NCR_Error
};

static NameCollisionResolution cases[4][4] = {
  //regular     absolute    undef      sharedLib
  {
    // first is regular
    NCR_DupDef, NCR_Error,   NCR_First, NCR_First
  },
  {
    // first is absolute
    NCR_Error,  NCR_Error,  NCR_First, NCR_First
  },
  {
    // first is undef
    NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second
  },
  {
    // first is sharedLib
    NCR_Second, NCR_Second, NCR_First, NCR_DupShLib
  }
};

static NameCollisionResolution collide(Atom::Definition first,
                                       Atom::Definition second) {
  return cases[first][second];
}

enum MergeResolution {
  MCR_First,
  MCR_Second,
  MCR_Largest,
  MCR_SameSize,
  MCR_Error
};

static MergeResolution mergeCases[][6] = {
  // no          tentative      weak          weakAddress   sameNameAndSize largest
  {MCR_Error,    MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // no
  {MCR_Second,   MCR_Largest,   MCR_Second,   MCR_Second,   MCR_SameSize,   MCR_Largest},  // tentative
  {MCR_Second,   MCR_First,     MCR_First,    MCR_Second,   MCR_SameSize,   MCR_Largest},  // weak
  {MCR_Second,   MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // weakAddress
  {MCR_SameSize, MCR_SameSize,  MCR_SameSize, MCR_SameSize, MCR_SameSize,   MCR_SameSize}, // sameSize
  {MCR_Largest,  MCR_Largest,   MCR_Largest,  MCR_Largest,  MCR_SameSize,   MCR_Largest},  // largest
};

static MergeResolution mergeSelect(DefinedAtom::Merge first,
                                   DefinedAtom::Merge second) {
  assert(first != DefinedAtom::mergeByContent);
  assert(second != DefinedAtom::mergeByContent);
  return mergeCases[first][second];
}

bool SymbolTable::addByName(const Atom &newAtom) {
  StringRef name = newAtom.name();
  assert(!name.empty());
  const Atom *existing = findByName(name);
  if (existing == nullptr) {
    // Name is not in symbol table yet, add it associate with this atom.
    _nameTable[name] = &newAtom;
    return true;
  }

  // Do nothing if the same object is added more than once.
  if (existing == &newAtom)
    return false;

  // Name is already in symbol table and associated with another atom.
  bool useNew = true;
  switch (collide(existing->definition(), newAtom.definition())) {
  case NCR_First:
    useNew = false;
    break;
  case NCR_Second:
    useNew = true;
    break;
  case NCR_DupDef: {
    const auto *existingDef = cast<DefinedAtom>(existing);
    const auto *newDef = cast<DefinedAtom>(&newAtom);
    switch (mergeSelect(existingDef->merge(), newDef->merge())) {
    case MCR_First:
      useNew = false;
      break;
    case MCR_Second:
      useNew = true;
      break;
    case MCR_Largest: {
      uint64_t existingSize = existingDef->sectionSize();
      uint64_t newSize = newDef->sectionSize();
      useNew = (newSize >= existingSize);
      break;
    }
    case MCR_SameSize: {
      uint64_t existingSize = existingDef->sectionSize();
      uint64_t newSize = newDef->sectionSize();
      if (existingSize == newSize) {
        useNew = true;
        break;
      }
      llvm::errs() << "Size mismatch: "
                   << existing->name() << " (" << existingSize << ") "
                   << newAtom.name() << " (" << newSize << ")\n";
      // fallthrough
    }
    case MCR_Error:
      llvm::errs() << "Duplicate symbols: "
                   << existing->name()
                   << ":"
                   << existing->file().path()
                   << " and "
                   << newAtom.name()
                   << ":"
                   << newAtom.file().path()
                   << "\n";
      llvm::report_fatal_error("duplicate symbol error");
      break;
    }
    break;
  }
  case NCR_DupUndef: {
    const UndefinedAtom* existingUndef = cast<UndefinedAtom>(existing);
    const UndefinedAtom* newUndef = cast<UndefinedAtom>(&newAtom);

    bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull());
    if (sameCanBeNull)
      useNew = false;
    else
      useNew = (newUndef->canBeNull() < existingUndef->canBeNull());
    break;
  }
  case NCR_DupShLib: {
    useNew = false;
    break;
  }
  case NCR_Error:
    llvm::errs() << "SymbolTable: error while merging " << name << "\n";
    llvm::report_fatal_error("duplicate symbol error");
    break;
  }

  if (useNew) {
    // Update name table to use new atom.
    _nameTable[name] = &newAtom;
    // Add existing atom to replacement table.
    _replacedAtoms[existing] = &newAtom;
  } else {
    // New atom is not being used.  Add it to replacement table.
    _replacedAtoms[&newAtom] = existing;
  }
  return false;
}

unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) {
  auto content = atom->rawContent();
  return llvm::hash_combine(atom->size(),
                            atom->contentType(),
                            llvm::hash_combine_range(content.begin(),
                                                     content.end()));
}

bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l,
                                           const DefinedAtom * const r) {
  if (l == r)
    return true;
  if (l == getEmptyKey())
    return false;
  if (r == getEmptyKey())
    return false;
  if (l == getTombstoneKey())
    return false;
  if (r == getTombstoneKey())
    return false;
  if (l->contentType() != r->contentType())
    return false;
  if (l->size() != r->size())
    return false;
  if (l->sectionChoice() != r->sectionChoice())
    return false;
  if (l->sectionChoice() == DefinedAtom::sectionCustomRequired) {
    if (!l->customSectionName().equals(r->customSectionName()))
      return false;
  }
  ArrayRef<uint8_t> lc = l->rawContent();
  ArrayRef<uint8_t> rc = r->rawContent();
  return memcmp(lc.data(), rc.data(), lc.size()) == 0;
}

bool SymbolTable::addByContent(const DefinedAtom &newAtom) {
  AtomContentSet::iterator pos = _contentTable.find(&newAtom);
  if (pos == _contentTable.end()) {
    _contentTable.insert(&newAtom);
    return true;
  }
  const Atom* existing = *pos;
  // New atom is not being used.  Add it to replacement table.
  _replacedAtoms[&newAtom] = existing;
  return false;
}

const Atom *SymbolTable::findByName(StringRef sym) {
  NameToAtom::iterator pos = _nameTable.find(sym);
  if (pos == _nameTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::isDefined(StringRef sym) {
  if (const Atom *atom = findByName(sym))
    return !isa<UndefinedAtom>(atom);
  return false;
}

const Atom *SymbolTable::replacement(const Atom *atom) {
  // Find the replacement for a given atom. Atoms in _replacedAtoms
  // may be chained, so find the last one.
  for (;;) {
    AtomToAtom::iterator pos = _replacedAtoms.find(atom);
    if (pos == _replacedAtoms.end())
      return atom;
    atom = pos->second;
  }
}

bool SymbolTable::isCoalescedAway(const Atom *atom) {
  return _replacedAtoms.count(atom) > 0;
}

std::vector<const UndefinedAtom *> SymbolTable::undefines() {
  std::vector<const UndefinedAtom *> ret;
  for (auto it : _nameTable) {
    const Atom *atom = it.second;
    assert(atom != nullptr);
    if (const auto *undef = dyn_cast<const UndefinedAtom>(atom))
      if (_replacedAtoms.count(undef) == 0)
        ret.push_back(undef);
  }
  return ret;
}

} // namespace lld
<commit_msg>[Core] Simplify a bit. NFCI.<commit_after>//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/SymbolTable.h"
#include "lld/Core/AbsoluteAtom.h"
#include "lld/Core/Atom.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "lld/Core/UndefinedAtom.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <vector>

namespace lld {
bool SymbolTable::add(const UndefinedAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const SharedLibraryAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const AbsoluteAtom &atom) { return addByName(atom); }

bool SymbolTable::add(const DefinedAtom &atom) {
  if (!atom.name().empty() &&
      atom.scope() != DefinedAtom::scopeTranslationUnit) {
    // Named atoms cannot be merged by content.
    assert(atom.merge() != DefinedAtom::mergeByContent);
    // Track named atoms that are not scoped to file (static).
    return addByName(atom);
  }
  if (atom.merge() == DefinedAtom::mergeByContent) {
    // Named atoms cannot be merged by content.
    assert(atom.name().empty());
    // Currently only read-only constants can be merged.
    if (atom.permissions() == DefinedAtom::permR__)
      return addByContent(atom);
    // TODO: support mergeByContent of data atoms by comparing content & fixups.
  }
  return false;
}

enum NameCollisionResolution {
  NCR_First,
  NCR_Second,
  NCR_DupDef,
  NCR_DupUndef,
  NCR_DupShLib,
  NCR_Error
};

static NameCollisionResolution cases[4][4] = {
  //regular     absolute    undef      sharedLib
  {
    // first is regular
    NCR_DupDef, NCR_Error,   NCR_First, NCR_First
  },
  {
    // first is absolute
    NCR_Error,  NCR_Error,  NCR_First, NCR_First
  },
  {
    // first is undef
    NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second
  },
  {
    // first is sharedLib
    NCR_Second, NCR_Second, NCR_First, NCR_DupShLib
  }
};

static NameCollisionResolution collide(Atom::Definition first,
                                       Atom::Definition second) {
  return cases[first][second];
}

enum MergeResolution {
  MCR_First,
  MCR_Second,
  MCR_Largest,
  MCR_SameSize,
  MCR_Error
};

static MergeResolution mergeCases[][6] = {
  // no          tentative      weak          weakAddress   sameNameAndSize largest
  {MCR_Error,    MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // no
  {MCR_Second,   MCR_Largest,   MCR_Second,   MCR_Second,   MCR_SameSize,   MCR_Largest},  // tentative
  {MCR_Second,   MCR_First,     MCR_First,    MCR_Second,   MCR_SameSize,   MCR_Largest},  // weak
  {MCR_Second,   MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // weakAddress
  {MCR_SameSize, MCR_SameSize,  MCR_SameSize, MCR_SameSize, MCR_SameSize,   MCR_SameSize}, // sameSize
  {MCR_Largest,  MCR_Largest,   MCR_Largest,  MCR_Largest,  MCR_SameSize,   MCR_Largest},  // largest
};

static MergeResolution mergeSelect(DefinedAtom::Merge first,
                                   DefinedAtom::Merge second) {
  assert(first != DefinedAtom::mergeByContent);
  assert(second != DefinedAtom::mergeByContent);
  return mergeCases[first][second];
}

bool SymbolTable::addByName(const Atom &newAtom) {
  StringRef name = newAtom.name();
  assert(!name.empty());
  const Atom *existing = findByName(name);
  if (existing == nullptr) {
    // Name is not in symbol table yet, add it associate with this atom.
    _nameTable[name] = &newAtom;
    return true;
  }

  // Do nothing if the same object is added more than once.
  if (existing == &newAtom)
    return false;

  // Name is already in symbol table and associated with another atom.
  bool useNew = true;
  switch (collide(existing->definition(), newAtom.definition())) {
  case NCR_First:
    useNew = false;
    break;
  case NCR_Second:
    useNew = true;
    break;
  case NCR_DupDef: {
    const auto *existingDef = cast<DefinedAtom>(existing);
    const auto *newDef = cast<DefinedAtom>(&newAtom);
    switch (mergeSelect(existingDef->merge(), newDef->merge())) {
    case MCR_First:
      useNew = false;
      break;
    case MCR_Second:
      useNew = true;
      break;
    case MCR_Largest: {
      uint64_t existingSize = existingDef->sectionSize();
      uint64_t newSize = newDef->sectionSize();
      useNew = (newSize >= existingSize);
      break;
    }
    case MCR_SameSize: {
      uint64_t existingSize = existingDef->sectionSize();
      uint64_t newSize = newDef->sectionSize();
      if (existingSize == newSize) {
        useNew = true;
        break;
      }
      llvm::errs() << "Size mismatch: "
                   << existing->name() << " (" << existingSize << ") "
                   << newAtom.name() << " (" << newSize << ")\n";
      // fallthrough
    }
    case MCR_Error:
      llvm::errs() << "Duplicate symbols: "
                   << existing->name()
                   << ":"
                   << existing->file().path()
                   << " and "
                   << newAtom.name()
                   << ":"
                   << newAtom.file().path()
                   << "\n";
      llvm::report_fatal_error("duplicate symbol error");
      break;
    }
    break;
  }
  case NCR_DupUndef: {
    const UndefinedAtom* existingUndef = cast<UndefinedAtom>(existing);
    const UndefinedAtom* newUndef = cast<UndefinedAtom>(&newAtom);

    bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull());
    if (sameCanBeNull)
      useNew = false;
    else
      useNew = (newUndef->canBeNull() < existingUndef->canBeNull());
    break;
  }
  case NCR_DupShLib: {
    useNew = false;
    break;
  }
  case NCR_Error:
    llvm::errs() << "SymbolTable: error while merging " << name << "\n";
    llvm::report_fatal_error("duplicate symbol error");
    break;
  }

  if (useNew) {
    // Update name table to use new atom.
    _nameTable[name] = &newAtom;
    // Add existing atom to replacement table.
    _replacedAtoms[existing] = &newAtom;
  } else {
    // New atom is not being used.  Add it to replacement table.
    _replacedAtoms[&newAtom] = existing;
  }
  return false;
}

unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) {
  auto content = atom->rawContent();
  return llvm::hash_combine(atom->size(),
                            atom->contentType(),
                            llvm::hash_combine_range(content.begin(),
                                                     content.end()));
}

bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l,
                                           const DefinedAtom * const r) {
  if (l == r)
    return true;
  if (l == getEmptyKey() || r == getEmptyKey())
    return false;
  if (l == getTombstoneKey() || r == getTombstoneKey())
    return false;
  if (l->contentType() != r->contentType())
    return false;
  if (l->size() != r->size())
    return false;
  if (l->sectionChoice() != r->sectionChoice())
    return false;
  if (l->sectionChoice() == DefinedAtom::sectionCustomRequired) {
    if (!l->customSectionName().equals(r->customSectionName()))
      return false;
  }
  ArrayRef<uint8_t> lc = l->rawContent();
  ArrayRef<uint8_t> rc = r->rawContent();
  return memcmp(lc.data(), rc.data(), lc.size()) == 0;
}

bool SymbolTable::addByContent(const DefinedAtom &newAtom) {
  AtomContentSet::iterator pos = _contentTable.find(&newAtom);
  if (pos == _contentTable.end()) {
    _contentTable.insert(&newAtom);
    return true;
  }
  const Atom* existing = *pos;
  // New atom is not being used.  Add it to replacement table.
  _replacedAtoms[&newAtom] = existing;
  return false;
}

const Atom *SymbolTable::findByName(StringRef sym) {
  NameToAtom::iterator pos = _nameTable.find(sym);
  if (pos == _nameTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::isDefined(StringRef sym) {
  if (const Atom *atom = findByName(sym))
    return !isa<UndefinedAtom>(atom);
  return false;
}

const Atom *SymbolTable::replacement(const Atom *atom) {
  // Find the replacement for a given atom. Atoms in _replacedAtoms
  // may be chained, so find the last one.
  for (;;) {
    AtomToAtom::iterator pos = _replacedAtoms.find(atom);
    if (pos == _replacedAtoms.end())
      return atom;
    atom = pos->second;
  }
}

bool SymbolTable::isCoalescedAway(const Atom *atom) {
  return _replacedAtoms.count(atom) > 0;
}

std::vector<const UndefinedAtom *> SymbolTable::undefines() {
  std::vector<const UndefinedAtom *> ret;
  for (auto it : _nameTable) {
    const Atom *atom = it.second;
    assert(atom != nullptr);
    if (const auto *undef = dyn_cast<const UndefinedAtom>(atom))
      if (_replacedAtoms.count(undef) == 0)
        ret.push_back(undef);
  }
  return ret;
}

} // namespace lld
<|endoftext|>


<commit_before>//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/SymbolTable.h"
#include "lld/Core/AbsoluteAtom.h"
#include "lld/Core/Atom.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/UndefinedAtom.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <vector>

namespace lld {
SymbolTable::SymbolTable(const LinkingContext &context) : _context(context) {}

void SymbolTable::add(const UndefinedAtom &atom) { addByName(atom); }

void SymbolTable::add(const SharedLibraryAtom &atom) { addByName(atom); }

void SymbolTable::add(const AbsoluteAtom &atom) { addByName(atom); }

void SymbolTable::add(const DefinedAtom &atom) {
  if (!atom.name().empty() &&
      atom.scope() != DefinedAtom::scopeTranslationUnit) {
    // Named atoms cannot be merged by content.
    assert(atom.merge() != DefinedAtom::mergeByContent);
    // Track named atoms that are not scoped to file (static).
    addByName(atom);
    return;
  }
  if (atom.merge() == DefinedAtom::mergeByContent) {
    // Named atoms cannot be merged by content.
    assert(atom.name().empty());
    addByContent(atom);
  }
}

const Atom *SymbolTable::findGroup(StringRef sym) {
  NameToAtom::iterator pos = _groupTable.find(sym);
  if (pos == _groupTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::addGroup(const DefinedAtom &da) {
  StringRef name = da.name();
  assert(!name.empty());
  const Atom *existing = findGroup(name);
  if (existing == nullptr) {
    _groupTable[name] = &da;
    return true;
  }
  _replacedAtoms[&da] = existing;
  return false;
}

enum NameCollisionResolution {
  NCR_First,
  NCR_Second,
  NCR_DupDef,
  NCR_DupUndef,
  NCR_DupShLib,
  NCR_Error
};

static NameCollisionResolution cases[4][4] = {
  //regular     absolute    undef      sharedLib
  {
    // first is regular
    NCR_DupDef, NCR_Error,   NCR_First, NCR_First
  },
  {
    // first is absolute
    NCR_Error,  NCR_Error,  NCR_First, NCR_First
  },
  {
    // first is undef
    NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second
  },
  {
    // first is sharedLib
    NCR_Second, NCR_Second, NCR_First, NCR_DupShLib
  }
};

static NameCollisionResolution collide(Atom::Definition first,
                                       Atom::Definition second) {
  return cases[first][second];
}

enum MergeResolution {
  MCR_First,
  MCR_Second,
  MCR_Largest,
  MCR_SameSize,
  MCR_Error
};

static MergeResolution mergeCases[][6] = {
  // no          tentative      weak          weakAddress   sameNameAndSize largest
  {MCR_Error,    MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // no
  {MCR_Second,   MCR_Largest,   MCR_Second,   MCR_Second,   MCR_SameSize,   MCR_Largest},  // tentative
  {MCR_Second,   MCR_First,     MCR_First,    MCR_Second,   MCR_SameSize,   MCR_Largest},  // weak
  {MCR_Second,   MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // weakAddress
  {MCR_SameSize, MCR_SameSize,  MCR_SameSize, MCR_SameSize, MCR_SameSize,   MCR_SameSize}, // sameSize
  {MCR_Largest,  MCR_Largest,   MCR_Largest,  MCR_Largest,  MCR_SameSize,   MCR_Largest},  // largest
};

static MergeResolution mergeSelect(DefinedAtom::Merge first,
                                   DefinedAtom::Merge second) {
  assert(first != DefinedAtom::mergeByContent);
  assert(second != DefinedAtom::mergeByContent);
  return mergeCases[first][second];
}

static uint64_t getSizeFollowReferences(const DefinedAtom *atom, uint32_t kind) {
  uint64_t size = 0;
redo:
  while (atom) {
    for (const Reference *r : *atom) {
      if (r->kindNamespace() == Reference::KindNamespace::all &&
          r->kindArch() == Reference::KindArch::all &&
          r->kindValue() == kind) {
        atom = cast<DefinedAtom>(r->target());
        size += atom->size();
        goto redo;
      }
    }
    break;
  }
  return size;
}

// Returns the size of the section containing the given atom. Atoms in the same
// section are connected by layout-before and layout-after edges, so this
// function traverses them to get the total size of atoms in the same section.
static uint64_t sectionSize(const DefinedAtom *atom) {
  return atom->size()
      + getSizeFollowReferences(atom, lld::Reference::kindLayoutBefore)
      + getSizeFollowReferences(atom, lld::Reference::kindLayoutAfter);
}

void SymbolTable::addByName(const Atom &newAtom) {
  StringRef name = newAtom.name();
  assert(!name.empty());
  const Atom *existing = findByName(name);
  if (existing == nullptr) {
    // Name is not in symbol table yet, add it associate with this atom.
    _nameTable[name] = &newAtom;
    return;
  }

  // Name is already in symbol table and associated with another atom.
  bool useNew = true;
  switch (collide(existing->definition(), newAtom.definition())) {
  case NCR_First:
    useNew = false;
    break;
  case NCR_Second:
    useNew = true;
    break;
  case NCR_DupDef:
    assert(existing->definition() == Atom::definitionRegular);
    assert(newAtom.definition() == Atom::definitionRegular);
    switch (mergeSelect(((DefinedAtom*)existing)->merge(),
                        ((DefinedAtom*)&newAtom)->merge())) {
    case MCR_First:
      useNew = false;
      break;
    case MCR_Second:
      useNew = true;
      break;
    case MCR_Largest: {
      uint64_t existingSize = sectionSize((DefinedAtom*)existing);
      uint64_t newSize = sectionSize((DefinedAtom*)&newAtom);
      useNew = (newSize >= existingSize);
      break;
    }
    case MCR_SameSize: {
      uint64_t existingSize = sectionSize((DefinedAtom*)existing);
      uint64_t newSize = sectionSize((DefinedAtom*)&newAtom);
      if (existingSize == newSize) {
        useNew = true;
        break;
      }
      llvm::errs() << "Size mismatch: "
                   << existing->name() << " (" << existingSize << ") "
                   << newAtom.name() << " (" << newSize << ")\n";
      // fallthrough
    }
    case MCR_Error:
      if (!_context.getAllowDuplicates()) {
        llvm::errs() << "Duplicate symbols: "
                     << existing->name()
                     << ":"
                     << existing->file().path()
                     << " and "
                     << newAtom.name()
                     << ":"
                     << newAtom.file().path()
                     << "\n";
        llvm::report_fatal_error("duplicate symbol error");
      }
      useNew = false;
      break;
    }
    break;
  case NCR_DupUndef: {
    const UndefinedAtom* existingUndef = dyn_cast<UndefinedAtom>(existing);
    const UndefinedAtom* newUndef = dyn_cast<UndefinedAtom>(&newAtom);
    assert(existingUndef != nullptr);
    assert(newUndef != nullptr);

    bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull());
    if (!sameCanBeNull &&
        _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) {
      llvm::errs() << "lld warning: undefined symbol "
                   << existingUndef->name()
                   << " has different weakness in "
                   << existingUndef->file().path()
                   << " and in " << newUndef->file().path() << "\n";
    }

    const UndefinedAtom *existingFallback = existingUndef->fallback();
    const UndefinedAtom *newFallback = newUndef->fallback();
    bool hasDifferentFallback =
        (existingFallback && newFallback &&
         existingFallback->name() != newFallback->name());
    if (hasDifferentFallback) {
      llvm::errs() << "lld warning: undefined symbol "
                   << existingUndef->name() << " has different fallback: "
                   << existingFallback->name() << " in "
                   << existingUndef->file().path() << " and "
                   << newFallback->name() << " in "
                   << newUndef->file().path() << "\n";
    }

    bool hasNewFallback = newUndef->fallback();
    if (sameCanBeNull)
      useNew = hasNewFallback;
    else
      useNew = (newUndef->canBeNull() < existingUndef->canBeNull());
    break;
  }
  case NCR_DupShLib: {
      const SharedLibraryAtom* curShLib =
        dyn_cast<SharedLibraryAtom>(existing);
      const SharedLibraryAtom* newShLib =
        dyn_cast<SharedLibraryAtom>(&newAtom);
      assert(curShLib != nullptr);
      assert(newShLib != nullptr);
      bool sameNullness = (curShLib->canBeNullAtRuntime()
                                      == newShLib->canBeNullAtRuntime());
      bool sameName = curShLib->loadName().equals(newShLib->loadName());
      if (!sameName) {
        useNew = false;
        if (_context.warnIfCoalesableAtomsHaveDifferentLoadName()) {
          // FIXME: need diagonstics interface for writing warning messages
          llvm::errs() << "lld warning: shared library symbol "
                       << curShLib->name()
                       << " has different load path in "
                       << curShLib->file().path()
                       << " and in "
                       << newShLib->file().path();
        }
      } else if (!sameNullness) {
        useNew = false;
        if (_context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) {
          // FIXME: need diagonstics interface for writing warning messages
          llvm::errs() << "lld warning: shared library symbol "
                       << curShLib->name()
                       << " has different weakness in "
                       << curShLib->file().path()
                       << " and in "
                       << newShLib->file().path();
        }
      } else {
        // Both shlib atoms are identical and can be coalesced.
        useNew = false;
      }
    }
    break;
  case NCR_Error:
    llvm::errs() << "SymbolTable: error while merging " << name << "\n";
    llvm::report_fatal_error("duplicate symbol error");
    break;
  }

  if (useNew) {
    // Update name table to use new atom.
    _nameTable[name] = &newAtom;
    // Add existing atom to replacement table.
    _replacedAtoms[existing] = &newAtom;
  } else {
    // New atom is not being used.  Add it to replacement table.
    _replacedAtoms[&newAtom] = existing;
  }
}

unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) {
  auto content = atom->rawContent();
  return llvm::hash_combine(atom->size(),
                            atom->contentType(),
                            llvm::hash_combine_range(content.begin(),
                                                     content.end()));
}

bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l,
                                           const DefinedAtom * const r) {
  if (l == r)
    return true;
  if (l == getEmptyKey())
    return false;
  if (r == getEmptyKey())
    return false;
  if (l == getTombstoneKey())
    return false;
  if (r == getTombstoneKey())
    return false;

  if (l->contentType() != r->contentType())
    return false;
  if (l->size() != r->size())
    return false;
  ArrayRef<uint8_t> lc = l->rawContent();
  ArrayRef<uint8_t> rc = r->rawContent();
  return memcmp(lc.data(), rc.data(), lc.size()) == 0;
}

void SymbolTable::addByContent(const DefinedAtom & newAtom) {
  // Currently only read-only constants can be merged.
  assert(newAtom.permissions() == DefinedAtom::permR__);
  AtomContentSet::iterator pos = _contentTable.find(&newAtom);
  if (pos == _contentTable.end()) {
    _contentTable.insert(&newAtom);
    return;
  }
  const Atom* existing = *pos;
  // New atom is not being used.  Add it to replacement table.
  _replacedAtoms[&newAtom] = existing;
}

const Atom *SymbolTable::findByName(StringRef sym) {
  NameToAtom::iterator pos = _nameTable.find(sym);
  if (pos == _nameTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::isDefined(StringRef sym) {
  if (const Atom *atom = findByName(sym))
    return atom->definition() != Atom::definitionUndefined;
  return false;
}

void SymbolTable::addReplacement(const Atom *replaced,
                                 const Atom *replacement) {
  _replacedAtoms[replaced] = replacement;
}

const Atom *SymbolTable::replacement(const Atom *atom) {
  for (;;) {
    AtomToAtom::iterator pos = _replacedAtoms.find(atom);
    if (pos == _replacedAtoms.end())
      return atom;
    // might be chain, recurse to end
    atom = pos->second;
  }
}

unsigned int SymbolTable::size() {
  return _nameTable.size();
}

void SymbolTable::undefines(std::vector<const UndefinedAtom *> &undefs) {
  for (auto it : _nameTable) {
    const Atom *atom = it.second;
    assert(atom != nullptr);
    if (const auto undef = dyn_cast<const UndefinedAtom>(atom)) {
      AtomToAtom::iterator pos = _replacedAtoms.find(undef);
      if (pos != _replacedAtoms.end())
        continue;
      undefs.push_back(undef);
    }
  }
}

void SymbolTable::tentativeDefinitions(std::vector<StringRef> &names) {
  for (auto entry : _nameTable) {
    const Atom *atom = entry.second;
    StringRef name   = entry.first;
    assert(atom != nullptr);
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom))
      if (defAtom->merge() == DefinedAtom::mergeAsTentative)
        names.push_back(name);
  }
}
} // namespace lld
<commit_msg>Update comment.<commit_after>//===- Core/SymbolTable.cpp - Main Symbol Table ---------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/SymbolTable.h"
#include "lld/Core/AbsoluteAtom.h"
#include "lld/Core/Atom.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/File.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/UndefinedAtom.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"

#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <vector>

namespace lld {
SymbolTable::SymbolTable(const LinkingContext &context) : _context(context) {}

void SymbolTable::add(const UndefinedAtom &atom) { addByName(atom); }

void SymbolTable::add(const SharedLibraryAtom &atom) { addByName(atom); }

void SymbolTable::add(const AbsoluteAtom &atom) { addByName(atom); }

void SymbolTable::add(const DefinedAtom &atom) {
  if (!atom.name().empty() &&
      atom.scope() != DefinedAtom::scopeTranslationUnit) {
    // Named atoms cannot be merged by content.
    assert(atom.merge() != DefinedAtom::mergeByContent);
    // Track named atoms that are not scoped to file (static).
    addByName(atom);
    return;
  }
  if (atom.merge() == DefinedAtom::mergeByContent) {
    // Named atoms cannot be merged by content.
    assert(atom.name().empty());
    addByContent(atom);
  }
}

const Atom *SymbolTable::findGroup(StringRef sym) {
  NameToAtom::iterator pos = _groupTable.find(sym);
  if (pos == _groupTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::addGroup(const DefinedAtom &da) {
  StringRef name = da.name();
  assert(!name.empty());
  const Atom *existing = findGroup(name);
  if (existing == nullptr) {
    _groupTable[name] = &da;
    return true;
  }
  _replacedAtoms[&da] = existing;
  return false;
}

enum NameCollisionResolution {
  NCR_First,
  NCR_Second,
  NCR_DupDef,
  NCR_DupUndef,
  NCR_DupShLib,
  NCR_Error
};

static NameCollisionResolution cases[4][4] = {
  //regular     absolute    undef      sharedLib
  {
    // first is regular
    NCR_DupDef, NCR_Error,   NCR_First, NCR_First
  },
  {
    // first is absolute
    NCR_Error,  NCR_Error,  NCR_First, NCR_First
  },
  {
    // first is undef
    NCR_Second, NCR_Second, NCR_DupUndef, NCR_Second
  },
  {
    // first is sharedLib
    NCR_Second, NCR_Second, NCR_First, NCR_DupShLib
  }
};

static NameCollisionResolution collide(Atom::Definition first,
                                       Atom::Definition second) {
  return cases[first][second];
}

enum MergeResolution {
  MCR_First,
  MCR_Second,
  MCR_Largest,
  MCR_SameSize,
  MCR_Error
};

static MergeResolution mergeCases[][6] = {
  // no          tentative      weak          weakAddress   sameNameAndSize largest
  {MCR_Error,    MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // no
  {MCR_Second,   MCR_Largest,   MCR_Second,   MCR_Second,   MCR_SameSize,   MCR_Largest},  // tentative
  {MCR_Second,   MCR_First,     MCR_First,    MCR_Second,   MCR_SameSize,   MCR_Largest},  // weak
  {MCR_Second,   MCR_First,     MCR_First,    MCR_First,    MCR_SameSize,   MCR_Largest},  // weakAddress
  {MCR_SameSize, MCR_SameSize,  MCR_SameSize, MCR_SameSize, MCR_SameSize,   MCR_SameSize}, // sameSize
  {MCR_Largest,  MCR_Largest,   MCR_Largest,  MCR_Largest,  MCR_SameSize,   MCR_Largest},  // largest
};

static MergeResolution mergeSelect(DefinedAtom::Merge first,
                                   DefinedAtom::Merge second) {
  assert(first != DefinedAtom::mergeByContent);
  assert(second != DefinedAtom::mergeByContent);
  return mergeCases[first][second];
}

static uint64_t getSizeFollowReferences(const DefinedAtom *atom, uint32_t kind) {
  uint64_t size = 0;
redo:
  while (atom) {
    for (const Reference *r : *atom) {
      if (r->kindNamespace() == Reference::KindNamespace::all &&
          r->kindArch() == Reference::KindArch::all &&
          r->kindValue() == kind) {
        atom = cast<DefinedAtom>(r->target());
        size += atom->size();
        goto redo;
      }
    }
    break;
  }
  return size;
}

// Returns the size of the section containing the given atom. Atoms in the same
// section are connected by layout-before and layout-after edges, so this
// function traverses them to get the total size of atoms in the same section.
static uint64_t sectionSize(const DefinedAtom *atom) {
  return atom->size()
      + getSizeFollowReferences(atom, lld::Reference::kindLayoutBefore)
      + getSizeFollowReferences(atom, lld::Reference::kindLayoutAfter);
}

void SymbolTable::addByName(const Atom &newAtom) {
  StringRef name = newAtom.name();
  assert(!name.empty());
  const Atom *existing = findByName(name);
  if (existing == nullptr) {
    // Name is not in symbol table yet, add it associate with this atom.
    _nameTable[name] = &newAtom;
    return;
  }

  // Name is already in symbol table and associated with another atom.
  bool useNew = true;
  switch (collide(existing->definition(), newAtom.definition())) {
  case NCR_First:
    useNew = false;
    break;
  case NCR_Second:
    useNew = true;
    break;
  case NCR_DupDef:
    assert(existing->definition() == Atom::definitionRegular);
    assert(newAtom.definition() == Atom::definitionRegular);
    switch (mergeSelect(((DefinedAtom*)existing)->merge(),
                        ((DefinedAtom*)&newAtom)->merge())) {
    case MCR_First:
      useNew = false;
      break;
    case MCR_Second:
      useNew = true;
      break;
    case MCR_Largest: {
      uint64_t existingSize = sectionSize((DefinedAtom*)existing);
      uint64_t newSize = sectionSize((DefinedAtom*)&newAtom);
      useNew = (newSize >= existingSize);
      break;
    }
    case MCR_SameSize: {
      uint64_t existingSize = sectionSize((DefinedAtom*)existing);
      uint64_t newSize = sectionSize((DefinedAtom*)&newAtom);
      if (existingSize == newSize) {
        useNew = true;
        break;
      }
      llvm::errs() << "Size mismatch: "
                   << existing->name() << " (" << existingSize << ") "
                   << newAtom.name() << " (" << newSize << ")\n";
      // fallthrough
    }
    case MCR_Error:
      if (!_context.getAllowDuplicates()) {
        llvm::errs() << "Duplicate symbols: "
                     << existing->name()
                     << ":"
                     << existing->file().path()
                     << " and "
                     << newAtom.name()
                     << ":"
                     << newAtom.file().path()
                     << "\n";
        llvm::report_fatal_error("duplicate symbol error");
      }
      useNew = false;
      break;
    }
    break;
  case NCR_DupUndef: {
    const UndefinedAtom* existingUndef = dyn_cast<UndefinedAtom>(existing);
    const UndefinedAtom* newUndef = dyn_cast<UndefinedAtom>(&newAtom);
    assert(existingUndef != nullptr);
    assert(newUndef != nullptr);

    bool sameCanBeNull = (existingUndef->canBeNull() == newUndef->canBeNull());
    if (!sameCanBeNull &&
        _context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) {
      llvm::errs() << "lld warning: undefined symbol "
                   << existingUndef->name()
                   << " has different weakness in "
                   << existingUndef->file().path()
                   << " and in " << newUndef->file().path() << "\n";
    }

    const UndefinedAtom *existingFallback = existingUndef->fallback();
    const UndefinedAtom *newFallback = newUndef->fallback();
    bool hasDifferentFallback =
        (existingFallback && newFallback &&
         existingFallback->name() != newFallback->name());
    if (hasDifferentFallback) {
      llvm::errs() << "lld warning: undefined symbol "
                   << existingUndef->name() << " has different fallback: "
                   << existingFallback->name() << " in "
                   << existingUndef->file().path() << " and "
                   << newFallback->name() << " in "
                   << newUndef->file().path() << "\n";
    }

    bool hasNewFallback = newUndef->fallback();
    if (sameCanBeNull)
      useNew = hasNewFallback;
    else
      useNew = (newUndef->canBeNull() < existingUndef->canBeNull());
    break;
  }
  case NCR_DupShLib: {
      const SharedLibraryAtom* curShLib =
        dyn_cast<SharedLibraryAtom>(existing);
      const SharedLibraryAtom* newShLib =
        dyn_cast<SharedLibraryAtom>(&newAtom);
      assert(curShLib != nullptr);
      assert(newShLib != nullptr);
      bool sameNullness = (curShLib->canBeNullAtRuntime()
                                      == newShLib->canBeNullAtRuntime());
      bool sameName = curShLib->loadName().equals(newShLib->loadName());
      if (!sameName) {
        useNew = false;
        if (_context.warnIfCoalesableAtomsHaveDifferentLoadName()) {
          // FIXME: need diagonstics interface for writing warning messages
          llvm::errs() << "lld warning: shared library symbol "
                       << curShLib->name()
                       << " has different load path in "
                       << curShLib->file().path()
                       << " and in "
                       << newShLib->file().path();
        }
      } else if (!sameNullness) {
        useNew = false;
        if (_context.warnIfCoalesableAtomsHaveDifferentCanBeNull()) {
          // FIXME: need diagonstics interface for writing warning messages
          llvm::errs() << "lld warning: shared library symbol "
                       << curShLib->name()
                       << " has different weakness in "
                       << curShLib->file().path()
                       << " and in "
                       << newShLib->file().path();
        }
      } else {
        // Both shlib atoms are identical and can be coalesced.
        useNew = false;
      }
    }
    break;
  case NCR_Error:
    llvm::errs() << "SymbolTable: error while merging " << name << "\n";
    llvm::report_fatal_error("duplicate symbol error");
    break;
  }

  if (useNew) {
    // Update name table to use new atom.
    _nameTable[name] = &newAtom;
    // Add existing atom to replacement table.
    _replacedAtoms[existing] = &newAtom;
  } else {
    // New atom is not being used.  Add it to replacement table.
    _replacedAtoms[&newAtom] = existing;
  }
}

unsigned SymbolTable::AtomMappingInfo::getHashValue(const DefinedAtom *atom) {
  auto content = atom->rawContent();
  return llvm::hash_combine(atom->size(),
                            atom->contentType(),
                            llvm::hash_combine_range(content.begin(),
                                                     content.end()));
}

bool SymbolTable::AtomMappingInfo::isEqual(const DefinedAtom * const l,
                                           const DefinedAtom * const r) {
  if (l == r)
    return true;
  if (l == getEmptyKey())
    return false;
  if (r == getEmptyKey())
    return false;
  if (l == getTombstoneKey())
    return false;
  if (r == getTombstoneKey())
    return false;

  if (l->contentType() != r->contentType())
    return false;
  if (l->size() != r->size())
    return false;
  ArrayRef<uint8_t> lc = l->rawContent();
  ArrayRef<uint8_t> rc = r->rawContent();
  return memcmp(lc.data(), rc.data(), lc.size()) == 0;
}

void SymbolTable::addByContent(const DefinedAtom & newAtom) {
  // Currently only read-only constants can be merged.
  assert(newAtom.permissions() == DefinedAtom::permR__);
  AtomContentSet::iterator pos = _contentTable.find(&newAtom);
  if (pos == _contentTable.end()) {
    _contentTable.insert(&newAtom);
    return;
  }
  const Atom* existing = *pos;
  // New atom is not being used.  Add it to replacement table.
  _replacedAtoms[&newAtom] = existing;
}

const Atom *SymbolTable::findByName(StringRef sym) {
  NameToAtom::iterator pos = _nameTable.find(sym);
  if (pos == _nameTable.end())
    return nullptr;
  return pos->second;
}

bool SymbolTable::isDefined(StringRef sym) {
  if (const Atom *atom = findByName(sym))
    return atom->definition() != Atom::definitionUndefined;
  return false;
}

void SymbolTable::addReplacement(const Atom *replaced,
                                 const Atom *replacement) {
  _replacedAtoms[replaced] = replacement;
}

const Atom *SymbolTable::replacement(const Atom *atom) {
  // Find the replacement for a given atom. Atoms in _replacedAtoms
  // may be chained, so find the last one.
  for (;;) {
    AtomToAtom::iterator pos = _replacedAtoms.find(atom);
    if (pos == _replacedAtoms.end())
      return atom;
    atom = pos->second;
  }
}

unsigned int SymbolTable::size() {
  return _nameTable.size();
}

void SymbolTable::undefines(std::vector<const UndefinedAtom *> &undefs) {
  for (auto it : _nameTable) {
    const Atom *atom = it.second;
    assert(atom != nullptr);
    if (const auto undef = dyn_cast<const UndefinedAtom>(atom)) {
      AtomToAtom::iterator pos = _replacedAtoms.find(undef);
      if (pos != _replacedAtoms.end())
        continue;
      undefs.push_back(undef);
    }
  }
}

void SymbolTable::tentativeDefinitions(std::vector<StringRef> &names) {
  for (auto entry : _nameTable) {
    const Atom *atom = entry.second;
    StringRef name   = entry.first;
    assert(atom != nullptr);
    if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom))
      if (defAtom->merge() == DefinedAtom::mergeAsTentative)
        names.push_back(name);
  }
}
} // namespace lld
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "UriEndPoint.hpp"

#include "KmsMediaUriEndPointType_constants.h"
#include "KmsMediaErrorCodes_constants.h"

#include "utils/utils.hpp"
#include "utils/marshalling.hpp"

#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"

#define GST_CAT_DEFAULT kurento_uri_end_point
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoUriEndPoint"

using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;

namespace kurento
{

UriEndPoint::UriEndPoint (MediaSet &mediaSet,
                          std::shared_ptr<MediaPipeline> parent,
                          const std::string &type,
                          const std::map<std::string, KmsMediaParam> &params,
                          const std::string &factoryName)
throw (KmsMediaServerException)
  : EndPoint (mediaSet, parent, type, params, factoryName)
{
  KmsMediaUriEndPointConstructorParams uriEpParams;
  const KmsMediaParam *p;

  p = getParam (params,
                g_KmsMediaUriEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);

  if (p == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except,
                                   g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_ILLEGAL_PARAM_ERROR,
                                   "Param '" + g_KmsMediaUriEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE +
                                   "' not found");
    throw except;
  }

  unmarshalKmsMediaUriEndPointConstructorParams (uriEpParams, p->data);

  g_object_set (G_OBJECT (element), "uri", uriEpParams.uri.c_str(), NULL);
}

UriEndPoint::~UriEndPoint() throw ()
{

}

std::string
UriEndPoint::getUri ()
{
  char *uri_str;

  g_object_get (G_OBJECT (element), "uri", &uri_str, NULL);
  std::string uri (uri_str);
  g_free (uri_str);

  return uri;
}

void
UriEndPoint::start ()
{
  g_object_set (G_OBJECT (element), "state", 1 /* start */, NULL);
}

void
UriEndPoint::pause ()
{
  g_object_set (G_OBJECT (element), "state", 2 /* pause */, NULL);
}

void
UriEndPoint::stop ()
{
  g_object_set (G_OBJECT (element), "state", 0 /* stop */, NULL);
}

void
UriEndPoint::invoke (KmsMediaInvocationReturn &_return,
                     const std::string &command,
                     const std::map<std::string, KmsMediaParam> &params)
throw (KmsMediaServerException)
{
  if (g_KmsMediaUriEndPointType_constants.GET_URI.compare (command) == 0) {
    createStringInvocationReturn (_return, getUri () );
  } else if (g_KmsMediaUriEndPointType_constants.START.compare (command) == 0) {
    start ();
    createVoidInvocationReturn (_return);
  } else if (g_KmsMediaUriEndPointType_constants.PAUSE.compare (command) == 0) {
    pause ();
    createVoidInvocationReturn (_return);
  } else if (g_KmsMediaUriEndPointType_constants.STOP.compare (command) == 0) {
    stop ();
    createVoidInvocationReturn (_return);
  } else {
    EndPoint::invoke (_return, command, params);
  }
}

UriEndPoint::StaticConstructor UriEndPoint::staticConstructor;

UriEndPoint::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} // kurento
<commit_msg>UriEndPoint: Remove magic numbers<commit_after>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "UriEndPoint.hpp"

#include "KmsMediaUriEndPointType_constants.h"
#include "KmsMediaErrorCodes_constants.h"

#include "utils/utils.hpp"
#include "utils/marshalling.hpp"

#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"

#define GST_CAT_DEFAULT kurento_uri_end_point
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoUriEndPoint"

using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;

namespace kurento
{

typedef enum {
  KMS_URI_END_POINT_STATE_STOP,
  KMS_URI_END_POINT_STATE_START,
  KMS_URI_END_POINT_STATE_PAUSE
} KmsUriEndPointState;

UriEndPoint::UriEndPoint (MediaSet &mediaSet,
                          std::shared_ptr<MediaPipeline> parent,
                          const std::string &type,
                          const std::map<std::string, KmsMediaParam> &params,
                          const std::string &factoryName)
throw (KmsMediaServerException)
  : EndPoint (mediaSet, parent, type, params, factoryName)
{
  KmsMediaUriEndPointConstructorParams uriEpParams;
  const KmsMediaParam *p;

  p = getParam (params,
                g_KmsMediaUriEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);

  if (p == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except,
                                   g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_ILLEGAL_PARAM_ERROR,
                                   "Param '" + g_KmsMediaUriEndPointType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE +
                                   "' not found");
    throw except;
  }

  unmarshalKmsMediaUriEndPointConstructorParams (uriEpParams, p->data);

  g_object_set (G_OBJECT (element), "uri", uriEpParams.uri.c_str(), NULL);
}

UriEndPoint::~UriEndPoint() throw ()
{

}

std::string
UriEndPoint::getUri ()
{
  char *uri_str;

  g_object_get (G_OBJECT (element), "uri", &uri_str, NULL);
  std::string uri (uri_str);
  g_free (uri_str);

  return uri;
}

void
UriEndPoint::start ()
{
  g_object_set (G_OBJECT (element), "state", KMS_URI_END_POINT_STATE_START, NULL);
}

void
UriEndPoint::pause ()
{
  g_object_set (G_OBJECT (element), "state", KMS_URI_END_POINT_STATE_PAUSE, NULL);
}

void
UriEndPoint::stop ()
{
  g_object_set (G_OBJECT (element), "state", KMS_URI_END_POINT_STATE_STOP, NULL);
}

void
UriEndPoint::invoke (KmsMediaInvocationReturn &_return,
                     const std::string &command,
                     const std::map<std::string, KmsMediaParam> &params)
throw (KmsMediaServerException)
{
  if (g_KmsMediaUriEndPointType_constants.GET_URI.compare (command) == 0) {
    createStringInvocationReturn (_return, getUri () );
  } else if (g_KmsMediaUriEndPointType_constants.START.compare (command) == 0) {
    start ();
    createVoidInvocationReturn (_return);
  } else if (g_KmsMediaUriEndPointType_constants.PAUSE.compare (command) == 0) {
    pause ();
    createVoidInvocationReturn (_return);
  } else if (g_KmsMediaUriEndPointType_constants.STOP.compare (command) == 0) {
    stop ();
    createVoidInvocationReturn (_return);
  } else {
    EndPoint::invoke (_return, command, params);
  }
}

UriEndPoint::StaticConstructor UriEndPoint::staticConstructor;

UriEndPoint::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} // kurento
<|endoftext|>


<commit_before>// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"

#include "vm/isolate.h"
#include "vm/object.h"
#include "vm/regexp.h"
#include "vm/unit_test.h"

namespace dart {

static RawArray* Match(const String& pat, const String& str) {
  Isolate* isolate = Isolate::Current();
  const JSRegExp& regexp = JSRegExp::Handle(
      RegExpEngine::CreateJSRegExp(isolate, pat, false, false));
  const intptr_t cid = str.GetClassId();
  const Function& fn = Function::Handle(regexp.function(cid));
  EXPECT(!fn.IsNull());
  const Smi& idx = Smi::Handle(Smi::New(0));
  return IRRegExpMacroAssembler::Execute(fn, str, idx, Isolate::Current());
}

TEST_CASE(RegExp_OneByteString) {
  uint8_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      OneByteString::New(chars, len, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_TwoByteString) {
  uint16_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      TwoByteString::New(chars, len, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_ExternalOneByteString) {
  uint8_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      ExternalOneByteString::New(chars, len, NULL, NULL, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_ExternalTwoByteString) {
  uint16_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      ExternalTwoByteString::New(chars, len, NULL, NULL, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

}  // namespace dart
<commit_msg>Disable RegExp tests when using JSCRE backend.<commit_after>// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"

#include "vm/isolate.h"
#include "vm/object.h"
#include "vm/regexp.h"
#include "vm/unit_test.h"

namespace dart {

DECLARE_FLAG(bool, use_jscre);

static RawArray* Match(const String& pat, const String& str) {
  Isolate* isolate = Isolate::Current();
  const JSRegExp& regexp = JSRegExp::Handle(
      RegExpEngine::CreateJSRegExp(isolate, pat, false, false));
  const intptr_t cid = str.GetClassId();
  const Function& fn = Function::Handle(regexp.function(cid));
  EXPECT(!fn.IsNull());
  const Smi& idx = Smi::Handle(Smi::New(0));
  return IRRegExpMacroAssembler::Execute(fn, str, idx, Isolate::Current());
}

TEST_CASE(RegExp_OneByteString) {
  if (FLAG_use_jscre)
    return;

  uint8_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      OneByteString::New(chars, len, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_TwoByteString) {
  if (FLAG_use_jscre)
    return;

  uint16_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      TwoByteString::New(chars, len, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_ExternalOneByteString) {
  if (FLAG_use_jscre)
    return;

  uint8_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      ExternalOneByteString::New(chars, len, NULL, NULL, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

TEST_CASE(RegExp_ExternalTwoByteString) {
  if (FLAG_use_jscre)
    return;

  uint16_t chars[] = { 'a', 'b', 'c', 'b', 'a' };
  intptr_t len = ARRAY_SIZE(chars);
  const String& str = String::Handle(
      ExternalTwoByteString::New(chars, len, NULL, NULL, Heap::kNew));

  const String& pat = String::Handle(String::New("bc"));
  const Array& res = Array::Handle(Match(pat, str));
  EXPECT_EQ(2, res.Length());

  const Object& res_1 = Object::Handle(res.At(0));
  const Object& res_2 = Object::Handle(res.At(1));
  EXPECT(res_1.IsSmi());
  EXPECT(res_2.IsSmi());

  const Smi& smi_1 = Smi::Cast(res_1);
  const Smi& smi_2 = Smi::Cast(res_2);
  EXPECT_EQ(1, smi_1.Value());
  EXPECT_EQ(3, smi_2.Value());
}

}  // namespace dart
<|endoftext|>


<commit_before><commit_msg>fdo#83529: Only preserve metadata of moved, not copied files<commit_after><|endoftext|>