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