blob: 9b051e02d1275a28faf6f8d08a7a3ce1bff887fb [file] [log] [blame]
Chad Rosier571c5e92012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier0731aff2012-08-17 21:19:40 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chad Rosier0731aff2012-08-17 21:19:40 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for inline asm statements.
10//
11//===----------------------------------------------------------------------===//
12
Weiming Zhao71ac2402015-02-03 22:35:58 +000013#include "clang/AST/ExprCXX.h"
Chad Rosier5c563642012-10-25 21:49:22 +000014#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000015#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000016#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000017#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Scope.h"
21#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000022#include "clang/Sema/SemaInternal.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000023#include "llvm/ADT/ArrayRef.h"
Marina Yatsinac42fd032016-12-26 12:23:42 +000024#include "llvm/ADT/StringSet.h"
Alp Toker10399272014-06-08 05:11:37 +000025#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000026using namespace clang;
27using namespace sema;
28
Aleksei Sidorin55365e42018-10-20 22:49:23 +000029/// Remove the upper-level LValueToRValue cast from an expression.
30static void removeLValueToRValueCast(Expr *E) {
31 Expr *Parent = E;
32 Expr *ExprUnderCast = nullptr;
33 SmallVector<Expr *, 8> ParentsToUpdate;
34
35 while (true) {
36 ParentsToUpdate.push_back(Parent);
37 if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
38 Parent = ParenE->getSubExpr();
39 continue;
40 }
41
42 Expr *Child = nullptr;
43 CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
44 if (ParentCast)
45 Child = ParentCast->getSubExpr();
46 else
47 return;
48
49 if (auto *CastE = dyn_cast<CastExpr>(Child))
50 if (CastE->getCastKind() == CK_LValueToRValue) {
51 ExprUnderCast = CastE->getSubExpr();
52 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
53 ParentCast->setSubExpr(ExprUnderCast);
54 break;
55 }
56 Parent = Child;
57 }
58
59 // Update parent expressions to have same ValueType as the underlying.
60 assert(ExprUnderCast &&
61 "Should be reachable only if LValueToRValue cast was found!");
62 auto ValueKind = ExprUnderCast->getValueKind();
63 for (Expr *E : ParentsToUpdate)
64 E->setValueKind(ValueKind);
65}
66
67/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
68/// and fix the argument with removing LValueToRValue cast from the expression.
69static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
70 Sema &S) {
71 if (!S.getLangOpts().HeinousExtensions) {
72 S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
73 << BadArgument->getSourceRange();
74 } else {
75 S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
76 << BadArgument->getSourceRange();
77 }
78 removeLValueToRValueCast(BadArgument);
79}
80
Chad Rosier0731aff2012-08-17 21:19:40 +000081/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
82/// ignore "noop" casts in places where an lvalue is required by an inline asm.
83/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
84/// provide a strong guidance to not use it.
85///
86/// This method checks to see if the argument is an acceptable l-value and
87/// returns false if it is a case we can handle.
Aleksei Sidorin55365e42018-10-20 22:49:23 +000088static bool CheckAsmLValue(Expr *E, Sema &S) {
Chad Rosier0731aff2012-08-17 21:19:40 +000089 // Type dependent expressions will be checked during instantiation.
90 if (E->isTypeDependent())
91 return false;
92
93 if (E->isLValue())
94 return false; // Cool, this is an lvalue.
95
96 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
97 // are supposed to allow.
98 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
99 if (E != E2 && E2->isLValue()) {
Aleksei Sidorin55365e42018-10-20 22:49:23 +0000100 emitAndFixInvalidAsmCastLValue(E2, E, S);
Chad Rosier0731aff2012-08-17 21:19:40 +0000101 // Accept, even if we emitted an error diagnostic.
102 return false;
103 }
104
105 // None of the above, just randomly invalid non-lvalue.
106 return true;
107}
108
109/// isOperandMentioned - Return true if the specified operand # is mentioned
110/// anywhere in the decomposed asm string.
Coby Tayree18f92182017-09-10 12:39:21 +0000111static bool
112isOperandMentioned(unsigned OpNo,
113 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000114 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +0000115 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Coby Tayree18f92182017-09-10 12:39:21 +0000116 if (!Piece.isOperand())
117 continue;
Chad Rosier0731aff2012-08-17 21:19:40 +0000118
119 // If this is a reference to the input and if the input was the smaller
120 // one, then we have to reject this asm.
121 if (Piece.getOperandNo() == OpNo)
122 return true;
123 }
124 return false;
125}
126
Hans Wennborge9d240a2014-10-08 01:58:02 +0000127static bool CheckNakedParmReference(Expr *E, Sema &S) {
128 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
129 if (!Func)
130 return false;
131 if (!Func->hasAttr<NakedAttr>())
132 return false;
133
134 SmallVector<Expr*, 4> WorkList;
135 WorkList.push_back(E);
136 while (WorkList.size()) {
137 Expr *E = WorkList.pop_back_val();
Weiming Zhao71ac2402015-02-03 22:35:58 +0000138 if (isa<CXXThisExpr>(E)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000139 S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
Weiming Zhao71ac2402015-02-03 22:35:58 +0000140 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
141 return true;
142 }
Hans Wennborge9d240a2014-10-08 01:58:02 +0000143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
144 if (isa<ParmVarDecl>(DRE->getDecl())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000145 S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
Hans Wennborge9d240a2014-10-08 01:58:02 +0000146 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
147 return true;
148 }
149 }
150 for (Stmt *Child : E->children()) {
151 if (Expr *E = dyn_cast_or_null<Expr>(Child))
152 WorkList.push_back(E);
153 }
154 }
155 return false;
156}
157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000158/// Returns true if given expression is not compatible with inline
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000159/// assembly's memory constraint; false otherwise.
160static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
161 TargetInfo::ConstraintInfo &Info,
162 bool is_input_expr) {
163 enum {
164 ExprBitfield = 0,
165 ExprVectorElt,
166 ExprGlobalRegVar,
167 ExprSafeType
168 } EType = ExprSafeType;
169
170 // Bitfields, vector elements and global register variables are not
171 // compatible.
172 if (E->refersToBitField())
173 EType = ExprBitfield;
174 else if (E->refersToVectorElement())
175 EType = ExprVectorElt;
176 else if (E->refersToGlobalRegisterVar())
177 EType = ExprGlobalRegVar;
178
179 if (EType != ExprSafeType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000180 S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000181 << EType << is_input_expr << Info.getConstraintStr()
182 << E->getSourceRange();
183 return true;
184 }
185
186 return false;
187}
188
Marina Yatsinac42fd032016-12-26 12:23:42 +0000189// Extracting the register name from the Expression value,
190// if there is no register name to extract, returns ""
191static StringRef extractRegisterName(const Expr *Expression,
192 const TargetInfo &Target) {
193 Expression = Expression->IgnoreImpCasts();
194 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
195 // Handle cases where the expression is a variable
196 const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
197 if (Variable && Variable->getStorageClass() == SC_Register) {
198 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
199 if (Target.isValidGCCRegisterName(Attr->getLabel()))
200 return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
201 }
202 }
203 return "";
204}
205
206// Checks if there is a conflict between the input and output lists with the
207// clobbers list. If there's a conflict, returns the location of the
208// conflicted clobber, else returns nullptr
209static SourceLocation
210getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
211 StringLiteral **Clobbers, int NumClobbers,
Jennifer Yub8fee672019-06-03 15:57:25 +0000212 unsigned NumLabels,
Marina Yatsinac42fd032016-12-26 12:23:42 +0000213 const TargetInfo &Target, ASTContext &Cont) {
214 llvm::StringSet<> InOutVars;
215 // Collect all the input and output registers from the extended asm
Marina Yatsinac5cf7a82016-12-26 13:16:40 +0000216 // statement in order to check for conflicts with the clobber list
Jennifer Yub8fee672019-06-03 15:57:25 +0000217 for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
Marina Yatsinac42fd032016-12-26 12:23:42 +0000218 StringRef Constraint = Constraints[i]->getString();
219 StringRef InOutReg = Target.getConstraintRegister(
220 Constraint, extractRegisterName(Exprs[i], Target));
221 if (InOutReg != "")
222 InOutVars.insert(InOutReg);
223 }
224 // Check for each item in the clobber list if it conflicts with the input
225 // or output
226 for (int i = 0; i < NumClobbers; ++i) {
227 StringRef Clobber = Clobbers[i]->getString();
228 // We only check registers, therefore we don't check cc and memory
229 // clobbers
230 if (Clobber == "cc" || Clobber == "memory")
231 continue;
232 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
233 // Go over the output's registers we collected
234 if (InOutVars.count(Clobber))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000235 return Clobbers[i]->getBeginLoc();
Marina Yatsinac42fd032016-12-26 12:23:42 +0000236 }
237 return SourceLocation();
238}
239
Chad Rosierde70e0e2012-08-25 00:11:56 +0000240StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
241 bool IsVolatile, unsigned NumOutputs,
242 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000243 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000244 Expr *asmString, MultiExprArg clobbers,
Jennifer Yub8fee672019-06-03 15:57:25 +0000245 unsigned NumLabels,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000246 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000247 unsigned NumClobbers = clobbers.size();
248 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000249 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000250 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000251 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000252
253 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
254
255 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000256 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000257
258 for (unsigned i = 0; i != NumOutputs; i++) {
259 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000260 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000261
262 StringRef OutputName;
263 if (Names[i])
264 OutputName = Names[i]->getName();
265
266 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Alexey Bataev305b6b92019-02-26 21:51:16 +0000267 if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
268 targetDiag(Literal->getBeginLoc(),
269 diag::err_asm_invalid_output_constraint)
270 << Info.getConstraintStr();
271 return new (Context)
272 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
273 NumInputs, Names, Constraints, Exprs.data(), AsmString,
Jennifer Yub8fee672019-06-03 15:57:25 +0000274 NumClobbers, Clobbers, NumLabels, RParenLoc);
Alexey Bataev305b6b92019-02-26 21:51:16 +0000275 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000276
David Majnemer0f4d6412014-12-29 09:30:33 +0000277 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
278 if (ER.isInvalid())
279 return StmtError();
280 Exprs[i] = ER.get();
281
Chad Rosier0731aff2012-08-17 21:19:40 +0000282 // Check that the output exprs are valid lvalues.
283 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000284
Hans Wennborge9d240a2014-10-08 01:58:02 +0000285 // Referring to parameters is not allowed in naked functions.
286 if (CheckNakedParmReference(OutputExpr, *this))
287 return StmtError();
288
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000289 // Check that the output expression is compatible with memory constraint.
290 if (Info.allowsMemory() &&
291 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
292 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000293
Chad Rosier0731aff2012-08-17 21:19:40 +0000294 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000295
David Majnemer0f4d6412014-12-29 09:30:33 +0000296 // If this is dependent, just continue.
297 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000298 continue;
299
David Majnemer0f4d6412014-12-29 09:30:33 +0000300 Expr::isModifiableLvalueResult IsLV =
301 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
302 switch (IsLV) {
303 case Expr::MLV_Valid:
304 // Cool, this is an lvalue.
305 break;
David Majnemer04b78412014-12-29 10:29:53 +0000306 case Expr::MLV_ArrayType:
307 // This is OK too.
308 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000309 case Expr::MLV_LValueCast: {
310 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
Aleksei Sidorin55365e42018-10-20 22:49:23 +0000311 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
David Majnemer0f4d6412014-12-29 09:30:33 +0000312 // Accept, even if we emitted an error diagnostic.
313 break;
314 }
315 case Expr::MLV_IncompleteType:
316 case Expr::MLV_IncompleteVoidType:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000317 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
David Majnemer0f4d6412014-12-29 09:30:33 +0000318 diag::err_dereference_incomplete_type))
319 return StmtError();
Galina Kistanova33399112017-06-03 06:35:06 +0000320 LLVM_FALLTHROUGH;
David Majnemer0f4d6412014-12-29 09:30:33 +0000321 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000322 return StmtError(Diag(OutputExpr->getBeginLoc(),
David Majnemer0f4d6412014-12-29 09:30:33 +0000323 diag::err_asm_invalid_lvalue_in_output)
324 << OutputExpr->getSourceRange());
325 }
326
327 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Alexey Bataev305b6b92019-02-26 21:51:16 +0000328 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
329 Size)) {
330 targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
331 << Info.getConstraintStr();
332 return new (Context)
333 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
334 NumInputs, Names, Constraints, Exprs.data(), AsmString,
Jennifer Yub8fee672019-06-03 15:57:25 +0000335 NumClobbers, Clobbers, NumLabels, RParenLoc);
Alexey Bataev305b6b92019-02-26 21:51:16 +0000336 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000337 }
338
339 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
340
341 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
342 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000343 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000344
345 StringRef InputName;
346 if (Names[i])
347 InputName = Names[i]->getName();
348
349 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Craig Topper55765ca2015-10-21 02:34:10 +0000350 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
351 Info)) {
Alexey Bataev305b6b92019-02-26 21:51:16 +0000352 targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
353 << Info.getConstraintStr();
354 return new (Context)
355 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
356 NumInputs, Names, Constraints, Exprs.data(), AsmString,
Jennifer Yub8fee672019-06-03 15:57:25 +0000357 NumClobbers, Clobbers, NumLabels, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000358 }
359
David Majnemer0f4d6412014-12-29 09:30:33 +0000360 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
361 if (ER.isInvalid())
362 return StmtError();
363 Exprs[i] = ER.get();
364
Chad Rosier0731aff2012-08-17 21:19:40 +0000365 Expr *InputExpr = Exprs[i];
366
Hans Wennborge9d240a2014-10-08 01:58:02 +0000367 // Referring to parameters is not allowed in naked functions.
368 if (CheckNakedParmReference(InputExpr, *this))
369 return StmtError();
370
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000371 // Check that the input expression is compatible with memory constraint.
372 if (Info.allowsMemory() &&
373 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
374 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000375
Chad Rosier0731aff2012-08-17 21:19:40 +0000376 // Only allow void types for memory constraints.
377 if (Info.allowsMemory() && !Info.allowsRegister()) {
378 if (CheckAsmLValue(InputExpr, *this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000379 return StmtError(Diag(InputExpr->getBeginLoc(),
Chad Rosier0731aff2012-08-17 21:19:40 +0000380 diag::err_asm_invalid_lvalue_in_input)
381 << Info.getConstraintStr()
382 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000383 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
Sunil Srivastava780e5012015-07-14 18:08:50 +0000384 if (!InputExpr->isValueDependent()) {
Bill Wendling13381fb2018-12-19 04:36:42 +0000385 Expr::EvalResult EVResult;
Bill Wendlingce292912019-08-06 22:41:22 +0000386 if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
387 // For compatibility with GCC, we also allow pointers that would be
388 // integral constant expressions if they were cast to int.
389 llvm::APSInt IntResult;
390 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
391 Context))
392 if (!Info.isValidAsmImmediate(IntResult))
393 return StmtError(Diag(InputExpr->getBeginLoc(),
394 diag::err_invalid_asm_value_for_constraint)
395 << IntResult.toString(10)
396 << Info.getConstraintStr()
397 << InputExpr->getSourceRange());
398 }
Sunil Srivastava780e5012015-07-14 18:08:50 +0000399 }
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000400
David Majnemerade4bee2014-07-14 16:27:53 +0000401 } else {
402 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
403 if (Result.isInvalid())
404 return StmtError();
405
406 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000407 }
408
409 if (Info.allowsRegister()) {
410 if (InputExpr->getType()->isVoidType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000411 return StmtError(
412 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
413 << InputExpr->getType() << Info.getConstraintStr()
414 << InputExpr->getSourceRange());
Chad Rosier0731aff2012-08-17 21:19:40 +0000415 }
416 }
417
Chad Rosier0731aff2012-08-17 21:19:40 +0000418 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000419
420 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000421 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000422 continue;
423
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000424 if (!Ty->isVoidType() || !Info.allowsMemory())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000425 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
Bill Wendlingb68b7572013-03-27 06:06:26 +0000426 diag::err_dereference_incomplete_type))
427 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000428
Bill Wendling887b4852012-11-12 06:42:51 +0000429 unsigned Size = Context.getTypeSize(Ty);
430 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
431 Size))
Alexey Bataev5c96c1c2019-02-20 17:42:57 +0000432 return StmtResult(
433 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000434 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000435 }
436
437 // Check that the clobbers are valid.
438 for (unsigned i = 0; i != NumClobbers; i++) {
439 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000440 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000441
442 StringRef Clobber = Literal->getString();
443
Alexey Bataev305b6b92019-02-26 21:51:16 +0000444 if (!Context.getTargetInfo().isValidClobber(Clobber)) {
445 targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
446 << Clobber;
447 return new (Context)
448 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
449 NumInputs, Names, Constraints, Exprs.data(), AsmString,
Jennifer Yub8fee672019-06-03 15:57:25 +0000450 NumClobbers, Clobbers, NumLabels, RParenLoc);
Alexey Bataev305b6b92019-02-26 21:51:16 +0000451 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000452 }
453
Chad Rosierde70e0e2012-08-25 00:11:56 +0000454 GCCAsmStmt *NS =
455 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000456 NumInputs, Names, Constraints, Exprs.data(),
Jennifer Yub8fee672019-06-03 15:57:25 +0000457 AsmString, NumClobbers, Clobbers, NumLabels,
458 RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000459 // Validate the asm string, ensuring it makes sense given the operands we
460 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000461 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000462 unsigned DiagOffs;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000463 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
464 targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
465 << AsmString->getSourceRange();
466 return NS;
467 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000468
Bill Wendling9d1ee112012-10-25 23:28:48 +0000469 // Validate constraints and modifiers.
470 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
471 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
472 if (!Piece.isOperand()) continue;
473
474 // Look for the correct constraint index.
Akira Hatanaka96a36012015-02-04 00:27:13 +0000475 unsigned ConstraintIdx = Piece.getOperandNo();
Jennifer Yub8fee672019-06-03 15:57:25 +0000476 // Labels are the last in the Exprs list.
477 if (NS->isAsmGoto() && ConstraintIdx >= NS->getNumInputs())
478 continue;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000479 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Akira Hatanaka96a36012015-02-04 00:27:13 +0000480 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
481 // modifier '+'.
482 if (ConstraintIdx >= NumOperands) {
483 unsigned I = 0, E = NS->getNumOutputs();
484
485 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
486 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
487 ConstraintIdx = I;
Bill Wendling9d1ee112012-10-25 23:28:48 +0000488 break;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000489 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000490
Akira Hatanaka96a36012015-02-04 00:27:13 +0000491 assert(I != E && "Invalid operand number should have been caught in "
492 " AnalyzeAsmString");
Bill Wendling9d1ee112012-10-25 23:28:48 +0000493 }
494
495 // Now that we have the right indexes go ahead and check.
496 StringLiteral *Literal = Constraints[ConstraintIdx];
497 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
498 if (Ty->isDependentType() || Ty->isIncompleteType())
499 continue;
500
501 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000502 std::string SuggestedModifier;
503 if (!Context.getTargetInfo().validateConstraintModifier(
504 Literal->getString(), Piece.getModifier(), Size,
505 SuggestedModifier)) {
Alexey Bataev5c96c1c2019-02-20 17:42:57 +0000506 targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
507 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000508
509 if (!SuggestedModifier.empty()) {
Alexey Bataev5c96c1c2019-02-20 17:42:57 +0000510 auto B = targetDiag(Piece.getRange().getBegin(),
511 diag::note_asm_missing_constraint_modifier)
Akira Hatanaka987f1862014-08-22 06:05:21 +0000512 << SuggestedModifier;
513 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
Alexey Bataev5c96c1c2019-02-20 17:42:57 +0000514 B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000515 }
516 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000517 }
518
Chad Rosier0731aff2012-08-17 21:19:40 +0000519 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000520 unsigned NumAlternatives = ~0U;
521 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
522 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
523 StringRef ConstraintStr = Info.getConstraintStr();
524 unsigned AltCount = ConstraintStr.count(',') + 1;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000525 if (NumAlternatives == ~0U) {
David Majnemerc63fa612014-12-29 04:09:59 +0000526 NumAlternatives = AltCount;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000527 } else if (NumAlternatives != AltCount) {
528 targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
529 diag::err_asm_unexpected_constraint_alternatives)
530 << NumAlternatives << AltCount;
531 return NS;
532 }
David Majnemerc63fa612014-12-29 04:09:59 +0000533 }
Alexander Musman8e261be2015-09-21 14:41:00 +0000534 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
535 ~0U);
Chad Rosier0731aff2012-08-17 21:19:40 +0000536 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
537 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000538 StringRef ConstraintStr = Info.getConstraintStr();
539 unsigned AltCount = ConstraintStr.count(',') + 1;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000540 if (NumAlternatives == ~0U) {
David Majnemerc63fa612014-12-29 04:09:59 +0000541 NumAlternatives = AltCount;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000542 } else if (NumAlternatives != AltCount) {
543 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
544 diag::err_asm_unexpected_constraint_alternatives)
545 << NumAlternatives << AltCount;
546 return NS;
547 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000548
549 // If this is a tied constraint, verify that the output and input have
550 // either exactly the same type, or that they are int/ptr operands with the
551 // same size (int/long, int*/long, are ok etc).
552 if (!Info.hasTiedOperand()) continue;
553
554 unsigned TiedTo = Info.getTiedOperand();
555 unsigned InputOpNo = i+NumOutputs;
556 Expr *OutputExpr = Exprs[TiedTo];
557 Expr *InputExpr = Exprs[InputOpNo];
558
Alexander Musman8e261be2015-09-21 14:41:00 +0000559 // Make sure no more than one input constraint matches each output.
560 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
561 if (InputMatchedToOutput[TiedTo] != ~0U) {
Alexey Bataev5c96c1c2019-02-20 17:42:57 +0000562 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
563 diag::err_asm_input_duplicate_match)
Alexander Musman8e261be2015-09-21 14:41:00 +0000564 << TiedTo;
Alexey Bataev305b6b92019-02-26 21:51:16 +0000565 targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
566 diag::note_asm_input_duplicate_first)
567 << TiedTo;
568 return NS;
Alexander Musman8e261be2015-09-21 14:41:00 +0000569 }
570 InputMatchedToOutput[TiedTo] = i;
571
Chad Rosier0731aff2012-08-17 21:19:40 +0000572 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
573 continue;
574
575 QualType InTy = InputExpr->getType();
576 QualType OutTy = OutputExpr->getType();
577 if (Context.hasSameType(InTy, OutTy))
578 continue; // All types can be tied to themselves.
579
580 // Decide if the input and output are in the same domain (integer/ptr or
581 // floating point.
582 enum AsmDomain {
583 AD_Int, AD_FP, AD_Other
584 } InputDomain, OutputDomain;
585
586 if (InTy->isIntegerType() || InTy->isPointerType())
587 InputDomain = AD_Int;
588 else if (InTy->isRealFloatingType())
589 InputDomain = AD_FP;
590 else
591 InputDomain = AD_Other;
592
593 if (OutTy->isIntegerType() || OutTy->isPointerType())
594 OutputDomain = AD_Int;
595 else if (OutTy->isRealFloatingType())
596 OutputDomain = AD_FP;
597 else
598 OutputDomain = AD_Other;
599
600 // They are ok if they are the same size and in the same domain. This
601 // allows tying things like:
602 // void* to int*
603 // void* to int if they are the same size.
604 // double to long double if they are the same size.
605 //
606 uint64_t OutSize = Context.getTypeSize(OutTy);
607 uint64_t InSize = Context.getTypeSize(InTy);
608 if (OutSize == InSize && InputDomain == OutputDomain &&
609 InputDomain != AD_Other)
610 continue;
611
612 // If the smaller input/output operand is not mentioned in the asm string,
613 // then we can promote the smaller one to a larger input and the asm string
614 // won't notice.
615 bool SmallerValueMentioned = false;
616
617 // If this is a reference to the input and if the input was the smaller
618 // one, then we have to reject this asm.
619 if (isOperandMentioned(InputOpNo, Pieces)) {
620 // This is a use in the asm string of the smaller operand. Since we
621 // codegen this by promoting to a wider value, the asm will get printed
622 // "wrong".
623 SmallerValueMentioned |= InSize < OutSize;
624 }
625 if (isOperandMentioned(TiedTo, Pieces)) {
626 // If this is a reference to the output, and if the output is the larger
627 // value, then it's ok because we'll promote the input to the larger type.
628 SmallerValueMentioned |= OutSize < InSize;
629 }
630
631 // If the smaller value wasn't mentioned in the asm string, and if the
632 // output was a register, just extend the shorter one to the size of the
633 // larger one.
634 if (!SmallerValueMentioned && InputDomain != AD_Other &&
635 OutputConstraintInfos[TiedTo].allowsRegister())
636 continue;
637
638 // Either both of the operands were mentioned or the smaller one was
639 // mentioned. One more special case that we'll allow: if the tied input is
640 // integer, unmentioned, and is a constant, then we'll allow truncating it
641 // down to the size of the destination.
642 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
643 !isOperandMentioned(InputOpNo, Pieces) &&
644 InputExpr->isEvaluatable(Context)) {
645 CastKind castKind =
646 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000647 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000648 Exprs[InputOpNo] = InputExpr;
649 NS->setInputExpr(i, InputExpr);
650 continue;
651 }
652
Alexey Bataev305b6b92019-02-26 21:51:16 +0000653 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
654 << InTy << OutTy << OutputExpr->getSourceRange()
655 << InputExpr->getSourceRange();
656 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000657 }
658
Marina Yatsinac42fd032016-12-26 12:23:42 +0000659 // Check for conflicts between clobber list and input or output lists
660 SourceLocation ConstraintLoc =
661 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
Jennifer Yub8fee672019-06-03 15:57:25 +0000662 NumLabels,
Marina Yatsinac42fd032016-12-26 12:23:42 +0000663 Context.getTargetInfo(), Context);
664 if (ConstraintLoc.isValid())
Alexey Bataev305b6b92019-02-26 21:51:16 +0000665 targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
Fangrui Song6907ce22018-07-30 19:24:48 +0000666
Jennifer Yub8fee672019-06-03 15:57:25 +0000667 // Check for duplicate asm operand name between input, output and label lists.
668 typedef std::pair<StringRef , Expr *> NamedOperand;
669 SmallVector<NamedOperand, 4> NamedOperandList;
670 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
671 if (Names[i])
672 NamedOperandList.emplace_back(
673 std::make_pair(Names[i]->getName(), Exprs[i]));
674 // Sort NamedOperandList.
675 std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(),
676 [](const NamedOperand &LHS, const NamedOperand &RHS) {
677 return LHS.first < RHS.first;
678 });
679 // Find adjacent duplicate operand.
680 SmallVector<NamedOperand, 4>::iterator Found =
681 std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
682 [](const NamedOperand &LHS, const NamedOperand &RHS) {
683 return LHS.first == RHS.first;
684 });
685 if (Found != NamedOperandList.end()) {
686 Diag((Found + 1)->second->getBeginLoc(),
687 diag::error_duplicate_asm_operand_name)
688 << (Found + 1)->first;
689 Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
690 << Found->first;
691 return StmtError();
692 }
693 if (NS->isAsmGoto())
694 setFunctionHasBranchIntoScope();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000695 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000696}
697
Coby Tayree61504192017-09-29 07:02:49 +0000698void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
699 llvm::InlineAsmIdentifierInfo &Info) {
700 QualType T = Res->getType();
701 Expr::EvalResult Eval;
702 if (T->isFunctionType() || T->isDependentType())
703 return Info.setLabel(Res);
704 if (Res->isRValue()) {
705 if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context))
706 return Info.setEnum(Eval.Val.getInt().getSExtValue());
707 return Info.setLabel(Res);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000708 }
Coby Tayree61504192017-09-29 07:02:49 +0000709 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
710 unsigned Type = Size;
711 if (const auto *ATy = Context.getAsArrayType(T))
712 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
713 bool IsGlobalLV = false;
714 if (Res->EvaluateAsLValue(Eval, Context))
715 IsGlobalLV = Eval.isGlobalLValue();
716 Info.setVar(Res, IsGlobalLV, Size, Type);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000717}
718
John McCallf413f5e2013-05-03 00:10:13 +0000719ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
720 SourceLocation TemplateKWLoc,
721 UnqualifiedId &Id,
John McCallf413f5e2013-05-03 00:10:13 +0000722 bool IsUnevaluatedContext) {
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000723
John McCallf413f5e2013-05-03 00:10:13 +0000724 if (IsUnevaluatedContext)
Faisal Valid143a0c2017-04-01 21:30:49 +0000725 PushExpressionEvaluationContext(
726 ExpressionEvaluationContext::UnevaluatedAbstract,
727 ReuseLambdaContextDecl);
John McCallf413f5e2013-05-03 00:10:13 +0000728
729 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
730 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000731 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000732 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000733 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000734
735 if (IsUnevaluatedContext)
736 PopExpressionEvaluationContext();
737
738 if (!Result.isUsable()) return Result;
739
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000740 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000741 if (!Result.isUsable()) return Result;
742
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000743 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000744 if (CheckNakedParmReference(Result.get(), *this))
745 return ExprError();
Eric Christophercf941522017-07-25 19:17:32 +0000746
747 QualType T = Result.get()->getType();
John McCallf413f5e2013-05-03 00:10:13 +0000748
John McCallf413f5e2013-05-03 00:10:13 +0000749 if (T->isDependentType()) {
David Majnemerf8b569c2016-01-04 23:51:15 +0000750 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000751 }
752
John McCallf413f5e2013-05-03 00:10:13 +0000753 // Any sort of function type is fine.
754 if (T->isFunctionType()) {
755 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000756 }
757
John McCallf413f5e2013-05-03 00:10:13 +0000758 // Otherwise, it needs to be a complete type.
Eric Christophercf941522017-07-25 19:17:32 +0000759 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
John McCallf413f5e2013-05-03 00:10:13 +0000760 return ExprError();
761 }
762
John McCallf413f5e2013-05-03 00:10:13 +0000763 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000764}
Chad Rosierd997bd12012-08-22 19:18:30 +0000765
Chad Rosier5c563642012-10-25 21:49:22 +0000766bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
767 unsigned &Offset, SourceLocation AsmLoc) {
768 Offset = 0;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000769 SmallVector<StringRef, 2> Members;
770 Member.split(Members, ".");
771
Coby Tayree69eb6962017-08-09 13:31:41 +0000772 NamedDecl *FoundDecl = nullptr;
Chad Rosier5c563642012-10-25 21:49:22 +0000773
Coby Tayree69eb6962017-08-09 13:31:41 +0000774 // MS InlineAsm uses 'this' as a base
775 if (getLangOpts().CPlusPlus && Base.equals("this")) {
776 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
777 FoundDecl = PT->getPointeeType()->getAsTagDecl();
778 } else {
779 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
780 LookupOrdinaryName);
781 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
782 FoundDecl = BaseResult.getFoundDecl();
783 }
784
785 if (!FoundDecl)
Chad Rosier5c563642012-10-25 21:49:22 +0000786 return true;
Coby Tayree69eb6962017-08-09 13:31:41 +0000787
Marina Yatsina71ebc692015-12-17 12:51:51 +0000788 for (StringRef NextMember : Members) {
Marina Yatsina71ebc692015-12-17 12:51:51 +0000789 const RecordType *RT = nullptr;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000790 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
791 RT = VD->getType()->getAs<RecordType>();
792 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
793 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Coby Tayree69eb6962017-08-09 13:31:41 +0000794 // MS InlineAsm often uses struct pointer aliases as a base
795 QualType QT = TD->getUnderlyingType();
796 if (const auto *PT = QT->getAs<PointerType>())
797 QT = PT->getPointeeType();
798 RT = QT->getAs<RecordType>();
Marina Yatsina71ebc692015-12-17 12:51:51 +0000799 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
800 RT = TD->getTypeForDecl()->getAs<RecordType>();
801 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
802 RT = TD->getType()->getAs<RecordType>();
803 if (!RT)
804 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000805
Richard Smithdb0ac552015-12-18 22:40:25 +0000806 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
807 diag::err_asm_incomplete_type))
Marina Yatsina71ebc692015-12-17 12:51:51 +0000808 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000809
Marina Yatsina71ebc692015-12-17 12:51:51 +0000810 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
811 SourceLocation(), LookupMemberName);
Chad Rosier5c563642012-10-25 21:49:22 +0000812
Marina Yatsina71ebc692015-12-17 12:51:51 +0000813 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
814 return true;
815
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000816 if (!FieldResult.isSingleResult())
817 return true;
818 FoundDecl = FieldResult.getFoundDecl();
819
Marina Yatsina71ebc692015-12-17 12:51:51 +0000820 // FIXME: Handle IndirectFieldDecl?
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000821 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
Marina Yatsina71ebc692015-12-17 12:51:51 +0000822 if (!FD)
823 return true;
824
Marina Yatsina71ebc692015-12-17 12:51:51 +0000825 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
826 unsigned i = FD->getFieldIndex();
827 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
828 Offset += (unsigned)Result.getQuantity();
829 }
Chad Rosier5c563642012-10-25 21:49:22 +0000830
831 return false;
832}
833
Reid Kleckner14e96b42015-08-26 21:57:20 +0000834ExprResult
David Majnemer758e7982016-01-05 00:08:41 +0000835Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
Reid Kleckner14e96b42015-08-26 21:57:20 +0000836 SourceLocation AsmLoc) {
Reid Kleckner14e96b42015-08-26 21:57:20 +0000837
David Majnemerf8b569c2016-01-04 23:51:15 +0000838 QualType T = E->getType();
839 if (T->isDependentType()) {
840 DeclarationNameInfo NameInfo;
841 NameInfo.setLoc(AsmLoc);
842 NameInfo.setName(&Context.Idents.get(Member));
843 return CXXDependentScopeMemberExpr::Create(
844 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
845 SourceLocation(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000846 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
David Majnemerf8b569c2016-01-04 23:51:15 +0000847 }
848
849 const RecordType *RT = T->getAs<RecordType>();
Reid Kleckner14e96b42015-08-26 21:57:20 +0000850 // FIXME: Diagnose this as field access into a scalar type.
851 if (!RT)
852 return ExprResult();
853
854 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
855 LookupMemberName);
856
857 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
858 return ExprResult();
859
860 // Only normal and indirect field results will work.
861 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
862 if (!FD)
863 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
864 if (!FD)
865 return ExprResult();
866
Reid Kleckner14e96b42015-08-26 21:57:20 +0000867 // Make an Expr to thread through OpDecl.
868 ExprResult Result = BuildMemberReferenceExpr(
869 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000870 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000871
872 return Result;
873}
874
Chad Rosierb261a502012-09-13 00:06:55 +0000875StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000876 ArrayRef<Token> AsmToks,
877 StringRef AsmString,
878 unsigned NumOutputs, unsigned NumInputs,
879 ArrayRef<StringRef> Constraints,
880 ArrayRef<StringRef> Clobbers,
881 ArrayRef<Expr*> Exprs,
882 SourceLocation EndLoc) {
883 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Reid Kleckner87a31802018-03-12 21:43:02 +0000884 setFunctionHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000885 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000886 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
887 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000888 Constraints, Exprs, AsmString,
889 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000890 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000891}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000892
893LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
894 SourceLocation Location,
895 bool AlwaysCreate) {
896 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
897 Location);
898
Ehsan Akhgari42924432014-10-08 17:28:34 +0000899 if (Label->isMSAsmLabel()) {
900 // If we have previously created this label implicitly, mark it as used.
901 Label->markUsed(Context);
902 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000903 // Otherwise, insert it, but only resolve it if we have seen the label itself.
904 std::string InternalName;
905 llvm::raw_string_ostream OS(InternalName);
Reid Kleckner36c201a2016-12-07 00:17:18 +0000906 // Create an internal name for the label. The name should not be a valid
907 // mangled name, and should be unique. We use a dot to make the name an
908 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
909 // unique label is generated each time this blob is emitted, even after
910 // inlining or LTO.
Reid Klecknerfec0f322016-11-29 00:39:37 +0000911 OS << "__MSASMLABEL_.${:uid}__";
Reid Kleckner08ebbce2016-11-28 20:52:19 +0000912 for (char C : ExternalLabelName) {
913 OS << C;
914 // We escape '$' in asm strings by replacing it with "$$"
915 if (C == '$')
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000916 OS << '$';
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000917 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000918 Label->setMSAsmLabel(OS.str());
919 }
920 if (AlwaysCreate) {
921 // The label might have been created implicitly from a previously encountered
922 // goto statement. So, for both newly created and looked up labels, we mark
923 // them as resolved.
924 Label->setMSAsmLabelResolved();
925 }
926 // Adjust their location for being able to generate accurate diagnostics.
927 Label->setLocation(Location);
928
929 return Label;
930}