#include "clang/AST/ExprCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
using namespace clang;
using namespace sema;
static void removeLValueToRValueCast(Expr *E) {
Expr *Parent = E;
Expr *ExprUnderCast = nullptr;
SmallVector<Expr *, 8> ParentsToUpdate;
while (true) {
ParentsToUpdate.push_back(Parent);
if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
Parent = ParenE->getSubExpr();
continue;
}
Expr *Child = nullptr;
CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
if (ParentCast)
Child = ParentCast->getSubExpr();
else
return;
if (auto *CastE = dyn_cast<CastExpr>(Child))
if (CastE->getCastKind() == CK_LValueToRValue) {
ExprUnderCast = CastE->getSubExpr();
ParentCast->setSubExpr(ExprUnderCast);
break;
}
Parent = Child;
}
assert(ExprUnderCast &&
"Should be reachable only if LValueToRValue cast was found!");
auto ValueKind = ExprUnderCast->getValueKind();
for (Expr *E : ParentsToUpdate)
E->setValueKind(ValueKind);
}
static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
Sema &S) {
if (!S.getLangOpts().HeinousExtensions) {
S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
<< BadArgument->getSourceRange();
} else {
S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
<< BadArgument->getSourceRange();
}
removeLValueToRValueCast(BadArgument);
}
static bool CheckAsmLValue(Expr *E, Sema &S) {
if (E->isTypeDependent())
return false;
if (E->isLValue())
return false;
const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
if (E != E2 && E2->isLValue()) {
emitAndFixInvalidAsmCastLValue(E2, E, S);
return false;
}
return true;
}
static bool
isOperandMentioned(unsigned OpNo,
ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
if (!Piece.isOperand())
continue;
if (Piece.getOperandNo() == OpNo)
return true;
}
return false;
}
static bool CheckNakedParmReference(Expr *E, Sema &S) {
FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
if (!Func)
return false;
if (!Func->hasAttr<NakedAttr>())
return false;
SmallVector<Expr*, 4> WorkList;
WorkList.push_back(E);
while (WorkList.size()) {
Expr *E = WorkList.pop_back_val();
if (isa<CXXThisExpr>(E)) {
S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (isa<ParmVarDecl>(DRE->getDecl())) {
S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
}
for (Stmt *Child : E->children()) {
if (Expr *E = dyn_cast_or_null<Expr>(Child))
WorkList.push_back(E);
}
}
return false;
}
static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
TargetInfo::ConstraintInfo &Info,
bool is_input_expr) {
enum {
ExprBitfield = 0,
ExprVectorElt,
ExprGlobalRegVar,
ExprSafeType
} EType = ExprSafeType;
if (E->refersToBitField())
EType = ExprBitfield;
else if (E->refersToVectorElement())
EType = ExprVectorElt;
else if (E->refersToGlobalRegisterVar())
EType = ExprGlobalRegVar;
if (EType != ExprSafeType) {
S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
<< EType << is_input_expr << Info.getConstraintStr()
<< E->getSourceRange();
return true;
}
return false;
}
static StringRef extractRegisterName(const Expr *Expression,
const TargetInfo &Target) {
Expression = Expression->IgnoreImpCasts();
if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
if (Variable && Variable->getStorageClass() == SC_Register) {
if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
if (Target.isValidGCCRegisterName(Attr->getLabel()))
return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
}
}
return "";
}
static SourceLocation
getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
StringLiteral **Clobbers, int NumClobbers,
unsigned NumLabels,
const TargetInfo &Target, ASTContext &Cont) {
llvm::StringSet<> InOutVars;
for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
StringRef Constraint = Constraints[i]->getString();
StringRef InOutReg = Target.getConstraintRegister(
Constraint, extractRegisterName(Exprs[i], Target));
if (InOutReg != "")
InOutVars.insert(InOutReg);
}
for (int i = 0; i < NumClobbers; ++i) {
StringRef Clobber = Clobbers[i]->getString();
if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
continue;
Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
if (InOutVars.count(Clobber))
return Clobbers[i]->getBeginLoc();
}
return SourceLocation();
}
StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg constraints, MultiExprArg Exprs,
Expr *asmString, MultiExprArg clobbers,
unsigned NumLabels,
SourceLocation RParenLoc) {
unsigned NumClobbers = clobbers.size();
StringLiteral **Constraints =
reinterpret_cast<StringLiteral**>(constraints.data());
StringLiteral *AsmString = cast<StringLiteral>(asmString);
StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
assert(AsmString->isOrdinary());
FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext());
llvm::StringMap<bool> FeatureMap;
Context.getFunctionFeatureMap(FeatureMap, FD);
for (unsigned i = 0; i != NumOutputs; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isOrdinary());
StringRef OutputName;
if (Names[i])
OutputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
targetDiag(Literal->getBeginLoc(),
diag::err_asm_invalid_output_constraint)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
Expr *OutputExpr = Exprs[i];
if (CheckNakedParmReference(OutputExpr, *this))
return StmtError();
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
return StmtError();
if (OutputExpr->getType()->isBitIntType())
return StmtError(
Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_type)
<< OutputExpr->getType() << 0
<< OutputExpr->getSourceRange());
OutputConstraintInfos.push_back(Info);
if (OutputExpr->isTypeDependent())
continue;
Expr::isModifiableLvalueResult IsLV =
OutputExpr->isModifiableLvalue(Context, nullptr);
switch (IsLV) {
case Expr::MLV_Valid:
break;
case Expr::MLV_ArrayType:
break;
case Expr::MLV_LValueCast: {
const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
break;
}
case Expr::MLV_IncompleteType:
case Expr::MLV_IncompleteVoidType:
if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
LLVM_FALLTHROUGH;
default:
return StmtError(Diag(OutputExpr->getBeginLoc(),
diag::err_asm_invalid_lvalue_in_output)
<< OutputExpr->getSourceRange());
}
unsigned Size = Context.getTypeSize(OutputExpr->getType());
if (!Context.getTargetInfo().validateOutputSize(
FeatureMap, Literal->getString(), Size)) {
targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
}
SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isOrdinary());
StringRef InputName;
if (Names[i])
InputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
Info)) {
targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
<< Info.getConstraintStr();
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
Expr *InputExpr = Exprs[i];
if (CheckNakedParmReference(InputExpr, *this))
return StmtError();
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
return StmtError();
if (Info.allowsMemory() && !Info.allowsRegister()) {
if (CheckAsmLValue(InputExpr, *this))
return StmtError(Diag(InputExpr->getBeginLoc(),
diag::err_asm_invalid_lvalue_in_input)
<< Info.getConstraintStr()
<< InputExpr->getSourceRange());
} else {
ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
if (Result.isInvalid())
return StmtError();
InputExpr = Exprs[i] = Result.get();
if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
if (!InputExpr->isValueDependent()) {
Expr::EvalResult EVResult;
if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
llvm::APSInt IntResult;
if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
Context))
if (!Info.isValidAsmImmediate(IntResult))
return StmtError(
Diag(InputExpr->getBeginLoc(),
diag::err_invalid_asm_value_for_constraint)
<< toString(IntResult, 10) << Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
}
}
}
if (Info.allowsRegister()) {
if (InputExpr->getType()->isVoidType()) {
return StmtError(
Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
<< InputExpr->getType() << Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
}
if (InputExpr->getType()->isBitIntType())
return StmtError(
Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type)
<< InputExpr->getType() << 1
<< InputExpr->getSourceRange());
InputConstraintInfos.push_back(Info);
const Type *Ty = Exprs[i]->getType().getTypePtr();
if (Ty->isDependentType())
continue;
if (!Ty->isVoidType() || !Info.allowsMemory())
if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
unsigned Size = Context.getTypeSize(Ty);
if (!Context.getTargetInfo().validateInputSize(FeatureMap,
Literal->getString(), Size))
return targetDiag(InputExpr->getBeginLoc(),
diag::err_asm_invalid_input_size)
<< Info.getConstraintStr();
}
Optional<SourceLocation> UnwindClobberLoc;
for (unsigned i = 0; i != NumClobbers; i++) {
StringLiteral *Literal = Clobbers[i];
assert(Literal->isOrdinary());
StringRef Clobber = Literal->getString();
if (!Context.getTargetInfo().isValidClobber(Clobber)) {
targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
<< Clobber;
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(), AsmString,
NumClobbers, Clobbers, NumLabels, RParenLoc);
}
if (Clobber == "unwind") {
UnwindClobberLoc = Literal->getBeginLoc();
}
}
if (UnwindClobberLoc && NumLabels > 0) {
targetDiag(*UnwindClobberLoc, diag::err_asm_unwind_and_goto);
return new (Context)
GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
Names, Constraints, Exprs.data(), AsmString, NumClobbers,
Clobbers, NumLabels, RParenLoc);
}
GCCAsmStmt *NS =
new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(),
AsmString, NumClobbers, Clobbers, NumLabels,
RParenLoc);
SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
unsigned DiagOffs;
if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
<< AsmString->getSourceRange();
return NS;
}
for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
if (!Piece.isOperand()) continue;
unsigned ConstraintIdx = Piece.getOperandNo();
unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
continue;
if (ConstraintIdx >= NumOperands) {
unsigned I = 0, E = NS->getNumOutputs();
for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
ConstraintIdx = I;
break;
}
assert(I != E && "Invalid operand number should have been caught in "
" AnalyzeAsmString");
}
StringLiteral *Literal = Constraints[ConstraintIdx];
const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
if (Ty->isDependentType() || Ty->isIncompleteType())
continue;
unsigned Size = Context.getTypeSize(Ty);
std::string SuggestedModifier;
if (!Context.getTargetInfo().validateConstraintModifier(
Literal->getString(), Piece.getModifier(), Size,
SuggestedModifier)) {
targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
diag::warn_asm_mismatched_size_modifier);
if (!SuggestedModifier.empty()) {
auto B = targetDiag(Piece.getRange().getBegin(),
diag::note_asm_missing_constraint_modifier)
<< SuggestedModifier;
SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
}
}
}
unsigned NumAlternatives = ~0U;
for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U) {
NumAlternatives = AltCount;
} else if (NumAlternatives != AltCount) {
targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount;
return NS;
}
}
SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
~0U);
for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U) {
NumAlternatives = AltCount;
} else if (NumAlternatives != AltCount) {
targetDiag(NS->getInputExpr(i)->getBeginLoc(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount;
return NS;
}
if (!Info.hasTiedOperand()) continue;
unsigned TiedTo = Info.getTiedOperand();
unsigned InputOpNo = i+NumOutputs;
Expr *OutputExpr = Exprs[TiedTo];
Expr *InputExpr = Exprs[InputOpNo];
assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
if (InputMatchedToOutput[TiedTo] != ~0U) {
targetDiag(NS->getInputExpr(i)->getBeginLoc(),
diag::err_asm_input_duplicate_match)
<< TiedTo;
targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
diag::note_asm_input_duplicate_first)
<< TiedTo;
return NS;
}
InputMatchedToOutput[TiedTo] = i;
if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
continue;
QualType InTy = InputExpr->getType();
QualType OutTy = OutputExpr->getType();
if (Context.hasSameType(InTy, OutTy))
continue;
enum AsmDomain {
AD_Int, AD_FP, AD_Other
} InputDomain, OutputDomain;
if (InTy->isIntegerType() || InTy->isPointerType())
InputDomain = AD_Int;
else if (InTy->isRealFloatingType())
InputDomain = AD_FP;
else
InputDomain = AD_Other;
if (OutTy->isIntegerType() || OutTy->isPointerType())
OutputDomain = AD_Int;
else if (OutTy->isRealFloatingType())
OutputDomain = AD_FP;
else
OutputDomain = AD_Other;
uint64_t OutSize = Context.getTypeSize(OutTy);
uint64_t InSize = Context.getTypeSize(InTy);
if (OutSize == InSize && InputDomain == OutputDomain &&
InputDomain != AD_Other)
continue;
bool SmallerValueMentioned = false;
if (isOperandMentioned(InputOpNo, Pieces)) {
SmallerValueMentioned |= InSize < OutSize;
}
if (isOperandMentioned(TiedTo, Pieces)) {
SmallerValueMentioned |= OutSize < InSize;
}
if (!SmallerValueMentioned && InputDomain != AD_Other &&
OutputConstraintInfos[TiedTo].allowsRegister()) {
if (OutTy->isStructureType() &&
Context.getIntTypeForBitwidth(OutSize, false).isNull()) {
targetDiag(OutputExpr->getExprLoc(), diag::err_store_value_to_reg);
return NS;
}
continue;
}
if (InputDomain == AD_Int && OutputDomain == AD_Int &&
!isOperandMentioned(InputOpNo, Pieces) &&
InputExpr->isEvaluatable(Context)) {
CastKind castKind =
(OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Exprs[InputOpNo] = InputExpr;
NS->setInputExpr(i, InputExpr);
continue;
}
targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
<< InTy << OutTy << OutputExpr->getSourceRange()
<< InputExpr->getSourceRange();
return NS;
}
SourceLocation ConstraintLoc =
getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
NumLabels,
Context.getTargetInfo(), Context);
if (ConstraintLoc.isValid())
targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
typedef std::pair<StringRef , Expr *> NamedOperand;
SmallVector<NamedOperand, 4> NamedOperandList;
for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
if (Names[i])
NamedOperandList.emplace_back(
std::make_pair(Names[i]->getName(), Exprs[i]));
llvm::stable_sort(NamedOperandList, llvm::less_first());
SmallVector<NamedOperand, 4>::iterator Found =
std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
[](const NamedOperand &LHS, const NamedOperand &RHS) {
return LHS.first == RHS.first;
});
if (Found != NamedOperandList.end()) {
Diag((Found + 1)->second->getBeginLoc(),
diag::error_duplicate_asm_operand_name)
<< (Found + 1)->first;
Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
<< Found->first;
return StmtError();
}
if (NS->isAsmGoto())
setFunctionHasBranchIntoScope();
CleanupVarDeclMarking();
DiscardCleanupsInEvaluationContext();
return NS;
}
void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info) {
QualType T = Res->getType();
Expr::EvalResult Eval;
if (T->isFunctionType() || T->isDependentType())
return Info.setLabel(Res);
if (Res->isPRValue()) {
bool IsEnum = isa<clang::EnumType>(T);
if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res))
if (DRE->getDecl()->getKind() == Decl::EnumConstant)
IsEnum = true;
if (IsEnum && Res->EvaluateAsRValue(Eval, Context))
return Info.setEnum(Eval.Val.getInt().getSExtValue());
return Info.setLabel(Res);
}
unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
unsigned Type = Size;
if (const auto *ATy = Context.getAsArrayType(T))
Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
bool IsGlobalLV = false;
if (Res->EvaluateAsLValue(Eval, Context))
IsGlobalLV = Eval.isGlobalLValue();
Info.setVar(Res, IsGlobalLV, Size, Type);
}
ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext) {
if (IsUnevaluatedContext)
PushExpressionEvaluationContext(
ExpressionEvaluationContext::UnevaluatedAbstract,
ReuseLambdaContextDecl);
ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
false,
false,
nullptr,
true);
if (IsUnevaluatedContext)
PopExpressionEvaluationContext();
if (!Result.isUsable()) return Result;
Result = CheckPlaceholderExpr(Result.get());
if (!Result.isUsable()) return Result;
if (CheckNakedParmReference(Result.get(), *this))
return ExprError();
QualType T = Result.get()->getType();
if (T->isDependentType()) {
return Result;
}
if (T->isFunctionType()) {
return Result;
}
if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
return ExprError();
}
return Result;
}
bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc) {
Offset = 0;
SmallVector<StringRef, 2> Members;
Member.split(Members, ".");
NamedDecl *FoundDecl = nullptr;
if (getLangOpts().CPlusPlus && Base.equals("this")) {
if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
FoundDecl = PT->getPointeeType()->getAsTagDecl();
} else {
LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
LookupOrdinaryName);
if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
FoundDecl = BaseResult.getFoundDecl();
}
if (!FoundDecl)
return true;
for (StringRef NextMember : Members) {
const RecordType *RT = nullptr;
if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
RT = VD->getType()->getAs<RecordType>();
else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
MarkAnyDeclReferenced(TD->getLocation(), TD, false);
QualType QT = TD->getUnderlyingType();
if (const auto *PT = QT->getAs<PointerType>())
QT = PT->getPointeeType();
RT = QT->getAs<RecordType>();
} else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
RT = TD->getTypeForDecl()->getAs<RecordType>();
else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
RT = TD->getType()->getAs<RecordType>();
if (!RT)
return true;
if (RequireCompleteType(AsmLoc, QualType(RT, 0),
diag::err_asm_incomplete_type))
return true;
LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
SourceLocation(), LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return true;
if (!FieldResult.isSingleResult())
return true;
FoundDecl = FieldResult.getFoundDecl();
FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
if (!FD)
return true;
const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
unsigned i = FD->getFieldIndex();
CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
Offset += (unsigned)Result.getQuantity();
}
return false;
}
ExprResult
Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
SourceLocation AsmLoc) {
QualType T = E->getType();
if (T->isDependentType()) {
DeclarationNameInfo NameInfo;
NameInfo.setLoc(AsmLoc);
NameInfo.setName(&Context.Idents.get(Member));
return CXXDependentScopeMemberExpr::Create(
Context, E, T, false, AsmLoc, NestedNameSpecifierLoc(),
SourceLocation(),
nullptr, NameInfo, nullptr);
}
const RecordType *RT = T->getAs<RecordType>();
if (!RT)
return ExprResult();
LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return ExprResult();
ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
if (!FD)
FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
if (!FD)
return ExprResult();
ExprResult Result = BuildMemberReferenceExpr(
E, E->getType(), AsmLoc, false, CXXScopeSpec(),
SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
return Result;
}
StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc) {
bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
setFunctionHasBranchProtectedScope();
for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
if (Exprs[I]->getType()->isBitIntType())
return StmtError(
Diag(Exprs[I]->getBeginLoc(), diag::err_asm_invalid_type)
<< Exprs[I]->getType() << (I < NumOutputs)
<< Exprs[I]->getSourceRange());
}
MSAsmStmt *NS =
new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
true, AsmToks, NumOutputs, NumInputs,
Constraints, Exprs, AsmString,
Clobbers, EndLoc);
return NS;
}
LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate) {
LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
Location);
if (Label->isMSAsmLabel()) {
Label->markUsed(Context);
} else {
std::string InternalName;
llvm::raw_string_ostream OS(InternalName);
OS << "__MSASMLABEL_.${:uid}__";
for (char C : ExternalLabelName) {
OS << C;
if (C == '$')
OS << '$';
}
Label->setMSAsmLabel(OS.str());
}
if (AlwaysCreate) {
Label->setMSAsmLabelResolved();
}
Label->setLocation(Location);
return Label;
}