1//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for inline asm statements.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ExprCXX.h"
14#include "clang/AST/RecordLayout.h"
15#include "clang/AST/TypeLoc.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Ownership.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringSet.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include <optional>
28using namespace clang;
29using namespace sema;
30
31/// Remove the upper-level LValueToRValue cast from an expression.
32static void removeLValueToRValueCast(Expr *E) {
33 Expr *Parent = E;
34 Expr *ExprUnderCast = nullptr;
35 SmallVector<Expr *, 8> ParentsToUpdate;
36
37 while (true) {
38 ParentsToUpdate.push_back(Elt: Parent);
39 if (auto *ParenE = dyn_cast<ParenExpr>(Val: Parent)) {
40 Parent = ParenE->getSubExpr();
41 continue;
42 }
43
44 Expr *Child = nullptr;
45 CastExpr *ParentCast = dyn_cast<CastExpr>(Val: Parent);
46 if (ParentCast)
47 Child = ParentCast->getSubExpr();
48 else
49 return;
50
51 if (auto *CastE = dyn_cast<CastExpr>(Val: Child))
52 if (CastE->getCastKind() == CK_LValueToRValue) {
53 ExprUnderCast = CastE->getSubExpr();
54 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
55 ParentCast->setSubExpr(ExprUnderCast);
56 break;
57 }
58 Parent = Child;
59 }
60
61 // Update parent expressions to have same ValueType as the underlying.
62 assert(ExprUnderCast &&
63 "Should be reachable only if LValueToRValue cast was found!");
64 auto ValueKind = ExprUnderCast->getValueKind();
65 for (Expr *E : ParentsToUpdate)
66 E->setValueKind(ValueKind);
67}
68
69/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
70/// and fix the argument with removing LValueToRValue cast from the expression.
71static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
72 Sema &S) {
73 S.Diag(Loc: LVal->getBeginLoc(), DiagID: diag::warn_invalid_asm_cast_lvalue)
74 << BadArgument->getSourceRange();
75 removeLValueToRValueCast(E: BadArgument);
76}
77
78/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
79/// ignore "noop" casts in places where an lvalue is required by an inline asm.
80/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
81/// provide a strong guidance to not use it.
82///
83/// This method checks to see if the argument is an acceptable l-value and
84/// returns false if it is a case we can handle.
85static bool CheckAsmLValue(Expr *E, Sema &S) {
86 // Type dependent expressions will be checked during instantiation.
87 if (E->isTypeDependent())
88 return false;
89
90 if (E->isLValue())
91 return false; // Cool, this is an lvalue.
92
93 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
94 // are supposed to allow.
95 const Expr *E2 = E->IgnoreParenNoopCasts(Ctx: S.Context);
96 if (E != E2 && E2->isLValue()) {
97 emitAndFixInvalidAsmCastLValue(LVal: E2, BadArgument: E, S);
98 // Accept, even if we emitted an error diagnostic.
99 return false;
100 }
101
102 // None of the above, just randomly invalid non-lvalue.
103 return true;
104}
105
106/// isOperandMentioned - Return true if the specified operand # is mentioned
107/// anywhere in the decomposed asm string.
108static bool
109isOperandMentioned(unsigned OpNo,
110 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
111 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
112 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
113 if (!Piece.isOperand())
114 continue;
115
116 // If this is a reference to the input and if the input was the smaller
117 // one, then we have to reject this asm.
118 if (Piece.getOperandNo() == OpNo)
119 return true;
120 }
121 return false;
122}
123
124static bool CheckNakedParmReference(Expr *E, Sema &S) {
125 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: S.CurContext);
126 if (!Func)
127 return false;
128 if (!Func->hasAttr<NakedAttr>())
129 return false;
130
131 SmallVector<Expr*, 4> WorkList;
132 WorkList.push_back(Elt: E);
133 while (WorkList.size()) {
134 Expr *E = WorkList.pop_back_val();
135 if (isa<CXXThisExpr>(Val: E)) {
136 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_naked_this_ref);
137 S.Diag(Loc: Func->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
138 return true;
139 }
140 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
141 if (isa<ParmVarDecl>(Val: DRE->getDecl())) {
142 S.Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_asm_naked_parm_ref);
143 S.Diag(Loc: Func->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
144 return true;
145 }
146 }
147 for (Stmt *Child : E->children()) {
148 if (Expr *E = dyn_cast_or_null<Expr>(Val: Child))
149 WorkList.push_back(Elt: E);
150 }
151 }
152 return false;
153}
154
155/// Returns true if given expression is not compatible with inline
156/// assembly's memory constraint; false otherwise.
157static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
158 TargetInfo::ConstraintInfo &Info,
159 bool is_input_expr) {
160 enum {
161 ExprBitfield = 0,
162 ExprVectorElt,
163 ExprGlobalRegVar,
164 ExprSafeType
165 } EType = ExprSafeType;
166
167 // Bitfields, vector elements and global register variables are not
168 // compatible.
169 if (E->refersToBitField())
170 EType = ExprBitfield;
171 else if (E->refersToVectorElement())
172 EType = ExprVectorElt;
173 else if (E->refersToGlobalRegisterVar())
174 EType = ExprGlobalRegVar;
175
176 if (EType != ExprSafeType) {
177 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_non_addr_value_in_memory_constraint)
178 << EType << is_input_expr << Info.getConstraintStr()
179 << E->getSourceRange();
180 return true;
181 }
182
183 return false;
184}
185
186// Extracting the register name from the Expression value,
187// if there is no register name to extract, returns ""
188static StringRef extractRegisterName(const Expr *Expression,
189 const TargetInfo &Target) {
190 Expression = Expression->IgnoreImpCasts();
191 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Val: Expression)) {
192 // Handle cases where the expression is a variable
193 const VarDecl *Variable = dyn_cast<VarDecl>(Val: AsmDeclRef->getDecl());
194 if (Variable && Variable->getStorageClass() == SC_Register) {
195 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
196 if (Target.isValidGCCRegisterName(Name: Attr->getLabel()))
197 return Target.getNormalizedGCCRegisterName(Name: Attr->getLabel(), ReturnCanonical: true);
198 }
199 }
200 return "";
201}
202
203// Checks if there is a conflict between the input and output lists with the
204// clobbers list. If there's a conflict, returns the location of the
205// conflicted clobber, else returns nullptr
206static SourceLocation
207getClobberConflictLocation(MultiExprArg Exprs, Expr **Constraints,
208 Expr **Clobbers, int NumClobbers, unsigned NumLabels,
209 const TargetInfo &Target, ASTContext &Cont) {
210 llvm::StringSet<> InOutVars;
211 // Collect all the input and output registers from the extended asm
212 // statement in order to check for conflicts with the clobber list
213 for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
214 std::string Constraint =
215 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraints[i]);
216 StringRef InOutReg = Target.getConstraintRegister(
217 Constraint, Expression: extractRegisterName(Expression: Exprs[i], Target));
218 if (InOutReg != "")
219 InOutVars.insert(key: InOutReg);
220 }
221 // Check for each item in the clobber list if it conflicts with the input
222 // or output
223 for (int i = 0; i < NumClobbers; ++i) {
224 std::string Clobber =
225 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Clobbers[i]);
226 // We only check registers, therefore we don't check cc and memory
227 // clobbers
228 if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
229 continue;
230 Clobber = Target.getNormalizedGCCRegisterName(Name: Clobber, ReturnCanonical: true);
231 // Go over the output's registers we collected
232 if (InOutVars.count(Key: Clobber))
233 return Clobbers[i]->getBeginLoc();
234 }
235 return SourceLocation();
236}
237
238ExprResult Sema::ActOnGCCAsmStmtString(Expr *Expr, bool ForAsmLabel) {
239 if (!Expr)
240 return ExprError();
241
242 if (auto *SL = dyn_cast<StringLiteral>(Val: Expr)) {
243 assert(SL->isOrdinary());
244 if (ForAsmLabel && SL->getString().empty()) {
245 Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_asm_operand_empty_string)
246 << SL->getSourceRange();
247 }
248 return SL;
249 }
250 if (DiagnoseUnexpandedParameterPack(E: Expr))
251 return ExprError();
252 if (Expr->getDependence() != ExprDependence::None)
253 return Expr;
254 APValue V;
255 if (!EvaluateAsString(Message: Expr, Result&: V, Ctx&: getASTContext(), EvalContext: StringEvaluationContext::Asm,
256 /*ErrorOnInvalid=*/ErrorOnInvalidMessage: true))
257 return ExprError();
258
259 if (ForAsmLabel && V.getArrayInitializedElts() == 0) {
260 Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_asm_operand_empty_string);
261 }
262
263 ConstantExpr *Res = ConstantExpr::Create(Context: getASTContext(), E: Expr,
264 Storage: ConstantResultStorageKind::APValue);
265 Res->SetResult(Value: V, Context: getASTContext());
266 return Res;
267}
268
269StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
270 bool IsVolatile, unsigned NumOutputs,
271 unsigned NumInputs, IdentifierInfo **Names,
272 MultiExprArg constraints, MultiExprArg Exprs,
273 Expr *asmString, MultiExprArg clobbers,
274 unsigned NumLabels,
275 SourceLocation RParenLoc) {
276 unsigned NumClobbers = clobbers.size();
277
278 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
279
280 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: getCurLexicalContext());
281 llvm::StringMap<bool> FeatureMap;
282 Context.getFunctionFeatureMap(FeatureMap, FD);
283
284 auto CreateGCCAsmStmt = [&] {
285 return new (Context)
286 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
287 Names, constraints.data(), Exprs.data(), asmString,
288 NumClobbers, clobbers.data(), NumLabels, RParenLoc);
289 };
290
291 if (asmString->getDependence() != ExprDependence::None ||
292 llvm::any_of(
293 Range&: constraints,
294 P: [](Expr *E) { return E->getDependence() != ExprDependence::None; }) ||
295 llvm::any_of(Range&: clobbers, P: [](Expr *E) {
296 return E->getDependence() != ExprDependence::None;
297 }))
298 return CreateGCCAsmStmt();
299
300 for (unsigned i = 0; i != NumOutputs; i++) {
301 Expr *Constraint = constraints[i];
302 StringRef OutputName;
303 if (Names[i])
304 OutputName = Names[i]->getName();
305
306 std::string ConstraintStr =
307 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint);
308
309 if (ConstraintStr.find(c: '\0') != std::string::npos) {
310 Diag(Loc: Constraint->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
311 << /*output*/ 0;
312 return CreateGCCAsmStmt();
313 }
314
315 TargetInfo::ConstraintInfo Info(ConstraintStr, OutputName);
316 if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
317 !(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
318 targetDiag(Loc: Constraint->getBeginLoc(),
319 DiagID: diag::err_asm_invalid_output_constraint)
320 << Info.getConstraintStr();
321 return CreateGCCAsmStmt();
322 }
323
324 ExprResult ER = CheckPlaceholderExpr(E: Exprs[i]);
325 if (ER.isInvalid())
326 return StmtError();
327 Exprs[i] = ER.get();
328
329 // Check that the output exprs are valid lvalues.
330 Expr *OutputExpr = Exprs[i];
331
332 // Referring to parameters is not allowed in naked functions.
333 if (CheckNakedParmReference(E: OutputExpr, S&: *this))
334 return StmtError();
335
336 // Check that the output expression is compatible with memory constraint.
337 if (Info.allowsMemory() &&
338 checkExprMemoryConstraintCompat(S&: *this, E: OutputExpr, Info, is_input_expr: false))
339 return StmtError();
340
341 // Disallow bit-precise integer types, since the backends tend to have
342 // difficulties with abnormal sizes.
343 if (OutputExpr->getType()->isBitIntType())
344 return StmtError(
345 Diag(Loc: OutputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
346 << OutputExpr->getType() << 0 /*Input*/
347 << OutputExpr->getSourceRange());
348
349 OutputConstraintInfos.push_back(Elt: Info);
350
351 // If this is dependent, just continue.
352 if (OutputExpr->isTypeDependent())
353 continue;
354
355 Expr::isModifiableLvalueResult IsLV =
356 OutputExpr->isModifiableLvalue(Ctx&: Context, /*Loc=*/nullptr);
357 switch (IsLV) {
358 case Expr::MLV_Valid:
359 // Cool, this is an lvalue.
360 break;
361 case Expr::MLV_ArrayType:
362 // This is OK too.
363 break;
364 case Expr::MLV_LValueCast: {
365 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Ctx: Context);
366 emitAndFixInvalidAsmCastLValue(LVal, BadArgument: OutputExpr, S&: *this);
367 // Accept, even if we emitted an error diagnostic.
368 break;
369 }
370 case Expr::MLV_IncompleteType:
371 case Expr::MLV_IncompleteVoidType:
372 if (RequireCompleteType(Loc: OutputExpr->getBeginLoc(), T: Exprs[i]->getType(),
373 DiagID: diag::err_dereference_incomplete_type))
374 return StmtError();
375 [[fallthrough]];
376 default:
377 return StmtError(Diag(Loc: OutputExpr->getBeginLoc(),
378 DiagID: diag::err_asm_invalid_lvalue_in_output)
379 << OutputExpr->getSourceRange());
380 }
381
382 unsigned Size = Context.getTypeSize(T: OutputExpr->getType());
383 if (!Context.getTargetInfo().validateOutputSize(
384 FeatureMap,
385 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint),
386 Size)) {
387 targetDiag(Loc: OutputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_output_size)
388 << Info.getConstraintStr();
389 return CreateGCCAsmStmt();
390 }
391 }
392
393 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
394
395 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
396 Expr *Constraint = constraints[i];
397
398 StringRef InputName;
399 if (Names[i])
400 InputName = Names[i]->getName();
401
402 std::string ConstraintStr =
403 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint);
404
405 if (ConstraintStr.find(c: '\0') != std::string::npos) {
406 Diag(Loc: Constraint->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
407 << /*input*/ 1;
408 return CreateGCCAsmStmt();
409 }
410
411 TargetInfo::ConstraintInfo Info(ConstraintStr, InputName);
412 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraints: OutputConstraintInfos,
413 info&: Info)) {
414 targetDiag(Loc: Constraint->getBeginLoc(),
415 DiagID: diag::err_asm_invalid_input_constraint)
416 << Info.getConstraintStr();
417 return CreateGCCAsmStmt();
418 }
419
420 ExprResult ER = CheckPlaceholderExpr(E: Exprs[i]);
421 if (ER.isInvalid())
422 return StmtError();
423 Exprs[i] = ER.get();
424
425 Expr *InputExpr = Exprs[i];
426
427 if (InputExpr->getType()->isMemberPointerType())
428 return StmtError(Diag(Loc: InputExpr->getBeginLoc(),
429 DiagID: diag::err_asm_pmf_through_constraint_not_permitted)
430 << InputExpr->getSourceRange());
431
432 // Referring to parameters is not allowed in naked functions.
433 if (CheckNakedParmReference(E: InputExpr, S&: *this))
434 return StmtError();
435
436 // Check that the input expression is compatible with memory constraint.
437 if (Info.allowsMemory() &&
438 checkExprMemoryConstraintCompat(S&: *this, E: InputExpr, Info, is_input_expr: true))
439 return StmtError();
440
441 // Only allow void types for memory constraints.
442 if (Info.allowsMemory() && !Info.allowsRegister()) {
443 if (CheckAsmLValue(E: InputExpr, S&: *this))
444 return StmtError(Diag(Loc: InputExpr->getBeginLoc(),
445 DiagID: diag::err_asm_invalid_lvalue_in_input)
446 << Info.getConstraintStr()
447 << InputExpr->getSourceRange());
448 } else {
449 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: Exprs[i]);
450 if (Result.isInvalid())
451 return StmtError();
452
453 InputExpr = Exprs[i] = Result.get();
454
455 if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
456 if (!InputExpr->isValueDependent()) {
457 Expr::EvalResult EVResult;
458 if (InputExpr->EvaluateAsRValue(Result&: EVResult, Ctx: Context, InConstantContext: true)) {
459 // For compatibility with GCC, we also allow pointers that would be
460 // integral constant expressions if they were cast to int.
461 llvm::APSInt IntResult;
462 if (EVResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: InputExpr->getType(),
463 Ctx: Context))
464 if (!Info.isValidAsmImmediate(Value: IntResult))
465 return StmtError(
466 Diag(Loc: InputExpr->getBeginLoc(),
467 DiagID: diag::err_invalid_asm_value_for_constraint)
468 << toString(I: IntResult, Radix: 10) << Info.getConstraintStr()
469 << InputExpr->getSourceRange());
470 }
471 }
472 }
473 }
474
475 if (Info.allowsRegister()) {
476 if (InputExpr->getType()->isVoidType()) {
477 return StmtError(
478 Diag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type_in_input)
479 << InputExpr->getType() << Info.getConstraintStr()
480 << InputExpr->getSourceRange());
481 }
482 }
483
484 if (InputExpr->getType()->isBitIntType())
485 return StmtError(
486 Diag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
487 << InputExpr->getType() << 1 /*Output*/
488 << InputExpr->getSourceRange());
489
490 InputConstraintInfos.push_back(Elt: Info);
491
492 const Type *Ty = Exprs[i]->getType().getTypePtr();
493 if (Ty->isDependentType())
494 continue;
495
496 if (!Ty->isVoidType() || !Info.allowsMemory())
497 if (RequireCompleteType(Loc: InputExpr->getBeginLoc(), T: Exprs[i]->getType(),
498 DiagID: diag::err_dereference_incomplete_type))
499 return StmtError();
500
501 unsigned Size = Context.getTypeSize(T: Ty);
502 if (!Context.getTargetInfo().validateInputSize(FeatureMap, ConstraintStr,
503 Size))
504 return targetDiag(Loc: InputExpr->getBeginLoc(),
505 DiagID: diag::err_asm_invalid_input_size)
506 << Info.getConstraintStr();
507 }
508
509 std::optional<SourceLocation> UnwindClobberLoc;
510
511 // Check that the clobbers are valid.
512 for (unsigned i = 0; i != NumClobbers; i++) {
513 Expr *ClobberExpr = clobbers[i];
514
515 std::string Clobber =
516 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: ClobberExpr);
517
518 if (Clobber.find(c: '\0') != std::string::npos) {
519 Diag(Loc: ClobberExpr->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
520 << /*clobber*/ 2;
521 return CreateGCCAsmStmt();
522 }
523
524 if (!Context.getTargetInfo().isValidClobber(Name: Clobber)) {
525 targetDiag(Loc: ClobberExpr->getBeginLoc(),
526 DiagID: diag::err_asm_unknown_register_name)
527 << Clobber;
528 return new (Context) GCCAsmStmt(
529 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
530 constraints.data(), Exprs.data(), asmString, NumClobbers,
531 clobbers.data(), NumLabels, RParenLoc);
532 }
533
534 if (Clobber == "unwind") {
535 UnwindClobberLoc = ClobberExpr->getBeginLoc();
536 }
537 }
538
539 // Using unwind clobber and asm-goto together is not supported right now.
540 if (UnwindClobberLoc && NumLabels > 0) {
541 targetDiag(Loc: *UnwindClobberLoc, DiagID: diag::err_asm_unwind_and_goto);
542 return CreateGCCAsmStmt();
543 }
544
545 GCCAsmStmt *NS = CreateGCCAsmStmt();
546 // Validate the asm string, ensuring it makes sense given the operands we
547 // have.
548
549 auto GetLocation = [this](const Expr *Str, unsigned Offset) {
550 if (auto *SL = dyn_cast<StringLiteral>(Val: Str))
551 return getLocationOfStringLiteralByte(SL, ByteNo: Offset);
552 return Str->getBeginLoc();
553 };
554
555 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
556 unsigned DiagOffs;
557 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, C: Context, DiagOffs)) {
558 targetDiag(Loc: GetLocation(asmString, DiagOffs), DiagID)
559 << asmString->getSourceRange();
560 return NS;
561 }
562
563 // Validate constraints and modifiers.
564 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
565 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
566 if (!Piece.isOperand()) continue;
567
568 // Look for the correct constraint index.
569 unsigned ConstraintIdx = Piece.getOperandNo();
570 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
571 // Labels are the last in the Exprs list.
572 if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
573 continue;
574 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
575 // modifier '+'.
576 if (ConstraintIdx >= NumOperands) {
577 unsigned I = 0, E = NS->getNumOutputs();
578
579 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
580 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
581 ConstraintIdx = I;
582 break;
583 }
584
585 assert(I != E && "Invalid operand number should have been caught in "
586 " AnalyzeAsmString");
587 }
588
589 // Now that we have the right indexes go ahead and check.
590 Expr *Constraint = constraints[ConstraintIdx];
591 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
592 if (Ty->isDependentType() || Ty->isIncompleteType())
593 continue;
594
595 unsigned Size = Context.getTypeSize(T: Ty);
596 std::string SuggestedModifier;
597 if (!Context.getTargetInfo().validateConstraintModifier(
598 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint),
599 Piece.getModifier(), Size, SuggestedModifier)) {
600 targetDiag(Loc: Exprs[ConstraintIdx]->getBeginLoc(),
601 DiagID: diag::warn_asm_mismatched_size_modifier);
602
603 if (!SuggestedModifier.empty()) {
604 auto B = targetDiag(Loc: Piece.getRange().getBegin(),
605 DiagID: diag::note_asm_missing_constraint_modifier)
606 << SuggestedModifier;
607 if (isa<StringLiteral>(Val: Constraint)) {
608 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
609 B << FixItHint::CreateReplacement(RemoveRange: Piece.getRange(),
610 Code: SuggestedModifier);
611 }
612 }
613 }
614 }
615
616 // Validate tied input operands for type mismatches.
617 unsigned NumAlternatives = ~0U;
618 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
619 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
620 StringRef ConstraintStr = Info.getConstraintStr();
621 unsigned AltCount = ConstraintStr.count(C: ',') + 1;
622 if (NumAlternatives == ~0U) {
623 NumAlternatives = AltCount;
624 } else if (NumAlternatives != AltCount) {
625 targetDiag(Loc: NS->getOutputExpr(i)->getBeginLoc(),
626 DiagID: diag::err_asm_unexpected_constraint_alternatives)
627 << NumAlternatives << AltCount;
628 return NS;
629 }
630 }
631 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
632 ~0U);
633 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
634 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
635 StringRef ConstraintStr = Info.getConstraintStr();
636 unsigned AltCount = ConstraintStr.count(C: ',') + 1;
637 if (NumAlternatives == ~0U) {
638 NumAlternatives = AltCount;
639 } else if (NumAlternatives != AltCount) {
640 targetDiag(Loc: NS->getInputExpr(i)->getBeginLoc(),
641 DiagID: diag::err_asm_unexpected_constraint_alternatives)
642 << NumAlternatives << AltCount;
643 return NS;
644 }
645
646 // If this is a tied constraint, verify that the output and input have
647 // either exactly the same type, or that they are int/ptr operands with the
648 // same size (int/long, int*/long, are ok etc).
649 if (!Info.hasTiedOperand()) continue;
650
651 unsigned TiedTo = Info.getTiedOperand();
652 unsigned InputOpNo = i+NumOutputs;
653 Expr *OutputExpr = Exprs[TiedTo];
654 Expr *InputExpr = Exprs[InputOpNo];
655
656 // Make sure no more than one input constraint matches each output.
657 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
658 if (InputMatchedToOutput[TiedTo] != ~0U) {
659 targetDiag(Loc: NS->getInputExpr(i)->getBeginLoc(),
660 DiagID: diag::err_asm_input_duplicate_match)
661 << TiedTo;
662 targetDiag(Loc: NS->getInputExpr(i: InputMatchedToOutput[TiedTo])->getBeginLoc(),
663 DiagID: diag::note_asm_input_duplicate_first)
664 << TiedTo;
665 return NS;
666 }
667 InputMatchedToOutput[TiedTo] = i;
668
669 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
670 continue;
671
672 QualType InTy = InputExpr->getType();
673 QualType OutTy = OutputExpr->getType();
674 if (Context.hasSameType(T1: InTy, T2: OutTy))
675 continue; // All types can be tied to themselves.
676
677 // Decide if the input and output are in the same domain (integer/ptr or
678 // floating point.
679 enum AsmDomain {
680 AD_Int, AD_FP, AD_Other
681 } InputDomain, OutputDomain;
682
683 if (InTy->isIntegerType() || InTy->isPointerType())
684 InputDomain = AD_Int;
685 else if (InTy->isRealFloatingType())
686 InputDomain = AD_FP;
687 else
688 InputDomain = AD_Other;
689
690 if (OutTy->isIntegerType() || OutTy->isPointerType())
691 OutputDomain = AD_Int;
692 else if (OutTy->isRealFloatingType())
693 OutputDomain = AD_FP;
694 else
695 OutputDomain = AD_Other;
696
697 // They are ok if they are the same size and in the same domain. This
698 // allows tying things like:
699 // void* to int*
700 // void* to int if they are the same size.
701 // double to long double if they are the same size.
702 //
703 uint64_t OutSize = Context.getTypeSize(T: OutTy);
704 uint64_t InSize = Context.getTypeSize(T: InTy);
705 if (OutSize == InSize && InputDomain == OutputDomain &&
706 InputDomain != AD_Other)
707 continue;
708
709 // If the smaller input/output operand is not mentioned in the asm string,
710 // then we can promote the smaller one to a larger input and the asm string
711 // won't notice.
712 bool SmallerValueMentioned = false;
713
714 // If this is a reference to the input and if the input was the smaller
715 // one, then we have to reject this asm.
716 if (isOperandMentioned(OpNo: InputOpNo, AsmStrPieces: Pieces)) {
717 // This is a use in the asm string of the smaller operand. Since we
718 // codegen this by promoting to a wider value, the asm will get printed
719 // "wrong".
720 SmallerValueMentioned |= InSize < OutSize;
721 }
722 if (isOperandMentioned(OpNo: TiedTo, AsmStrPieces: Pieces)) {
723 // If this is a reference to the output, and if the output is the larger
724 // value, then it's ok because we'll promote the input to the larger type.
725 SmallerValueMentioned |= OutSize < InSize;
726 }
727
728 // If the input is an integer register while the output is floating point,
729 // or vice-versa, there is no way they can work together.
730 bool FPTiedToInt = (InputDomain == AD_FP) ^ (OutputDomain == AD_FP);
731
732 // If the smaller value wasn't mentioned in the asm string, and if the
733 // output was a register, just extend the shorter one to the size of the
734 // larger one.
735 if (!SmallerValueMentioned && !FPTiedToInt && InputDomain != AD_Other &&
736 OutputConstraintInfos[TiedTo].allowsRegister()) {
737
738 // FIXME: GCC supports the OutSize to be 128 at maximum. Currently codegen
739 // crash when the size larger than the register size. So we limit it here.
740 if (OutTy->isStructureType() &&
741 Context.getIntTypeForBitwidth(DestWidth: OutSize, /*Signed*/ false).isNull()) {
742 targetDiag(Loc: OutputExpr->getExprLoc(), DiagID: diag::err_store_value_to_reg);
743 return NS;
744 }
745
746 continue;
747 }
748
749 // Either both of the operands were mentioned or the smaller one was
750 // mentioned. One more special case that we'll allow: if the tied input is
751 // integer, unmentioned, and is a constant, then we'll allow truncating it
752 // down to the size of the destination.
753 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
754 !isOperandMentioned(OpNo: InputOpNo, AsmStrPieces: Pieces) &&
755 InputExpr->isEvaluatable(Ctx: Context)) {
756 CastKind castKind =
757 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
758 InputExpr = ImpCastExprToType(E: InputExpr, Type: OutTy, CK: castKind).get();
759 Exprs[InputOpNo] = InputExpr;
760 NS->setInputExpr(i, E: InputExpr);
761 continue;
762 }
763
764 targetDiag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_tying_incompatible_types)
765 << InTy << OutTy << OutputExpr->getSourceRange()
766 << InputExpr->getSourceRange();
767 return NS;
768 }
769
770 // Check for conflicts between clobber list and input or output lists
771 SourceLocation ConstraintLoc = getClobberConflictLocation(
772 Exprs, Constraints: constraints.data(), Clobbers: clobbers.data(), NumClobbers, NumLabels,
773 Target: Context.getTargetInfo(), Cont&: Context);
774 if (ConstraintLoc.isValid())
775 targetDiag(Loc: ConstraintLoc, DiagID: diag::error_inoutput_conflict_with_clobber);
776
777 // Check for duplicate asm operand name between input, output and label lists.
778 typedef std::pair<StringRef , Expr *> NamedOperand;
779 SmallVector<NamedOperand, 4> NamedOperandList;
780 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
781 if (Names[i])
782 NamedOperandList.emplace_back(
783 Args: std::make_pair(x: Names[i]->getName(), y&: Exprs[i]));
784 // Sort NamedOperandList.
785 llvm::stable_sort(Range&: NamedOperandList, C: llvm::less_first());
786 // Find adjacent duplicate operand.
787 SmallVector<NamedOperand, 4>::iterator Found =
788 std::adjacent_find(first: begin(cont&: NamedOperandList), last: end(cont&: NamedOperandList),
789 binary_pred: [](const NamedOperand &LHS, const NamedOperand &RHS) {
790 return LHS.first == RHS.first;
791 });
792 if (Found != NamedOperandList.end()) {
793 Diag(Loc: (Found + 1)->second->getBeginLoc(),
794 DiagID: diag::error_duplicate_asm_operand_name)
795 << (Found + 1)->first;
796 Diag(Loc: Found->second->getBeginLoc(), DiagID: diag::note_duplicate_asm_operand_name)
797 << Found->first;
798 return StmtError();
799 }
800 if (NS->isAsmGoto())
801 setFunctionHasBranchIntoScope();
802
803 CleanupVarDeclMarking();
804 DiscardCleanupsInEvaluationContext();
805 return NS;
806}
807
808void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
809 llvm::InlineAsmIdentifierInfo &Info) {
810 QualType T = Res->getType();
811 Expr::EvalResult Eval;
812 if (T->isFunctionType() || T->isDependentType())
813 return Info.setLabel(Res);
814 if (Res->isPRValue()) {
815 bool IsEnum = isa<clang::EnumType>(Val: T);
816 if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Val: Res))
817 if (DRE->getDecl()->getKind() == Decl::EnumConstant)
818 IsEnum = true;
819 if (IsEnum && Res->EvaluateAsRValue(Result&: Eval, Ctx: Context))
820 return Info.setEnum(Eval.Val.getInt().getSExtValue());
821
822 return Info.setLabel(Res);
823 }
824 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
825 unsigned Type = Size;
826 if (const auto *ATy = Context.getAsArrayType(T))
827 Type = Context.getTypeSizeInChars(T: ATy->getElementType()).getQuantity();
828 bool IsGlobalLV = false;
829 if (Res->EvaluateAsLValue(Result&: Eval, Ctx: Context))
830 IsGlobalLV = Eval.isGlobalLValue();
831 Info.setVar(decl: Res, isGlobalLV: IsGlobalLV, size: Size, type: Type);
832}
833
834ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
835 SourceLocation TemplateKWLoc,
836 UnqualifiedId &Id,
837 bool IsUnevaluatedContext) {
838
839 if (IsUnevaluatedContext)
840 PushExpressionEvaluationContext(
841 NewContext: ExpressionEvaluationContext::UnevaluatedAbstract,
842 ReuseLambdaContextDecl);
843
844 ExprResult Result = ActOnIdExpression(S: getCurScope(), SS, TemplateKWLoc, Id,
845 /*trailing lparen*/ HasTrailingLParen: false,
846 /*is & operand*/ IsAddressOfOperand: false,
847 /*CorrectionCandidateCallback=*/CCC: nullptr,
848 /*IsInlineAsmIdentifier=*/ true);
849
850 if (IsUnevaluatedContext)
851 PopExpressionEvaluationContext();
852
853 if (!Result.isUsable()) return Result;
854
855 Result = CheckPlaceholderExpr(E: Result.get());
856 if (!Result.isUsable()) return Result;
857
858 // Referring to parameters is not allowed in naked functions.
859 if (CheckNakedParmReference(E: Result.get(), S&: *this))
860 return ExprError();
861
862 QualType T = Result.get()->getType();
863
864 if (T->isDependentType()) {
865 return Result;
866 }
867
868 // Any sort of function type is fine.
869 if (T->isFunctionType()) {
870 return Result;
871 }
872
873 // Otherwise, it needs to be a complete type.
874 if (RequireCompleteExprType(E: Result.get(), DiagID: diag::err_asm_incomplete_type)) {
875 return ExprError();
876 }
877
878 return Result;
879}
880
881bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
882 unsigned &Offset, SourceLocation AsmLoc) {
883 Offset = 0;
884 SmallVector<StringRef, 2> Members;
885 Member.split(A&: Members, Separator: ".");
886
887 NamedDecl *FoundDecl = nullptr;
888
889 // MS InlineAsm uses 'this' as a base
890 if (getLangOpts().CPlusPlus && Base == "this") {
891 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
892 FoundDecl = PT->getPointeeType()->getAsTagDecl();
893 } else {
894 LookupResult BaseResult(*this, &Context.Idents.get(Name: Base), SourceLocation(),
895 LookupOrdinaryName);
896 if (LookupName(R&: BaseResult, S: getCurScope()) && BaseResult.isSingleResult())
897 FoundDecl = BaseResult.getFoundDecl();
898 }
899
900 if (!FoundDecl)
901 return true;
902
903 for (StringRef NextMember : Members) {
904 const RecordType *RT = nullptr;
905 if (VarDecl *VD = dyn_cast<VarDecl>(Val: FoundDecl))
906 RT = VD->getType()->getAsCanonical<RecordType>();
907 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: FoundDecl)) {
908 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
909 // MS InlineAsm often uses struct pointer aliases as a base
910 QualType QT = TD->getUnderlyingType();
911 if (const auto *PT = QT->getAs<PointerType>())
912 QT = PT->getPointeeType();
913 RT = QT->getAsCanonical<RecordType>();
914 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: FoundDecl))
915 RT = QualType(Context.getCanonicalTypeDeclType(TD))
916 ->getAsCanonical<RecordType>();
917 else if (FieldDecl *TD = dyn_cast<FieldDecl>(Val: FoundDecl))
918 RT = TD->getType()->getAsCanonical<RecordType>();
919 if (!RT)
920 return true;
921
922 if (RequireCompleteType(Loc: AsmLoc, T: QualType(RT, 0),
923 DiagID: diag::err_asm_incomplete_type))
924 return true;
925
926 LookupResult FieldResult(*this, &Context.Idents.get(Name: NextMember),
927 SourceLocation(), LookupMemberName);
928
929 RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
930 if (!LookupQualifiedName(R&: FieldResult, LookupCtx: RD))
931 return true;
932
933 if (!FieldResult.isSingleResult())
934 return true;
935 FoundDecl = FieldResult.getFoundDecl();
936
937 // FIXME: Handle IndirectFieldDecl?
938 FieldDecl *FD = dyn_cast<FieldDecl>(Val: FoundDecl);
939 if (!FD)
940 return true;
941
942 const ASTRecordLayout &RL = Context.getASTRecordLayout(D: RD);
943 unsigned i = FD->getFieldIndex();
944 CharUnits Result = Context.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: i));
945 Offset += (unsigned)Result.getQuantity();
946 }
947
948 return false;
949}
950
951ExprResult
952Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
953 SourceLocation AsmLoc) {
954
955 QualType T = E->getType();
956 if (T->isDependentType()) {
957 DeclarationNameInfo NameInfo;
958 NameInfo.setLoc(AsmLoc);
959 NameInfo.setName(&Context.Idents.get(Name: Member));
960 return CXXDependentScopeMemberExpr::Create(
961 Ctx: Context, Base: E, BaseType: T, /*IsArrow=*/false, OperatorLoc: AsmLoc, QualifierLoc: NestedNameSpecifierLoc(),
962 TemplateKWLoc: SourceLocation(),
963 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, /*TemplateArgs=*/nullptr);
964 }
965
966 auto *RD = T->getAsRecordDecl();
967 // FIXME: Diagnose this as field access into a scalar type.
968 if (!RD)
969 return ExprResult();
970
971 LookupResult FieldResult(*this, &Context.Idents.get(Name: Member), AsmLoc,
972 LookupMemberName);
973
974 if (!LookupQualifiedName(R&: FieldResult, LookupCtx: RD))
975 return ExprResult();
976
977 // Only normal and indirect field results will work.
978 ValueDecl *FD = dyn_cast<FieldDecl>(Val: FieldResult.getFoundDecl());
979 if (!FD)
980 FD = dyn_cast<IndirectFieldDecl>(Val: FieldResult.getFoundDecl());
981 if (!FD)
982 return ExprResult();
983
984 // Make an Expr to thread through OpDecl.
985 ExprResult Result = BuildMemberReferenceExpr(
986 Base: E, BaseType: E->getType(), OpLoc: AsmLoc, /*IsArrow=*/false, SS: CXXScopeSpec(),
987 TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: FieldResult, TemplateArgs: nullptr, S: nullptr);
988
989 return Result;
990}
991
992StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
993 ArrayRef<Token> AsmToks,
994 StringRef AsmString,
995 unsigned NumOutputs, unsigned NumInputs,
996 ArrayRef<StringRef> Constraints,
997 ArrayRef<StringRef> Clobbers,
998 ArrayRef<Expr*> Exprs,
999 SourceLocation EndLoc) {
1000 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
1001 setFunctionHasBranchProtectedScope();
1002
1003 bool InvalidOperand = false;
1004 for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
1005 Expr *E = Exprs[I];
1006 if (E->getType()->isBitIntType()) {
1007 InvalidOperand = true;
1008 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
1009 << E->getType() << (I < NumOutputs)
1010 << E->getSourceRange();
1011 } else if (E->refersToBitField()) {
1012 InvalidOperand = true;
1013 FieldDecl *BitField = E->getSourceBitField();
1014 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_ms_asm_bitfield_unsupported)
1015 << E->getSourceRange();
1016 Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl);
1017 }
1018 }
1019 if (InvalidOperand)
1020 return StmtError();
1021
1022 MSAsmStmt *NS =
1023 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
1024 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
1025 Constraints, Exprs, AsmString,
1026 Clobbers, EndLoc);
1027 return NS;
1028}
1029
1030LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
1031 SourceLocation Location,
1032 bool AlwaysCreate) {
1033 LabelDecl* Label = LookupOrCreateLabel(II: PP.getIdentifierInfo(Name: ExternalLabelName),
1034 IdentLoc: Location);
1035
1036 if (Label->isMSAsmLabel()) {
1037 // If we have previously created this label implicitly, mark it as used.
1038 Label->markUsed(C&: Context);
1039 } else {
1040 // Otherwise, insert it, but only resolve it if we have seen the label itself.
1041 std::string InternalName;
1042 llvm::raw_string_ostream OS(InternalName);
1043 // Create an internal name for the label. The name should not be a valid
1044 // mangled name, and should be unique. We use a dot to make the name an
1045 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
1046 // unique label is generated each time this blob is emitted, even after
1047 // inlining or LTO.
1048 OS << "__MSASMLABEL_.${:uid}__";
1049 for (char C : ExternalLabelName) {
1050 OS << C;
1051 // We escape '$' in asm strings by replacing it with "$$"
1052 if (C == '$')
1053 OS << '$';
1054 }
1055 Label->setMSAsmLabel(OS.str());
1056 }
1057 if (AlwaysCreate) {
1058 // The label might have been created implicitly from a previously encountered
1059 // goto statement. So, for both newly created and looked up labels, we mark
1060 // them as resolved.
1061 Label->setMSAsmLabelResolved();
1062 }
1063 // Adjust their location for being able to generate accurate diagnostics.
1064 Label->setLocation(Location);
1065
1066 return Label;
1067}
1068