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/Scope.h" 21 #include "clang/Sema/ScopeInfo.h" 22 #include "clang/Sema/SemaInternal.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/StringSet.h" 25 #include "llvm/MC/MCParser/MCAsmParser.h" 26 using namespace clang; 27 using namespace sema; 28 29 /// Remove the upper-level LValueToRValue cast from an expression. 30 static 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. 69 static 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 81 /// 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. 88 static bool CheckAsmLValue(Expr *E, Sema &S) { 89 // 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()) { 100 emitAndFixInvalidAsmCastLValue(E2, E, S); 101 // 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. 111 static bool 112 isOperandMentioned(unsigned OpNo, 113 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) { 114 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 115 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 116 if (!Piece.isOperand()) 117 continue; 118 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 127 static 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(); 138 if (isa<CXXThisExpr>(E)) { 139 S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref); 140 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 141 return true; 142 } 143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 144 if (isa<ParmVarDecl>(DRE->getDecl())) { 145 S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref); 146 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 158 /// Returns true if given expression is not compatible with inline 159 /// assembly's memory constraint; false otherwise. 160 static 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) { 180 S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint) 181 << EType << is_input_expr << Info.getConstraintStr() 182 << E->getSourceRange(); 183 return true; 184 } 185 186 return false; 187 } 188 189 // Extracting the register name from the Expression value, 190 // if there is no register name to extract, returns "" 191 static 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 209 static SourceLocation 210 getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints, 211 StringLiteral **Clobbers, int NumClobbers, 212 const TargetInfo &Target, ASTContext &Cont) { 213 llvm::StringSet<> InOutVars; 214 // Collect all the input and output registers from the extended asm 215 // statement in order to check for conflicts with the clobber list 216 for (unsigned int i = 0; i < Exprs.size(); ++i) { 217 StringRef Constraint = Constraints[i]->getString(); 218 StringRef InOutReg = Target.getConstraintRegister( 219 Constraint, extractRegisterName(Exprs[i], Target)); 220 if (InOutReg != "") 221 InOutVars.insert(InOutReg); 222 } 223 // Check for each item in the clobber list if it conflicts with the input 224 // or output 225 for (int i = 0; i < NumClobbers; ++i) { 226 StringRef Clobber = Clobbers[i]->getString(); 227 // We only check registers, therefore we don't check cc and memory 228 // clobbers 229 if (Clobber == "cc" || Clobber == "memory") 230 continue; 231 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true); 232 // Go over the output's registers we collected 233 if (InOutVars.count(Clobber)) 234 return Clobbers[i]->getBeginLoc(); 235 } 236 return SourceLocation(); 237 } 238 239 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 240 bool IsVolatile, unsigned NumOutputs, 241 unsigned NumInputs, IdentifierInfo **Names, 242 MultiExprArg constraints, MultiExprArg Exprs, 243 Expr *asmString, MultiExprArg clobbers, 244 SourceLocation RParenLoc) { 245 unsigned NumClobbers = clobbers.size(); 246 StringLiteral **Constraints = 247 reinterpret_cast<StringLiteral**>(constraints.data()); 248 StringLiteral *AsmString = cast<StringLiteral>(asmString); 249 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data()); 250 251 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 252 253 // The parser verifies that there is a string literal here. 254 assert(AsmString->isAscii()); 255 256 for (unsigned i = 0; i != NumOutputs; i++) { 257 StringLiteral *Literal = Constraints[i]; 258 assert(Literal->isAscii()); 259 260 StringRef OutputName; 261 if (Names[i]) 262 OutputName = Names[i]->getName(); 263 264 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 265 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 266 return StmtResult(targetDiag(Literal->getBeginLoc(), 267 diag::err_asm_invalid_output_constraint) 268 << Info.getConstraintStr()); 269 270 ExprResult ER = CheckPlaceholderExpr(Exprs[i]); 271 if (ER.isInvalid()) 272 return StmtError(); 273 Exprs[i] = ER.get(); 274 275 // Check that the output exprs are valid lvalues. 276 Expr *OutputExpr = Exprs[i]; 277 278 // Referring to parameters is not allowed in naked functions. 279 if (CheckNakedParmReference(OutputExpr, *this)) 280 return StmtError(); 281 282 // Check that the output expression is compatible with memory constraint. 283 if (Info.allowsMemory() && 284 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false)) 285 return StmtError(); 286 287 OutputConstraintInfos.push_back(Info); 288 289 // If this is dependent, just continue. 290 if (OutputExpr->isTypeDependent()) 291 continue; 292 293 Expr::isModifiableLvalueResult IsLV = 294 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr); 295 switch (IsLV) { 296 case Expr::MLV_Valid: 297 // Cool, this is an lvalue. 298 break; 299 case Expr::MLV_ArrayType: 300 // This is OK too. 301 break; 302 case Expr::MLV_LValueCast: { 303 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context); 304 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this); 305 // Accept, even if we emitted an error diagnostic. 306 break; 307 } 308 case Expr::MLV_IncompleteType: 309 case Expr::MLV_IncompleteVoidType: 310 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(), 311 diag::err_dereference_incomplete_type)) 312 return StmtError(); 313 LLVM_FALLTHROUGH; 314 default: 315 return StmtError(Diag(OutputExpr->getBeginLoc(), 316 diag::err_asm_invalid_lvalue_in_output) 317 << OutputExpr->getSourceRange()); 318 } 319 320 unsigned Size = Context.getTypeSize(OutputExpr->getType()); 321 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(), Size)) 322 return StmtResult(targetDiag(OutputExpr->getBeginLoc(), 323 diag::err_asm_invalid_output_size) 324 << Info.getConstraintStr()); 325 } 326 327 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 328 329 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 330 StringLiteral *Literal = Constraints[i]; 331 assert(Literal->isAscii()); 332 333 StringRef InputName; 334 if (Names[i]) 335 InputName = Names[i]->getName(); 336 337 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 338 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos, 339 Info)) { 340 return StmtResult(targetDiag(Literal->getBeginLoc(), 341 diag::err_asm_invalid_input_constraint) 342 << Info.getConstraintStr()); 343 } 344 345 ExprResult ER = CheckPlaceholderExpr(Exprs[i]); 346 if (ER.isInvalid()) 347 return StmtError(); 348 Exprs[i] = ER.get(); 349 350 Expr *InputExpr = Exprs[i]; 351 352 // Referring to parameters is not allowed in naked functions. 353 if (CheckNakedParmReference(InputExpr, *this)) 354 return StmtError(); 355 356 // Check that the input expression is compatible with memory constraint. 357 if (Info.allowsMemory() && 358 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true)) 359 return StmtError(); 360 361 // Only allow void types for memory constraints. 362 if (Info.allowsMemory() && !Info.allowsRegister()) { 363 if (CheckAsmLValue(InputExpr, *this)) 364 return StmtError(Diag(InputExpr->getBeginLoc(), 365 diag::err_asm_invalid_lvalue_in_input) 366 << Info.getConstraintStr() 367 << InputExpr->getSourceRange()); 368 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) { 369 if (!InputExpr->isValueDependent()) { 370 Expr::EvalResult EVResult; 371 if (!InputExpr->EvaluateAsRValue(EVResult, Context, true)) 372 return StmtError( 373 Diag(InputExpr->getBeginLoc(), diag::err_asm_immediate_expected) 374 << Info.getConstraintStr() << InputExpr->getSourceRange()); 375 llvm::APSInt Result = EVResult.Val.getInt(); 376 if (!Info.isValidAsmImmediate(Result)) 377 return StmtError(Diag(InputExpr->getBeginLoc(), 378 diag::err_invalid_asm_value_for_constraint) 379 << Result.toString(10) << Info.getConstraintStr() 380 << InputExpr->getSourceRange()); 381 } 382 383 } else { 384 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 385 if (Result.isInvalid()) 386 return StmtError(); 387 388 Exprs[i] = Result.get(); 389 } 390 391 if (Info.allowsRegister()) { 392 if (InputExpr->getType()->isVoidType()) { 393 return StmtError( 394 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input) 395 << InputExpr->getType() << Info.getConstraintStr() 396 << InputExpr->getSourceRange()); 397 } 398 } 399 400 InputConstraintInfos.push_back(Info); 401 402 const Type *Ty = Exprs[i]->getType().getTypePtr(); 403 if (Ty->isDependentType()) 404 continue; 405 406 if (!Ty->isVoidType() || !Info.allowsMemory()) 407 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(), 408 diag::err_dereference_incomplete_type)) 409 return StmtError(); 410 411 unsigned Size = Context.getTypeSize(Ty); 412 if (!Context.getTargetInfo().validateInputSize(Literal->getString(), 413 Size)) 414 return StmtResult( 415 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size) 416 << Info.getConstraintStr()); 417 } 418 419 // Check that the clobbers are valid. 420 for (unsigned i = 0; i != NumClobbers; i++) { 421 StringLiteral *Literal = Clobbers[i]; 422 assert(Literal->isAscii()); 423 424 StringRef Clobber = Literal->getString(); 425 426 if (!Context.getTargetInfo().isValidClobber(Clobber)) 427 return StmtResult(targetDiag(Literal->getBeginLoc(), 428 diag::err_asm_unknown_register_name) 429 << Clobber); 430 } 431 432 GCCAsmStmt *NS = 433 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, 434 NumInputs, Names, Constraints, Exprs.data(), 435 AsmString, NumClobbers, Clobbers, RParenLoc); 436 // Validate the asm string, ensuring it makes sense given the operands we 437 // have. 438 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces; 439 unsigned DiagOffs; 440 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) 441 return StmtResult( 442 targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 443 << AsmString->getSourceRange()); 444 445 // Validate constraints and modifiers. 446 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { 447 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i]; 448 if (!Piece.isOperand()) continue; 449 450 // Look for the correct constraint index. 451 unsigned ConstraintIdx = Piece.getOperandNo(); 452 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs(); 453 454 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with 455 // modifier '+'. 456 if (ConstraintIdx >= NumOperands) { 457 unsigned I = 0, E = NS->getNumOutputs(); 458 459 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I) 460 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) { 461 ConstraintIdx = I; 462 break; 463 } 464 465 assert(I != E && "Invalid operand number should have been caught in " 466 " AnalyzeAsmString"); 467 } 468 469 // Now that we have the right indexes go ahead and check. 470 StringLiteral *Literal = Constraints[ConstraintIdx]; 471 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr(); 472 if (Ty->isDependentType() || Ty->isIncompleteType()) 473 continue; 474 475 unsigned Size = Context.getTypeSize(Ty); 476 std::string SuggestedModifier; 477 if (!Context.getTargetInfo().validateConstraintModifier( 478 Literal->getString(), Piece.getModifier(), Size, 479 SuggestedModifier)) { 480 targetDiag(Exprs[ConstraintIdx]->getBeginLoc(), 481 diag::warn_asm_mismatched_size_modifier); 482 483 if (!SuggestedModifier.empty()) { 484 auto B = targetDiag(Piece.getRange().getBegin(), 485 diag::note_asm_missing_constraint_modifier) 486 << SuggestedModifier; 487 SuggestedModifier = "%" + SuggestedModifier + Piece.getString(); 488 B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier); 489 } 490 } 491 } 492 493 // Validate tied input operands for type mismatches. 494 unsigned NumAlternatives = ~0U; 495 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) { 496 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 497 StringRef ConstraintStr = Info.getConstraintStr(); 498 unsigned AltCount = ConstraintStr.count(',') + 1; 499 if (NumAlternatives == ~0U) 500 NumAlternatives = AltCount; 501 else if (NumAlternatives != AltCount) 502 return StmtResult( 503 targetDiag(NS->getOutputExpr(i)->getBeginLoc(), 504 diag::err_asm_unexpected_constraint_alternatives) 505 << NumAlternatives << AltCount); 506 } 507 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(), 508 ~0U); 509 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 510 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 511 StringRef ConstraintStr = Info.getConstraintStr(); 512 unsigned AltCount = ConstraintStr.count(',') + 1; 513 if (NumAlternatives == ~0U) 514 NumAlternatives = AltCount; 515 else if (NumAlternatives != AltCount) 516 return StmtResult( 517 targetDiag(NS->getInputExpr(i)->getBeginLoc(), 518 diag::err_asm_unexpected_constraint_alternatives) 519 << NumAlternatives << AltCount); 520 521 // If this is a tied constraint, verify that the output and input have 522 // either exactly the same type, or that they are int/ptr operands with the 523 // same size (int/long, int*/long, are ok etc). 524 if (!Info.hasTiedOperand()) continue; 525 526 unsigned TiedTo = Info.getTiedOperand(); 527 unsigned InputOpNo = i+NumOutputs; 528 Expr *OutputExpr = Exprs[TiedTo]; 529 Expr *InputExpr = Exprs[InputOpNo]; 530 531 // Make sure no more than one input constraint matches each output. 532 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range"); 533 if (InputMatchedToOutput[TiedTo] != ~0U) { 534 targetDiag(NS->getInputExpr(i)->getBeginLoc(), 535 diag::err_asm_input_duplicate_match) 536 << TiedTo; 537 return StmtResult( 538 targetDiag( 539 NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(), 540 diag::note_asm_input_duplicate_first) 541 << TiedTo); 542 } 543 InputMatchedToOutput[TiedTo] = i; 544 545 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 546 continue; 547 548 QualType InTy = InputExpr->getType(); 549 QualType OutTy = OutputExpr->getType(); 550 if (Context.hasSameType(InTy, OutTy)) 551 continue; // All types can be tied to themselves. 552 553 // Decide if the input and output are in the same domain (integer/ptr or 554 // floating point. 555 enum AsmDomain { 556 AD_Int, AD_FP, AD_Other 557 } InputDomain, OutputDomain; 558 559 if (InTy->isIntegerType() || InTy->isPointerType()) 560 InputDomain = AD_Int; 561 else if (InTy->isRealFloatingType()) 562 InputDomain = AD_FP; 563 else 564 InputDomain = AD_Other; 565 566 if (OutTy->isIntegerType() || OutTy->isPointerType()) 567 OutputDomain = AD_Int; 568 else if (OutTy->isRealFloatingType()) 569 OutputDomain = AD_FP; 570 else 571 OutputDomain = AD_Other; 572 573 // They are ok if they are the same size and in the same domain. This 574 // allows tying things like: 575 // void* to int* 576 // void* to int if they are the same size. 577 // double to long double if they are the same size. 578 // 579 uint64_t OutSize = Context.getTypeSize(OutTy); 580 uint64_t InSize = Context.getTypeSize(InTy); 581 if (OutSize == InSize && InputDomain == OutputDomain && 582 InputDomain != AD_Other) 583 continue; 584 585 // If the smaller input/output operand is not mentioned in the asm string, 586 // then we can promote the smaller one to a larger input and the asm string 587 // won't notice. 588 bool SmallerValueMentioned = false; 589 590 // If this is a reference to the input and if the input was the smaller 591 // one, then we have to reject this asm. 592 if (isOperandMentioned(InputOpNo, Pieces)) { 593 // This is a use in the asm string of the smaller operand. Since we 594 // codegen this by promoting to a wider value, the asm will get printed 595 // "wrong". 596 SmallerValueMentioned |= InSize < OutSize; 597 } 598 if (isOperandMentioned(TiedTo, Pieces)) { 599 // If this is a reference to the output, and if the output is the larger 600 // value, then it's ok because we'll promote the input to the larger type. 601 SmallerValueMentioned |= OutSize < InSize; 602 } 603 604 // If the smaller value wasn't mentioned in the asm string, and if the 605 // output was a register, just extend the shorter one to the size of the 606 // larger one. 607 if (!SmallerValueMentioned && InputDomain != AD_Other && 608 OutputConstraintInfos[TiedTo].allowsRegister()) 609 continue; 610 611 // Either both of the operands were mentioned or the smaller one was 612 // mentioned. One more special case that we'll allow: if the tied input is 613 // integer, unmentioned, and is a constant, then we'll allow truncating it 614 // down to the size of the destination. 615 if (InputDomain == AD_Int && OutputDomain == AD_Int && 616 !isOperandMentioned(InputOpNo, Pieces) && 617 InputExpr->isEvaluatable(Context)) { 618 CastKind castKind = 619 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 620 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get(); 621 Exprs[InputOpNo] = InputExpr; 622 NS->setInputExpr(i, InputExpr); 623 continue; 624 } 625 626 return StmtResult(targetDiag(InputExpr->getBeginLoc(), 627 diag::err_asm_tying_incompatible_types) 628 << InTy << OutTy << OutputExpr->getSourceRange() 629 << InputExpr->getSourceRange()); 630 } 631 632 // Check for conflicts between clobber list and input or output lists 633 SourceLocation ConstraintLoc = 634 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers, 635 Context.getTargetInfo(), Context); 636 if (ConstraintLoc.isValid()) 637 return StmtResult( 638 targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber)); 639 640 return NS; 641 } 642 643 void Sema::FillInlineAsmIdentifierInfo(Expr *Res, 644 llvm::InlineAsmIdentifierInfo &Info) { 645 QualType T = Res->getType(); 646 Expr::EvalResult Eval; 647 if (T->isFunctionType() || T->isDependentType()) 648 return Info.setLabel(Res); 649 if (Res->isRValue()) { 650 if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context)) 651 return Info.setEnum(Eval.Val.getInt().getSExtValue()); 652 return Info.setLabel(Res); 653 } 654 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 655 unsigned Type = Size; 656 if (const auto *ATy = Context.getAsArrayType(T)) 657 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity(); 658 bool IsGlobalLV = false; 659 if (Res->EvaluateAsLValue(Eval, Context)) 660 IsGlobalLV = Eval.isGlobalLValue(); 661 Info.setVar(Res, IsGlobalLV, Size, Type); 662 } 663 664 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS, 665 SourceLocation TemplateKWLoc, 666 UnqualifiedId &Id, 667 bool IsUnevaluatedContext) { 668 669 if (IsUnevaluatedContext) 670 PushExpressionEvaluationContext( 671 ExpressionEvaluationContext::UnevaluatedAbstract, 672 ReuseLambdaContextDecl); 673 674 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id, 675 /*trailing lparen*/ false, 676 /*is & operand*/ false, 677 /*CorrectionCandidateCallback=*/nullptr, 678 /*IsInlineAsmIdentifier=*/ true); 679 680 if (IsUnevaluatedContext) 681 PopExpressionEvaluationContext(); 682 683 if (!Result.isUsable()) return Result; 684 685 Result = CheckPlaceholderExpr(Result.get()); 686 if (!Result.isUsable()) return Result; 687 688 // Referring to parameters is not allowed in naked functions. 689 if (CheckNakedParmReference(Result.get(), *this)) 690 return ExprError(); 691 692 QualType T = Result.get()->getType(); 693 694 if (T->isDependentType()) { 695 return Result; 696 } 697 698 // Any sort of function type is fine. 699 if (T->isFunctionType()) { 700 return Result; 701 } 702 703 // Otherwise, it needs to be a complete type. 704 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) { 705 return ExprError(); 706 } 707 708 return Result; 709 } 710 711 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member, 712 unsigned &Offset, SourceLocation AsmLoc) { 713 Offset = 0; 714 SmallVector<StringRef, 2> Members; 715 Member.split(Members, "."); 716 717 NamedDecl *FoundDecl = nullptr; 718 719 // MS InlineAsm uses 'this' as a base 720 if (getLangOpts().CPlusPlus && Base.equals("this")) { 721 if (const Type *PT = getCurrentThisType().getTypePtrOrNull()) 722 FoundDecl = PT->getPointeeType()->getAsTagDecl(); 723 } else { 724 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(), 725 LookupOrdinaryName); 726 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult()) 727 FoundDecl = BaseResult.getFoundDecl(); 728 } 729 730 if (!FoundDecl) 731 return true; 732 733 for (StringRef NextMember : Members) { 734 const RecordType *RT = nullptr; 735 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) 736 RT = VD->getType()->getAs<RecordType>(); 737 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) { 738 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 739 // MS InlineAsm often uses struct pointer aliases as a base 740 QualType QT = TD->getUnderlyingType(); 741 if (const auto *PT = QT->getAs<PointerType>()) 742 QT = PT->getPointeeType(); 743 RT = QT->getAs<RecordType>(); 744 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl)) 745 RT = TD->getTypeForDecl()->getAs<RecordType>(); 746 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl)) 747 RT = TD->getType()->getAs<RecordType>(); 748 if (!RT) 749 return true; 750 751 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 752 diag::err_asm_incomplete_type)) 753 return true; 754 755 LookupResult FieldResult(*this, &Context.Idents.get(NextMember), 756 SourceLocation(), LookupMemberName); 757 758 if (!LookupQualifiedName(FieldResult, RT->getDecl())) 759 return true; 760 761 if (!FieldResult.isSingleResult()) 762 return true; 763 FoundDecl = FieldResult.getFoundDecl(); 764 765 // FIXME: Handle IndirectFieldDecl? 766 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl); 767 if (!FD) 768 return true; 769 770 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl()); 771 unsigned i = FD->getFieldIndex(); 772 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i)); 773 Offset += (unsigned)Result.getQuantity(); 774 } 775 776 return false; 777 } 778 779 ExprResult 780 Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member, 781 SourceLocation AsmLoc) { 782 783 QualType T = E->getType(); 784 if (T->isDependentType()) { 785 DeclarationNameInfo NameInfo; 786 NameInfo.setLoc(AsmLoc); 787 NameInfo.setName(&Context.Idents.get(Member)); 788 return CXXDependentScopeMemberExpr::Create( 789 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(), 790 SourceLocation(), 791 /*FirstQualifierInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr); 792 } 793 794 const RecordType *RT = T->getAs<RecordType>(); 795 // FIXME: Diagnose this as field access into a scalar type. 796 if (!RT) 797 return ExprResult(); 798 799 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc, 800 LookupMemberName); 801 802 if (!LookupQualifiedName(FieldResult, RT->getDecl())) 803 return ExprResult(); 804 805 // Only normal and indirect field results will work. 806 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl()); 807 if (!FD) 808 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl()); 809 if (!FD) 810 return ExprResult(); 811 812 // Make an Expr to thread through OpDecl. 813 ExprResult Result = BuildMemberReferenceExpr( 814 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(), 815 SourceLocation(), nullptr, FieldResult, nullptr, nullptr); 816 817 return Result; 818 } 819 820 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 821 ArrayRef<Token> AsmToks, 822 StringRef AsmString, 823 unsigned NumOutputs, unsigned NumInputs, 824 ArrayRef<StringRef> Constraints, 825 ArrayRef<StringRef> Clobbers, 826 ArrayRef<Expr*> Exprs, 827 SourceLocation EndLoc) { 828 bool IsSimple = (NumOutputs != 0 || NumInputs != 0); 829 setFunctionHasBranchProtectedScope(); 830 MSAsmStmt *NS = 831 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple, 832 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs, 833 Constraints, Exprs, AsmString, 834 Clobbers, EndLoc); 835 return NS; 836 } 837 838 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 839 SourceLocation Location, 840 bool AlwaysCreate) { 841 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName), 842 Location); 843 844 if (Label->isMSAsmLabel()) { 845 // If we have previously created this label implicitly, mark it as used. 846 Label->markUsed(Context); 847 } else { 848 // Otherwise, insert it, but only resolve it if we have seen the label itself. 849 std::string InternalName; 850 llvm::raw_string_ostream OS(InternalName); 851 // Create an internal name for the label. The name should not be a valid 852 // mangled name, and should be unique. We use a dot to make the name an 853 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a 854 // unique label is generated each time this blob is emitted, even after 855 // inlining or LTO. 856 OS << "__MSASMLABEL_.${:uid}__"; 857 for (char C : ExternalLabelName) { 858 OS << C; 859 // We escape '$' in asm strings by replacing it with "$$" 860 if (C == '$') 861 OS << '$'; 862 } 863 Label->setMSAsmLabel(OS.str()); 864 } 865 if (AlwaysCreate) { 866 // The label might have been created implicitly from a previously encountered 867 // goto statement. So, for both newly created and looked up labels, we mark 868 // them as resolved. 869 Label->setMSAsmLabelResolved(); 870 } 871 // Adjust their location for being able to generate accurate diagnostics. 872 Label->setLocation(Location); 873 874 return Label; 875 } 876