blob: e6d9b34dee917601347e5349e9932e40fadfa79f [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for inline asm statements.
11//
12//===----------------------------------------------------------------------===//
13
Weiming Zhao71ac2402015-02-03 22:35:58 +000014#include "clang/AST/ExprCXX.h"
Chad Rosier5c563642012-10-25 21:49:22 +000015#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000016#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000018#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000023#include "clang/Sema/SemaInternal.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000024#include "llvm/ADT/ArrayRef.h"
Marina Yatsinac42fd032016-12-26 12:23:42 +000025#include "llvm/ADT/StringSet.h"
Alp Toker10399272014-06-08 05:11:37 +000026#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000027using namespace clang;
28using namespace sema;
29
Aleksei Sidorin55365e42018-10-20 22:49:23 +000030/// Remove the upper-level LValueToRValue cast from an expression.
31static void removeLValueToRValueCast(Expr *E) {
32 Expr *Parent = E;
33 Expr *ExprUnderCast = nullptr;
34 SmallVector<Expr *, 8> ParentsToUpdate;
35
36 while (true) {
37 ParentsToUpdate.push_back(Parent);
38 if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
39 Parent = ParenE->getSubExpr();
40 continue;
41 }
42
43 Expr *Child = nullptr;
44 CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
45 if (ParentCast)
46 Child = ParentCast->getSubExpr();
47 else
48 return;
49
50 if (auto *CastE = dyn_cast<CastExpr>(Child))
51 if (CastE->getCastKind() == CK_LValueToRValue) {
52 ExprUnderCast = CastE->getSubExpr();
53 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
54 ParentCast->setSubExpr(ExprUnderCast);
55 break;
56 }
57 Parent = Child;
58 }
59
60 // Update parent expressions to have same ValueType as the underlying.
61 assert(ExprUnderCast &&
62 "Should be reachable only if LValueToRValue cast was found!");
63 auto ValueKind = ExprUnderCast->getValueKind();
64 for (Expr *E : ParentsToUpdate)
65 E->setValueKind(ValueKind);
66}
67
68/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
69/// and fix the argument with removing LValueToRValue cast from the expression.
70static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
71 Sema &S) {
72 if (!S.getLangOpts().HeinousExtensions) {
73 S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
74 << BadArgument->getSourceRange();
75 } else {
76 S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
77 << BadArgument->getSourceRange();
78 }
79 removeLValueToRValueCast(BadArgument);
80}
81
Chad Rosier0731aff2012-08-17 21:19:40 +000082/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
83/// ignore "noop" casts in places where an lvalue is required by an inline asm.
84/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
85/// provide a strong guidance to not use it.
86///
87/// This method checks to see if the argument is an acceptable l-value and
88/// returns false if it is a case we can handle.
Aleksei Sidorin55365e42018-10-20 22:49:23 +000089static bool CheckAsmLValue(Expr *E, Sema &S) {
Chad Rosier0731aff2012-08-17 21:19:40 +000090 // Type dependent expressions will be checked during instantiation.
91 if (E->isTypeDependent())
92 return false;
93
94 if (E->isLValue())
95 return false; // Cool, this is an lvalue.
96
97 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
98 // are supposed to allow.
99 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
100 if (E != E2 && E2->isLValue()) {
Aleksei Sidorin55365e42018-10-20 22:49:23 +0000101 emitAndFixInvalidAsmCastLValue(E2, E, S);
Chad Rosier0731aff2012-08-17 21:19:40 +0000102 // Accept, even if we emitted an error diagnostic.
103 return false;
104 }
105
106 // None of the above, just randomly invalid non-lvalue.
107 return true;
108}
109
110/// isOperandMentioned - Return true if the specified operand # is mentioned
111/// anywhere in the decomposed asm string.
Coby Tayree18f92182017-09-10 12:39:21 +0000112static bool
113isOperandMentioned(unsigned OpNo,
114 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000115 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +0000116 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Coby Tayree18f92182017-09-10 12:39:21 +0000117 if (!Piece.isOperand())
118 continue;
Chad Rosier0731aff2012-08-17 21:19:40 +0000119
120 // If this is a reference to the input and if the input was the smaller
121 // one, then we have to reject this asm.
122 if (Piece.getOperandNo() == OpNo)
123 return true;
124 }
125 return false;
126}
127
Hans Wennborge9d240a2014-10-08 01:58:02 +0000128static bool CheckNakedParmReference(Expr *E, Sema &S) {
129 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
130 if (!Func)
131 return false;
132 if (!Func->hasAttr<NakedAttr>())
133 return false;
134
135 SmallVector<Expr*, 4> WorkList;
136 WorkList.push_back(E);
137 while (WorkList.size()) {
138 Expr *E = WorkList.pop_back_val();
Weiming Zhao71ac2402015-02-03 22:35:58 +0000139 if (isa<CXXThisExpr>(E)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000140 S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
Weiming Zhao71ac2402015-02-03 22:35:58 +0000141 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
142 return true;
143 }
Hans Wennborge9d240a2014-10-08 01:58:02 +0000144 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
145 if (isa<ParmVarDecl>(DRE->getDecl())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000146 S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
Hans Wennborge9d240a2014-10-08 01:58:02 +0000147 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
148 return true;
149 }
150 }
151 for (Stmt *Child : E->children()) {
152 if (Expr *E = dyn_cast_or_null<Expr>(Child))
153 WorkList.push_back(E);
154 }
155 }
156 return false;
157}
158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159/// Returns true if given expression is not compatible with inline
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000160/// assembly's memory constraint; false otherwise.
161static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
162 TargetInfo::ConstraintInfo &Info,
163 bool is_input_expr) {
164 enum {
165 ExprBitfield = 0,
166 ExprVectorElt,
167 ExprGlobalRegVar,
168 ExprSafeType
169 } EType = ExprSafeType;
170
171 // Bitfields, vector elements and global register variables are not
172 // compatible.
173 if (E->refersToBitField())
174 EType = ExprBitfield;
175 else if (E->refersToVectorElement())
176 EType = ExprVectorElt;
177 else if (E->refersToGlobalRegisterVar())
178 EType = ExprGlobalRegVar;
179
180 if (EType != ExprSafeType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000181 S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000182 << EType << is_input_expr << Info.getConstraintStr()
183 << E->getSourceRange();
184 return true;
185 }
186
187 return false;
188}
189
Marina Yatsinac42fd032016-12-26 12:23:42 +0000190// Extracting the register name from the Expression value,
191// if there is no register name to extract, returns ""
192static StringRef extractRegisterName(const Expr *Expression,
193 const TargetInfo &Target) {
194 Expression = Expression->IgnoreImpCasts();
195 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
196 // Handle cases where the expression is a variable
197 const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
198 if (Variable && Variable->getStorageClass() == SC_Register) {
199 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
200 if (Target.isValidGCCRegisterName(Attr->getLabel()))
201 return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
202 }
203 }
204 return "";
205}
206
207// Checks if there is a conflict between the input and output lists with the
208// clobbers list. If there's a conflict, returns the location of the
209// conflicted clobber, else returns nullptr
210static SourceLocation
211getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
212 StringLiteral **Clobbers, int NumClobbers,
213 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
217 for (unsigned int i = 0; i < Exprs.size(); ++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,
245 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000246 unsigned NumClobbers = clobbers.size();
247 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000248 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000249 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000250 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000251
252 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
253
254 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000255 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000256
Artem Belevich5ef02c22015-08-27 19:54:21 +0000257 // If we're compiling CUDA file and function attributes indicate that it's not
258 // for this compilation side, skip all the checks.
259 if (!DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) {
260 GCCAsmStmt *NS = new (Context) GCCAsmStmt(
261 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
262 Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, RParenLoc);
263 return NS;
264 }
Artem Belevich5196fe72015-03-19 18:40:25 +0000265
Chad Rosier0731aff2012-08-17 21:19:40 +0000266 for (unsigned i = 0; i != NumOutputs; i++) {
267 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000268 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000269
270 StringRef OutputName;
271 if (Names[i])
272 OutputName = Names[i]->getName();
273
274 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Artem Belevich5ef02c22015-08-27 19:54:21 +0000275 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000276 return StmtError(
277 Diag(Literal->getBeginLoc(), diag::err_asm_invalid_output_constraint)
278 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000279
David Majnemer0f4d6412014-12-29 09:30:33 +0000280 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
281 if (ER.isInvalid())
282 return StmtError();
283 Exprs[i] = ER.get();
284
Chad Rosier0731aff2012-08-17 21:19:40 +0000285 // Check that the output exprs are valid lvalues.
286 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000287
Hans Wennborge9d240a2014-10-08 01:58:02 +0000288 // Referring to parameters is not allowed in naked functions.
289 if (CheckNakedParmReference(OutputExpr, *this))
290 return StmtError();
291
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000292 // Check that the output expression is compatible with memory constraint.
293 if (Info.allowsMemory() &&
294 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
295 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000296
Chad Rosier0731aff2012-08-17 21:19:40 +0000297 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000298
David Majnemer0f4d6412014-12-29 09:30:33 +0000299 // If this is dependent, just continue.
300 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000301 continue;
302
David Majnemer0f4d6412014-12-29 09:30:33 +0000303 Expr::isModifiableLvalueResult IsLV =
304 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
305 switch (IsLV) {
306 case Expr::MLV_Valid:
307 // Cool, this is an lvalue.
308 break;
David Majnemer04b78412014-12-29 10:29:53 +0000309 case Expr::MLV_ArrayType:
310 // This is OK too.
311 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000312 case Expr::MLV_LValueCast: {
313 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
Aleksei Sidorin55365e42018-10-20 22:49:23 +0000314 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
David Majnemer0f4d6412014-12-29 09:30:33 +0000315 // Accept, even if we emitted an error diagnostic.
316 break;
317 }
318 case Expr::MLV_IncompleteType:
319 case Expr::MLV_IncompleteVoidType:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000320 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
David Majnemer0f4d6412014-12-29 09:30:33 +0000321 diag::err_dereference_incomplete_type))
322 return StmtError();
Galina Kistanova33399112017-06-03 06:35:06 +0000323 LLVM_FALLTHROUGH;
David Majnemer0f4d6412014-12-29 09:30:33 +0000324 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000325 return StmtError(Diag(OutputExpr->getBeginLoc(),
David Majnemer0f4d6412014-12-29 09:30:33 +0000326 diag::err_asm_invalid_lvalue_in_output)
327 << OutputExpr->getSourceRange());
328 }
329
330 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000331 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
332 Size))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000333 return StmtError(
334 Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
335 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000336 }
337
338 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
339
340 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
341 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000342 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000343
344 StringRef InputName;
345 if (Names[i])
346 InputName = Names[i]->getName();
347
348 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Craig Topper55765ca2015-10-21 02:34:10 +0000349 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
350 Info)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000351 return StmtError(
352 Diag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
353 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000354 }
355
David Majnemer0f4d6412014-12-29 09:30:33 +0000356 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
357 if (ER.isInvalid())
358 return StmtError();
359 Exprs[i] = ER.get();
360
Chad Rosier0731aff2012-08-17 21:19:40 +0000361 Expr *InputExpr = Exprs[i];
362
Hans Wennborge9d240a2014-10-08 01:58:02 +0000363 // Referring to parameters is not allowed in naked functions.
364 if (CheckNakedParmReference(InputExpr, *this))
365 return StmtError();
366
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000367 // Check that the input expression is compatible with memory constraint.
368 if (Info.allowsMemory() &&
369 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
370 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000371
Chad Rosier0731aff2012-08-17 21:19:40 +0000372 // Only allow void types for memory constraints.
373 if (Info.allowsMemory() && !Info.allowsRegister()) {
374 if (CheckAsmLValue(InputExpr, *this))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000375 return StmtError(Diag(InputExpr->getBeginLoc(),
Chad Rosier0731aff2012-08-17 21:19:40 +0000376 diag::err_asm_invalid_lvalue_in_input)
377 << Info.getConstraintStr()
378 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000379 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
Sunil Srivastava780e5012015-07-14 18:08:50 +0000380 if (!InputExpr->isValueDependent()) {
Nico Weber9f0246d2018-11-21 12:47:43 +0000381 llvm::APSInt Result;
382 if (!InputExpr->EvaluateAsInt(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000383 return StmtError(
384 Diag(InputExpr->getBeginLoc(), diag::err_asm_immediate_expected)
385 << Info.getConstraintStr() << InputExpr->getSourceRange());
Alexey Bataev91e58602015-07-20 12:08:00 +0000386 if (!Info.isValidAsmImmediate(Result))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000387 return StmtError(Diag(InputExpr->getBeginLoc(),
Sunil Srivastava780e5012015-07-14 18:08:50 +0000388 diag::err_invalid_asm_value_for_constraint)
389 << Result.toString(10) << Info.getConstraintStr()
390 << InputExpr->getSourceRange());
391 }
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000392
David Majnemerade4bee2014-07-14 16:27:53 +0000393 } else {
394 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
395 if (Result.isInvalid())
396 return StmtError();
397
398 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000399 }
400
401 if (Info.allowsRegister()) {
402 if (InputExpr->getType()->isVoidType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000403 return StmtError(
404 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
405 << InputExpr->getType() << Info.getConstraintStr()
406 << InputExpr->getSourceRange());
Chad Rosier0731aff2012-08-17 21:19:40 +0000407 }
408 }
409
Chad Rosier0731aff2012-08-17 21:19:40 +0000410 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000411
412 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000413 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000414 continue;
415
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000416 if (!Ty->isVoidType() || !Info.allowsMemory())
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000417 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
Bill Wendlingb68b7572013-03-27 06:06:26 +0000418 diag::err_dereference_incomplete_type))
419 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000420
Bill Wendling887b4852012-11-12 06:42:51 +0000421 unsigned Size = Context.getTypeSize(Ty);
422 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
423 Size))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000424 return StmtError(
425 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
426 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000427 }
428
429 // Check that the clobbers are valid.
430 for (unsigned i = 0; i != NumClobbers; i++) {
431 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000432 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000433
434 StringRef Clobber = Literal->getString();
435
436 if (!Context.getTargetInfo().isValidClobber(Clobber))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000437 return StmtError(
438 Diag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
439 << Clobber);
Chad Rosier0731aff2012-08-17 21:19:40 +0000440 }
441
Chad Rosierde70e0e2012-08-25 00:11:56 +0000442 GCCAsmStmt *NS =
443 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000444 NumInputs, Names, Constraints, Exprs.data(),
445 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000446 // Validate the asm string, ensuring it makes sense given the operands we
447 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000448 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000449 unsigned DiagOffs;
450 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
451 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
452 << AsmString->getSourceRange();
453 return StmtError();
454 }
455
Bill Wendling9d1ee112012-10-25 23:28:48 +0000456 // Validate constraints and modifiers.
457 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
458 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
459 if (!Piece.isOperand()) continue;
460
461 // Look for the correct constraint index.
Akira Hatanaka96a36012015-02-04 00:27:13 +0000462 unsigned ConstraintIdx = Piece.getOperandNo();
463 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Bill Wendling9d1ee112012-10-25 23:28:48 +0000464
Akira Hatanaka96a36012015-02-04 00:27:13 +0000465 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
466 // modifier '+'.
467 if (ConstraintIdx >= NumOperands) {
468 unsigned I = 0, E = NS->getNumOutputs();
469
470 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
471 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
472 ConstraintIdx = I;
Bill Wendling9d1ee112012-10-25 23:28:48 +0000473 break;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000474 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000475
Akira Hatanaka96a36012015-02-04 00:27:13 +0000476 assert(I != E && "Invalid operand number should have been caught in "
477 " AnalyzeAsmString");
Bill Wendling9d1ee112012-10-25 23:28:48 +0000478 }
479
480 // Now that we have the right indexes go ahead and check.
481 StringLiteral *Literal = Constraints[ConstraintIdx];
482 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
483 if (Ty->isDependentType() || Ty->isIncompleteType())
484 continue;
485
486 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000487 std::string SuggestedModifier;
488 if (!Context.getTargetInfo().validateConstraintModifier(
489 Literal->getString(), Piece.getModifier(), Size,
490 SuggestedModifier)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000491 Diag(Exprs[ConstraintIdx]->getBeginLoc(),
Bill Wendling9d1ee112012-10-25 23:28:48 +0000492 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000493
494 if (!SuggestedModifier.empty()) {
495 auto B = Diag(Piece.getRange().getBegin(),
496 diag::note_asm_missing_constraint_modifier)
497 << SuggestedModifier;
498 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
499 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
500 SuggestedModifier));
501 }
502 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000503 }
504
Chad Rosier0731aff2012-08-17 21:19:40 +0000505 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000506 unsigned NumAlternatives = ~0U;
507 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
508 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
509 StringRef ConstraintStr = Info.getConstraintStr();
510 unsigned AltCount = ConstraintStr.count(',') + 1;
511 if (NumAlternatives == ~0U)
512 NumAlternatives = AltCount;
513 else if (NumAlternatives != AltCount)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000514 return StmtError(Diag(NS->getOutputExpr(i)->getBeginLoc(),
David Majnemerc63fa612014-12-29 04:09:59 +0000515 diag::err_asm_unexpected_constraint_alternatives)
516 << NumAlternatives << AltCount);
517 }
Alexander Musman8e261be2015-09-21 14:41:00 +0000518 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
519 ~0U);
Chad Rosier0731aff2012-08-17 21:19:40 +0000520 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
521 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000522 StringRef ConstraintStr = Info.getConstraintStr();
523 unsigned AltCount = ConstraintStr.count(',') + 1;
524 if (NumAlternatives == ~0U)
525 NumAlternatives = AltCount;
526 else if (NumAlternatives != AltCount)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000527 return StmtError(Diag(NS->getInputExpr(i)->getBeginLoc(),
David Majnemerc63fa612014-12-29 04:09:59 +0000528 diag::err_asm_unexpected_constraint_alternatives)
529 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000530
531 // If this is a tied constraint, verify that the output and input have
532 // either exactly the same type, or that they are int/ptr operands with the
533 // same size (int/long, int*/long, are ok etc).
534 if (!Info.hasTiedOperand()) continue;
535
536 unsigned TiedTo = Info.getTiedOperand();
537 unsigned InputOpNo = i+NumOutputs;
538 Expr *OutputExpr = Exprs[TiedTo];
539 Expr *InputExpr = Exprs[InputOpNo];
540
Alexander Musman8e261be2015-09-21 14:41:00 +0000541 // Make sure no more than one input constraint matches each output.
542 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
543 if (InputMatchedToOutput[TiedTo] != ~0U) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000544 Diag(NS->getInputExpr(i)->getBeginLoc(),
Alexander Musman8e261be2015-09-21 14:41:00 +0000545 diag::err_asm_input_duplicate_match)
546 << TiedTo;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000547 Diag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
Alexander Musman8e261be2015-09-21 14:41:00 +0000548 diag::note_asm_input_duplicate_first)
549 << TiedTo;
550 return StmtError();
551 }
552 InputMatchedToOutput[TiedTo] = i;
553
Chad Rosier0731aff2012-08-17 21:19:40 +0000554 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
555 continue;
556
557 QualType InTy = InputExpr->getType();
558 QualType OutTy = OutputExpr->getType();
559 if (Context.hasSameType(InTy, OutTy))
560 continue; // All types can be tied to themselves.
561
562 // Decide if the input and output are in the same domain (integer/ptr or
563 // floating point.
564 enum AsmDomain {
565 AD_Int, AD_FP, AD_Other
566 } InputDomain, OutputDomain;
567
568 if (InTy->isIntegerType() || InTy->isPointerType())
569 InputDomain = AD_Int;
570 else if (InTy->isRealFloatingType())
571 InputDomain = AD_FP;
572 else
573 InputDomain = AD_Other;
574
575 if (OutTy->isIntegerType() || OutTy->isPointerType())
576 OutputDomain = AD_Int;
577 else if (OutTy->isRealFloatingType())
578 OutputDomain = AD_FP;
579 else
580 OutputDomain = AD_Other;
581
582 // They are ok if they are the same size and in the same domain. This
583 // allows tying things like:
584 // void* to int*
585 // void* to int if they are the same size.
586 // double to long double if they are the same size.
587 //
588 uint64_t OutSize = Context.getTypeSize(OutTy);
589 uint64_t InSize = Context.getTypeSize(InTy);
590 if (OutSize == InSize && InputDomain == OutputDomain &&
591 InputDomain != AD_Other)
592 continue;
593
594 // If the smaller input/output operand is not mentioned in the asm string,
595 // then we can promote the smaller one to a larger input and the asm string
596 // won't notice.
597 bool SmallerValueMentioned = false;
598
599 // If this is a reference to the input and if the input was the smaller
600 // one, then we have to reject this asm.
601 if (isOperandMentioned(InputOpNo, Pieces)) {
602 // This is a use in the asm string of the smaller operand. Since we
603 // codegen this by promoting to a wider value, the asm will get printed
604 // "wrong".
605 SmallerValueMentioned |= InSize < OutSize;
606 }
607 if (isOperandMentioned(TiedTo, Pieces)) {
608 // If this is a reference to the output, and if the output is the larger
609 // value, then it's ok because we'll promote the input to the larger type.
610 SmallerValueMentioned |= OutSize < InSize;
611 }
612
613 // If the smaller value wasn't mentioned in the asm string, and if the
614 // output was a register, just extend the shorter one to the size of the
615 // larger one.
616 if (!SmallerValueMentioned && InputDomain != AD_Other &&
617 OutputConstraintInfos[TiedTo].allowsRegister())
618 continue;
619
620 // Either both of the operands were mentioned or the smaller one was
621 // mentioned. One more special case that we'll allow: if the tied input is
622 // integer, unmentioned, and is a constant, then we'll allow truncating it
623 // down to the size of the destination.
624 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
625 !isOperandMentioned(InputOpNo, Pieces) &&
626 InputExpr->isEvaluatable(Context)) {
627 CastKind castKind =
628 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000629 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000630 Exprs[InputOpNo] = InputExpr;
631 NS->setInputExpr(i, InputExpr);
632 continue;
633 }
634
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000635 Diag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
636 << InTy << OutTy << OutputExpr->getSourceRange()
637 << InputExpr->getSourceRange();
Chad Rosier0731aff2012-08-17 21:19:40 +0000638 return StmtError();
639 }
640
Marina Yatsinac42fd032016-12-26 12:23:42 +0000641 // Check for conflicts between clobber list and input or output lists
642 SourceLocation ConstraintLoc =
643 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
644 Context.getTargetInfo(), Context);
645 if (ConstraintLoc.isValid())
646 return Diag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
Fangrui Song6907ce22018-07-30 19:24:48 +0000647
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000648 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000649}
650
Coby Tayree61504192017-09-29 07:02:49 +0000651void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
652 llvm::InlineAsmIdentifierInfo &Info) {
653 QualType T = Res->getType();
654 Expr::EvalResult Eval;
655 if (T->isFunctionType() || T->isDependentType())
656 return Info.setLabel(Res);
657 if (Res->isRValue()) {
658 if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context))
659 return Info.setEnum(Eval.Val.getInt().getSExtValue());
660 return Info.setLabel(Res);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000661 }
Coby Tayree61504192017-09-29 07:02:49 +0000662 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
663 unsigned Type = Size;
664 if (const auto *ATy = Context.getAsArrayType(T))
665 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
666 bool IsGlobalLV = false;
667 if (Res->EvaluateAsLValue(Eval, Context))
668 IsGlobalLV = Eval.isGlobalLValue();
669 Info.setVar(Res, IsGlobalLV, Size, Type);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000670}
671
John McCallf413f5e2013-05-03 00:10:13 +0000672ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
673 SourceLocation TemplateKWLoc,
674 UnqualifiedId &Id,
John McCallf413f5e2013-05-03 00:10:13 +0000675 bool IsUnevaluatedContext) {
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000676
John McCallf413f5e2013-05-03 00:10:13 +0000677 if (IsUnevaluatedContext)
Faisal Valid143a0c2017-04-01 21:30:49 +0000678 PushExpressionEvaluationContext(
679 ExpressionEvaluationContext::UnevaluatedAbstract,
680 ReuseLambdaContextDecl);
John McCallf413f5e2013-05-03 00:10:13 +0000681
682 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
683 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000684 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000685 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000686 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000687
688 if (IsUnevaluatedContext)
689 PopExpressionEvaluationContext();
690
691 if (!Result.isUsable()) return Result;
692
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000693 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000694 if (!Result.isUsable()) return Result;
695
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000696 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000697 if (CheckNakedParmReference(Result.get(), *this))
698 return ExprError();
Eric Christophercf941522017-07-25 19:17:32 +0000699
700 QualType T = Result.get()->getType();
John McCallf413f5e2013-05-03 00:10:13 +0000701
John McCallf413f5e2013-05-03 00:10:13 +0000702 if (T->isDependentType()) {
David Majnemerf8b569c2016-01-04 23:51:15 +0000703 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000704 }
705
John McCallf413f5e2013-05-03 00:10:13 +0000706 // Any sort of function type is fine.
707 if (T->isFunctionType()) {
708 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000709 }
710
John McCallf413f5e2013-05-03 00:10:13 +0000711 // Otherwise, it needs to be a complete type.
Eric Christophercf941522017-07-25 19:17:32 +0000712 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
John McCallf413f5e2013-05-03 00:10:13 +0000713 return ExprError();
714 }
715
John McCallf413f5e2013-05-03 00:10:13 +0000716 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000717}
Chad Rosierd997bd12012-08-22 19:18:30 +0000718
Chad Rosier5c563642012-10-25 21:49:22 +0000719bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
720 unsigned &Offset, SourceLocation AsmLoc) {
721 Offset = 0;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000722 SmallVector<StringRef, 2> Members;
723 Member.split(Members, ".");
724
Coby Tayree69eb6962017-08-09 13:31:41 +0000725 NamedDecl *FoundDecl = nullptr;
Chad Rosier5c563642012-10-25 21:49:22 +0000726
Coby Tayree69eb6962017-08-09 13:31:41 +0000727 // MS InlineAsm uses 'this' as a base
728 if (getLangOpts().CPlusPlus && Base.equals("this")) {
729 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
730 FoundDecl = PT->getPointeeType()->getAsTagDecl();
731 } else {
732 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
733 LookupOrdinaryName);
734 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
735 FoundDecl = BaseResult.getFoundDecl();
736 }
737
738 if (!FoundDecl)
Chad Rosier5c563642012-10-25 21:49:22 +0000739 return true;
Coby Tayree69eb6962017-08-09 13:31:41 +0000740
Marina Yatsina71ebc692015-12-17 12:51:51 +0000741 for (StringRef NextMember : Members) {
Marina Yatsina71ebc692015-12-17 12:51:51 +0000742 const RecordType *RT = nullptr;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000743 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
744 RT = VD->getType()->getAs<RecordType>();
745 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
746 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Coby Tayree69eb6962017-08-09 13:31:41 +0000747 // MS InlineAsm often uses struct pointer aliases as a base
748 QualType QT = TD->getUnderlyingType();
749 if (const auto *PT = QT->getAs<PointerType>())
750 QT = PT->getPointeeType();
751 RT = QT->getAs<RecordType>();
Marina Yatsina71ebc692015-12-17 12:51:51 +0000752 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
753 RT = TD->getTypeForDecl()->getAs<RecordType>();
754 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
755 RT = TD->getType()->getAs<RecordType>();
756 if (!RT)
757 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000758
Richard Smithdb0ac552015-12-18 22:40:25 +0000759 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
760 diag::err_asm_incomplete_type))
Marina Yatsina71ebc692015-12-17 12:51:51 +0000761 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000762
Marina Yatsina71ebc692015-12-17 12:51:51 +0000763 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
764 SourceLocation(), LookupMemberName);
Chad Rosier5c563642012-10-25 21:49:22 +0000765
Marina Yatsina71ebc692015-12-17 12:51:51 +0000766 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
767 return true;
768
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000769 if (!FieldResult.isSingleResult())
770 return true;
771 FoundDecl = FieldResult.getFoundDecl();
772
Marina Yatsina71ebc692015-12-17 12:51:51 +0000773 // FIXME: Handle IndirectFieldDecl?
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000774 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
Marina Yatsina71ebc692015-12-17 12:51:51 +0000775 if (!FD)
776 return true;
777
Marina Yatsina71ebc692015-12-17 12:51:51 +0000778 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
779 unsigned i = FD->getFieldIndex();
780 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
781 Offset += (unsigned)Result.getQuantity();
782 }
Chad Rosier5c563642012-10-25 21:49:22 +0000783
784 return false;
785}
786
Reid Kleckner14e96b42015-08-26 21:57:20 +0000787ExprResult
David Majnemer758e7982016-01-05 00:08:41 +0000788Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
Reid Kleckner14e96b42015-08-26 21:57:20 +0000789 SourceLocation AsmLoc) {
Reid Kleckner14e96b42015-08-26 21:57:20 +0000790
David Majnemerf8b569c2016-01-04 23:51:15 +0000791 QualType T = E->getType();
792 if (T->isDependentType()) {
793 DeclarationNameInfo NameInfo;
794 NameInfo.setLoc(AsmLoc);
795 NameInfo.setName(&Context.Idents.get(Member));
796 return CXXDependentScopeMemberExpr::Create(
797 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
798 SourceLocation(),
799 /*FirstQualifierInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
800 }
801
802 const RecordType *RT = T->getAs<RecordType>();
Reid Kleckner14e96b42015-08-26 21:57:20 +0000803 // FIXME: Diagnose this as field access into a scalar type.
804 if (!RT)
805 return ExprResult();
806
807 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
808 LookupMemberName);
809
810 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
811 return ExprResult();
812
813 // Only normal and indirect field results will work.
814 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
815 if (!FD)
816 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
817 if (!FD)
818 return ExprResult();
819
Reid Kleckner14e96b42015-08-26 21:57:20 +0000820 // Make an Expr to thread through OpDecl.
821 ExprResult Result = BuildMemberReferenceExpr(
822 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000823 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000824
825 return Result;
826}
827
Chad Rosierb261a502012-09-13 00:06:55 +0000828StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000829 ArrayRef<Token> AsmToks,
830 StringRef AsmString,
831 unsigned NumOutputs, unsigned NumInputs,
832 ArrayRef<StringRef> Constraints,
833 ArrayRef<StringRef> Clobbers,
834 ArrayRef<Expr*> Exprs,
835 SourceLocation EndLoc) {
836 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Reid Kleckner87a31802018-03-12 21:43:02 +0000837 setFunctionHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000838 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000839 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
840 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000841 Constraints, Exprs, AsmString,
842 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000843 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000844}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000845
846LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
847 SourceLocation Location,
848 bool AlwaysCreate) {
849 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
850 Location);
851
Ehsan Akhgari42924432014-10-08 17:28:34 +0000852 if (Label->isMSAsmLabel()) {
853 // If we have previously created this label implicitly, mark it as used.
854 Label->markUsed(Context);
855 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000856 // Otherwise, insert it, but only resolve it if we have seen the label itself.
857 std::string InternalName;
858 llvm::raw_string_ostream OS(InternalName);
Reid Kleckner36c201a2016-12-07 00:17:18 +0000859 // Create an internal name for the label. The name should not be a valid
860 // mangled name, and should be unique. We use a dot to make the name an
861 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
862 // unique label is generated each time this blob is emitted, even after
863 // inlining or LTO.
Reid Klecknerfec0f322016-11-29 00:39:37 +0000864 OS << "__MSASMLABEL_.${:uid}__";
Reid Kleckner08ebbce2016-11-28 20:52:19 +0000865 for (char C : ExternalLabelName) {
866 OS << C;
867 // We escape '$' in asm strings by replacing it with "$$"
868 if (C == '$')
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000869 OS << '$';
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000870 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000871 Label->setMSAsmLabel(OS.str());
872 }
873 if (AlwaysCreate) {
874 // The label might have been created implicitly from a previously encountered
875 // goto statement. So, for both newly created and looked up labels, we mark
876 // them as resolved.
877 Label->setMSAsmLabelResolved();
878 }
879 // Adjust their location for being able to generate accurate diagnostics.
880 Label->setLocation(Location);
881
882 return Label;
883}