1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===// 2 // 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 14 #include "clang/AST/ExprCXX.h" 15 #include "clang/AST/RecordLayout.h" 16 #include "clang/AST/TypeLoc.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Lex/Preprocessor.h" 19 #include "clang/Sema/Initialization.h" 20 #include "clang/Sema/Lookup.h" 21 #include "clang/Sema/Scope.h" 22 #include "clang/Sema/ScopeInfo.h" 23 #include "clang/Sema/SemaInternal.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/MC/MCParser/MCAsmParser.h" 26 using namespace clang; 27 using namespace sema; 28 29 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 30 /// ignore "noop" casts in places where an lvalue is required by an inline asm. 31 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but 32 /// provide a strong guidance to not use it. 33 /// 34 /// This method checks to see if the argument is an acceptable l-value and 35 /// returns false if it is a case we can handle. 36 static bool CheckAsmLValue(const Expr *E, Sema &S) { 37 // Type dependent expressions will be checked during instantiation. 38 if (E->isTypeDependent()) 39 return false; 40 41 if (E->isLValue()) 42 return false; // Cool, this is an lvalue. 43 44 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 45 // are supposed to allow. 46 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 47 if (E != E2 && E2->isLValue()) { 48 if (!S.getLangOpts().HeinousExtensions) 49 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 50 << E->getSourceRange(); 51 else 52 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 53 << E->getSourceRange(); 54 // Accept, even if we emitted an error diagnostic. 55 return false; 56 } 57 58 // None of the above, just randomly invalid non-lvalue. 59 return true; 60 } 61 62 /// isOperandMentioned - Return true if the specified operand # is mentioned 63 /// anywhere in the decomposed asm string. 64 static bool isOperandMentioned(unsigned OpNo, 65 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) { 66 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 67 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 68 if (!Piece.isOperand()) continue; 69 70 // If this is a reference to the input and if the input was the smaller 71 // one, then we have to reject this asm. 72 if (Piece.getOperandNo() == OpNo) 73 return true; 74 } 75 return false; 76 } 77 78 static bool CheckNakedParmReference(Expr *E, Sema &S) { 79 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext); 80 if (!Func) 81 return false; 82 if (!Func->hasAttr<NakedAttr>()) 83 return false; 84 85 SmallVector<Expr*, 4> WorkList; 86 WorkList.push_back(E); 87 while (WorkList.size()) { 88 Expr *E = WorkList.pop_back_val(); 89 if (isa<CXXThisExpr>(E)) { 90 S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref); 91 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 92 return true; 93 } 94 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 95 if (isa<ParmVarDecl>(DRE->getDecl())) { 96 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref); 97 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 98 return true; 99 } 100 } 101 for (Stmt *Child : E->children()) { 102 if (Expr *E = dyn_cast_or_null<Expr>(Child)) 103 WorkList.push_back(E); 104 } 105 } 106 return false; 107 } 108 109 /// \brief Returns true if given expression is not compatible with inline 110 /// assembly's memory constraint; false otherwise. 111 static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E, 112 TargetInfo::ConstraintInfo &Info, 113 bool is_input_expr) { 114 enum { 115 ExprBitfield = 0, 116 ExprVectorElt, 117 ExprGlobalRegVar, 118 ExprSafeType 119 } EType = ExprSafeType; 120 121 // Bitfields, vector elements and global register variables are not 122 // compatible. 123 if (E->refersToBitField()) 124 EType = ExprBitfield; 125 else if (E->refersToVectorElement()) 126 EType = ExprVectorElt; 127 else if (E->refersToGlobalRegisterVar()) 128 EType = ExprGlobalRegVar; 129 130 if (EType != ExprSafeType) { 131 S.Diag(E->getLocStart(), diag::err_asm_non_addr_value_in_memory_constraint) 132 << EType << is_input_expr << Info.getConstraintStr() 133 << E->getSourceRange(); 134 return true; 135 } 136 137 return false; 138 } 139 140 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 141 bool IsVolatile, unsigned NumOutputs, 142 unsigned NumInputs, IdentifierInfo **Names, 143 MultiExprArg constraints, MultiExprArg Exprs, 144 Expr *asmString, MultiExprArg clobbers, 145 SourceLocation RParenLoc) { 146 unsigned NumClobbers = clobbers.size(); 147 StringLiteral **Constraints = 148 reinterpret_cast<StringLiteral**>(constraints.data()); 149 StringLiteral *AsmString = cast<StringLiteral>(asmString); 150 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data()); 151 152 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 153 154 // The parser verifies that there is a string literal here. 155 assert(AsmString->isAscii()); 156 157 // If we're compiling CUDA file and function attributes indicate that it's not 158 // for this compilation side, skip all the checks. 159 if (!DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) { 160 GCCAsmStmt *NS = new (Context) GCCAsmStmt( 161 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, 162 Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, RParenLoc); 163 return NS; 164 } 165 166 for (unsigned i = 0; i != NumOutputs; i++) { 167 StringLiteral *Literal = Constraints[i]; 168 assert(Literal->isAscii()); 169 170 StringRef OutputName; 171 if (Names[i]) 172 OutputName = Names[i]->getName(); 173 174 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 175 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 176 return StmtError(Diag(Literal->getLocStart(), 177 diag::err_asm_invalid_output_constraint) 178 << Info.getConstraintStr()); 179 180 ExprResult ER = CheckPlaceholderExpr(Exprs[i]); 181 if (ER.isInvalid()) 182 return StmtError(); 183 Exprs[i] = ER.get(); 184 185 // Check that the output exprs are valid lvalues. 186 Expr *OutputExpr = Exprs[i]; 187 188 // Referring to parameters is not allowed in naked functions. 189 if (CheckNakedParmReference(OutputExpr, *this)) 190 return StmtError(); 191 192 // Check that the output expression is compatible with memory constraint. 193 if (Info.allowsMemory() && 194 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false)) 195 return StmtError(); 196 197 OutputConstraintInfos.push_back(Info); 198 199 // If this is dependent, just continue. 200 if (OutputExpr->isTypeDependent()) 201 continue; 202 203 Expr::isModifiableLvalueResult IsLV = 204 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr); 205 switch (IsLV) { 206 case Expr::MLV_Valid: 207 // Cool, this is an lvalue. 208 break; 209 case Expr::MLV_ArrayType: 210 // This is OK too. 211 break; 212 case Expr::MLV_LValueCast: { 213 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context); 214 if (!getLangOpts().HeinousExtensions) { 215 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue) 216 << OutputExpr->getSourceRange(); 217 } else { 218 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 219 << OutputExpr->getSourceRange(); 220 } 221 // Accept, even if we emitted an error diagnostic. 222 break; 223 } 224 case Expr::MLV_IncompleteType: 225 case Expr::MLV_IncompleteVoidType: 226 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(), 227 diag::err_dereference_incomplete_type)) 228 return StmtError(); 229 default: 230 return StmtError(Diag(OutputExpr->getLocStart(), 231 diag::err_asm_invalid_lvalue_in_output) 232 << OutputExpr->getSourceRange()); 233 } 234 235 unsigned Size = Context.getTypeSize(OutputExpr->getType()); 236 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(), 237 Size)) 238 return StmtError(Diag(OutputExpr->getLocStart(), 239 diag::err_asm_invalid_output_size) 240 << Info.getConstraintStr()); 241 } 242 243 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 244 245 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 246 StringLiteral *Literal = Constraints[i]; 247 assert(Literal->isAscii()); 248 249 StringRef InputName; 250 if (Names[i]) 251 InputName = Names[i]->getName(); 252 253 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 254 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos, 255 Info)) { 256 return StmtError(Diag(Literal->getLocStart(), 257 diag::err_asm_invalid_input_constraint) 258 << Info.getConstraintStr()); 259 } 260 261 ExprResult ER = CheckPlaceholderExpr(Exprs[i]); 262 if (ER.isInvalid()) 263 return StmtError(); 264 Exprs[i] = ER.get(); 265 266 Expr *InputExpr = Exprs[i]; 267 268 // Referring to parameters is not allowed in naked functions. 269 if (CheckNakedParmReference(InputExpr, *this)) 270 return StmtError(); 271 272 // Check that the input expression is compatible with memory constraint. 273 if (Info.allowsMemory() && 274 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true)) 275 return StmtError(); 276 277 // Only allow void types for memory constraints. 278 if (Info.allowsMemory() && !Info.allowsRegister()) { 279 if (CheckAsmLValue(InputExpr, *this)) 280 return StmtError(Diag(InputExpr->getLocStart(), 281 diag::err_asm_invalid_lvalue_in_input) 282 << Info.getConstraintStr() 283 << InputExpr->getSourceRange()); 284 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) { 285 if (!InputExpr->isValueDependent()) { 286 llvm::APSInt Result; 287 if (!InputExpr->EvaluateAsInt(Result, Context)) 288 return StmtError( 289 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected) 290 << Info.getConstraintStr() << InputExpr->getSourceRange()); 291 if (!Info.isValidAsmImmediate(Result)) 292 return StmtError(Diag(InputExpr->getLocStart(), 293 diag::err_invalid_asm_value_for_constraint) 294 << Result.toString(10) << Info.getConstraintStr() 295 << InputExpr->getSourceRange()); 296 } 297 298 } else { 299 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 300 if (Result.isInvalid()) 301 return StmtError(); 302 303 Exprs[i] = Result.get(); 304 } 305 306 if (Info.allowsRegister()) { 307 if (InputExpr->getType()->isVoidType()) { 308 return StmtError(Diag(InputExpr->getLocStart(), 309 diag::err_asm_invalid_type_in_input) 310 << InputExpr->getType() << Info.getConstraintStr() 311 << InputExpr->getSourceRange()); 312 } 313 } 314 315 InputConstraintInfos.push_back(Info); 316 317 const Type *Ty = Exprs[i]->getType().getTypePtr(); 318 if (Ty->isDependentType()) 319 continue; 320 321 if (!Ty->isVoidType() || !Info.allowsMemory()) 322 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(), 323 diag::err_dereference_incomplete_type)) 324 return StmtError(); 325 326 unsigned Size = Context.getTypeSize(Ty); 327 if (!Context.getTargetInfo().validateInputSize(Literal->getString(), 328 Size)) 329 return StmtError(Diag(InputExpr->getLocStart(), 330 diag::err_asm_invalid_input_size) 331 << Info.getConstraintStr()); 332 } 333 334 // Check that the clobbers are valid. 335 for (unsigned i = 0; i != NumClobbers; i++) { 336 StringLiteral *Literal = Clobbers[i]; 337 assert(Literal->isAscii()); 338 339 StringRef Clobber = Literal->getString(); 340 341 if (!Context.getTargetInfo().isValidClobber(Clobber)) 342 return StmtError(Diag(Literal->getLocStart(), 343 diag::err_asm_unknown_register_name) << Clobber); 344 } 345 346 GCCAsmStmt *NS = 347 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, 348 NumInputs, Names, Constraints, Exprs.data(), 349 AsmString, NumClobbers, Clobbers, RParenLoc); 350 // Validate the asm string, ensuring it makes sense given the operands we 351 // have. 352 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces; 353 unsigned DiagOffs; 354 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 355 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 356 << AsmString->getSourceRange(); 357 return StmtError(); 358 } 359 360 // Validate constraints and modifiers. 361 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { 362 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i]; 363 if (!Piece.isOperand()) continue; 364 365 // Look for the correct constraint index. 366 unsigned ConstraintIdx = Piece.getOperandNo(); 367 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs(); 368 369 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with 370 // modifier '+'. 371 if (ConstraintIdx >= NumOperands) { 372 unsigned I = 0, E = NS->getNumOutputs(); 373 374 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I) 375 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) { 376 ConstraintIdx = I; 377 break; 378 } 379 380 assert(I != E && "Invalid operand number should have been caught in " 381 " AnalyzeAsmString"); 382 } 383 384 // Now that we have the right indexes go ahead and check. 385 StringLiteral *Literal = Constraints[ConstraintIdx]; 386 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr(); 387 if (Ty->isDependentType() || Ty->isIncompleteType()) 388 continue; 389 390 unsigned Size = Context.getTypeSize(Ty); 391 std::string SuggestedModifier; 392 if (!Context.getTargetInfo().validateConstraintModifier( 393 Literal->getString(), Piece.getModifier(), Size, 394 SuggestedModifier)) { 395 Diag(Exprs[ConstraintIdx]->getLocStart(), 396 diag::warn_asm_mismatched_size_modifier); 397 398 if (!SuggestedModifier.empty()) { 399 auto B = Diag(Piece.getRange().getBegin(), 400 diag::note_asm_missing_constraint_modifier) 401 << SuggestedModifier; 402 SuggestedModifier = "%" + SuggestedModifier + Piece.getString(); 403 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(), 404 SuggestedModifier)); 405 } 406 } 407 } 408 409 // Validate tied input operands for type mismatches. 410 unsigned NumAlternatives = ~0U; 411 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) { 412 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 413 StringRef ConstraintStr = Info.getConstraintStr(); 414 unsigned AltCount = ConstraintStr.count(',') + 1; 415 if (NumAlternatives == ~0U) 416 NumAlternatives = AltCount; 417 else if (NumAlternatives != AltCount) 418 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(), 419 diag::err_asm_unexpected_constraint_alternatives) 420 << NumAlternatives << AltCount); 421 } 422 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(), 423 ~0U); 424 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 425 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 426 StringRef ConstraintStr = Info.getConstraintStr(); 427 unsigned AltCount = ConstraintStr.count(',') + 1; 428 if (NumAlternatives == ~0U) 429 NumAlternatives = AltCount; 430 else if (NumAlternatives != AltCount) 431 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(), 432 diag::err_asm_unexpected_constraint_alternatives) 433 << NumAlternatives << AltCount); 434 435 // If this is a tied constraint, verify that the output and input have 436 // either exactly the same type, or that they are int/ptr operands with the 437 // same size (int/long, int*/long, are ok etc). 438 if (!Info.hasTiedOperand()) continue; 439 440 unsigned TiedTo = Info.getTiedOperand(); 441 unsigned InputOpNo = i+NumOutputs; 442 Expr *OutputExpr = Exprs[TiedTo]; 443 Expr *InputExpr = Exprs[InputOpNo]; 444 445 // Make sure no more than one input constraint matches each output. 446 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range"); 447 if (InputMatchedToOutput[TiedTo] != ~0U) { 448 Diag(NS->getInputExpr(i)->getLocStart(), 449 diag::err_asm_input_duplicate_match) 450 << TiedTo; 451 Diag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getLocStart(), 452 diag::note_asm_input_duplicate_first) 453 << TiedTo; 454 return StmtError(); 455 } 456 InputMatchedToOutput[TiedTo] = i; 457 458 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 459 continue; 460 461 QualType InTy = InputExpr->getType(); 462 QualType OutTy = OutputExpr->getType(); 463 if (Context.hasSameType(InTy, OutTy)) 464 continue; // All types can be tied to themselves. 465 466 // Decide if the input and output are in the same domain (integer/ptr or 467 // floating point. 468 enum AsmDomain { 469 AD_Int, AD_FP, AD_Other 470 } InputDomain, OutputDomain; 471 472 if (InTy->isIntegerType() || InTy->isPointerType()) 473 InputDomain = AD_Int; 474 else if (InTy->isRealFloatingType()) 475 InputDomain = AD_FP; 476 else 477 InputDomain = AD_Other; 478 479 if (OutTy->isIntegerType() || OutTy->isPointerType()) 480 OutputDomain = AD_Int; 481 else if (OutTy->isRealFloatingType()) 482 OutputDomain = AD_FP; 483 else 484 OutputDomain = AD_Other; 485 486 // They are ok if they are the same size and in the same domain. This 487 // allows tying things like: 488 // void* to int* 489 // void* to int if they are the same size. 490 // double to long double if they are the same size. 491 // 492 uint64_t OutSize = Context.getTypeSize(OutTy); 493 uint64_t InSize = Context.getTypeSize(InTy); 494 if (OutSize == InSize && InputDomain == OutputDomain && 495 InputDomain != AD_Other) 496 continue; 497 498 // If the smaller input/output operand is not mentioned in the asm string, 499 // then we can promote the smaller one to a larger input and the asm string 500 // won't notice. 501 bool SmallerValueMentioned = false; 502 503 // If this is a reference to the input and if the input was the smaller 504 // one, then we have to reject this asm. 505 if (isOperandMentioned(InputOpNo, Pieces)) { 506 // This is a use in the asm string of the smaller operand. Since we 507 // codegen this by promoting to a wider value, the asm will get printed 508 // "wrong". 509 SmallerValueMentioned |= InSize < OutSize; 510 } 511 if (isOperandMentioned(TiedTo, Pieces)) { 512 // If this is a reference to the output, and if the output is the larger 513 // value, then it's ok because we'll promote the input to the larger type. 514 SmallerValueMentioned |= OutSize < InSize; 515 } 516 517 // If the smaller value wasn't mentioned in the asm string, and if the 518 // output was a register, just extend the shorter one to the size of the 519 // larger one. 520 if (!SmallerValueMentioned && InputDomain != AD_Other && 521 OutputConstraintInfos[TiedTo].allowsRegister()) 522 continue; 523 524 // Either both of the operands were mentioned or the smaller one was 525 // mentioned. One more special case that we'll allow: if the tied input is 526 // integer, unmentioned, and is a constant, then we'll allow truncating it 527 // down to the size of the destination. 528 if (InputDomain == AD_Int && OutputDomain == AD_Int && 529 !isOperandMentioned(InputOpNo, Pieces) && 530 InputExpr->isEvaluatable(Context)) { 531 CastKind castKind = 532 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 533 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get(); 534 Exprs[InputOpNo] = InputExpr; 535 NS->setInputExpr(i, InputExpr); 536 continue; 537 } 538 539 Diag(InputExpr->getLocStart(), 540 diag::err_asm_tying_incompatible_types) 541 << InTy << OutTy << OutputExpr->getSourceRange() 542 << InputExpr->getSourceRange(); 543 return StmtError(); 544 } 545 546 return NS; 547 } 548 549 static void fillInlineAsmTypeInfo(const ASTContext &Context, QualType T, 550 llvm::InlineAsmIdentifierInfo &Info) { 551 // Compute the type size (and array length if applicable?). 552 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity(); 553 if (T->isArrayType()) { 554 const ArrayType *ATy = Context.getAsArrayType(T); 555 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity(); 556 Info.Length = Info.Size / Info.Type; 557 } 558 } 559 560 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS, 561 SourceLocation TemplateKWLoc, 562 UnqualifiedId &Id, 563 llvm::InlineAsmIdentifierInfo &Info, 564 bool IsUnevaluatedContext) { 565 Info.clear(); 566 567 if (IsUnevaluatedContext) 568 PushExpressionEvaluationContext(UnevaluatedAbstract, 569 ReuseLambdaContextDecl); 570 571 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id, 572 /*trailing lparen*/ false, 573 /*is & operand*/ false, 574 /*CorrectionCandidateCallback=*/nullptr, 575 /*IsInlineAsmIdentifier=*/ true); 576 577 if (IsUnevaluatedContext) 578 PopExpressionEvaluationContext(); 579 580 if (!Result.isUsable()) return Result; 581 582 Result = CheckPlaceholderExpr(Result.get()); 583 if (!Result.isUsable()) return Result; 584 585 // Referring to parameters is not allowed in naked functions. 586 if (CheckNakedParmReference(Result.get(), *this)) 587 return ExprError(); 588 589 QualType T = Result.get()->getType(); 590 591 if (T->isDependentType()) { 592 return Result; 593 } 594 595 // Any sort of function type is fine. 596 if (T->isFunctionType()) { 597 return Result; 598 } 599 600 // Otherwise, it needs to be a complete type. 601 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) { 602 return ExprError(); 603 } 604 605 fillInlineAsmTypeInfo(Context, T, Info); 606 607 // We can work with the expression as long as it's not an r-value. 608 if (!Result.get()->isRValue()) 609 Info.IsVarDecl = true; 610 611 return Result; 612 } 613 614 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member, 615 unsigned &Offset, SourceLocation AsmLoc) { 616 Offset = 0; 617 SmallVector<StringRef, 2> Members; 618 Member.split(Members, "."); 619 620 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(), 621 LookupOrdinaryName); 622 623 if (!LookupName(BaseResult, getCurScope())) 624 return true; 625 626 if(!BaseResult.isSingleResult()) 627 return true; 628 NamedDecl *FoundDecl = BaseResult.getFoundDecl(); 629 for (StringRef NextMember : Members) { 630 const RecordType *RT = nullptr; 631 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) 632 RT = VD->getType()->getAs<RecordType>(); 633 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) { 634 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 635 RT = TD->getUnderlyingType()->getAs<RecordType>(); 636 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl)) 637 RT = TD->getTypeForDecl()->getAs<RecordType>(); 638 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl)) 639 RT = TD->getType()->getAs<RecordType>(); 640 if (!RT) 641 return true; 642 643 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 644 diag::err_asm_incomplete_type)) 645 return true; 646 647 LookupResult FieldResult(*this, &Context.Idents.get(NextMember), 648 SourceLocation(), LookupMemberName); 649 650 if (!LookupQualifiedName(FieldResult, RT->getDecl())) 651 return true; 652 653 if (!FieldResult.isSingleResult()) 654 return true; 655 FoundDecl = FieldResult.getFoundDecl(); 656 657 // FIXME: Handle IndirectFieldDecl? 658 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl); 659 if (!FD) 660 return true; 661 662 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl()); 663 unsigned i = FD->getFieldIndex(); 664 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i)); 665 Offset += (unsigned)Result.getQuantity(); 666 } 667 668 return false; 669 } 670 671 ExprResult 672 Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member, 673 llvm::InlineAsmIdentifierInfo &Info, 674 SourceLocation AsmLoc) { 675 Info.clear(); 676 677 QualType T = E->getType(); 678 if (T->isDependentType()) { 679 DeclarationNameInfo NameInfo; 680 NameInfo.setLoc(AsmLoc); 681 NameInfo.setName(&Context.Idents.get(Member)); 682 return CXXDependentScopeMemberExpr::Create( 683 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(), 684 SourceLocation(), 685 /*FirstQualifierInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr); 686 } 687 688 const RecordType *RT = T->getAs<RecordType>(); 689 // FIXME: Diagnose this as field access into a scalar type. 690 if (!RT) 691 return ExprResult(); 692 693 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc, 694 LookupMemberName); 695 696 if (!LookupQualifiedName(FieldResult, RT->getDecl())) 697 return ExprResult(); 698 699 // Only normal and indirect field results will work. 700 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl()); 701 if (!FD) 702 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl()); 703 if (!FD) 704 return ExprResult(); 705 706 // Make an Expr to thread through OpDecl. 707 ExprResult Result = BuildMemberReferenceExpr( 708 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(), 709 SourceLocation(), nullptr, FieldResult, nullptr, nullptr); 710 if (Result.isInvalid()) 711 return Result; 712 Info.OpDecl = Result.get(); 713 714 fillInlineAsmTypeInfo(Context, Result.get()->getType(), Info); 715 716 // Fields are "variables" as far as inline assembly is concerned. 717 Info.IsVarDecl = true; 718 719 return Result; 720 } 721 722 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 723 ArrayRef<Token> AsmToks, 724 StringRef AsmString, 725 unsigned NumOutputs, unsigned NumInputs, 726 ArrayRef<StringRef> Constraints, 727 ArrayRef<StringRef> Clobbers, 728 ArrayRef<Expr*> Exprs, 729 SourceLocation EndLoc) { 730 bool IsSimple = (NumOutputs != 0 || NumInputs != 0); 731 getCurFunction()->setHasBranchProtectedScope(); 732 MSAsmStmt *NS = 733 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple, 734 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs, 735 Constraints, Exprs, AsmString, 736 Clobbers, EndLoc); 737 return NS; 738 } 739 740 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 741 SourceLocation Location, 742 bool AlwaysCreate) { 743 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName), 744 Location); 745 746 if (Label->isMSAsmLabel()) { 747 // If we have previously created this label implicitly, mark it as used. 748 Label->markUsed(Context); 749 } else { 750 // Otherwise, insert it, but only resolve it if we have seen the label itself. 751 std::string InternalName; 752 llvm::raw_string_ostream OS(InternalName); 753 // Create an internal name for the label. The name should not be a valid mangled 754 // name, and should be unique. We use a dot to make the name an invalid mangled 755 // name. 756 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__"; 757 for (auto it = ExternalLabelName.begin(); it != ExternalLabelName.end(); 758 ++it) { 759 OS << *it; 760 if (*it == '$') { 761 // We escape '$' in asm strings by replacing it with "$$" 762 OS << '$'; 763 } 764 } 765 Label->setMSAsmLabel(OS.str()); 766 } 767 if (AlwaysCreate) { 768 // The label might have been created implicitly from a previously encountered 769 // goto statement. So, for both newly created and looked up labels, we mark 770 // them as resolved. 771 Label->setMSAsmLabelResolved(); 772 } 773 // Adjust their location for being able to generate accurate diagnostics. 774 Label->setLocation(Location); 775 776 return Label; 777 } 778