1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 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 extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 /// Check the number of arguments and set the result type to 195 /// the argument type. 196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 197 if (checkArgCount(S, TheCall, 1)) 198 return true; 199 200 TheCall->setType(TheCall->getArg(0)->getType()); 201 return false; 202 } 203 204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 206 /// type (but not a function pointer) and that the alignment is a power-of-two. 207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 208 if (checkArgCount(S, TheCall, 2)) 209 return true; 210 211 clang::Expr *Source = TheCall->getArg(0); 212 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 213 214 auto IsValidIntegerType = [](QualType Ty) { 215 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 216 }; 217 QualType SrcTy = Source->getType(); 218 // We should also be able to use it with arrays (but not functions!). 219 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 220 SrcTy = S.Context.getDecayedType(SrcTy); 221 } 222 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 223 SrcTy->isFunctionPointerType()) { 224 // FIXME: this is not quite the right error message since we don't allow 225 // floating point types, or member pointers. 226 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 227 << SrcTy; 228 return true; 229 } 230 231 clang::Expr *AlignOp = TheCall->getArg(1); 232 if (!IsValidIntegerType(AlignOp->getType())) { 233 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 234 << AlignOp->getType(); 235 return true; 236 } 237 Expr::EvalResult AlignResult; 238 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 239 // We can't check validity of alignment if it is type dependent. 240 if (!AlignOp->isInstantiationDependent() && 241 AlignOp->EvaluateAsInt(AlignResult, S.Context, 242 Expr::SE_AllowSideEffects)) { 243 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 244 llvm::APSInt MaxValue( 245 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 246 if (AlignValue < 1) { 247 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 248 return true; 249 } 250 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 252 << MaxValue.toString(10); 253 return true; 254 } 255 if (!AlignValue.isPowerOf2()) { 256 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 257 return true; 258 } 259 if (AlignValue == 1) { 260 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 261 << IsBooleanAlignBuiltin; 262 } 263 } 264 265 ExprResult SrcArg = S.PerformCopyInitialization( 266 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 267 SourceLocation(), Source); 268 if (SrcArg.isInvalid()) 269 return true; 270 TheCall->setArg(0, SrcArg.get()); 271 ExprResult AlignArg = 272 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 273 S.Context, AlignOp->getType(), false), 274 SourceLocation(), AlignOp); 275 if (AlignArg.isInvalid()) 276 return true; 277 TheCall->setArg(1, AlignArg.get()); 278 // For align_up/align_down, the return type is the same as the (potentially 279 // decayed) argument type including qualifiers. For is_aligned(), the result 280 // is always bool. 281 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 282 return false; 283 } 284 285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 286 if (checkArgCount(S, TheCall, 3)) 287 return true; 288 289 // First two arguments should be integers. 290 for (unsigned I = 0; I < 2; ++I) { 291 ExprResult Arg = TheCall->getArg(I); 292 QualType Ty = Arg.get()->getType(); 293 if (!Ty->isIntegerType()) { 294 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 295 << Ty << Arg.get()->getSourceRange(); 296 return true; 297 } 298 InitializedEntity Entity = InitializedEntity::InitializeParameter( 299 S.getASTContext(), Ty, /*consume*/ false); 300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 301 if (Arg.isInvalid()) 302 return true; 303 TheCall->setArg(I, Arg.get()); 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = TheCall->getArg(2); 311 QualType Ty = Arg.get()->getType(); 312 const auto *PtrTy = Ty->getAs<PointerType>(); 313 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 314 !PtrTy->getPointeeType().isConstQualified())) { 315 S.Diag(Arg.get()->getBeginLoc(), 316 diag::err_overflow_builtin_must_be_ptr_int) 317 << Ty << Arg.get()->getSourceRange(); 318 return true; 319 } 320 InitializedEntity Entity = InitializedEntity::InitializeParameter( 321 S.getASTContext(), Ty, /*consume*/ false); 322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 323 if (Arg.isInvalid()) 324 return true; 325 TheCall->setArg(2, Arg.get()); 326 } 327 return false; 328 } 329 330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 331 if (checkArgCount(S, BuiltinCall, 2)) 332 return true; 333 334 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 335 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 336 Expr *Call = BuiltinCall->getArg(0); 337 Expr *Chain = BuiltinCall->getArg(1); 338 339 if (Call->getStmtClass() != Stmt::CallExprClass) { 340 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 341 << Call->getSourceRange(); 342 return true; 343 } 344 345 auto CE = cast<CallExpr>(Call); 346 if (CE->getCallee()->getType()->isBlockPointerType()) { 347 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 348 << Call->getSourceRange(); 349 return true; 350 } 351 352 const Decl *TargetDecl = CE->getCalleeDecl(); 353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 354 if (FD->getBuiltinID()) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 367 if (ChainResult.isInvalid()) 368 return true; 369 if (!ChainResult.get()->getType()->isPointerType()) { 370 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 371 << Chain->getSourceRange(); 372 return true; 373 } 374 375 QualType ReturnTy = CE->getCallReturnType(S.Context); 376 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 377 QualType BuiltinTy = S.Context.getFunctionType( 378 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 379 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 380 381 Builtin = 382 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 383 384 BuiltinCall->setType(CE->getType()); 385 BuiltinCall->setValueKind(CE->getValueKind()); 386 BuiltinCall->setObjectKind(CE->getObjectKind()); 387 BuiltinCall->setCallee(Builtin); 388 BuiltinCall->setArg(1, ChainResult.get()); 389 390 return false; 391 } 392 393 namespace { 394 395 class EstimateSizeFormatHandler 396 : public analyze_format_string::FormatStringHandler { 397 size_t Size; 398 399 public: 400 EstimateSizeFormatHandler(StringRef Format) 401 : Size(std::min(Format.find(0), Format.size()) + 402 1 /* null byte always written by sprintf */) {} 403 404 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 405 const char *, unsigned SpecifierLen) override { 406 407 const size_t FieldWidth = computeFieldWidth(FS); 408 const size_t Precision = computePrecision(FS); 409 410 // The actual format. 411 switch (FS.getConversionSpecifier().getKind()) { 412 // Just a char. 413 case analyze_format_string::ConversionSpecifier::cArg: 414 case analyze_format_string::ConversionSpecifier::CArg: 415 Size += std::max(FieldWidth, (size_t)1); 416 break; 417 // Just an integer. 418 case analyze_format_string::ConversionSpecifier::dArg: 419 case analyze_format_string::ConversionSpecifier::DArg: 420 case analyze_format_string::ConversionSpecifier::iArg: 421 case analyze_format_string::ConversionSpecifier::oArg: 422 case analyze_format_string::ConversionSpecifier::OArg: 423 case analyze_format_string::ConversionSpecifier::uArg: 424 case analyze_format_string::ConversionSpecifier::UArg: 425 case analyze_format_string::ConversionSpecifier::xArg: 426 case analyze_format_string::ConversionSpecifier::XArg: 427 Size += std::max(FieldWidth, Precision); 428 break; 429 430 // %g style conversion switches between %f or %e style dynamically. 431 // %f always takes less space, so default to it. 432 case analyze_format_string::ConversionSpecifier::gArg: 433 case analyze_format_string::ConversionSpecifier::GArg: 434 435 // Floating point number in the form '[+]ddd.ddd'. 436 case analyze_format_string::ConversionSpecifier::fArg: 437 case analyze_format_string::ConversionSpecifier::FArg: 438 Size += std::max(FieldWidth, 1 /* integer part */ + 439 (Precision ? 1 + Precision 440 : 0) /* period + decimal */); 441 break; 442 443 // Floating point number in the form '[-]d.ddde[+-]dd'. 444 case analyze_format_string::ConversionSpecifier::eArg: 445 case analyze_format_string::ConversionSpecifier::EArg: 446 Size += 447 std::max(FieldWidth, 448 1 /* integer part */ + 449 (Precision ? 1 + Precision : 0) /* period + decimal */ + 450 1 /* e or E letter */ + 2 /* exponent */); 451 break; 452 453 // Floating point number in the form '[-]0xh.hhhhp±dd'. 454 case analyze_format_string::ConversionSpecifier::aArg: 455 case analyze_format_string::ConversionSpecifier::AArg: 456 Size += 457 std::max(FieldWidth, 458 2 /* 0x */ + 1 /* integer part */ + 459 (Precision ? 1 + Precision : 0) /* period + decimal */ + 460 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 461 break; 462 463 // Just a string. 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::SArg: 466 Size += FieldWidth; 467 break; 468 469 // Just a pointer in the form '0xddd'. 470 case analyze_format_string::ConversionSpecifier::pArg: 471 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 472 break; 473 474 // A plain percent. 475 case analyze_format_string::ConversionSpecifier::PercentArg: 476 Size += 1; 477 break; 478 479 default: 480 break; 481 } 482 483 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 484 485 if (FS.hasAlternativeForm()) { 486 switch (FS.getConversionSpecifier().getKind()) { 487 default: 488 break; 489 // Force a leading '0'. 490 case analyze_format_string::ConversionSpecifier::oArg: 491 Size += 1; 492 break; 493 // Force a leading '0x'. 494 case analyze_format_string::ConversionSpecifier::xArg: 495 case analyze_format_string::ConversionSpecifier::XArg: 496 Size += 2; 497 break; 498 // Force a period '.' before decimal, even if precision is 0. 499 case analyze_format_string::ConversionSpecifier::aArg: 500 case analyze_format_string::ConversionSpecifier::AArg: 501 case analyze_format_string::ConversionSpecifier::eArg: 502 case analyze_format_string::ConversionSpecifier::EArg: 503 case analyze_format_string::ConversionSpecifier::fArg: 504 case analyze_format_string::ConversionSpecifier::FArg: 505 case analyze_format_string::ConversionSpecifier::gArg: 506 case analyze_format_string::ConversionSpecifier::GArg: 507 Size += (Precision ? 0 : 1); 508 break; 509 } 510 } 511 assert(SpecifierLen <= Size && "no underflow"); 512 Size -= SpecifierLen; 513 return true; 514 } 515 516 size_t getSizeLowerBound() const { return Size; } 517 518 private: 519 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 520 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 521 size_t FieldWidth = 0; 522 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 523 FieldWidth = FW.getConstantAmount(); 524 return FieldWidth; 525 } 526 527 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 528 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 529 size_t Precision = 0; 530 531 // See man 3 printf for default precision value based on the specifier. 532 switch (FW.getHowSpecified()) { 533 case analyze_format_string::OptionalAmount::NotSpecified: 534 switch (FS.getConversionSpecifier().getKind()) { 535 default: 536 break; 537 case analyze_format_string::ConversionSpecifier::dArg: // %d 538 case analyze_format_string::ConversionSpecifier::DArg: // %D 539 case analyze_format_string::ConversionSpecifier::iArg: // %i 540 Precision = 1; 541 break; 542 case analyze_format_string::ConversionSpecifier::oArg: // %d 543 case analyze_format_string::ConversionSpecifier::OArg: // %D 544 case analyze_format_string::ConversionSpecifier::uArg: // %d 545 case analyze_format_string::ConversionSpecifier::UArg: // %D 546 case analyze_format_string::ConversionSpecifier::xArg: // %d 547 case analyze_format_string::ConversionSpecifier::XArg: // %D 548 Precision = 1; 549 break; 550 case analyze_format_string::ConversionSpecifier::fArg: // %f 551 case analyze_format_string::ConversionSpecifier::FArg: // %F 552 case analyze_format_string::ConversionSpecifier::eArg: // %e 553 case analyze_format_string::ConversionSpecifier::EArg: // %E 554 case analyze_format_string::ConversionSpecifier::gArg: // %g 555 case analyze_format_string::ConversionSpecifier::GArg: // %G 556 Precision = 6; 557 break; 558 case analyze_format_string::ConversionSpecifier::pArg: // %d 559 Precision = 1; 560 break; 561 } 562 break; 563 case analyze_format_string::OptionalAmount::Constant: 564 Precision = FW.getConstantAmount(); 565 break; 566 default: 567 break; 568 } 569 return Precision; 570 } 571 }; 572 573 } // namespace 574 575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 576 /// __builtin_*_chk function, then use the object size argument specified in the 577 /// source. Otherwise, infer the object size using __builtin_object_size. 578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 579 CallExpr *TheCall) { 580 // FIXME: There are some more useful checks we could be doing here: 581 // - Evaluate strlen of strcpy arguments, use as object size. 582 583 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 584 isConstantEvaluated()) 585 return; 586 587 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 588 if (!BuiltinID) 589 return; 590 591 const TargetInfo &TI = getASTContext().getTargetInfo(); 592 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 593 594 unsigned DiagID = 0; 595 bool IsChkVariant = false; 596 Optional<llvm::APSInt> UsedSize; 597 unsigned SizeIndex, ObjectIndex; 598 switch (BuiltinID) { 599 default: 600 return; 601 case Builtin::BIsprintf: 602 case Builtin::BI__builtin___sprintf_chk: { 603 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 604 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 605 606 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 607 608 if (!Format->isAscii() && !Format->isUTF8()) 609 return; 610 611 StringRef FormatStrRef = Format->getString(); 612 EstimateSizeFormatHandler H(FormatStrRef); 613 const char *FormatBytes = FormatStrRef.data(); 614 const ConstantArrayType *T = 615 Context.getAsConstantArrayType(Format->getType()); 616 assert(T && "String literal not of constant array type!"); 617 size_t TypeSize = T->getSize().getZExtValue(); 618 619 // In case there's a null byte somewhere. 620 size_t StrLen = 621 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 622 if (!analyze_format_string::ParsePrintfString( 623 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 624 Context.getTargetInfo(), false)) { 625 DiagID = diag::warn_fortify_source_format_overflow; 626 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 627 .extOrTrunc(SizeTypeWidth); 628 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 629 IsChkVariant = true; 630 ObjectIndex = 2; 631 } else { 632 IsChkVariant = false; 633 ObjectIndex = 0; 634 } 635 break; 636 } 637 } 638 return; 639 } 640 case Builtin::BI__builtin___memcpy_chk: 641 case Builtin::BI__builtin___memmove_chk: 642 case Builtin::BI__builtin___memset_chk: 643 case Builtin::BI__builtin___strlcat_chk: 644 case Builtin::BI__builtin___strlcpy_chk: 645 case Builtin::BI__builtin___strncat_chk: 646 case Builtin::BI__builtin___strncpy_chk: 647 case Builtin::BI__builtin___stpncpy_chk: 648 case Builtin::BI__builtin___memccpy_chk: 649 case Builtin::BI__builtin___mempcpy_chk: { 650 DiagID = diag::warn_builtin_chk_overflow; 651 IsChkVariant = true; 652 SizeIndex = TheCall->getNumArgs() - 2; 653 ObjectIndex = TheCall->getNumArgs() - 1; 654 break; 655 } 656 657 case Builtin::BI__builtin___snprintf_chk: 658 case Builtin::BI__builtin___vsnprintf_chk: { 659 DiagID = diag::warn_builtin_chk_overflow; 660 IsChkVariant = true; 661 SizeIndex = 1; 662 ObjectIndex = 3; 663 break; 664 } 665 666 case Builtin::BIstrncat: 667 case Builtin::BI__builtin_strncat: 668 case Builtin::BIstrncpy: 669 case Builtin::BI__builtin_strncpy: 670 case Builtin::BIstpncpy: 671 case Builtin::BI__builtin_stpncpy: { 672 // Whether these functions overflow depends on the runtime strlen of the 673 // string, not just the buffer size, so emitting the "always overflow" 674 // diagnostic isn't quite right. We should still diagnose passing a buffer 675 // size larger than the destination buffer though; this is a runtime abort 676 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 677 DiagID = diag::warn_fortify_source_size_mismatch; 678 SizeIndex = TheCall->getNumArgs() - 1; 679 ObjectIndex = 0; 680 break; 681 } 682 683 case Builtin::BImemcpy: 684 case Builtin::BI__builtin_memcpy: 685 case Builtin::BImemmove: 686 case Builtin::BI__builtin_memmove: 687 case Builtin::BImemset: 688 case Builtin::BI__builtin_memset: 689 case Builtin::BImempcpy: 690 case Builtin::BI__builtin_mempcpy: { 691 DiagID = diag::warn_fortify_source_overflow; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 case Builtin::BIsnprintf: 697 case Builtin::BI__builtin_snprintf: 698 case Builtin::BIvsnprintf: 699 case Builtin::BI__builtin_vsnprintf: { 700 DiagID = diag::warn_fortify_source_size_mismatch; 701 SizeIndex = 1; 702 ObjectIndex = 0; 703 break; 704 } 705 } 706 707 llvm::APSInt ObjectSize; 708 // For __builtin___*_chk, the object size is explicitly provided by the caller 709 // (usually using __builtin_object_size). Use that value to check this call. 710 if (IsChkVariant) { 711 Expr::EvalResult Result; 712 Expr *SizeArg = TheCall->getArg(ObjectIndex); 713 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 714 return; 715 ObjectSize = Result.Val.getInt(); 716 717 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 718 } else { 719 // If the parameter has a pass_object_size attribute, then we should use its 720 // (potentially) more strict checking mode. Otherwise, conservatively assume 721 // type 0. 722 int BOSType = 0; 723 if (const auto *POS = 724 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 725 BOSType = POS->getType(); 726 727 Expr *ObjArg = TheCall->getArg(ObjectIndex); 728 uint64_t Result; 729 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 730 return; 731 // Get the object size in the target's size_t width. 732 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 733 } 734 735 // Evaluate the number of bytes of the object that this call will use. 736 if (!UsedSize) { 737 Expr::EvalResult Result; 738 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 739 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 740 return; 741 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 742 } 743 744 if (UsedSize.getValue().ule(ObjectSize)) 745 return; 746 747 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 748 // Skim off the details of whichever builtin was called to produce a better 749 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 750 if (IsChkVariant) { 751 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 752 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 753 } else if (FunctionName.startswith("__builtin_")) { 754 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 755 } 756 757 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 758 PDiag(DiagID) 759 << FunctionName << ObjectSize.toString(/*Radix=*/10) 760 << UsedSize.getValue().toString(/*Radix=*/10)); 761 } 762 763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 764 Scope::ScopeFlags NeededScopeFlags, 765 unsigned DiagID) { 766 // Scopes aren't available during instantiation. Fortunately, builtin 767 // functions cannot be template args so they cannot be formed through template 768 // instantiation. Therefore checking once during the parse is sufficient. 769 if (SemaRef.inTemplateInstantiation()) 770 return false; 771 772 Scope *S = SemaRef.getCurScope(); 773 while (S && !S->isSEHExceptScope()) 774 S = S->getParent(); 775 if (!S || !(S->getFlags() & NeededScopeFlags)) { 776 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 777 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 778 << DRE->getDecl()->getIdentifier(); 779 return true; 780 } 781 782 return false; 783 } 784 785 static inline bool isBlockPointer(Expr *Arg) { 786 return Arg->getType()->isBlockPointerType(); 787 } 788 789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 790 /// void*, which is a requirement of device side enqueue. 791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 792 const BlockPointerType *BPT = 793 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 794 ArrayRef<QualType> Params = 795 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 796 unsigned ArgCounter = 0; 797 bool IllegalParams = false; 798 // Iterate through the block parameters until either one is found that is not 799 // a local void*, or the block is valid. 800 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 801 I != E; ++I, ++ArgCounter) { 802 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 803 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 804 LangAS::opencl_local) { 805 // Get the location of the error. If a block literal has been passed 806 // (BlockExpr) then we can point straight to the offending argument, 807 // else we just point to the variable reference. 808 SourceLocation ErrorLoc; 809 if (isa<BlockExpr>(BlockArg)) { 810 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 811 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 812 } else if (isa<DeclRefExpr>(BlockArg)) { 813 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 814 } 815 S.Diag(ErrorLoc, 816 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 817 IllegalParams = true; 818 } 819 } 820 821 return IllegalParams; 822 } 823 824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 825 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 826 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 827 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 828 return true; 829 } 830 return false; 831 } 832 833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 834 if (checkArgCount(S, TheCall, 2)) 835 return true; 836 837 if (checkOpenCLSubgroupExt(S, TheCall)) 838 return true; 839 840 // First argument is an ndrange_t type. 841 Expr *NDRangeArg = TheCall->getArg(0); 842 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 843 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 844 << TheCall->getDirectCallee() << "'ndrange_t'"; 845 return true; 846 } 847 848 Expr *BlockArg = TheCall->getArg(1); 849 if (!isBlockPointer(BlockArg)) { 850 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 851 << TheCall->getDirectCallee() << "block"; 852 return true; 853 } 854 return checkOpenCLBlockArgs(S, BlockArg); 855 } 856 857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 858 /// get_kernel_work_group_size 859 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 861 if (checkArgCount(S, TheCall, 1)) 862 return true; 863 864 Expr *BlockArg = TheCall->getArg(0); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// Diagnose integer type and any valid implicit conversion to it. 874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 875 const QualType &IntType); 876 877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 878 unsigned Start, unsigned End) { 879 bool IllegalParams = false; 880 for (unsigned I = Start; I <= End; ++I) 881 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 882 S.Context.getSizeType()); 883 return IllegalParams; 884 } 885 886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 887 /// 'local void*' parameter of passed block. 888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 889 Expr *BlockArg, 890 unsigned NumNonVarArgs) { 891 const BlockPointerType *BPT = 892 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 893 unsigned NumBlockParams = 894 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 895 unsigned TotalNumArgs = TheCall->getNumArgs(); 896 897 // For each argument passed to the block, a corresponding uint needs to 898 // be passed to describe the size of the local memory. 899 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 900 S.Diag(TheCall->getBeginLoc(), 901 diag::err_opencl_enqueue_kernel_local_size_args); 902 return true; 903 } 904 905 // Check that the sizes of the local memory are specified by integers. 906 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 907 TotalNumArgs - 1); 908 } 909 910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 911 /// overload formats specified in Table 6.13.17.1. 912 /// int enqueue_kernel(queue_t queue, 913 /// kernel_enqueue_flags_t flags, 914 /// const ndrange_t ndrange, 915 /// void (^block)(void)) 916 /// int enqueue_kernel(queue_t queue, 917 /// kernel_enqueue_flags_t flags, 918 /// const ndrange_t ndrange, 919 /// uint num_events_in_wait_list, 920 /// clk_event_t *event_wait_list, 921 /// clk_event_t *event_ret, 922 /// void (^block)(void)) 923 /// int enqueue_kernel(queue_t queue, 924 /// kernel_enqueue_flags_t flags, 925 /// const ndrange_t ndrange, 926 /// void (^block)(local void*, ...), 927 /// uint size0, ...) 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// uint num_events_in_wait_list, 932 /// clk_event_t *event_wait_list, 933 /// clk_event_t *event_ret, 934 /// void (^block)(local void*, ...), 935 /// uint size0, ...) 936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 937 unsigned NumArgs = TheCall->getNumArgs(); 938 939 if (NumArgs < 4) { 940 S.Diag(TheCall->getBeginLoc(), 941 diag::err_typecheck_call_too_few_args_at_least) 942 << 0 << 4 << NumArgs; 943 return true; 944 } 945 946 Expr *Arg0 = TheCall->getArg(0); 947 Expr *Arg1 = TheCall->getArg(1); 948 Expr *Arg2 = TheCall->getArg(2); 949 Expr *Arg3 = TheCall->getArg(3); 950 951 // First argument always needs to be a queue_t type. 952 if (!Arg0->getType()->isQueueT()) { 953 S.Diag(TheCall->getArg(0)->getBeginLoc(), 954 diag::err_opencl_builtin_expected_type) 955 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 956 return true; 957 } 958 959 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 960 if (!Arg1->getType()->isIntegerType()) { 961 S.Diag(TheCall->getArg(1)->getBeginLoc(), 962 diag::err_opencl_builtin_expected_type) 963 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 964 return true; 965 } 966 967 // Third argument is always an ndrange_t type. 968 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 969 S.Diag(TheCall->getArg(2)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << "'ndrange_t'"; 972 return true; 973 } 974 975 // With four arguments, there is only one form that the function could be 976 // called in: no events and no variable arguments. 977 if (NumArgs == 4) { 978 // check that the last argument is the right block type. 979 if (!isBlockPointer(Arg3)) { 980 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 981 << TheCall->getDirectCallee() << "block"; 982 return true; 983 } 984 // we have a block type, check the prototype 985 const BlockPointerType *BPT = 986 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 987 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 988 S.Diag(Arg3->getBeginLoc(), 989 diag::err_opencl_enqueue_kernel_blocks_no_args); 990 return true; 991 } 992 return false; 993 } 994 // we can have block + varargs. 995 if (isBlockPointer(Arg3)) 996 return (checkOpenCLBlockArgs(S, Arg3) || 997 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 998 // last two cases with either exactly 7 args or 7 args and varargs. 999 if (NumArgs >= 7) { 1000 // check common block argument. 1001 Expr *Arg6 = TheCall->getArg(6); 1002 if (!isBlockPointer(Arg6)) { 1003 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1004 << TheCall->getDirectCallee() << "block"; 1005 return true; 1006 } 1007 if (checkOpenCLBlockArgs(S, Arg6)) 1008 return true; 1009 1010 // Forth argument has to be any integer type. 1011 if (!Arg3->getType()->isIntegerType()) { 1012 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1013 diag::err_opencl_builtin_expected_type) 1014 << TheCall->getDirectCallee() << "integer"; 1015 return true; 1016 } 1017 // check remaining common arguments. 1018 Expr *Arg4 = TheCall->getArg(4); 1019 Expr *Arg5 = TheCall->getArg(5); 1020 1021 // Fifth argument is always passed as a pointer to clk_event_t. 1022 if (!Arg4->isNullPointerConstant(S.Context, 1023 Expr::NPC_ValueDependentIsNotNull) && 1024 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1025 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1026 diag::err_opencl_builtin_expected_type) 1027 << TheCall->getDirectCallee() 1028 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1029 return true; 1030 } 1031 1032 // Sixth argument is always passed as a pointer to clk_event_t. 1033 if (!Arg5->isNullPointerConstant(S.Context, 1034 Expr::NPC_ValueDependentIsNotNull) && 1035 !(Arg5->getType()->isPointerType() && 1036 Arg5->getType()->getPointeeType()->isClkEventT())) { 1037 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1038 diag::err_opencl_builtin_expected_type) 1039 << TheCall->getDirectCallee() 1040 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1041 return true; 1042 } 1043 1044 if (NumArgs == 7) 1045 return false; 1046 1047 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1048 } 1049 1050 // None of the specific case has been detected, give generic error 1051 S.Diag(TheCall->getBeginLoc(), 1052 diag::err_opencl_enqueue_kernel_incorrect_args); 1053 return true; 1054 } 1055 1056 /// Returns OpenCL access qual. 1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1058 return D->getAttr<OpenCLAccessAttr>(); 1059 } 1060 1061 /// Returns true if pipe element type is different from the pointer. 1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1063 const Expr *Arg0 = Call->getArg(0); 1064 // First argument type should always be pipe. 1065 if (!Arg0->getType()->isPipeType()) { 1066 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1067 << Call->getDirectCallee() << Arg0->getSourceRange(); 1068 return true; 1069 } 1070 OpenCLAccessAttr *AccessQual = 1071 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1072 // Validates the access qualifier is compatible with the call. 1073 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1074 // read_only and write_only, and assumed to be read_only if no qualifier is 1075 // specified. 1076 switch (Call->getDirectCallee()->getBuiltinID()) { 1077 case Builtin::BIread_pipe: 1078 case Builtin::BIreserve_read_pipe: 1079 case Builtin::BIcommit_read_pipe: 1080 case Builtin::BIwork_group_reserve_read_pipe: 1081 case Builtin::BIsub_group_reserve_read_pipe: 1082 case Builtin::BIwork_group_commit_read_pipe: 1083 case Builtin::BIsub_group_commit_read_pipe: 1084 if (!(!AccessQual || AccessQual->isReadOnly())) { 1085 S.Diag(Arg0->getBeginLoc(), 1086 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1087 << "read_only" << Arg0->getSourceRange(); 1088 return true; 1089 } 1090 break; 1091 case Builtin::BIwrite_pipe: 1092 case Builtin::BIreserve_write_pipe: 1093 case Builtin::BIcommit_write_pipe: 1094 case Builtin::BIwork_group_reserve_write_pipe: 1095 case Builtin::BIsub_group_reserve_write_pipe: 1096 case Builtin::BIwork_group_commit_write_pipe: 1097 case Builtin::BIsub_group_commit_write_pipe: 1098 if (!(AccessQual && AccessQual->isWriteOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "write_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 default: 1106 break; 1107 } 1108 return false; 1109 } 1110 1111 /// Returns true if pipe element type is different from the pointer. 1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1113 const Expr *Arg0 = Call->getArg(0); 1114 const Expr *ArgIdx = Call->getArg(Idx); 1115 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1116 const QualType EltTy = PipeTy->getElementType(); 1117 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1118 // The Idx argument should be a pointer and the type of the pointer and 1119 // the type of pipe element should also be the same. 1120 if (!ArgTy || 1121 !S.Context.hasSameType( 1122 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1123 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1124 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1125 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 // Performs semantic analysis for the read/write_pipe call. 1132 // \param S Reference to the semantic analyzer. 1133 // \param Call A pointer to the builtin call. 1134 // \return True if a semantic error has been found, false otherwise. 1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1136 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1137 // functions have two forms. 1138 switch (Call->getNumArgs()) { 1139 case 2: 1140 if (checkOpenCLPipeArg(S, Call)) 1141 return true; 1142 // The call with 2 arguments should be 1143 // read/write_pipe(pipe T, T*). 1144 // Check packet type T. 1145 if (checkOpenCLPipePacketType(S, Call, 1)) 1146 return true; 1147 break; 1148 1149 case 4: { 1150 if (checkOpenCLPipeArg(S, Call)) 1151 return true; 1152 // The call with 4 arguments should be 1153 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1154 // Check reserve_id_t. 1155 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1156 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1157 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1158 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1159 return true; 1160 } 1161 1162 // Check the index. 1163 const Expr *Arg2 = Call->getArg(2); 1164 if (!Arg2->getType()->isIntegerType() && 1165 !Arg2->getType()->isUnsignedIntegerType()) { 1166 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1167 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1168 << Arg2->getType() << Arg2->getSourceRange(); 1169 return true; 1170 } 1171 1172 // Check packet type T. 1173 if (checkOpenCLPipePacketType(S, Call, 3)) 1174 return true; 1175 } break; 1176 default: 1177 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1178 << Call->getDirectCallee() << Call->getSourceRange(); 1179 return true; 1180 } 1181 1182 return false; 1183 } 1184 1185 // Performs a semantic analysis on the {work_group_/sub_group_ 1186 // /_}reserve_{read/write}_pipe 1187 // \param S Reference to the semantic analyzer. 1188 // \param Call The call to the builtin function to be analyzed. 1189 // \return True if a semantic error was found, false otherwise. 1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1191 if (checkArgCount(S, Call, 2)) 1192 return true; 1193 1194 if (checkOpenCLPipeArg(S, Call)) 1195 return true; 1196 1197 // Check the reserve size. 1198 if (!Call->getArg(1)->getType()->isIntegerType() && 1199 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1200 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1201 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1202 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1203 return true; 1204 } 1205 1206 // Since return type of reserve_read/write_pipe built-in function is 1207 // reserve_id_t, which is not defined in the builtin def file , we used int 1208 // as return type and need to override the return type of these functions. 1209 Call->setType(S.Context.OCLReserveIDTy); 1210 1211 return false; 1212 } 1213 1214 // Performs a semantic analysis on {work_group_/sub_group_ 1215 // /_}commit_{read/write}_pipe 1216 // \param S Reference to the semantic analyzer. 1217 // \param Call The call to the builtin function to be analyzed. 1218 // \return True if a semantic error was found, false otherwise. 1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1220 if (checkArgCount(S, Call, 2)) 1221 return true; 1222 1223 if (checkOpenCLPipeArg(S, Call)) 1224 return true; 1225 1226 // Check reserve_id_t. 1227 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1228 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1229 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1230 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1231 return true; 1232 } 1233 1234 return false; 1235 } 1236 1237 // Performs a semantic analysis on the call to built-in Pipe 1238 // Query Functions. 1239 // \param S Reference to the semantic analyzer. 1240 // \param Call The call to the builtin function to be analyzed. 1241 // \return True if a semantic error was found, false otherwise. 1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1243 if (checkArgCount(S, Call, 1)) 1244 return true; 1245 1246 if (!Call->getArg(0)->getType()->isPipeType()) { 1247 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1248 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1249 return true; 1250 } 1251 1252 return false; 1253 } 1254 1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1256 // Performs semantic analysis for the to_global/local/private call. 1257 // \param S Reference to the semantic analyzer. 1258 // \param BuiltinID ID of the builtin function. 1259 // \param Call A pointer to the builtin call. 1260 // \return True if a semantic error has been found, false otherwise. 1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1262 CallExpr *Call) { 1263 if (Call->getNumArgs() != 1) { 1264 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1265 << Call->getDirectCallee() << Call->getSourceRange(); 1266 return true; 1267 } 1268 1269 auto RT = Call->getArg(0)->getType(); 1270 if (!RT->isPointerType() || RT->getPointeeType() 1271 .getAddressSpace() == LangAS::opencl_constant) { 1272 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1273 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1274 return true; 1275 } 1276 1277 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1278 S.Diag(Call->getArg(0)->getBeginLoc(), 1279 diag::warn_opencl_generic_address_space_arg) 1280 << Call->getDirectCallee()->getNameInfo().getAsString() 1281 << Call->getArg(0)->getSourceRange(); 1282 } 1283 1284 RT = RT->getPointeeType(); 1285 auto Qual = RT.getQualifiers(); 1286 switch (BuiltinID) { 1287 case Builtin::BIto_global: 1288 Qual.setAddressSpace(LangAS::opencl_global); 1289 break; 1290 case Builtin::BIto_local: 1291 Qual.setAddressSpace(LangAS::opencl_local); 1292 break; 1293 case Builtin::BIto_private: 1294 Qual.setAddressSpace(LangAS::opencl_private); 1295 break; 1296 default: 1297 llvm_unreachable("Invalid builtin function"); 1298 } 1299 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1300 RT.getUnqualifiedType(), Qual))); 1301 1302 return false; 1303 } 1304 1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1306 if (checkArgCount(S, TheCall, 1)) 1307 return ExprError(); 1308 1309 // Compute __builtin_launder's parameter type from the argument. 1310 // The parameter type is: 1311 // * The type of the argument if it's not an array or function type, 1312 // Otherwise, 1313 // * The decayed argument type. 1314 QualType ParamTy = [&]() { 1315 QualType ArgTy = TheCall->getArg(0)->getType(); 1316 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1317 return S.Context.getPointerType(Ty->getElementType()); 1318 if (ArgTy->isFunctionType()) { 1319 return S.Context.getPointerType(ArgTy); 1320 } 1321 return ArgTy; 1322 }(); 1323 1324 TheCall->setType(ParamTy); 1325 1326 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1327 if (!ParamTy->isPointerType()) 1328 return 0; 1329 if (ParamTy->isFunctionPointerType()) 1330 return 1; 1331 if (ParamTy->isVoidPointerType()) 1332 return 2; 1333 return llvm::Optional<unsigned>{}; 1334 }(); 1335 if (DiagSelect.hasValue()) { 1336 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1337 << DiagSelect.getValue() << TheCall->getSourceRange(); 1338 return ExprError(); 1339 } 1340 1341 // We either have an incomplete class type, or we have a class template 1342 // whose instantiation has not been forced. Example: 1343 // 1344 // template <class T> struct Foo { T value; }; 1345 // Foo<int> *p = nullptr; 1346 // auto *d = __builtin_launder(p); 1347 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1348 diag::err_incomplete_type)) 1349 return ExprError(); 1350 1351 assert(ParamTy->getPointeeType()->isObjectType() && 1352 "Unhandled non-object pointer case"); 1353 1354 InitializedEntity Entity = 1355 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1356 ExprResult Arg = 1357 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1358 if (Arg.isInvalid()) 1359 return ExprError(); 1360 TheCall->setArg(0, Arg.get()); 1361 1362 return TheCall; 1363 } 1364 1365 // Emit an error and return true if the current architecture is not in the list 1366 // of supported architectures. 1367 static bool 1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1369 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1370 llvm::Triple::ArchType CurArch = 1371 S.getASTContext().getTargetInfo().getTriple().getArch(); 1372 if (llvm::is_contained(SupportedArchs, CurArch)) 1373 return false; 1374 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1375 << TheCall->getSourceRange(); 1376 return true; 1377 } 1378 1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1380 SourceLocation CallSiteLoc); 1381 1382 ExprResult 1383 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1384 CallExpr *TheCall) { 1385 ExprResult TheCallResult(TheCall); 1386 1387 // Find out if any arguments are required to be integer constant expressions. 1388 unsigned ICEArguments = 0; 1389 ASTContext::GetBuiltinTypeError Error; 1390 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1391 if (Error != ASTContext::GE_None) 1392 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1393 1394 // If any arguments are required to be ICE's, check and diagnose. 1395 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1396 // Skip arguments not required to be ICE's. 1397 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1398 1399 llvm::APSInt Result; 1400 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1401 return true; 1402 ICEArguments &= ~(1 << ArgNo); 1403 } 1404 1405 switch (BuiltinID) { 1406 case Builtin::BI__builtin___CFStringMakeConstantString: 1407 assert(TheCall->getNumArgs() == 1 && 1408 "Wrong # arguments to builtin CFStringMakeConstantString"); 1409 if (CheckObjCString(TheCall->getArg(0))) 1410 return ExprError(); 1411 break; 1412 case Builtin::BI__builtin_ms_va_start: 1413 case Builtin::BI__builtin_stdarg_start: 1414 case Builtin::BI__builtin_va_start: 1415 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1416 return ExprError(); 1417 break; 1418 case Builtin::BI__va_start: { 1419 switch (Context.getTargetInfo().getTriple().getArch()) { 1420 case llvm::Triple::aarch64: 1421 case llvm::Triple::arm: 1422 case llvm::Triple::thumb: 1423 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1424 return ExprError(); 1425 break; 1426 default: 1427 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1428 return ExprError(); 1429 break; 1430 } 1431 break; 1432 } 1433 1434 // The acquire, release, and no fence variants are ARM and AArch64 only. 1435 case Builtin::BI_interlockedbittestandset_acq: 1436 case Builtin::BI_interlockedbittestandset_rel: 1437 case Builtin::BI_interlockedbittestandset_nf: 1438 case Builtin::BI_interlockedbittestandreset_acq: 1439 case Builtin::BI_interlockedbittestandreset_rel: 1440 case Builtin::BI_interlockedbittestandreset_nf: 1441 if (CheckBuiltinTargetSupport( 1442 *this, BuiltinID, TheCall, 1443 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1444 return ExprError(); 1445 break; 1446 1447 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1448 case Builtin::BI_bittest64: 1449 case Builtin::BI_bittestandcomplement64: 1450 case Builtin::BI_bittestandreset64: 1451 case Builtin::BI_bittestandset64: 1452 case Builtin::BI_interlockedbittestandreset64: 1453 case Builtin::BI_interlockedbittestandset64: 1454 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1455 {llvm::Triple::x86_64, llvm::Triple::arm, 1456 llvm::Triple::thumb, llvm::Triple::aarch64})) 1457 return ExprError(); 1458 break; 1459 1460 case Builtin::BI__builtin_isgreater: 1461 case Builtin::BI__builtin_isgreaterequal: 1462 case Builtin::BI__builtin_isless: 1463 case Builtin::BI__builtin_islessequal: 1464 case Builtin::BI__builtin_islessgreater: 1465 case Builtin::BI__builtin_isunordered: 1466 if (SemaBuiltinUnorderedCompare(TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_fpclassify: 1470 if (SemaBuiltinFPClassification(TheCall, 6)) 1471 return ExprError(); 1472 break; 1473 case Builtin::BI__builtin_isfinite: 1474 case Builtin::BI__builtin_isinf: 1475 case Builtin::BI__builtin_isinf_sign: 1476 case Builtin::BI__builtin_isnan: 1477 case Builtin::BI__builtin_isnormal: 1478 case Builtin::BI__builtin_signbit: 1479 case Builtin::BI__builtin_signbitf: 1480 case Builtin::BI__builtin_signbitl: 1481 if (SemaBuiltinFPClassification(TheCall, 1)) 1482 return ExprError(); 1483 break; 1484 case Builtin::BI__builtin_shufflevector: 1485 return SemaBuiltinShuffleVector(TheCall); 1486 // TheCall will be freed by the smart pointer here, but that's fine, since 1487 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1488 case Builtin::BI__builtin_prefetch: 1489 if (SemaBuiltinPrefetch(TheCall)) 1490 return ExprError(); 1491 break; 1492 case Builtin::BI__builtin_alloca_with_align: 1493 if (SemaBuiltinAllocaWithAlign(TheCall)) 1494 return ExprError(); 1495 LLVM_FALLTHROUGH; 1496 case Builtin::BI__builtin_alloca: 1497 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1498 << TheCall->getDirectCallee(); 1499 break; 1500 case Builtin::BI__assume: 1501 case Builtin::BI__builtin_assume: 1502 if (SemaBuiltinAssume(TheCall)) 1503 return ExprError(); 1504 break; 1505 case Builtin::BI__builtin_assume_aligned: 1506 if (SemaBuiltinAssumeAligned(TheCall)) 1507 return ExprError(); 1508 break; 1509 case Builtin::BI__builtin_dynamic_object_size: 1510 case Builtin::BI__builtin_object_size: 1511 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_longjmp: 1515 if (SemaBuiltinLongjmp(TheCall)) 1516 return ExprError(); 1517 break; 1518 case Builtin::BI__builtin_setjmp: 1519 if (SemaBuiltinSetjmp(TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI_setjmp: 1523 case Builtin::BI_setjmpex: 1524 if (checkArgCount(*this, TheCall, 1)) 1525 return true; 1526 break; 1527 case Builtin::BI__builtin_classify_type: 1528 if (checkArgCount(*this, TheCall, 1)) return true; 1529 TheCall->setType(Context.IntTy); 1530 break; 1531 case Builtin::BI__builtin_constant_p: { 1532 if (checkArgCount(*this, TheCall, 1)) return true; 1533 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1534 if (Arg.isInvalid()) return true; 1535 TheCall->setArg(0, Arg.get()); 1536 TheCall->setType(Context.IntTy); 1537 break; 1538 } 1539 case Builtin::BI__builtin_launder: 1540 return SemaBuiltinLaunder(*this, TheCall); 1541 case Builtin::BI__sync_fetch_and_add: 1542 case Builtin::BI__sync_fetch_and_add_1: 1543 case Builtin::BI__sync_fetch_and_add_2: 1544 case Builtin::BI__sync_fetch_and_add_4: 1545 case Builtin::BI__sync_fetch_and_add_8: 1546 case Builtin::BI__sync_fetch_and_add_16: 1547 case Builtin::BI__sync_fetch_and_sub: 1548 case Builtin::BI__sync_fetch_and_sub_1: 1549 case Builtin::BI__sync_fetch_and_sub_2: 1550 case Builtin::BI__sync_fetch_and_sub_4: 1551 case Builtin::BI__sync_fetch_and_sub_8: 1552 case Builtin::BI__sync_fetch_and_sub_16: 1553 case Builtin::BI__sync_fetch_and_or: 1554 case Builtin::BI__sync_fetch_and_or_1: 1555 case Builtin::BI__sync_fetch_and_or_2: 1556 case Builtin::BI__sync_fetch_and_or_4: 1557 case Builtin::BI__sync_fetch_and_or_8: 1558 case Builtin::BI__sync_fetch_and_or_16: 1559 case Builtin::BI__sync_fetch_and_and: 1560 case Builtin::BI__sync_fetch_and_and_1: 1561 case Builtin::BI__sync_fetch_and_and_2: 1562 case Builtin::BI__sync_fetch_and_and_4: 1563 case Builtin::BI__sync_fetch_and_and_8: 1564 case Builtin::BI__sync_fetch_and_and_16: 1565 case Builtin::BI__sync_fetch_and_xor: 1566 case Builtin::BI__sync_fetch_and_xor_1: 1567 case Builtin::BI__sync_fetch_and_xor_2: 1568 case Builtin::BI__sync_fetch_and_xor_4: 1569 case Builtin::BI__sync_fetch_and_xor_8: 1570 case Builtin::BI__sync_fetch_and_xor_16: 1571 case Builtin::BI__sync_fetch_and_nand: 1572 case Builtin::BI__sync_fetch_and_nand_1: 1573 case Builtin::BI__sync_fetch_and_nand_2: 1574 case Builtin::BI__sync_fetch_and_nand_4: 1575 case Builtin::BI__sync_fetch_and_nand_8: 1576 case Builtin::BI__sync_fetch_and_nand_16: 1577 case Builtin::BI__sync_add_and_fetch: 1578 case Builtin::BI__sync_add_and_fetch_1: 1579 case Builtin::BI__sync_add_and_fetch_2: 1580 case Builtin::BI__sync_add_and_fetch_4: 1581 case Builtin::BI__sync_add_and_fetch_8: 1582 case Builtin::BI__sync_add_and_fetch_16: 1583 case Builtin::BI__sync_sub_and_fetch: 1584 case Builtin::BI__sync_sub_and_fetch_1: 1585 case Builtin::BI__sync_sub_and_fetch_2: 1586 case Builtin::BI__sync_sub_and_fetch_4: 1587 case Builtin::BI__sync_sub_and_fetch_8: 1588 case Builtin::BI__sync_sub_and_fetch_16: 1589 case Builtin::BI__sync_and_and_fetch: 1590 case Builtin::BI__sync_and_and_fetch_1: 1591 case Builtin::BI__sync_and_and_fetch_2: 1592 case Builtin::BI__sync_and_and_fetch_4: 1593 case Builtin::BI__sync_and_and_fetch_8: 1594 case Builtin::BI__sync_and_and_fetch_16: 1595 case Builtin::BI__sync_or_and_fetch: 1596 case Builtin::BI__sync_or_and_fetch_1: 1597 case Builtin::BI__sync_or_and_fetch_2: 1598 case Builtin::BI__sync_or_and_fetch_4: 1599 case Builtin::BI__sync_or_and_fetch_8: 1600 case Builtin::BI__sync_or_and_fetch_16: 1601 case Builtin::BI__sync_xor_and_fetch: 1602 case Builtin::BI__sync_xor_and_fetch_1: 1603 case Builtin::BI__sync_xor_and_fetch_2: 1604 case Builtin::BI__sync_xor_and_fetch_4: 1605 case Builtin::BI__sync_xor_and_fetch_8: 1606 case Builtin::BI__sync_xor_and_fetch_16: 1607 case Builtin::BI__sync_nand_and_fetch: 1608 case Builtin::BI__sync_nand_and_fetch_1: 1609 case Builtin::BI__sync_nand_and_fetch_2: 1610 case Builtin::BI__sync_nand_and_fetch_4: 1611 case Builtin::BI__sync_nand_and_fetch_8: 1612 case Builtin::BI__sync_nand_and_fetch_16: 1613 case Builtin::BI__sync_val_compare_and_swap: 1614 case Builtin::BI__sync_val_compare_and_swap_1: 1615 case Builtin::BI__sync_val_compare_and_swap_2: 1616 case Builtin::BI__sync_val_compare_and_swap_4: 1617 case Builtin::BI__sync_val_compare_and_swap_8: 1618 case Builtin::BI__sync_val_compare_and_swap_16: 1619 case Builtin::BI__sync_bool_compare_and_swap: 1620 case Builtin::BI__sync_bool_compare_and_swap_1: 1621 case Builtin::BI__sync_bool_compare_and_swap_2: 1622 case Builtin::BI__sync_bool_compare_and_swap_4: 1623 case Builtin::BI__sync_bool_compare_and_swap_8: 1624 case Builtin::BI__sync_bool_compare_and_swap_16: 1625 case Builtin::BI__sync_lock_test_and_set: 1626 case Builtin::BI__sync_lock_test_and_set_1: 1627 case Builtin::BI__sync_lock_test_and_set_2: 1628 case Builtin::BI__sync_lock_test_and_set_4: 1629 case Builtin::BI__sync_lock_test_and_set_8: 1630 case Builtin::BI__sync_lock_test_and_set_16: 1631 case Builtin::BI__sync_lock_release: 1632 case Builtin::BI__sync_lock_release_1: 1633 case Builtin::BI__sync_lock_release_2: 1634 case Builtin::BI__sync_lock_release_4: 1635 case Builtin::BI__sync_lock_release_8: 1636 case Builtin::BI__sync_lock_release_16: 1637 case Builtin::BI__sync_swap: 1638 case Builtin::BI__sync_swap_1: 1639 case Builtin::BI__sync_swap_2: 1640 case Builtin::BI__sync_swap_4: 1641 case Builtin::BI__sync_swap_8: 1642 case Builtin::BI__sync_swap_16: 1643 return SemaBuiltinAtomicOverloaded(TheCallResult); 1644 case Builtin::BI__sync_synchronize: 1645 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1646 << TheCall->getCallee()->getSourceRange(); 1647 break; 1648 case Builtin::BI__builtin_nontemporal_load: 1649 case Builtin::BI__builtin_nontemporal_store: 1650 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1651 case Builtin::BI__builtin_memcpy_inline: { 1652 // __builtin_memcpy_inline size argument is a constant by definition. 1653 if (TheCall->getArg(2)->EvaluateKnownConstInt(Context).isNullValue()) 1654 break; 1655 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1656 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1657 break; 1658 } 1659 #define BUILTIN(ID, TYPE, ATTRS) 1660 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1661 case Builtin::BI##ID: \ 1662 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1663 #include "clang/Basic/Builtins.def" 1664 case Builtin::BI__annotation: 1665 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1666 return ExprError(); 1667 break; 1668 case Builtin::BI__builtin_annotation: 1669 if (SemaBuiltinAnnotation(*this, TheCall)) 1670 return ExprError(); 1671 break; 1672 case Builtin::BI__builtin_addressof: 1673 if (SemaBuiltinAddressof(*this, TheCall)) 1674 return ExprError(); 1675 break; 1676 case Builtin::BI__builtin_is_aligned: 1677 case Builtin::BI__builtin_align_up: 1678 case Builtin::BI__builtin_align_down: 1679 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1680 return ExprError(); 1681 break; 1682 case Builtin::BI__builtin_add_overflow: 1683 case Builtin::BI__builtin_sub_overflow: 1684 case Builtin::BI__builtin_mul_overflow: 1685 if (SemaBuiltinOverflow(*this, TheCall)) 1686 return ExprError(); 1687 break; 1688 case Builtin::BI__builtin_operator_new: 1689 case Builtin::BI__builtin_operator_delete: { 1690 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1691 ExprResult Res = 1692 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1693 if (Res.isInvalid()) 1694 CorrectDelayedTyposInExpr(TheCallResult.get()); 1695 return Res; 1696 } 1697 case Builtin::BI__builtin_dump_struct: { 1698 // We first want to ensure we are called with 2 arguments 1699 if (checkArgCount(*this, TheCall, 2)) 1700 return ExprError(); 1701 // Ensure that the first argument is of type 'struct XX *' 1702 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1703 const QualType PtrArgType = PtrArg->getType(); 1704 if (!PtrArgType->isPointerType() || 1705 !PtrArgType->getPointeeType()->isRecordType()) { 1706 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1707 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1708 << "structure pointer"; 1709 return ExprError(); 1710 } 1711 1712 // Ensure that the second argument is of type 'FunctionType' 1713 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1714 const QualType FnPtrArgType = FnPtrArg->getType(); 1715 if (!FnPtrArgType->isPointerType()) { 1716 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1717 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1718 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1719 return ExprError(); 1720 } 1721 1722 const auto *FuncType = 1723 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1724 1725 if (!FuncType) { 1726 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1727 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1728 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1729 return ExprError(); 1730 } 1731 1732 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1733 if (!FT->getNumParams()) { 1734 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1735 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1736 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1737 return ExprError(); 1738 } 1739 QualType PT = FT->getParamType(0); 1740 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1741 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1742 !PT->getPointeeType().isConstQualified()) { 1743 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1744 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1745 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1746 return ExprError(); 1747 } 1748 } 1749 1750 TheCall->setType(Context.IntTy); 1751 break; 1752 } 1753 case Builtin::BI__builtin_preserve_access_index: 1754 if (SemaBuiltinPreserveAI(*this, TheCall)) 1755 return ExprError(); 1756 break; 1757 case Builtin::BI__builtin_call_with_static_chain: 1758 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__exception_code: 1762 case Builtin::BI_exception_code: 1763 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1764 diag::err_seh___except_block)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__exception_info: 1768 case Builtin::BI_exception_info: 1769 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1770 diag::err_seh___except_filter)) 1771 return ExprError(); 1772 break; 1773 case Builtin::BI__GetExceptionInfo: 1774 if (checkArgCount(*this, TheCall, 1)) 1775 return ExprError(); 1776 1777 if (CheckCXXThrowOperand( 1778 TheCall->getBeginLoc(), 1779 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1780 TheCall)) 1781 return ExprError(); 1782 1783 TheCall->setType(Context.VoidPtrTy); 1784 break; 1785 // OpenCL v2.0, s6.13.16 - Pipe functions 1786 case Builtin::BIread_pipe: 1787 case Builtin::BIwrite_pipe: 1788 // Since those two functions are declared with var args, we need a semantic 1789 // check for the argument. 1790 if (SemaBuiltinRWPipe(*this, TheCall)) 1791 return ExprError(); 1792 break; 1793 case Builtin::BIreserve_read_pipe: 1794 case Builtin::BIreserve_write_pipe: 1795 case Builtin::BIwork_group_reserve_read_pipe: 1796 case Builtin::BIwork_group_reserve_write_pipe: 1797 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1798 return ExprError(); 1799 break; 1800 case Builtin::BIsub_group_reserve_read_pipe: 1801 case Builtin::BIsub_group_reserve_write_pipe: 1802 if (checkOpenCLSubgroupExt(*this, TheCall) || 1803 SemaBuiltinReserveRWPipe(*this, TheCall)) 1804 return ExprError(); 1805 break; 1806 case Builtin::BIcommit_read_pipe: 1807 case Builtin::BIcommit_write_pipe: 1808 case Builtin::BIwork_group_commit_read_pipe: 1809 case Builtin::BIwork_group_commit_write_pipe: 1810 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1811 return ExprError(); 1812 break; 1813 case Builtin::BIsub_group_commit_read_pipe: 1814 case Builtin::BIsub_group_commit_write_pipe: 1815 if (checkOpenCLSubgroupExt(*this, TheCall) || 1816 SemaBuiltinCommitRWPipe(*this, TheCall)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BIget_pipe_num_packets: 1820 case Builtin::BIget_pipe_max_packets: 1821 if (SemaBuiltinPipePackets(*this, TheCall)) 1822 return ExprError(); 1823 break; 1824 case Builtin::BIto_global: 1825 case Builtin::BIto_local: 1826 case Builtin::BIto_private: 1827 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1828 return ExprError(); 1829 break; 1830 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1831 case Builtin::BIenqueue_kernel: 1832 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1833 return ExprError(); 1834 break; 1835 case Builtin::BIget_kernel_work_group_size: 1836 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1837 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1838 return ExprError(); 1839 break; 1840 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1841 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1842 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__builtin_os_log_format: 1846 case Builtin::BI__builtin_os_log_format_buffer_size: 1847 if (SemaBuiltinOSLogFormat(TheCall)) 1848 return ExprError(); 1849 break; 1850 } 1851 1852 // Since the target specific builtins for each arch overlap, only check those 1853 // of the arch we are compiling for. 1854 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1855 switch (Context.getTargetInfo().getTriple().getArch()) { 1856 case llvm::Triple::arm: 1857 case llvm::Triple::armeb: 1858 case llvm::Triple::thumb: 1859 case llvm::Triple::thumbeb: 1860 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1861 return ExprError(); 1862 break; 1863 case llvm::Triple::aarch64: 1864 case llvm::Triple::aarch64_32: 1865 case llvm::Triple::aarch64_be: 1866 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1867 return ExprError(); 1868 break; 1869 case llvm::Triple::bpfeb: 1870 case llvm::Triple::bpfel: 1871 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1872 return ExprError(); 1873 break; 1874 case llvm::Triple::hexagon: 1875 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1876 return ExprError(); 1877 break; 1878 case llvm::Triple::mips: 1879 case llvm::Triple::mipsel: 1880 case llvm::Triple::mips64: 1881 case llvm::Triple::mips64el: 1882 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1883 return ExprError(); 1884 break; 1885 case llvm::Triple::systemz: 1886 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1887 return ExprError(); 1888 break; 1889 case llvm::Triple::x86: 1890 case llvm::Triple::x86_64: 1891 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1892 return ExprError(); 1893 break; 1894 case llvm::Triple::ppc: 1895 case llvm::Triple::ppc64: 1896 case llvm::Triple::ppc64le: 1897 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1898 return ExprError(); 1899 break; 1900 default: 1901 break; 1902 } 1903 } 1904 1905 return TheCallResult; 1906 } 1907 1908 // Get the valid immediate range for the specified NEON type code. 1909 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1910 NeonTypeFlags Type(t); 1911 int IsQuad = ForceQuad ? true : Type.isQuad(); 1912 switch (Type.getEltType()) { 1913 case NeonTypeFlags::Int8: 1914 case NeonTypeFlags::Poly8: 1915 return shift ? 7 : (8 << IsQuad) - 1; 1916 case NeonTypeFlags::Int16: 1917 case NeonTypeFlags::Poly16: 1918 return shift ? 15 : (4 << IsQuad) - 1; 1919 case NeonTypeFlags::Int32: 1920 return shift ? 31 : (2 << IsQuad) - 1; 1921 case NeonTypeFlags::Int64: 1922 case NeonTypeFlags::Poly64: 1923 return shift ? 63 : (1 << IsQuad) - 1; 1924 case NeonTypeFlags::Poly128: 1925 return shift ? 127 : (1 << IsQuad) - 1; 1926 case NeonTypeFlags::Float16: 1927 assert(!shift && "cannot shift float types!"); 1928 return (4 << IsQuad) - 1; 1929 case NeonTypeFlags::Float32: 1930 assert(!shift && "cannot shift float types!"); 1931 return (2 << IsQuad) - 1; 1932 case NeonTypeFlags::Float64: 1933 assert(!shift && "cannot shift float types!"); 1934 return (1 << IsQuad) - 1; 1935 } 1936 llvm_unreachable("Invalid NeonTypeFlag!"); 1937 } 1938 1939 /// getNeonEltType - Return the QualType corresponding to the elements of 1940 /// the vector type specified by the NeonTypeFlags. This is used to check 1941 /// the pointer arguments for Neon load/store intrinsics. 1942 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1943 bool IsPolyUnsigned, bool IsInt64Long) { 1944 switch (Flags.getEltType()) { 1945 case NeonTypeFlags::Int8: 1946 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1947 case NeonTypeFlags::Int16: 1948 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1949 case NeonTypeFlags::Int32: 1950 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1951 case NeonTypeFlags::Int64: 1952 if (IsInt64Long) 1953 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1954 else 1955 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1956 : Context.LongLongTy; 1957 case NeonTypeFlags::Poly8: 1958 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1959 case NeonTypeFlags::Poly16: 1960 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1961 case NeonTypeFlags::Poly64: 1962 if (IsInt64Long) 1963 return Context.UnsignedLongTy; 1964 else 1965 return Context.UnsignedLongLongTy; 1966 case NeonTypeFlags::Poly128: 1967 break; 1968 case NeonTypeFlags::Float16: 1969 return Context.HalfTy; 1970 case NeonTypeFlags::Float32: 1971 return Context.FloatTy; 1972 case NeonTypeFlags::Float64: 1973 return Context.DoubleTy; 1974 } 1975 llvm_unreachable("Invalid NeonTypeFlag!"); 1976 } 1977 1978 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1979 llvm::APSInt Result; 1980 uint64_t mask = 0; 1981 unsigned TV = 0; 1982 int PtrArgNum = -1; 1983 bool HasConstPtr = false; 1984 switch (BuiltinID) { 1985 #define GET_NEON_OVERLOAD_CHECK 1986 #include "clang/Basic/arm_neon.inc" 1987 #include "clang/Basic/arm_fp16.inc" 1988 #undef GET_NEON_OVERLOAD_CHECK 1989 } 1990 1991 // For NEON intrinsics which are overloaded on vector element type, validate 1992 // the immediate which specifies which variant to emit. 1993 unsigned ImmArg = TheCall->getNumArgs()-1; 1994 if (mask) { 1995 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 1996 return true; 1997 1998 TV = Result.getLimitedValue(64); 1999 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2000 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2001 << TheCall->getArg(ImmArg)->getSourceRange(); 2002 } 2003 2004 if (PtrArgNum >= 0) { 2005 // Check that pointer arguments have the specified type. 2006 Expr *Arg = TheCall->getArg(PtrArgNum); 2007 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2008 Arg = ICE->getSubExpr(); 2009 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2010 QualType RHSTy = RHS.get()->getType(); 2011 2012 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2013 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2014 Arch == llvm::Triple::aarch64_32 || 2015 Arch == llvm::Triple::aarch64_be; 2016 bool IsInt64Long = 2017 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2018 QualType EltTy = 2019 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2020 if (HasConstPtr) 2021 EltTy = EltTy.withConst(); 2022 QualType LHSTy = Context.getPointerType(EltTy); 2023 AssignConvertType ConvTy; 2024 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2025 if (RHS.isInvalid()) 2026 return true; 2027 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2028 RHS.get(), AA_Assigning)) 2029 return true; 2030 } 2031 2032 // For NEON intrinsics which take an immediate value as part of the 2033 // instruction, range check them here. 2034 unsigned i = 0, l = 0, u = 0; 2035 switch (BuiltinID) { 2036 default: 2037 return false; 2038 #define GET_NEON_IMMEDIATE_CHECK 2039 #include "clang/Basic/arm_neon.inc" 2040 #include "clang/Basic/arm_fp16.inc" 2041 #undef GET_NEON_IMMEDIATE_CHECK 2042 } 2043 2044 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2045 } 2046 2047 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2048 switch (BuiltinID) { 2049 default: 2050 return false; 2051 #include "clang/Basic/arm_mve_builtin_sema.inc" 2052 } 2053 } 2054 2055 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2056 unsigned MaxWidth) { 2057 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2058 BuiltinID == ARM::BI__builtin_arm_ldaex || 2059 BuiltinID == ARM::BI__builtin_arm_strex || 2060 BuiltinID == ARM::BI__builtin_arm_stlex || 2061 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2062 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2063 BuiltinID == AArch64::BI__builtin_arm_strex || 2064 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2065 "unexpected ARM builtin"); 2066 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2067 BuiltinID == ARM::BI__builtin_arm_ldaex || 2068 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2069 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2070 2071 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2072 2073 // Ensure that we have the proper number of arguments. 2074 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2075 return true; 2076 2077 // Inspect the pointer argument of the atomic builtin. This should always be 2078 // a pointer type, whose element is an integral scalar or pointer type. 2079 // Because it is a pointer type, we don't have to worry about any implicit 2080 // casts here. 2081 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2082 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2083 if (PointerArgRes.isInvalid()) 2084 return true; 2085 PointerArg = PointerArgRes.get(); 2086 2087 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2088 if (!pointerType) { 2089 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2090 << PointerArg->getType() << PointerArg->getSourceRange(); 2091 return true; 2092 } 2093 2094 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2095 // task is to insert the appropriate casts into the AST. First work out just 2096 // what the appropriate type is. 2097 QualType ValType = pointerType->getPointeeType(); 2098 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2099 if (IsLdrex) 2100 AddrType.addConst(); 2101 2102 // Issue a warning if the cast is dodgy. 2103 CastKind CastNeeded = CK_NoOp; 2104 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2105 CastNeeded = CK_BitCast; 2106 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2107 << PointerArg->getType() << Context.getPointerType(AddrType) 2108 << AA_Passing << PointerArg->getSourceRange(); 2109 } 2110 2111 // Finally, do the cast and replace the argument with the corrected version. 2112 AddrType = Context.getPointerType(AddrType); 2113 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2114 if (PointerArgRes.isInvalid()) 2115 return true; 2116 PointerArg = PointerArgRes.get(); 2117 2118 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2119 2120 // In general, we allow ints, floats and pointers to be loaded and stored. 2121 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2122 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2123 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2124 << PointerArg->getType() << PointerArg->getSourceRange(); 2125 return true; 2126 } 2127 2128 // But ARM doesn't have instructions to deal with 128-bit versions. 2129 if (Context.getTypeSize(ValType) > MaxWidth) { 2130 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2131 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2132 << PointerArg->getType() << PointerArg->getSourceRange(); 2133 return true; 2134 } 2135 2136 switch (ValType.getObjCLifetime()) { 2137 case Qualifiers::OCL_None: 2138 case Qualifiers::OCL_ExplicitNone: 2139 // okay 2140 break; 2141 2142 case Qualifiers::OCL_Weak: 2143 case Qualifiers::OCL_Strong: 2144 case Qualifiers::OCL_Autoreleasing: 2145 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2146 << ValType << PointerArg->getSourceRange(); 2147 return true; 2148 } 2149 2150 if (IsLdrex) { 2151 TheCall->setType(ValType); 2152 return false; 2153 } 2154 2155 // Initialize the argument to be stored. 2156 ExprResult ValArg = TheCall->getArg(0); 2157 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2158 Context, ValType, /*consume*/ false); 2159 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2160 if (ValArg.isInvalid()) 2161 return true; 2162 TheCall->setArg(0, ValArg.get()); 2163 2164 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2165 // but the custom checker bypasses all default analysis. 2166 TheCall->setType(Context.IntTy); 2167 return false; 2168 } 2169 2170 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2171 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2172 BuiltinID == ARM::BI__builtin_arm_ldaex || 2173 BuiltinID == ARM::BI__builtin_arm_strex || 2174 BuiltinID == ARM::BI__builtin_arm_stlex) { 2175 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2176 } 2177 2178 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2179 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2180 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2181 } 2182 2183 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2184 BuiltinID == ARM::BI__builtin_arm_wsr64) 2185 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2186 2187 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2188 BuiltinID == ARM::BI__builtin_arm_rsrp || 2189 BuiltinID == ARM::BI__builtin_arm_wsr || 2190 BuiltinID == ARM::BI__builtin_arm_wsrp) 2191 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2192 2193 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2194 return true; 2195 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2196 return true; 2197 2198 // For intrinsics which take an immediate value as part of the instruction, 2199 // range check them here. 2200 // FIXME: VFP Intrinsics should error if VFP not present. 2201 switch (BuiltinID) { 2202 default: return false; 2203 case ARM::BI__builtin_arm_ssat: 2204 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2205 case ARM::BI__builtin_arm_usat: 2206 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2207 case ARM::BI__builtin_arm_ssat16: 2208 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2209 case ARM::BI__builtin_arm_usat16: 2210 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2211 case ARM::BI__builtin_arm_vcvtr_f: 2212 case ARM::BI__builtin_arm_vcvtr_d: 2213 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2214 case ARM::BI__builtin_arm_dmb: 2215 case ARM::BI__builtin_arm_dsb: 2216 case ARM::BI__builtin_arm_isb: 2217 case ARM::BI__builtin_arm_dbg: 2218 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2219 } 2220 } 2221 2222 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2223 CallExpr *TheCall) { 2224 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2225 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2226 BuiltinID == AArch64::BI__builtin_arm_strex || 2227 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2228 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2229 } 2230 2231 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2232 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2233 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2234 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2235 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2236 } 2237 2238 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2239 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2240 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2241 2242 // Memory Tagging Extensions (MTE) Intrinsics 2243 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2244 BuiltinID == AArch64::BI__builtin_arm_addg || 2245 BuiltinID == AArch64::BI__builtin_arm_gmi || 2246 BuiltinID == AArch64::BI__builtin_arm_ldg || 2247 BuiltinID == AArch64::BI__builtin_arm_stg || 2248 BuiltinID == AArch64::BI__builtin_arm_subp) { 2249 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2250 } 2251 2252 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2253 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2254 BuiltinID == AArch64::BI__builtin_arm_wsr || 2255 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2256 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2257 2258 // Only check the valid encoding range. Any constant in this range would be 2259 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2260 // an exception for incorrect registers. This matches MSVC behavior. 2261 if (BuiltinID == AArch64::BI_ReadStatusReg || 2262 BuiltinID == AArch64::BI_WriteStatusReg) 2263 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2264 2265 if (BuiltinID == AArch64::BI__getReg) 2266 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2267 2268 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2269 return true; 2270 2271 // For intrinsics which take an immediate value as part of the instruction, 2272 // range check them here. 2273 unsigned i = 0, l = 0, u = 0; 2274 switch (BuiltinID) { 2275 default: return false; 2276 case AArch64::BI__builtin_arm_dmb: 2277 case AArch64::BI__builtin_arm_dsb: 2278 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2279 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2280 } 2281 2282 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2283 } 2284 2285 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2286 CallExpr *TheCall) { 2287 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2288 "unexpected ARM builtin"); 2289 2290 if (checkArgCount(*this, TheCall, 2)) 2291 return true; 2292 2293 // The first argument needs to be a record field access. 2294 // If it is an array element access, we delay decision 2295 // to BPF backend to check whether the access is a 2296 // field access or not. 2297 Expr *Arg = TheCall->getArg(0); 2298 if (Arg->getType()->getAsPlaceholderType() || 2299 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2300 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2301 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2302 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2303 << 1 << Arg->getSourceRange(); 2304 return true; 2305 } 2306 2307 // The second argument needs to be a constant int 2308 llvm::APSInt Value; 2309 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2310 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2311 << 2 << Arg->getSourceRange(); 2312 return true; 2313 } 2314 2315 TheCall->setType(Context.UnsignedIntTy); 2316 return false; 2317 } 2318 2319 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2320 struct ArgInfo { 2321 uint8_t OpNum; 2322 bool IsSigned; 2323 uint8_t BitWidth; 2324 uint8_t Align; 2325 }; 2326 struct BuiltinInfo { 2327 unsigned BuiltinID; 2328 ArgInfo Infos[2]; 2329 }; 2330 2331 static BuiltinInfo Infos[] = { 2332 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2333 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2334 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2335 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2336 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2337 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2338 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2339 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2340 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2341 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2342 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2343 2344 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2345 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2346 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2347 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2348 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2349 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2350 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2351 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2352 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2353 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2354 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2355 2356 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2357 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2358 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2359 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2360 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2361 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2362 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2363 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2364 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2365 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2366 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2367 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2368 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2369 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2370 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2371 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2372 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2373 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2374 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2375 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2376 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2377 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2378 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2379 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2380 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2381 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2382 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2383 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2384 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2385 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2386 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2387 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2388 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2389 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2390 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2391 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2392 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2393 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2394 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2395 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2396 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2397 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2398 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2399 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2400 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2401 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2402 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2403 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2404 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2405 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2406 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2407 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2408 {{ 1, false, 6, 0 }} }, 2409 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2410 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2411 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2412 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2413 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2414 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2415 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2416 {{ 1, false, 5, 0 }} }, 2417 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2418 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2419 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2420 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2421 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2422 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2423 { 2, false, 5, 0 }} }, 2424 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2425 { 2, false, 6, 0 }} }, 2426 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2427 { 3, false, 5, 0 }} }, 2428 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2429 { 3, false, 6, 0 }} }, 2430 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2431 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2432 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2433 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2434 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2435 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2436 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2437 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2438 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2439 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2440 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2441 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2442 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2443 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2444 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2445 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2446 {{ 2, false, 4, 0 }, 2447 { 3, false, 5, 0 }} }, 2448 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2449 {{ 2, false, 4, 0 }, 2450 { 3, false, 5, 0 }} }, 2451 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2452 {{ 2, false, 4, 0 }, 2453 { 3, false, 5, 0 }} }, 2454 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2455 {{ 2, false, 4, 0 }, 2456 { 3, false, 5, 0 }} }, 2457 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2458 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2459 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2460 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2461 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2462 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2463 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2464 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2465 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2466 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2467 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2468 { 2, false, 5, 0 }} }, 2469 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2470 { 2, false, 6, 0 }} }, 2471 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2472 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2473 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2474 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2475 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2476 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2477 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2478 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2479 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2480 {{ 1, false, 4, 0 }} }, 2481 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2482 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2483 {{ 1, false, 4, 0 }} }, 2484 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2485 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2486 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2487 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2488 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2489 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2490 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2491 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2492 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2493 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2494 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2495 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2496 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2497 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2498 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2499 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2500 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2501 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2502 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2503 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2504 {{ 3, false, 1, 0 }} }, 2505 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2506 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2507 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2508 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2509 {{ 3, false, 1, 0 }} }, 2510 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2511 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2512 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2513 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2514 {{ 3, false, 1, 0 }} }, 2515 }; 2516 2517 // Use a dynamically initialized static to sort the table exactly once on 2518 // first run. 2519 static const bool SortOnce = 2520 (llvm::sort(Infos, 2521 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2522 return LHS.BuiltinID < RHS.BuiltinID; 2523 }), 2524 true); 2525 (void)SortOnce; 2526 2527 const BuiltinInfo *F = llvm::partition_point( 2528 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2529 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2530 return false; 2531 2532 bool Error = false; 2533 2534 for (const ArgInfo &A : F->Infos) { 2535 // Ignore empty ArgInfo elements. 2536 if (A.BitWidth == 0) 2537 continue; 2538 2539 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2540 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2541 if (!A.Align) { 2542 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2543 } else { 2544 unsigned M = 1 << A.Align; 2545 Min *= M; 2546 Max *= M; 2547 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2548 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2549 } 2550 } 2551 return Error; 2552 } 2553 2554 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2555 CallExpr *TheCall) { 2556 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2557 } 2558 2559 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2560 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2561 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2562 } 2563 2564 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2565 const TargetInfo &TI = Context.getTargetInfo(); 2566 2567 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2568 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2569 if (!TI.hasFeature("dsp")) 2570 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2571 } 2572 2573 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2574 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2575 if (!TI.hasFeature("dspr2")) 2576 return Diag(TheCall->getBeginLoc(), 2577 diag::err_mips_builtin_requires_dspr2); 2578 } 2579 2580 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2581 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2582 if (!TI.hasFeature("msa")) 2583 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2584 } 2585 2586 return false; 2587 } 2588 2589 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2590 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2591 // ordering for DSP is unspecified. MSA is ordered by the data format used 2592 // by the underlying instruction i.e., df/m, df/n and then by size. 2593 // 2594 // FIXME: The size tests here should instead be tablegen'd along with the 2595 // definitions from include/clang/Basic/BuiltinsMips.def. 2596 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2597 // be too. 2598 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2599 unsigned i = 0, l = 0, u = 0, m = 0; 2600 switch (BuiltinID) { 2601 default: return false; 2602 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2603 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2604 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2605 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2606 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2607 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2608 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2609 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2610 // df/m field. 2611 // These intrinsics take an unsigned 3 bit immediate. 2612 case Mips::BI__builtin_msa_bclri_b: 2613 case Mips::BI__builtin_msa_bnegi_b: 2614 case Mips::BI__builtin_msa_bseti_b: 2615 case Mips::BI__builtin_msa_sat_s_b: 2616 case Mips::BI__builtin_msa_sat_u_b: 2617 case Mips::BI__builtin_msa_slli_b: 2618 case Mips::BI__builtin_msa_srai_b: 2619 case Mips::BI__builtin_msa_srari_b: 2620 case Mips::BI__builtin_msa_srli_b: 2621 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2622 case Mips::BI__builtin_msa_binsli_b: 2623 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2624 // These intrinsics take an unsigned 4 bit immediate. 2625 case Mips::BI__builtin_msa_bclri_h: 2626 case Mips::BI__builtin_msa_bnegi_h: 2627 case Mips::BI__builtin_msa_bseti_h: 2628 case Mips::BI__builtin_msa_sat_s_h: 2629 case Mips::BI__builtin_msa_sat_u_h: 2630 case Mips::BI__builtin_msa_slli_h: 2631 case Mips::BI__builtin_msa_srai_h: 2632 case Mips::BI__builtin_msa_srari_h: 2633 case Mips::BI__builtin_msa_srli_h: 2634 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2635 case Mips::BI__builtin_msa_binsli_h: 2636 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2637 // These intrinsics take an unsigned 5 bit immediate. 2638 // The first block of intrinsics actually have an unsigned 5 bit field, 2639 // not a df/n field. 2640 case Mips::BI__builtin_msa_cfcmsa: 2641 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2642 case Mips::BI__builtin_msa_clei_u_b: 2643 case Mips::BI__builtin_msa_clei_u_h: 2644 case Mips::BI__builtin_msa_clei_u_w: 2645 case Mips::BI__builtin_msa_clei_u_d: 2646 case Mips::BI__builtin_msa_clti_u_b: 2647 case Mips::BI__builtin_msa_clti_u_h: 2648 case Mips::BI__builtin_msa_clti_u_w: 2649 case Mips::BI__builtin_msa_clti_u_d: 2650 case Mips::BI__builtin_msa_maxi_u_b: 2651 case Mips::BI__builtin_msa_maxi_u_h: 2652 case Mips::BI__builtin_msa_maxi_u_w: 2653 case Mips::BI__builtin_msa_maxi_u_d: 2654 case Mips::BI__builtin_msa_mini_u_b: 2655 case Mips::BI__builtin_msa_mini_u_h: 2656 case Mips::BI__builtin_msa_mini_u_w: 2657 case Mips::BI__builtin_msa_mini_u_d: 2658 case Mips::BI__builtin_msa_addvi_b: 2659 case Mips::BI__builtin_msa_addvi_h: 2660 case Mips::BI__builtin_msa_addvi_w: 2661 case Mips::BI__builtin_msa_addvi_d: 2662 case Mips::BI__builtin_msa_bclri_w: 2663 case Mips::BI__builtin_msa_bnegi_w: 2664 case Mips::BI__builtin_msa_bseti_w: 2665 case Mips::BI__builtin_msa_sat_s_w: 2666 case Mips::BI__builtin_msa_sat_u_w: 2667 case Mips::BI__builtin_msa_slli_w: 2668 case Mips::BI__builtin_msa_srai_w: 2669 case Mips::BI__builtin_msa_srari_w: 2670 case Mips::BI__builtin_msa_srli_w: 2671 case Mips::BI__builtin_msa_srlri_w: 2672 case Mips::BI__builtin_msa_subvi_b: 2673 case Mips::BI__builtin_msa_subvi_h: 2674 case Mips::BI__builtin_msa_subvi_w: 2675 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2676 case Mips::BI__builtin_msa_binsli_w: 2677 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2678 // These intrinsics take an unsigned 6 bit immediate. 2679 case Mips::BI__builtin_msa_bclri_d: 2680 case Mips::BI__builtin_msa_bnegi_d: 2681 case Mips::BI__builtin_msa_bseti_d: 2682 case Mips::BI__builtin_msa_sat_s_d: 2683 case Mips::BI__builtin_msa_sat_u_d: 2684 case Mips::BI__builtin_msa_slli_d: 2685 case Mips::BI__builtin_msa_srai_d: 2686 case Mips::BI__builtin_msa_srari_d: 2687 case Mips::BI__builtin_msa_srli_d: 2688 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2689 case Mips::BI__builtin_msa_binsli_d: 2690 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2691 // These intrinsics take a signed 5 bit immediate. 2692 case Mips::BI__builtin_msa_ceqi_b: 2693 case Mips::BI__builtin_msa_ceqi_h: 2694 case Mips::BI__builtin_msa_ceqi_w: 2695 case Mips::BI__builtin_msa_ceqi_d: 2696 case Mips::BI__builtin_msa_clti_s_b: 2697 case Mips::BI__builtin_msa_clti_s_h: 2698 case Mips::BI__builtin_msa_clti_s_w: 2699 case Mips::BI__builtin_msa_clti_s_d: 2700 case Mips::BI__builtin_msa_clei_s_b: 2701 case Mips::BI__builtin_msa_clei_s_h: 2702 case Mips::BI__builtin_msa_clei_s_w: 2703 case Mips::BI__builtin_msa_clei_s_d: 2704 case Mips::BI__builtin_msa_maxi_s_b: 2705 case Mips::BI__builtin_msa_maxi_s_h: 2706 case Mips::BI__builtin_msa_maxi_s_w: 2707 case Mips::BI__builtin_msa_maxi_s_d: 2708 case Mips::BI__builtin_msa_mini_s_b: 2709 case Mips::BI__builtin_msa_mini_s_h: 2710 case Mips::BI__builtin_msa_mini_s_w: 2711 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2712 // These intrinsics take an unsigned 8 bit immediate. 2713 case Mips::BI__builtin_msa_andi_b: 2714 case Mips::BI__builtin_msa_nori_b: 2715 case Mips::BI__builtin_msa_ori_b: 2716 case Mips::BI__builtin_msa_shf_b: 2717 case Mips::BI__builtin_msa_shf_h: 2718 case Mips::BI__builtin_msa_shf_w: 2719 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2720 case Mips::BI__builtin_msa_bseli_b: 2721 case Mips::BI__builtin_msa_bmnzi_b: 2722 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2723 // df/n format 2724 // These intrinsics take an unsigned 4 bit immediate. 2725 case Mips::BI__builtin_msa_copy_s_b: 2726 case Mips::BI__builtin_msa_copy_u_b: 2727 case Mips::BI__builtin_msa_insve_b: 2728 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2729 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2730 // These intrinsics take an unsigned 3 bit immediate. 2731 case Mips::BI__builtin_msa_copy_s_h: 2732 case Mips::BI__builtin_msa_copy_u_h: 2733 case Mips::BI__builtin_msa_insve_h: 2734 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2735 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2736 // These intrinsics take an unsigned 2 bit immediate. 2737 case Mips::BI__builtin_msa_copy_s_w: 2738 case Mips::BI__builtin_msa_copy_u_w: 2739 case Mips::BI__builtin_msa_insve_w: 2740 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2741 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2742 // These intrinsics take an unsigned 1 bit immediate. 2743 case Mips::BI__builtin_msa_copy_s_d: 2744 case Mips::BI__builtin_msa_copy_u_d: 2745 case Mips::BI__builtin_msa_insve_d: 2746 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2747 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2748 // Memory offsets and immediate loads. 2749 // These intrinsics take a signed 10 bit immediate. 2750 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2751 case Mips::BI__builtin_msa_ldi_h: 2752 case Mips::BI__builtin_msa_ldi_w: 2753 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2754 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2755 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2756 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2757 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2758 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2759 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2760 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2761 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2762 } 2763 2764 if (!m) 2765 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2766 2767 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2768 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2769 } 2770 2771 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2772 unsigned i = 0, l = 0, u = 0; 2773 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2774 BuiltinID == PPC::BI__builtin_divdeu || 2775 BuiltinID == PPC::BI__builtin_bpermd; 2776 bool IsTarget64Bit = Context.getTargetInfo() 2777 .getTypeWidth(Context 2778 .getTargetInfo() 2779 .getIntPtrType()) == 64; 2780 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2781 BuiltinID == PPC::BI__builtin_divweu || 2782 BuiltinID == PPC::BI__builtin_divde || 2783 BuiltinID == PPC::BI__builtin_divdeu; 2784 2785 if (Is64BitBltin && !IsTarget64Bit) 2786 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2787 << TheCall->getSourceRange(); 2788 2789 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2790 (BuiltinID == PPC::BI__builtin_bpermd && 2791 !Context.getTargetInfo().hasFeature("bpermd"))) 2792 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2793 << TheCall->getSourceRange(); 2794 2795 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2796 if (!Context.getTargetInfo().hasFeature("vsx")) 2797 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2798 << TheCall->getSourceRange(); 2799 return false; 2800 }; 2801 2802 switch (BuiltinID) { 2803 default: return false; 2804 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2805 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2806 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2807 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2808 case PPC::BI__builtin_altivec_dss: 2809 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 2810 case PPC::BI__builtin_tbegin: 2811 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2812 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2813 case PPC::BI__builtin_tabortwc: 2814 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2815 case PPC::BI__builtin_tabortwci: 2816 case PPC::BI__builtin_tabortdci: 2817 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2818 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2819 case PPC::BI__builtin_altivec_dst: 2820 case PPC::BI__builtin_altivec_dstt: 2821 case PPC::BI__builtin_altivec_dstst: 2822 case PPC::BI__builtin_altivec_dststt: 2823 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 2824 case PPC::BI__builtin_vsx_xxpermdi: 2825 case PPC::BI__builtin_vsx_xxsldwi: 2826 return SemaBuiltinVSX(TheCall); 2827 case PPC::BI__builtin_unpack_vector_int128: 2828 return SemaVSXCheck(TheCall) || 2829 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2830 case PPC::BI__builtin_pack_vector_int128: 2831 return SemaVSXCheck(TheCall); 2832 } 2833 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2834 } 2835 2836 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2837 CallExpr *TheCall) { 2838 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2839 Expr *Arg = TheCall->getArg(0); 2840 llvm::APSInt AbortCode(32); 2841 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2842 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2843 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 2844 << Arg->getSourceRange(); 2845 } 2846 2847 // For intrinsics which take an immediate value as part of the instruction, 2848 // range check them here. 2849 unsigned i = 0, l = 0, u = 0; 2850 switch (BuiltinID) { 2851 default: return false; 2852 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2853 case SystemZ::BI__builtin_s390_verimb: 2854 case SystemZ::BI__builtin_s390_verimh: 2855 case SystemZ::BI__builtin_s390_verimf: 2856 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2857 case SystemZ::BI__builtin_s390_vfaeb: 2858 case SystemZ::BI__builtin_s390_vfaeh: 2859 case SystemZ::BI__builtin_s390_vfaef: 2860 case SystemZ::BI__builtin_s390_vfaebs: 2861 case SystemZ::BI__builtin_s390_vfaehs: 2862 case SystemZ::BI__builtin_s390_vfaefs: 2863 case SystemZ::BI__builtin_s390_vfaezb: 2864 case SystemZ::BI__builtin_s390_vfaezh: 2865 case SystemZ::BI__builtin_s390_vfaezf: 2866 case SystemZ::BI__builtin_s390_vfaezbs: 2867 case SystemZ::BI__builtin_s390_vfaezhs: 2868 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2869 case SystemZ::BI__builtin_s390_vfisb: 2870 case SystemZ::BI__builtin_s390_vfidb: 2871 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2872 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2873 case SystemZ::BI__builtin_s390_vftcisb: 2874 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2875 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2876 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2877 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2878 case SystemZ::BI__builtin_s390_vstrcb: 2879 case SystemZ::BI__builtin_s390_vstrch: 2880 case SystemZ::BI__builtin_s390_vstrcf: 2881 case SystemZ::BI__builtin_s390_vstrczb: 2882 case SystemZ::BI__builtin_s390_vstrczh: 2883 case SystemZ::BI__builtin_s390_vstrczf: 2884 case SystemZ::BI__builtin_s390_vstrcbs: 2885 case SystemZ::BI__builtin_s390_vstrchs: 2886 case SystemZ::BI__builtin_s390_vstrcfs: 2887 case SystemZ::BI__builtin_s390_vstrczbs: 2888 case SystemZ::BI__builtin_s390_vstrczhs: 2889 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2890 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2891 case SystemZ::BI__builtin_s390_vfminsb: 2892 case SystemZ::BI__builtin_s390_vfmaxsb: 2893 case SystemZ::BI__builtin_s390_vfmindb: 2894 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2895 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 2896 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 2897 } 2898 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2899 } 2900 2901 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2902 /// This checks that the target supports __builtin_cpu_supports and 2903 /// that the string argument is constant and valid. 2904 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2905 Expr *Arg = TheCall->getArg(0); 2906 2907 // Check if the argument is a string literal. 2908 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2909 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2910 << Arg->getSourceRange(); 2911 2912 // Check the contents of the string. 2913 StringRef Feature = 2914 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2915 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2916 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 2917 << Arg->getSourceRange(); 2918 return false; 2919 } 2920 2921 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 2922 /// This checks that the target supports __builtin_cpu_is and 2923 /// that the string argument is constant and valid. 2924 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 2925 Expr *Arg = TheCall->getArg(0); 2926 2927 // Check if the argument is a string literal. 2928 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2929 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2930 << Arg->getSourceRange(); 2931 2932 // Check the contents of the string. 2933 StringRef Feature = 2934 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2935 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 2936 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 2937 << Arg->getSourceRange(); 2938 return false; 2939 } 2940 2941 // Check if the rounding mode is legal. 2942 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 2943 // Indicates if this instruction has rounding control or just SAE. 2944 bool HasRC = false; 2945 2946 unsigned ArgNum = 0; 2947 switch (BuiltinID) { 2948 default: 2949 return false; 2950 case X86::BI__builtin_ia32_vcvttsd2si32: 2951 case X86::BI__builtin_ia32_vcvttsd2si64: 2952 case X86::BI__builtin_ia32_vcvttsd2usi32: 2953 case X86::BI__builtin_ia32_vcvttsd2usi64: 2954 case X86::BI__builtin_ia32_vcvttss2si32: 2955 case X86::BI__builtin_ia32_vcvttss2si64: 2956 case X86::BI__builtin_ia32_vcvttss2usi32: 2957 case X86::BI__builtin_ia32_vcvttss2usi64: 2958 ArgNum = 1; 2959 break; 2960 case X86::BI__builtin_ia32_maxpd512: 2961 case X86::BI__builtin_ia32_maxps512: 2962 case X86::BI__builtin_ia32_minpd512: 2963 case X86::BI__builtin_ia32_minps512: 2964 ArgNum = 2; 2965 break; 2966 case X86::BI__builtin_ia32_cvtps2pd512_mask: 2967 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 2968 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 2969 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 2970 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 2971 case X86::BI__builtin_ia32_cvttps2dq512_mask: 2972 case X86::BI__builtin_ia32_cvttps2qq512_mask: 2973 case X86::BI__builtin_ia32_cvttps2udq512_mask: 2974 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 2975 case X86::BI__builtin_ia32_exp2pd_mask: 2976 case X86::BI__builtin_ia32_exp2ps_mask: 2977 case X86::BI__builtin_ia32_getexppd512_mask: 2978 case X86::BI__builtin_ia32_getexpps512_mask: 2979 case X86::BI__builtin_ia32_rcp28pd_mask: 2980 case X86::BI__builtin_ia32_rcp28ps_mask: 2981 case X86::BI__builtin_ia32_rsqrt28pd_mask: 2982 case X86::BI__builtin_ia32_rsqrt28ps_mask: 2983 case X86::BI__builtin_ia32_vcomisd: 2984 case X86::BI__builtin_ia32_vcomiss: 2985 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 2986 ArgNum = 3; 2987 break; 2988 case X86::BI__builtin_ia32_cmppd512_mask: 2989 case X86::BI__builtin_ia32_cmpps512_mask: 2990 case X86::BI__builtin_ia32_cmpsd_mask: 2991 case X86::BI__builtin_ia32_cmpss_mask: 2992 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 2993 case X86::BI__builtin_ia32_getexpsd128_round_mask: 2994 case X86::BI__builtin_ia32_getexpss128_round_mask: 2995 case X86::BI__builtin_ia32_getmantpd512_mask: 2996 case X86::BI__builtin_ia32_getmantps512_mask: 2997 case X86::BI__builtin_ia32_maxsd_round_mask: 2998 case X86::BI__builtin_ia32_maxss_round_mask: 2999 case X86::BI__builtin_ia32_minsd_round_mask: 3000 case X86::BI__builtin_ia32_minss_round_mask: 3001 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3002 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3003 case X86::BI__builtin_ia32_reducepd512_mask: 3004 case X86::BI__builtin_ia32_reduceps512_mask: 3005 case X86::BI__builtin_ia32_rndscalepd_mask: 3006 case X86::BI__builtin_ia32_rndscaleps_mask: 3007 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3008 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3009 ArgNum = 4; 3010 break; 3011 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3012 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3013 case X86::BI__builtin_ia32_fixupimmps512_mask: 3014 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3015 case X86::BI__builtin_ia32_fixupimmsd_mask: 3016 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3017 case X86::BI__builtin_ia32_fixupimmss_mask: 3018 case X86::BI__builtin_ia32_fixupimmss_maskz: 3019 case X86::BI__builtin_ia32_getmantsd_round_mask: 3020 case X86::BI__builtin_ia32_getmantss_round_mask: 3021 case X86::BI__builtin_ia32_rangepd512_mask: 3022 case X86::BI__builtin_ia32_rangeps512_mask: 3023 case X86::BI__builtin_ia32_rangesd128_round_mask: 3024 case X86::BI__builtin_ia32_rangess128_round_mask: 3025 case X86::BI__builtin_ia32_reducesd_mask: 3026 case X86::BI__builtin_ia32_reducess_mask: 3027 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3028 case X86::BI__builtin_ia32_rndscaless_round_mask: 3029 ArgNum = 5; 3030 break; 3031 case X86::BI__builtin_ia32_vcvtsd2si64: 3032 case X86::BI__builtin_ia32_vcvtsd2si32: 3033 case X86::BI__builtin_ia32_vcvtsd2usi32: 3034 case X86::BI__builtin_ia32_vcvtsd2usi64: 3035 case X86::BI__builtin_ia32_vcvtss2si32: 3036 case X86::BI__builtin_ia32_vcvtss2si64: 3037 case X86::BI__builtin_ia32_vcvtss2usi32: 3038 case X86::BI__builtin_ia32_vcvtss2usi64: 3039 case X86::BI__builtin_ia32_sqrtpd512: 3040 case X86::BI__builtin_ia32_sqrtps512: 3041 ArgNum = 1; 3042 HasRC = true; 3043 break; 3044 case X86::BI__builtin_ia32_addpd512: 3045 case X86::BI__builtin_ia32_addps512: 3046 case X86::BI__builtin_ia32_divpd512: 3047 case X86::BI__builtin_ia32_divps512: 3048 case X86::BI__builtin_ia32_mulpd512: 3049 case X86::BI__builtin_ia32_mulps512: 3050 case X86::BI__builtin_ia32_subpd512: 3051 case X86::BI__builtin_ia32_subps512: 3052 case X86::BI__builtin_ia32_cvtsi2sd64: 3053 case X86::BI__builtin_ia32_cvtsi2ss32: 3054 case X86::BI__builtin_ia32_cvtsi2ss64: 3055 case X86::BI__builtin_ia32_cvtusi2sd64: 3056 case X86::BI__builtin_ia32_cvtusi2ss32: 3057 case X86::BI__builtin_ia32_cvtusi2ss64: 3058 ArgNum = 2; 3059 HasRC = true; 3060 break; 3061 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3062 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3063 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3064 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3065 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3066 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3067 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3068 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3069 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3070 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3071 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3072 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3073 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3074 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3075 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3076 ArgNum = 3; 3077 HasRC = true; 3078 break; 3079 case X86::BI__builtin_ia32_addss_round_mask: 3080 case X86::BI__builtin_ia32_addsd_round_mask: 3081 case X86::BI__builtin_ia32_divss_round_mask: 3082 case X86::BI__builtin_ia32_divsd_round_mask: 3083 case X86::BI__builtin_ia32_mulss_round_mask: 3084 case X86::BI__builtin_ia32_mulsd_round_mask: 3085 case X86::BI__builtin_ia32_subss_round_mask: 3086 case X86::BI__builtin_ia32_subsd_round_mask: 3087 case X86::BI__builtin_ia32_scalefpd512_mask: 3088 case X86::BI__builtin_ia32_scalefps512_mask: 3089 case X86::BI__builtin_ia32_scalefsd_round_mask: 3090 case X86::BI__builtin_ia32_scalefss_round_mask: 3091 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3092 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3093 case X86::BI__builtin_ia32_sqrtss_round_mask: 3094 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3095 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3096 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3097 case X86::BI__builtin_ia32_vfmaddss3_mask: 3098 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3099 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3100 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3101 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3102 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3103 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3104 case X86::BI__builtin_ia32_vfmaddps512_mask: 3105 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3106 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3107 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3108 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3109 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3110 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3111 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3112 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3113 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3114 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3115 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3116 ArgNum = 4; 3117 HasRC = true; 3118 break; 3119 } 3120 3121 llvm::APSInt Result; 3122 3123 // We can't check the value of a dependent argument. 3124 Expr *Arg = TheCall->getArg(ArgNum); 3125 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3126 return false; 3127 3128 // Check constant-ness first. 3129 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3130 return true; 3131 3132 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3133 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3134 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3135 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3136 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3137 Result == 8/*ROUND_NO_EXC*/ || 3138 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3139 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3140 return false; 3141 3142 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3143 << Arg->getSourceRange(); 3144 } 3145 3146 // Check if the gather/scatter scale is legal. 3147 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3148 CallExpr *TheCall) { 3149 unsigned ArgNum = 0; 3150 switch (BuiltinID) { 3151 default: 3152 return false; 3153 case X86::BI__builtin_ia32_gatherpfdpd: 3154 case X86::BI__builtin_ia32_gatherpfdps: 3155 case X86::BI__builtin_ia32_gatherpfqpd: 3156 case X86::BI__builtin_ia32_gatherpfqps: 3157 case X86::BI__builtin_ia32_scatterpfdpd: 3158 case X86::BI__builtin_ia32_scatterpfdps: 3159 case X86::BI__builtin_ia32_scatterpfqpd: 3160 case X86::BI__builtin_ia32_scatterpfqps: 3161 ArgNum = 3; 3162 break; 3163 case X86::BI__builtin_ia32_gatherd_pd: 3164 case X86::BI__builtin_ia32_gatherd_pd256: 3165 case X86::BI__builtin_ia32_gatherq_pd: 3166 case X86::BI__builtin_ia32_gatherq_pd256: 3167 case X86::BI__builtin_ia32_gatherd_ps: 3168 case X86::BI__builtin_ia32_gatherd_ps256: 3169 case X86::BI__builtin_ia32_gatherq_ps: 3170 case X86::BI__builtin_ia32_gatherq_ps256: 3171 case X86::BI__builtin_ia32_gatherd_q: 3172 case X86::BI__builtin_ia32_gatherd_q256: 3173 case X86::BI__builtin_ia32_gatherq_q: 3174 case X86::BI__builtin_ia32_gatherq_q256: 3175 case X86::BI__builtin_ia32_gatherd_d: 3176 case X86::BI__builtin_ia32_gatherd_d256: 3177 case X86::BI__builtin_ia32_gatherq_d: 3178 case X86::BI__builtin_ia32_gatherq_d256: 3179 case X86::BI__builtin_ia32_gather3div2df: 3180 case X86::BI__builtin_ia32_gather3div2di: 3181 case X86::BI__builtin_ia32_gather3div4df: 3182 case X86::BI__builtin_ia32_gather3div4di: 3183 case X86::BI__builtin_ia32_gather3div4sf: 3184 case X86::BI__builtin_ia32_gather3div4si: 3185 case X86::BI__builtin_ia32_gather3div8sf: 3186 case X86::BI__builtin_ia32_gather3div8si: 3187 case X86::BI__builtin_ia32_gather3siv2df: 3188 case X86::BI__builtin_ia32_gather3siv2di: 3189 case X86::BI__builtin_ia32_gather3siv4df: 3190 case X86::BI__builtin_ia32_gather3siv4di: 3191 case X86::BI__builtin_ia32_gather3siv4sf: 3192 case X86::BI__builtin_ia32_gather3siv4si: 3193 case X86::BI__builtin_ia32_gather3siv8sf: 3194 case X86::BI__builtin_ia32_gather3siv8si: 3195 case X86::BI__builtin_ia32_gathersiv8df: 3196 case X86::BI__builtin_ia32_gathersiv16sf: 3197 case X86::BI__builtin_ia32_gatherdiv8df: 3198 case X86::BI__builtin_ia32_gatherdiv16sf: 3199 case X86::BI__builtin_ia32_gathersiv8di: 3200 case X86::BI__builtin_ia32_gathersiv16si: 3201 case X86::BI__builtin_ia32_gatherdiv8di: 3202 case X86::BI__builtin_ia32_gatherdiv16si: 3203 case X86::BI__builtin_ia32_scatterdiv2df: 3204 case X86::BI__builtin_ia32_scatterdiv2di: 3205 case X86::BI__builtin_ia32_scatterdiv4df: 3206 case X86::BI__builtin_ia32_scatterdiv4di: 3207 case X86::BI__builtin_ia32_scatterdiv4sf: 3208 case X86::BI__builtin_ia32_scatterdiv4si: 3209 case X86::BI__builtin_ia32_scatterdiv8sf: 3210 case X86::BI__builtin_ia32_scatterdiv8si: 3211 case X86::BI__builtin_ia32_scattersiv2df: 3212 case X86::BI__builtin_ia32_scattersiv2di: 3213 case X86::BI__builtin_ia32_scattersiv4df: 3214 case X86::BI__builtin_ia32_scattersiv4di: 3215 case X86::BI__builtin_ia32_scattersiv4sf: 3216 case X86::BI__builtin_ia32_scattersiv4si: 3217 case X86::BI__builtin_ia32_scattersiv8sf: 3218 case X86::BI__builtin_ia32_scattersiv8si: 3219 case X86::BI__builtin_ia32_scattersiv8df: 3220 case X86::BI__builtin_ia32_scattersiv16sf: 3221 case X86::BI__builtin_ia32_scatterdiv8df: 3222 case X86::BI__builtin_ia32_scatterdiv16sf: 3223 case X86::BI__builtin_ia32_scattersiv8di: 3224 case X86::BI__builtin_ia32_scattersiv16si: 3225 case X86::BI__builtin_ia32_scatterdiv8di: 3226 case X86::BI__builtin_ia32_scatterdiv16si: 3227 ArgNum = 4; 3228 break; 3229 } 3230 3231 llvm::APSInt Result; 3232 3233 // We can't check the value of a dependent argument. 3234 Expr *Arg = TheCall->getArg(ArgNum); 3235 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3236 return false; 3237 3238 // Check constant-ness first. 3239 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3240 return true; 3241 3242 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3243 return false; 3244 3245 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3246 << Arg->getSourceRange(); 3247 } 3248 3249 static bool isX86_32Builtin(unsigned BuiltinID) { 3250 // These builtins only work on x86-32 targets. 3251 switch (BuiltinID) { 3252 case X86::BI__builtin_ia32_readeflags_u32: 3253 case X86::BI__builtin_ia32_writeeflags_u32: 3254 return true; 3255 } 3256 3257 return false; 3258 } 3259 3260 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3261 if (BuiltinID == X86::BI__builtin_cpu_supports) 3262 return SemaBuiltinCpuSupports(*this, TheCall); 3263 3264 if (BuiltinID == X86::BI__builtin_cpu_is) 3265 return SemaBuiltinCpuIs(*this, TheCall); 3266 3267 // Check for 32-bit only builtins on a 64-bit target. 3268 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3269 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3270 return Diag(TheCall->getCallee()->getBeginLoc(), 3271 diag::err_32_bit_builtin_64_bit_tgt); 3272 3273 // If the intrinsic has rounding or SAE make sure its valid. 3274 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3275 return true; 3276 3277 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3278 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3279 return true; 3280 3281 // For intrinsics which take an immediate value as part of the instruction, 3282 // range check them here. 3283 int i = 0, l = 0, u = 0; 3284 switch (BuiltinID) { 3285 default: 3286 return false; 3287 case X86::BI__builtin_ia32_vec_ext_v2si: 3288 case X86::BI__builtin_ia32_vec_ext_v2di: 3289 case X86::BI__builtin_ia32_vextractf128_pd256: 3290 case X86::BI__builtin_ia32_vextractf128_ps256: 3291 case X86::BI__builtin_ia32_vextractf128_si256: 3292 case X86::BI__builtin_ia32_extract128i256: 3293 case X86::BI__builtin_ia32_extractf64x4_mask: 3294 case X86::BI__builtin_ia32_extracti64x4_mask: 3295 case X86::BI__builtin_ia32_extractf32x8_mask: 3296 case X86::BI__builtin_ia32_extracti32x8_mask: 3297 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3298 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3299 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3300 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3301 i = 1; l = 0; u = 1; 3302 break; 3303 case X86::BI__builtin_ia32_vec_set_v2di: 3304 case X86::BI__builtin_ia32_vinsertf128_pd256: 3305 case X86::BI__builtin_ia32_vinsertf128_ps256: 3306 case X86::BI__builtin_ia32_vinsertf128_si256: 3307 case X86::BI__builtin_ia32_insert128i256: 3308 case X86::BI__builtin_ia32_insertf32x8: 3309 case X86::BI__builtin_ia32_inserti32x8: 3310 case X86::BI__builtin_ia32_insertf64x4: 3311 case X86::BI__builtin_ia32_inserti64x4: 3312 case X86::BI__builtin_ia32_insertf64x2_256: 3313 case X86::BI__builtin_ia32_inserti64x2_256: 3314 case X86::BI__builtin_ia32_insertf32x4_256: 3315 case X86::BI__builtin_ia32_inserti32x4_256: 3316 i = 2; l = 0; u = 1; 3317 break; 3318 case X86::BI__builtin_ia32_vpermilpd: 3319 case X86::BI__builtin_ia32_vec_ext_v4hi: 3320 case X86::BI__builtin_ia32_vec_ext_v4si: 3321 case X86::BI__builtin_ia32_vec_ext_v4sf: 3322 case X86::BI__builtin_ia32_vec_ext_v4di: 3323 case X86::BI__builtin_ia32_extractf32x4_mask: 3324 case X86::BI__builtin_ia32_extracti32x4_mask: 3325 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3326 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3327 i = 1; l = 0; u = 3; 3328 break; 3329 case X86::BI_mm_prefetch: 3330 case X86::BI__builtin_ia32_vec_ext_v8hi: 3331 case X86::BI__builtin_ia32_vec_ext_v8si: 3332 i = 1; l = 0; u = 7; 3333 break; 3334 case X86::BI__builtin_ia32_sha1rnds4: 3335 case X86::BI__builtin_ia32_blendpd: 3336 case X86::BI__builtin_ia32_shufpd: 3337 case X86::BI__builtin_ia32_vec_set_v4hi: 3338 case X86::BI__builtin_ia32_vec_set_v4si: 3339 case X86::BI__builtin_ia32_vec_set_v4di: 3340 case X86::BI__builtin_ia32_shuf_f32x4_256: 3341 case X86::BI__builtin_ia32_shuf_f64x2_256: 3342 case X86::BI__builtin_ia32_shuf_i32x4_256: 3343 case X86::BI__builtin_ia32_shuf_i64x2_256: 3344 case X86::BI__builtin_ia32_insertf64x2_512: 3345 case X86::BI__builtin_ia32_inserti64x2_512: 3346 case X86::BI__builtin_ia32_insertf32x4: 3347 case X86::BI__builtin_ia32_inserti32x4: 3348 i = 2; l = 0; u = 3; 3349 break; 3350 case X86::BI__builtin_ia32_vpermil2pd: 3351 case X86::BI__builtin_ia32_vpermil2pd256: 3352 case X86::BI__builtin_ia32_vpermil2ps: 3353 case X86::BI__builtin_ia32_vpermil2ps256: 3354 i = 3; l = 0; u = 3; 3355 break; 3356 case X86::BI__builtin_ia32_cmpb128_mask: 3357 case X86::BI__builtin_ia32_cmpw128_mask: 3358 case X86::BI__builtin_ia32_cmpd128_mask: 3359 case X86::BI__builtin_ia32_cmpq128_mask: 3360 case X86::BI__builtin_ia32_cmpb256_mask: 3361 case X86::BI__builtin_ia32_cmpw256_mask: 3362 case X86::BI__builtin_ia32_cmpd256_mask: 3363 case X86::BI__builtin_ia32_cmpq256_mask: 3364 case X86::BI__builtin_ia32_cmpb512_mask: 3365 case X86::BI__builtin_ia32_cmpw512_mask: 3366 case X86::BI__builtin_ia32_cmpd512_mask: 3367 case X86::BI__builtin_ia32_cmpq512_mask: 3368 case X86::BI__builtin_ia32_ucmpb128_mask: 3369 case X86::BI__builtin_ia32_ucmpw128_mask: 3370 case X86::BI__builtin_ia32_ucmpd128_mask: 3371 case X86::BI__builtin_ia32_ucmpq128_mask: 3372 case X86::BI__builtin_ia32_ucmpb256_mask: 3373 case X86::BI__builtin_ia32_ucmpw256_mask: 3374 case X86::BI__builtin_ia32_ucmpd256_mask: 3375 case X86::BI__builtin_ia32_ucmpq256_mask: 3376 case X86::BI__builtin_ia32_ucmpb512_mask: 3377 case X86::BI__builtin_ia32_ucmpw512_mask: 3378 case X86::BI__builtin_ia32_ucmpd512_mask: 3379 case X86::BI__builtin_ia32_ucmpq512_mask: 3380 case X86::BI__builtin_ia32_vpcomub: 3381 case X86::BI__builtin_ia32_vpcomuw: 3382 case X86::BI__builtin_ia32_vpcomud: 3383 case X86::BI__builtin_ia32_vpcomuq: 3384 case X86::BI__builtin_ia32_vpcomb: 3385 case X86::BI__builtin_ia32_vpcomw: 3386 case X86::BI__builtin_ia32_vpcomd: 3387 case X86::BI__builtin_ia32_vpcomq: 3388 case X86::BI__builtin_ia32_vec_set_v8hi: 3389 case X86::BI__builtin_ia32_vec_set_v8si: 3390 i = 2; l = 0; u = 7; 3391 break; 3392 case X86::BI__builtin_ia32_vpermilpd256: 3393 case X86::BI__builtin_ia32_roundps: 3394 case X86::BI__builtin_ia32_roundpd: 3395 case X86::BI__builtin_ia32_roundps256: 3396 case X86::BI__builtin_ia32_roundpd256: 3397 case X86::BI__builtin_ia32_getmantpd128_mask: 3398 case X86::BI__builtin_ia32_getmantpd256_mask: 3399 case X86::BI__builtin_ia32_getmantps128_mask: 3400 case X86::BI__builtin_ia32_getmantps256_mask: 3401 case X86::BI__builtin_ia32_getmantpd512_mask: 3402 case X86::BI__builtin_ia32_getmantps512_mask: 3403 case X86::BI__builtin_ia32_vec_ext_v16qi: 3404 case X86::BI__builtin_ia32_vec_ext_v16hi: 3405 i = 1; l = 0; u = 15; 3406 break; 3407 case X86::BI__builtin_ia32_pblendd128: 3408 case X86::BI__builtin_ia32_blendps: 3409 case X86::BI__builtin_ia32_blendpd256: 3410 case X86::BI__builtin_ia32_shufpd256: 3411 case X86::BI__builtin_ia32_roundss: 3412 case X86::BI__builtin_ia32_roundsd: 3413 case X86::BI__builtin_ia32_rangepd128_mask: 3414 case X86::BI__builtin_ia32_rangepd256_mask: 3415 case X86::BI__builtin_ia32_rangepd512_mask: 3416 case X86::BI__builtin_ia32_rangeps128_mask: 3417 case X86::BI__builtin_ia32_rangeps256_mask: 3418 case X86::BI__builtin_ia32_rangeps512_mask: 3419 case X86::BI__builtin_ia32_getmantsd_round_mask: 3420 case X86::BI__builtin_ia32_getmantss_round_mask: 3421 case X86::BI__builtin_ia32_vec_set_v16qi: 3422 case X86::BI__builtin_ia32_vec_set_v16hi: 3423 i = 2; l = 0; u = 15; 3424 break; 3425 case X86::BI__builtin_ia32_vec_ext_v32qi: 3426 i = 1; l = 0; u = 31; 3427 break; 3428 case X86::BI__builtin_ia32_cmpps: 3429 case X86::BI__builtin_ia32_cmpss: 3430 case X86::BI__builtin_ia32_cmppd: 3431 case X86::BI__builtin_ia32_cmpsd: 3432 case X86::BI__builtin_ia32_cmpps256: 3433 case X86::BI__builtin_ia32_cmppd256: 3434 case X86::BI__builtin_ia32_cmpps128_mask: 3435 case X86::BI__builtin_ia32_cmppd128_mask: 3436 case X86::BI__builtin_ia32_cmpps256_mask: 3437 case X86::BI__builtin_ia32_cmppd256_mask: 3438 case X86::BI__builtin_ia32_cmpps512_mask: 3439 case X86::BI__builtin_ia32_cmppd512_mask: 3440 case X86::BI__builtin_ia32_cmpsd_mask: 3441 case X86::BI__builtin_ia32_cmpss_mask: 3442 case X86::BI__builtin_ia32_vec_set_v32qi: 3443 i = 2; l = 0; u = 31; 3444 break; 3445 case X86::BI__builtin_ia32_permdf256: 3446 case X86::BI__builtin_ia32_permdi256: 3447 case X86::BI__builtin_ia32_permdf512: 3448 case X86::BI__builtin_ia32_permdi512: 3449 case X86::BI__builtin_ia32_vpermilps: 3450 case X86::BI__builtin_ia32_vpermilps256: 3451 case X86::BI__builtin_ia32_vpermilpd512: 3452 case X86::BI__builtin_ia32_vpermilps512: 3453 case X86::BI__builtin_ia32_pshufd: 3454 case X86::BI__builtin_ia32_pshufd256: 3455 case X86::BI__builtin_ia32_pshufd512: 3456 case X86::BI__builtin_ia32_pshufhw: 3457 case X86::BI__builtin_ia32_pshufhw256: 3458 case X86::BI__builtin_ia32_pshufhw512: 3459 case X86::BI__builtin_ia32_pshuflw: 3460 case X86::BI__builtin_ia32_pshuflw256: 3461 case X86::BI__builtin_ia32_pshuflw512: 3462 case X86::BI__builtin_ia32_vcvtps2ph: 3463 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3464 case X86::BI__builtin_ia32_vcvtps2ph256: 3465 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3466 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3467 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3468 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3469 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3470 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3471 case X86::BI__builtin_ia32_rndscaleps_mask: 3472 case X86::BI__builtin_ia32_rndscalepd_mask: 3473 case X86::BI__builtin_ia32_reducepd128_mask: 3474 case X86::BI__builtin_ia32_reducepd256_mask: 3475 case X86::BI__builtin_ia32_reducepd512_mask: 3476 case X86::BI__builtin_ia32_reduceps128_mask: 3477 case X86::BI__builtin_ia32_reduceps256_mask: 3478 case X86::BI__builtin_ia32_reduceps512_mask: 3479 case X86::BI__builtin_ia32_prold512: 3480 case X86::BI__builtin_ia32_prolq512: 3481 case X86::BI__builtin_ia32_prold128: 3482 case X86::BI__builtin_ia32_prold256: 3483 case X86::BI__builtin_ia32_prolq128: 3484 case X86::BI__builtin_ia32_prolq256: 3485 case X86::BI__builtin_ia32_prord512: 3486 case X86::BI__builtin_ia32_prorq512: 3487 case X86::BI__builtin_ia32_prord128: 3488 case X86::BI__builtin_ia32_prord256: 3489 case X86::BI__builtin_ia32_prorq128: 3490 case X86::BI__builtin_ia32_prorq256: 3491 case X86::BI__builtin_ia32_fpclasspd128_mask: 3492 case X86::BI__builtin_ia32_fpclasspd256_mask: 3493 case X86::BI__builtin_ia32_fpclassps128_mask: 3494 case X86::BI__builtin_ia32_fpclassps256_mask: 3495 case X86::BI__builtin_ia32_fpclassps512_mask: 3496 case X86::BI__builtin_ia32_fpclasspd512_mask: 3497 case X86::BI__builtin_ia32_fpclasssd_mask: 3498 case X86::BI__builtin_ia32_fpclassss_mask: 3499 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3500 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3501 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3502 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3503 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3504 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3505 case X86::BI__builtin_ia32_kshiftliqi: 3506 case X86::BI__builtin_ia32_kshiftlihi: 3507 case X86::BI__builtin_ia32_kshiftlisi: 3508 case X86::BI__builtin_ia32_kshiftlidi: 3509 case X86::BI__builtin_ia32_kshiftriqi: 3510 case X86::BI__builtin_ia32_kshiftrihi: 3511 case X86::BI__builtin_ia32_kshiftrisi: 3512 case X86::BI__builtin_ia32_kshiftridi: 3513 i = 1; l = 0; u = 255; 3514 break; 3515 case X86::BI__builtin_ia32_vperm2f128_pd256: 3516 case X86::BI__builtin_ia32_vperm2f128_ps256: 3517 case X86::BI__builtin_ia32_vperm2f128_si256: 3518 case X86::BI__builtin_ia32_permti256: 3519 case X86::BI__builtin_ia32_pblendw128: 3520 case X86::BI__builtin_ia32_pblendw256: 3521 case X86::BI__builtin_ia32_blendps256: 3522 case X86::BI__builtin_ia32_pblendd256: 3523 case X86::BI__builtin_ia32_palignr128: 3524 case X86::BI__builtin_ia32_palignr256: 3525 case X86::BI__builtin_ia32_palignr512: 3526 case X86::BI__builtin_ia32_alignq512: 3527 case X86::BI__builtin_ia32_alignd512: 3528 case X86::BI__builtin_ia32_alignd128: 3529 case X86::BI__builtin_ia32_alignd256: 3530 case X86::BI__builtin_ia32_alignq128: 3531 case X86::BI__builtin_ia32_alignq256: 3532 case X86::BI__builtin_ia32_vcomisd: 3533 case X86::BI__builtin_ia32_vcomiss: 3534 case X86::BI__builtin_ia32_shuf_f32x4: 3535 case X86::BI__builtin_ia32_shuf_f64x2: 3536 case X86::BI__builtin_ia32_shuf_i32x4: 3537 case X86::BI__builtin_ia32_shuf_i64x2: 3538 case X86::BI__builtin_ia32_shufpd512: 3539 case X86::BI__builtin_ia32_shufps: 3540 case X86::BI__builtin_ia32_shufps256: 3541 case X86::BI__builtin_ia32_shufps512: 3542 case X86::BI__builtin_ia32_dbpsadbw128: 3543 case X86::BI__builtin_ia32_dbpsadbw256: 3544 case X86::BI__builtin_ia32_dbpsadbw512: 3545 case X86::BI__builtin_ia32_vpshldd128: 3546 case X86::BI__builtin_ia32_vpshldd256: 3547 case X86::BI__builtin_ia32_vpshldd512: 3548 case X86::BI__builtin_ia32_vpshldq128: 3549 case X86::BI__builtin_ia32_vpshldq256: 3550 case X86::BI__builtin_ia32_vpshldq512: 3551 case X86::BI__builtin_ia32_vpshldw128: 3552 case X86::BI__builtin_ia32_vpshldw256: 3553 case X86::BI__builtin_ia32_vpshldw512: 3554 case X86::BI__builtin_ia32_vpshrdd128: 3555 case X86::BI__builtin_ia32_vpshrdd256: 3556 case X86::BI__builtin_ia32_vpshrdd512: 3557 case X86::BI__builtin_ia32_vpshrdq128: 3558 case X86::BI__builtin_ia32_vpshrdq256: 3559 case X86::BI__builtin_ia32_vpshrdq512: 3560 case X86::BI__builtin_ia32_vpshrdw128: 3561 case X86::BI__builtin_ia32_vpshrdw256: 3562 case X86::BI__builtin_ia32_vpshrdw512: 3563 i = 2; l = 0; u = 255; 3564 break; 3565 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3566 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3567 case X86::BI__builtin_ia32_fixupimmps512_mask: 3568 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3569 case X86::BI__builtin_ia32_fixupimmsd_mask: 3570 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3571 case X86::BI__builtin_ia32_fixupimmss_mask: 3572 case X86::BI__builtin_ia32_fixupimmss_maskz: 3573 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3574 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3575 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3576 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3577 case X86::BI__builtin_ia32_fixupimmps128_mask: 3578 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3579 case X86::BI__builtin_ia32_fixupimmps256_mask: 3580 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3581 case X86::BI__builtin_ia32_pternlogd512_mask: 3582 case X86::BI__builtin_ia32_pternlogd512_maskz: 3583 case X86::BI__builtin_ia32_pternlogq512_mask: 3584 case X86::BI__builtin_ia32_pternlogq512_maskz: 3585 case X86::BI__builtin_ia32_pternlogd128_mask: 3586 case X86::BI__builtin_ia32_pternlogd128_maskz: 3587 case X86::BI__builtin_ia32_pternlogd256_mask: 3588 case X86::BI__builtin_ia32_pternlogd256_maskz: 3589 case X86::BI__builtin_ia32_pternlogq128_mask: 3590 case X86::BI__builtin_ia32_pternlogq128_maskz: 3591 case X86::BI__builtin_ia32_pternlogq256_mask: 3592 case X86::BI__builtin_ia32_pternlogq256_maskz: 3593 i = 3; l = 0; u = 255; 3594 break; 3595 case X86::BI__builtin_ia32_gatherpfdpd: 3596 case X86::BI__builtin_ia32_gatherpfdps: 3597 case X86::BI__builtin_ia32_gatherpfqpd: 3598 case X86::BI__builtin_ia32_gatherpfqps: 3599 case X86::BI__builtin_ia32_scatterpfdpd: 3600 case X86::BI__builtin_ia32_scatterpfdps: 3601 case X86::BI__builtin_ia32_scatterpfqpd: 3602 case X86::BI__builtin_ia32_scatterpfqps: 3603 i = 4; l = 2; u = 3; 3604 break; 3605 case X86::BI__builtin_ia32_reducesd_mask: 3606 case X86::BI__builtin_ia32_reducess_mask: 3607 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3608 case X86::BI__builtin_ia32_rndscaless_round_mask: 3609 i = 4; l = 0; u = 255; 3610 break; 3611 } 3612 3613 // Note that we don't force a hard error on the range check here, allowing 3614 // template-generated or macro-generated dead code to potentially have out-of- 3615 // range values. These need to code generate, but don't need to necessarily 3616 // make any sense. We use a warning that defaults to an error. 3617 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3618 } 3619 3620 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3621 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3622 /// Returns true when the format fits the function and the FormatStringInfo has 3623 /// been populated. 3624 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3625 FormatStringInfo *FSI) { 3626 FSI->HasVAListArg = Format->getFirstArg() == 0; 3627 FSI->FormatIdx = Format->getFormatIdx() - 1; 3628 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3629 3630 // The way the format attribute works in GCC, the implicit this argument 3631 // of member functions is counted. However, it doesn't appear in our own 3632 // lists, so decrement format_idx in that case. 3633 if (IsCXXMember) { 3634 if(FSI->FormatIdx == 0) 3635 return false; 3636 --FSI->FormatIdx; 3637 if (FSI->FirstDataArg != 0) 3638 --FSI->FirstDataArg; 3639 } 3640 return true; 3641 } 3642 3643 /// Checks if a the given expression evaluates to null. 3644 /// 3645 /// Returns true if the value evaluates to null. 3646 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3647 // If the expression has non-null type, it doesn't evaluate to null. 3648 if (auto nullability 3649 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3650 if (*nullability == NullabilityKind::NonNull) 3651 return false; 3652 } 3653 3654 // As a special case, transparent unions initialized with zero are 3655 // considered null for the purposes of the nonnull attribute. 3656 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3657 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3658 if (const CompoundLiteralExpr *CLE = 3659 dyn_cast<CompoundLiteralExpr>(Expr)) 3660 if (const InitListExpr *ILE = 3661 dyn_cast<InitListExpr>(CLE->getInitializer())) 3662 Expr = ILE->getInit(0); 3663 } 3664 3665 bool Result; 3666 return (!Expr->isValueDependent() && 3667 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3668 !Result); 3669 } 3670 3671 static void CheckNonNullArgument(Sema &S, 3672 const Expr *ArgExpr, 3673 SourceLocation CallSiteLoc) { 3674 if (CheckNonNullExpr(S, ArgExpr)) 3675 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3676 S.PDiag(diag::warn_null_arg) 3677 << ArgExpr->getSourceRange()); 3678 } 3679 3680 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3681 FormatStringInfo FSI; 3682 if ((GetFormatStringType(Format) == FST_NSString) && 3683 getFormatStringInfo(Format, false, &FSI)) { 3684 Idx = FSI.FormatIdx; 3685 return true; 3686 } 3687 return false; 3688 } 3689 3690 /// Diagnose use of %s directive in an NSString which is being passed 3691 /// as formatting string to formatting method. 3692 static void 3693 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3694 const NamedDecl *FDecl, 3695 Expr **Args, 3696 unsigned NumArgs) { 3697 unsigned Idx = 0; 3698 bool Format = false; 3699 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3700 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3701 Idx = 2; 3702 Format = true; 3703 } 3704 else 3705 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3706 if (S.GetFormatNSStringIdx(I, Idx)) { 3707 Format = true; 3708 break; 3709 } 3710 } 3711 if (!Format || NumArgs <= Idx) 3712 return; 3713 const Expr *FormatExpr = Args[Idx]; 3714 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3715 FormatExpr = CSCE->getSubExpr(); 3716 const StringLiteral *FormatString; 3717 if (const ObjCStringLiteral *OSL = 3718 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3719 FormatString = OSL->getString(); 3720 else 3721 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3722 if (!FormatString) 3723 return; 3724 if (S.FormatStringHasSArg(FormatString)) { 3725 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3726 << "%s" << 1 << 1; 3727 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3728 << FDecl->getDeclName(); 3729 } 3730 } 3731 3732 /// Determine whether the given type has a non-null nullability annotation. 3733 static bool isNonNullType(ASTContext &ctx, QualType type) { 3734 if (auto nullability = type->getNullability(ctx)) 3735 return *nullability == NullabilityKind::NonNull; 3736 3737 return false; 3738 } 3739 3740 static void CheckNonNullArguments(Sema &S, 3741 const NamedDecl *FDecl, 3742 const FunctionProtoType *Proto, 3743 ArrayRef<const Expr *> Args, 3744 SourceLocation CallSiteLoc) { 3745 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3746 3747 // Already checked by by constant evaluator. 3748 if (S.isConstantEvaluated()) 3749 return; 3750 // Check the attributes attached to the method/function itself. 3751 llvm::SmallBitVector NonNullArgs; 3752 if (FDecl) { 3753 // Handle the nonnull attribute on the function/method declaration itself. 3754 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3755 if (!NonNull->args_size()) { 3756 // Easy case: all pointer arguments are nonnull. 3757 for (const auto *Arg : Args) 3758 if (S.isValidPointerAttrType(Arg->getType())) 3759 CheckNonNullArgument(S, Arg, CallSiteLoc); 3760 return; 3761 } 3762 3763 for (const ParamIdx &Idx : NonNull->args()) { 3764 unsigned IdxAST = Idx.getASTIndex(); 3765 if (IdxAST >= Args.size()) 3766 continue; 3767 if (NonNullArgs.empty()) 3768 NonNullArgs.resize(Args.size()); 3769 NonNullArgs.set(IdxAST); 3770 } 3771 } 3772 } 3773 3774 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3775 // Handle the nonnull attribute on the parameters of the 3776 // function/method. 3777 ArrayRef<ParmVarDecl*> parms; 3778 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3779 parms = FD->parameters(); 3780 else 3781 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3782 3783 unsigned ParamIndex = 0; 3784 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3785 I != E; ++I, ++ParamIndex) { 3786 const ParmVarDecl *PVD = *I; 3787 if (PVD->hasAttr<NonNullAttr>() || 3788 isNonNullType(S.Context, PVD->getType())) { 3789 if (NonNullArgs.empty()) 3790 NonNullArgs.resize(Args.size()); 3791 3792 NonNullArgs.set(ParamIndex); 3793 } 3794 } 3795 } else { 3796 // If we have a non-function, non-method declaration but no 3797 // function prototype, try to dig out the function prototype. 3798 if (!Proto) { 3799 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3800 QualType type = VD->getType().getNonReferenceType(); 3801 if (auto pointerType = type->getAs<PointerType>()) 3802 type = pointerType->getPointeeType(); 3803 else if (auto blockType = type->getAs<BlockPointerType>()) 3804 type = blockType->getPointeeType(); 3805 // FIXME: data member pointers? 3806 3807 // Dig out the function prototype, if there is one. 3808 Proto = type->getAs<FunctionProtoType>(); 3809 } 3810 } 3811 3812 // Fill in non-null argument information from the nullability 3813 // information on the parameter types (if we have them). 3814 if (Proto) { 3815 unsigned Index = 0; 3816 for (auto paramType : Proto->getParamTypes()) { 3817 if (isNonNullType(S.Context, paramType)) { 3818 if (NonNullArgs.empty()) 3819 NonNullArgs.resize(Args.size()); 3820 3821 NonNullArgs.set(Index); 3822 } 3823 3824 ++Index; 3825 } 3826 } 3827 } 3828 3829 // Check for non-null arguments. 3830 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3831 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3832 if (NonNullArgs[ArgIndex]) 3833 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3834 } 3835 } 3836 3837 /// Handles the checks for format strings, non-POD arguments to vararg 3838 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3839 /// attributes. 3840 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3841 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3842 bool IsMemberFunction, SourceLocation Loc, 3843 SourceRange Range, VariadicCallType CallType) { 3844 // FIXME: We should check as much as we can in the template definition. 3845 if (CurContext->isDependentContext()) 3846 return; 3847 3848 // Printf and scanf checking. 3849 llvm::SmallBitVector CheckedVarArgs; 3850 if (FDecl) { 3851 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3852 // Only create vector if there are format attributes. 3853 CheckedVarArgs.resize(Args.size()); 3854 3855 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3856 CheckedVarArgs); 3857 } 3858 } 3859 3860 // Refuse POD arguments that weren't caught by the format string 3861 // checks above. 3862 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3863 if (CallType != VariadicDoesNotApply && 3864 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3865 unsigned NumParams = Proto ? Proto->getNumParams() 3866 : FDecl && isa<FunctionDecl>(FDecl) 3867 ? cast<FunctionDecl>(FDecl)->getNumParams() 3868 : FDecl && isa<ObjCMethodDecl>(FDecl) 3869 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3870 : 0; 3871 3872 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3873 // Args[ArgIdx] can be null in malformed code. 3874 if (const Expr *Arg = Args[ArgIdx]) { 3875 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3876 checkVariadicArgument(Arg, CallType); 3877 } 3878 } 3879 } 3880 3881 if (FDecl || Proto) { 3882 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3883 3884 // Type safety checking. 3885 if (FDecl) { 3886 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3887 CheckArgumentWithTypeTag(I, Args, Loc); 3888 } 3889 } 3890 3891 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 3892 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 3893 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 3894 if (!Arg->isValueDependent()) { 3895 llvm::APSInt I(64); 3896 if (Arg->isIntegerConstantExpr(I, Context)) { 3897 if (!I.isPowerOf2()) { 3898 Diag(Arg->getExprLoc(), diag::err_alignment_not_power_of_two) 3899 << Arg->getSourceRange(); 3900 return; 3901 } 3902 3903 if (I > Sema::MaximumAlignment) 3904 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 3905 << Arg->getSourceRange() << Sema::MaximumAlignment; 3906 } 3907 } 3908 } 3909 3910 if (FD) 3911 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3912 } 3913 3914 /// CheckConstructorCall - Check a constructor call for correctness and safety 3915 /// properties not enforced by the C type system. 3916 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3917 ArrayRef<const Expr *> Args, 3918 const FunctionProtoType *Proto, 3919 SourceLocation Loc) { 3920 VariadicCallType CallType = 3921 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3922 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3923 Loc, SourceRange(), CallType); 3924 } 3925 3926 /// CheckFunctionCall - Check a direct function call for various correctness 3927 /// and safety properties not strictly enforced by the C type system. 3928 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3929 const FunctionProtoType *Proto) { 3930 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3931 isa<CXXMethodDecl>(FDecl); 3932 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3933 IsMemberOperatorCall; 3934 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3935 TheCall->getCallee()); 3936 Expr** Args = TheCall->getArgs(); 3937 unsigned NumArgs = TheCall->getNumArgs(); 3938 3939 Expr *ImplicitThis = nullptr; 3940 if (IsMemberOperatorCall) { 3941 // If this is a call to a member operator, hide the first argument 3942 // from checkCall. 3943 // FIXME: Our choice of AST representation here is less than ideal. 3944 ImplicitThis = Args[0]; 3945 ++Args; 3946 --NumArgs; 3947 } else if (IsMemberFunction) 3948 ImplicitThis = 3949 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3950 3951 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 3952 IsMemberFunction, TheCall->getRParenLoc(), 3953 TheCall->getCallee()->getSourceRange(), CallType); 3954 3955 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3956 // None of the checks below are needed for functions that don't have 3957 // simple names (e.g., C++ conversion functions). 3958 if (!FnInfo) 3959 return false; 3960 3961 CheckAbsoluteValueFunction(TheCall, FDecl); 3962 CheckMaxUnsignedZero(TheCall, FDecl); 3963 3964 if (getLangOpts().ObjC) 3965 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 3966 3967 unsigned CMId = FDecl->getMemoryFunctionKind(); 3968 if (CMId == 0) 3969 return false; 3970 3971 // Handle memory setting and copying functions. 3972 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 3973 CheckStrlcpycatArguments(TheCall, FnInfo); 3974 else if (CMId == Builtin::BIstrncat) 3975 CheckStrncatArguments(TheCall, FnInfo); 3976 else 3977 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3978 3979 return false; 3980 } 3981 3982 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 3983 ArrayRef<const Expr *> Args) { 3984 VariadicCallType CallType = 3985 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 3986 3987 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 3988 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 3989 CallType); 3990 3991 return false; 3992 } 3993 3994 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3995 const FunctionProtoType *Proto) { 3996 QualType Ty; 3997 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3998 Ty = V->getType().getNonReferenceType(); 3999 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4000 Ty = F->getType().getNonReferenceType(); 4001 else 4002 return false; 4003 4004 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4005 !Ty->isFunctionProtoType()) 4006 return false; 4007 4008 VariadicCallType CallType; 4009 if (!Proto || !Proto->isVariadic()) { 4010 CallType = VariadicDoesNotApply; 4011 } else if (Ty->isBlockPointerType()) { 4012 CallType = VariadicBlock; 4013 } else { // Ty->isFunctionPointerType() 4014 CallType = VariadicFunction; 4015 } 4016 4017 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4018 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4019 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4020 TheCall->getCallee()->getSourceRange(), CallType); 4021 4022 return false; 4023 } 4024 4025 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4026 /// such as function pointers returned from functions. 4027 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4028 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4029 TheCall->getCallee()); 4030 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4031 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4032 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4033 TheCall->getCallee()->getSourceRange(), CallType); 4034 4035 return false; 4036 } 4037 4038 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4039 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4040 return false; 4041 4042 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4043 switch (Op) { 4044 case AtomicExpr::AO__c11_atomic_init: 4045 case AtomicExpr::AO__opencl_atomic_init: 4046 llvm_unreachable("There is no ordering argument for an init"); 4047 4048 case AtomicExpr::AO__c11_atomic_load: 4049 case AtomicExpr::AO__opencl_atomic_load: 4050 case AtomicExpr::AO__atomic_load_n: 4051 case AtomicExpr::AO__atomic_load: 4052 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4053 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4054 4055 case AtomicExpr::AO__c11_atomic_store: 4056 case AtomicExpr::AO__opencl_atomic_store: 4057 case AtomicExpr::AO__atomic_store: 4058 case AtomicExpr::AO__atomic_store_n: 4059 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4060 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4061 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4062 4063 default: 4064 return true; 4065 } 4066 } 4067 4068 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4069 AtomicExpr::AtomicOp Op) { 4070 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4071 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4072 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4073 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4074 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4075 Op); 4076 } 4077 4078 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4079 SourceLocation RParenLoc, MultiExprArg Args, 4080 AtomicExpr::AtomicOp Op, 4081 AtomicArgumentOrder ArgOrder) { 4082 // All the non-OpenCL operations take one of the following forms. 4083 // The OpenCL operations take the __c11 forms with one extra argument for 4084 // synchronization scope. 4085 enum { 4086 // C __c11_atomic_init(A *, C) 4087 Init, 4088 4089 // C __c11_atomic_load(A *, int) 4090 Load, 4091 4092 // void __atomic_load(A *, CP, int) 4093 LoadCopy, 4094 4095 // void __atomic_store(A *, CP, int) 4096 Copy, 4097 4098 // C __c11_atomic_add(A *, M, int) 4099 Arithmetic, 4100 4101 // C __atomic_exchange_n(A *, CP, int) 4102 Xchg, 4103 4104 // void __atomic_exchange(A *, C *, CP, int) 4105 GNUXchg, 4106 4107 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4108 C11CmpXchg, 4109 4110 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4111 GNUCmpXchg 4112 } Form = Init; 4113 4114 const unsigned NumForm = GNUCmpXchg + 1; 4115 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4116 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4117 // where: 4118 // C is an appropriate type, 4119 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4120 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4121 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4122 // the int parameters are for orderings. 4123 4124 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4125 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4126 "need to update code for modified forms"); 4127 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4128 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4129 AtomicExpr::AO__atomic_load, 4130 "need to update code for modified C11 atomics"); 4131 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4132 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4133 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4134 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4135 IsOpenCL; 4136 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4137 Op == AtomicExpr::AO__atomic_store_n || 4138 Op == AtomicExpr::AO__atomic_exchange_n || 4139 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4140 bool IsAddSub = false; 4141 4142 switch (Op) { 4143 case AtomicExpr::AO__c11_atomic_init: 4144 case AtomicExpr::AO__opencl_atomic_init: 4145 Form = Init; 4146 break; 4147 4148 case AtomicExpr::AO__c11_atomic_load: 4149 case AtomicExpr::AO__opencl_atomic_load: 4150 case AtomicExpr::AO__atomic_load_n: 4151 Form = Load; 4152 break; 4153 4154 case AtomicExpr::AO__atomic_load: 4155 Form = LoadCopy; 4156 break; 4157 4158 case AtomicExpr::AO__c11_atomic_store: 4159 case AtomicExpr::AO__opencl_atomic_store: 4160 case AtomicExpr::AO__atomic_store: 4161 case AtomicExpr::AO__atomic_store_n: 4162 Form = Copy; 4163 break; 4164 4165 case AtomicExpr::AO__c11_atomic_fetch_add: 4166 case AtomicExpr::AO__c11_atomic_fetch_sub: 4167 case AtomicExpr::AO__opencl_atomic_fetch_add: 4168 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4169 case AtomicExpr::AO__atomic_fetch_add: 4170 case AtomicExpr::AO__atomic_fetch_sub: 4171 case AtomicExpr::AO__atomic_add_fetch: 4172 case AtomicExpr::AO__atomic_sub_fetch: 4173 IsAddSub = true; 4174 LLVM_FALLTHROUGH; 4175 case AtomicExpr::AO__c11_atomic_fetch_and: 4176 case AtomicExpr::AO__c11_atomic_fetch_or: 4177 case AtomicExpr::AO__c11_atomic_fetch_xor: 4178 case AtomicExpr::AO__opencl_atomic_fetch_and: 4179 case AtomicExpr::AO__opencl_atomic_fetch_or: 4180 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4181 case AtomicExpr::AO__atomic_fetch_and: 4182 case AtomicExpr::AO__atomic_fetch_or: 4183 case AtomicExpr::AO__atomic_fetch_xor: 4184 case AtomicExpr::AO__atomic_fetch_nand: 4185 case AtomicExpr::AO__atomic_and_fetch: 4186 case AtomicExpr::AO__atomic_or_fetch: 4187 case AtomicExpr::AO__atomic_xor_fetch: 4188 case AtomicExpr::AO__atomic_nand_fetch: 4189 case AtomicExpr::AO__c11_atomic_fetch_min: 4190 case AtomicExpr::AO__c11_atomic_fetch_max: 4191 case AtomicExpr::AO__opencl_atomic_fetch_min: 4192 case AtomicExpr::AO__opencl_atomic_fetch_max: 4193 case AtomicExpr::AO__atomic_min_fetch: 4194 case AtomicExpr::AO__atomic_max_fetch: 4195 case AtomicExpr::AO__atomic_fetch_min: 4196 case AtomicExpr::AO__atomic_fetch_max: 4197 Form = Arithmetic; 4198 break; 4199 4200 case AtomicExpr::AO__c11_atomic_exchange: 4201 case AtomicExpr::AO__opencl_atomic_exchange: 4202 case AtomicExpr::AO__atomic_exchange_n: 4203 Form = Xchg; 4204 break; 4205 4206 case AtomicExpr::AO__atomic_exchange: 4207 Form = GNUXchg; 4208 break; 4209 4210 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4211 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4212 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4213 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4214 Form = C11CmpXchg; 4215 break; 4216 4217 case AtomicExpr::AO__atomic_compare_exchange: 4218 case AtomicExpr::AO__atomic_compare_exchange_n: 4219 Form = GNUCmpXchg; 4220 break; 4221 } 4222 4223 unsigned AdjustedNumArgs = NumArgs[Form]; 4224 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4225 ++AdjustedNumArgs; 4226 // Check we have the right number of arguments. 4227 if (Args.size() < AdjustedNumArgs) { 4228 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4229 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4230 << ExprRange; 4231 return ExprError(); 4232 } else if (Args.size() > AdjustedNumArgs) { 4233 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4234 diag::err_typecheck_call_too_many_args) 4235 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4236 << ExprRange; 4237 return ExprError(); 4238 } 4239 4240 // Inspect the first argument of the atomic operation. 4241 Expr *Ptr = Args[0]; 4242 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4243 if (ConvertedPtr.isInvalid()) 4244 return ExprError(); 4245 4246 Ptr = ConvertedPtr.get(); 4247 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4248 if (!pointerType) { 4249 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4250 << Ptr->getType() << Ptr->getSourceRange(); 4251 return ExprError(); 4252 } 4253 4254 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4255 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4256 QualType ValType = AtomTy; // 'C' 4257 if (IsC11) { 4258 if (!AtomTy->isAtomicType()) { 4259 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4260 << Ptr->getType() << Ptr->getSourceRange(); 4261 return ExprError(); 4262 } 4263 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4264 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4265 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4266 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4267 << Ptr->getSourceRange(); 4268 return ExprError(); 4269 } 4270 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4271 } else if (Form != Load && Form != LoadCopy) { 4272 if (ValType.isConstQualified()) { 4273 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4274 << Ptr->getType() << Ptr->getSourceRange(); 4275 return ExprError(); 4276 } 4277 } 4278 4279 // For an arithmetic operation, the implied arithmetic must be well-formed. 4280 if (Form == Arithmetic) { 4281 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4282 if (IsAddSub && !ValType->isIntegerType() 4283 && !ValType->isPointerType()) { 4284 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4285 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4286 return ExprError(); 4287 } 4288 if (!IsAddSub && !ValType->isIntegerType()) { 4289 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4290 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4291 return ExprError(); 4292 } 4293 if (IsC11 && ValType->isPointerType() && 4294 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4295 diag::err_incomplete_type)) { 4296 return ExprError(); 4297 } 4298 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4299 // For __atomic_*_n operations, the value type must be a scalar integral or 4300 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4301 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4302 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4303 return ExprError(); 4304 } 4305 4306 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4307 !AtomTy->isScalarType()) { 4308 // For GNU atomics, require a trivially-copyable type. This is not part of 4309 // the GNU atomics specification, but we enforce it for sanity. 4310 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4311 << Ptr->getType() << Ptr->getSourceRange(); 4312 return ExprError(); 4313 } 4314 4315 switch (ValType.getObjCLifetime()) { 4316 case Qualifiers::OCL_None: 4317 case Qualifiers::OCL_ExplicitNone: 4318 // okay 4319 break; 4320 4321 case Qualifiers::OCL_Weak: 4322 case Qualifiers::OCL_Strong: 4323 case Qualifiers::OCL_Autoreleasing: 4324 // FIXME: Can this happen? By this point, ValType should be known 4325 // to be trivially copyable. 4326 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4327 << ValType << Ptr->getSourceRange(); 4328 return ExprError(); 4329 } 4330 4331 // All atomic operations have an overload which takes a pointer to a volatile 4332 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4333 // into the result or the other operands. Similarly atomic_load takes a 4334 // pointer to a const 'A'. 4335 ValType.removeLocalVolatile(); 4336 ValType.removeLocalConst(); 4337 QualType ResultType = ValType; 4338 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4339 Form == Init) 4340 ResultType = Context.VoidTy; 4341 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4342 ResultType = Context.BoolTy; 4343 4344 // The type of a parameter passed 'by value'. In the GNU atomics, such 4345 // arguments are actually passed as pointers. 4346 QualType ByValType = ValType; // 'CP' 4347 bool IsPassedByAddress = false; 4348 if (!IsC11 && !IsN) { 4349 ByValType = Ptr->getType(); 4350 IsPassedByAddress = true; 4351 } 4352 4353 SmallVector<Expr *, 5> APIOrderedArgs; 4354 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4355 APIOrderedArgs.push_back(Args[0]); 4356 switch (Form) { 4357 case Init: 4358 case Load: 4359 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4360 break; 4361 case LoadCopy: 4362 case Copy: 4363 case Arithmetic: 4364 case Xchg: 4365 APIOrderedArgs.push_back(Args[2]); // Val1 4366 APIOrderedArgs.push_back(Args[1]); // Order 4367 break; 4368 case GNUXchg: 4369 APIOrderedArgs.push_back(Args[2]); // Val1 4370 APIOrderedArgs.push_back(Args[3]); // Val2 4371 APIOrderedArgs.push_back(Args[1]); // Order 4372 break; 4373 case C11CmpXchg: 4374 APIOrderedArgs.push_back(Args[2]); // Val1 4375 APIOrderedArgs.push_back(Args[4]); // Val2 4376 APIOrderedArgs.push_back(Args[1]); // Order 4377 APIOrderedArgs.push_back(Args[3]); // OrderFail 4378 break; 4379 case GNUCmpXchg: 4380 APIOrderedArgs.push_back(Args[2]); // Val1 4381 APIOrderedArgs.push_back(Args[4]); // Val2 4382 APIOrderedArgs.push_back(Args[5]); // Weak 4383 APIOrderedArgs.push_back(Args[1]); // Order 4384 APIOrderedArgs.push_back(Args[3]); // OrderFail 4385 break; 4386 } 4387 } else 4388 APIOrderedArgs.append(Args.begin(), Args.end()); 4389 4390 // The first argument's non-CV pointer type is used to deduce the type of 4391 // subsequent arguments, except for: 4392 // - weak flag (always converted to bool) 4393 // - memory order (always converted to int) 4394 // - scope (always converted to int) 4395 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4396 QualType Ty; 4397 if (i < NumVals[Form] + 1) { 4398 switch (i) { 4399 case 0: 4400 // The first argument is always a pointer. It has a fixed type. 4401 // It is always dereferenced, a nullptr is undefined. 4402 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4403 // Nothing else to do: we already know all we want about this pointer. 4404 continue; 4405 case 1: 4406 // The second argument is the non-atomic operand. For arithmetic, this 4407 // is always passed by value, and for a compare_exchange it is always 4408 // passed by address. For the rest, GNU uses by-address and C11 uses 4409 // by-value. 4410 assert(Form != Load); 4411 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4412 Ty = ValType; 4413 else if (Form == Copy || Form == Xchg) { 4414 if (IsPassedByAddress) { 4415 // The value pointer is always dereferenced, a nullptr is undefined. 4416 CheckNonNullArgument(*this, APIOrderedArgs[i], 4417 ExprRange.getBegin()); 4418 } 4419 Ty = ByValType; 4420 } else if (Form == Arithmetic) 4421 Ty = Context.getPointerDiffType(); 4422 else { 4423 Expr *ValArg = APIOrderedArgs[i]; 4424 // The value pointer is always dereferenced, a nullptr is undefined. 4425 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4426 LangAS AS = LangAS::Default; 4427 // Keep address space of non-atomic pointer type. 4428 if (const PointerType *PtrTy = 4429 ValArg->getType()->getAs<PointerType>()) { 4430 AS = PtrTy->getPointeeType().getAddressSpace(); 4431 } 4432 Ty = Context.getPointerType( 4433 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4434 } 4435 break; 4436 case 2: 4437 // The third argument to compare_exchange / GNU exchange is the desired 4438 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4439 if (IsPassedByAddress) 4440 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4441 Ty = ByValType; 4442 break; 4443 case 3: 4444 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4445 Ty = Context.BoolTy; 4446 break; 4447 } 4448 } else { 4449 // The order(s) and scope are always converted to int. 4450 Ty = Context.IntTy; 4451 } 4452 4453 InitializedEntity Entity = 4454 InitializedEntity::InitializeParameter(Context, Ty, false); 4455 ExprResult Arg = APIOrderedArgs[i]; 4456 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4457 if (Arg.isInvalid()) 4458 return true; 4459 APIOrderedArgs[i] = Arg.get(); 4460 } 4461 4462 // Permute the arguments into a 'consistent' order. 4463 SmallVector<Expr*, 5> SubExprs; 4464 SubExprs.push_back(Ptr); 4465 switch (Form) { 4466 case Init: 4467 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4468 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4469 break; 4470 case Load: 4471 SubExprs.push_back(APIOrderedArgs[1]); // Order 4472 break; 4473 case LoadCopy: 4474 case Copy: 4475 case Arithmetic: 4476 case Xchg: 4477 SubExprs.push_back(APIOrderedArgs[2]); // Order 4478 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4479 break; 4480 case GNUXchg: 4481 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4482 SubExprs.push_back(APIOrderedArgs[3]); // Order 4483 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4484 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4485 break; 4486 case C11CmpXchg: 4487 SubExprs.push_back(APIOrderedArgs[3]); // Order 4488 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4489 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4490 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4491 break; 4492 case GNUCmpXchg: 4493 SubExprs.push_back(APIOrderedArgs[4]); // Order 4494 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4495 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4496 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4497 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4498 break; 4499 } 4500 4501 if (SubExprs.size() >= 2 && Form != Init) { 4502 llvm::APSInt Result(32); 4503 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4504 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4505 Diag(SubExprs[1]->getBeginLoc(), 4506 diag::warn_atomic_op_has_invalid_memory_order) 4507 << SubExprs[1]->getSourceRange(); 4508 } 4509 4510 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4511 auto *Scope = Args[Args.size() - 1]; 4512 llvm::APSInt Result(32); 4513 if (Scope->isIntegerConstantExpr(Result, Context) && 4514 !ScopeModel->isValid(Result.getZExtValue())) { 4515 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4516 << Scope->getSourceRange(); 4517 } 4518 SubExprs.push_back(Scope); 4519 } 4520 4521 AtomicExpr *AE = new (Context) 4522 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4523 4524 if ((Op == AtomicExpr::AO__c11_atomic_load || 4525 Op == AtomicExpr::AO__c11_atomic_store || 4526 Op == AtomicExpr::AO__opencl_atomic_load || 4527 Op == AtomicExpr::AO__opencl_atomic_store ) && 4528 Context.AtomicUsesUnsupportedLibcall(AE)) 4529 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4530 << ((Op == AtomicExpr::AO__c11_atomic_load || 4531 Op == AtomicExpr::AO__opencl_atomic_load) 4532 ? 0 4533 : 1); 4534 4535 return AE; 4536 } 4537 4538 /// checkBuiltinArgument - Given a call to a builtin function, perform 4539 /// normal type-checking on the given argument, updating the call in 4540 /// place. This is useful when a builtin function requires custom 4541 /// type-checking for some of its arguments but not necessarily all of 4542 /// them. 4543 /// 4544 /// Returns true on error. 4545 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4546 FunctionDecl *Fn = E->getDirectCallee(); 4547 assert(Fn && "builtin call without direct callee!"); 4548 4549 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4550 InitializedEntity Entity = 4551 InitializedEntity::InitializeParameter(S.Context, Param); 4552 4553 ExprResult Arg = E->getArg(0); 4554 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4555 if (Arg.isInvalid()) 4556 return true; 4557 4558 E->setArg(ArgIndex, Arg.get()); 4559 return false; 4560 } 4561 4562 /// We have a call to a function like __sync_fetch_and_add, which is an 4563 /// overloaded function based on the pointer type of its first argument. 4564 /// The main BuildCallExpr routines have already promoted the types of 4565 /// arguments because all of these calls are prototyped as void(...). 4566 /// 4567 /// This function goes through and does final semantic checking for these 4568 /// builtins, as well as generating any warnings. 4569 ExprResult 4570 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4571 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4572 Expr *Callee = TheCall->getCallee(); 4573 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4574 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4575 4576 // Ensure that we have at least one argument to do type inference from. 4577 if (TheCall->getNumArgs() < 1) { 4578 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4579 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4580 return ExprError(); 4581 } 4582 4583 // Inspect the first argument of the atomic builtin. This should always be 4584 // a pointer type, whose element is an integral scalar or pointer type. 4585 // Because it is a pointer type, we don't have to worry about any implicit 4586 // casts here. 4587 // FIXME: We don't allow floating point scalars as input. 4588 Expr *FirstArg = TheCall->getArg(0); 4589 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4590 if (FirstArgResult.isInvalid()) 4591 return ExprError(); 4592 FirstArg = FirstArgResult.get(); 4593 TheCall->setArg(0, FirstArg); 4594 4595 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4596 if (!pointerType) { 4597 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4598 << FirstArg->getType() << FirstArg->getSourceRange(); 4599 return ExprError(); 4600 } 4601 4602 QualType ValType = pointerType->getPointeeType(); 4603 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4604 !ValType->isBlockPointerType()) { 4605 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4606 << FirstArg->getType() << FirstArg->getSourceRange(); 4607 return ExprError(); 4608 } 4609 4610 if (ValType.isConstQualified()) { 4611 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4612 << FirstArg->getType() << FirstArg->getSourceRange(); 4613 return ExprError(); 4614 } 4615 4616 switch (ValType.getObjCLifetime()) { 4617 case Qualifiers::OCL_None: 4618 case Qualifiers::OCL_ExplicitNone: 4619 // okay 4620 break; 4621 4622 case Qualifiers::OCL_Weak: 4623 case Qualifiers::OCL_Strong: 4624 case Qualifiers::OCL_Autoreleasing: 4625 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4626 << ValType << FirstArg->getSourceRange(); 4627 return ExprError(); 4628 } 4629 4630 // Strip any qualifiers off ValType. 4631 ValType = ValType.getUnqualifiedType(); 4632 4633 // The majority of builtins return a value, but a few have special return 4634 // types, so allow them to override appropriately below. 4635 QualType ResultType = ValType; 4636 4637 // We need to figure out which concrete builtin this maps onto. For example, 4638 // __sync_fetch_and_add with a 2 byte object turns into 4639 // __sync_fetch_and_add_2. 4640 #define BUILTIN_ROW(x) \ 4641 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4642 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4643 4644 static const unsigned BuiltinIndices[][5] = { 4645 BUILTIN_ROW(__sync_fetch_and_add), 4646 BUILTIN_ROW(__sync_fetch_and_sub), 4647 BUILTIN_ROW(__sync_fetch_and_or), 4648 BUILTIN_ROW(__sync_fetch_and_and), 4649 BUILTIN_ROW(__sync_fetch_and_xor), 4650 BUILTIN_ROW(__sync_fetch_and_nand), 4651 4652 BUILTIN_ROW(__sync_add_and_fetch), 4653 BUILTIN_ROW(__sync_sub_and_fetch), 4654 BUILTIN_ROW(__sync_and_and_fetch), 4655 BUILTIN_ROW(__sync_or_and_fetch), 4656 BUILTIN_ROW(__sync_xor_and_fetch), 4657 BUILTIN_ROW(__sync_nand_and_fetch), 4658 4659 BUILTIN_ROW(__sync_val_compare_and_swap), 4660 BUILTIN_ROW(__sync_bool_compare_and_swap), 4661 BUILTIN_ROW(__sync_lock_test_and_set), 4662 BUILTIN_ROW(__sync_lock_release), 4663 BUILTIN_ROW(__sync_swap) 4664 }; 4665 #undef BUILTIN_ROW 4666 4667 // Determine the index of the size. 4668 unsigned SizeIndex; 4669 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4670 case 1: SizeIndex = 0; break; 4671 case 2: SizeIndex = 1; break; 4672 case 4: SizeIndex = 2; break; 4673 case 8: SizeIndex = 3; break; 4674 case 16: SizeIndex = 4; break; 4675 default: 4676 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4677 << FirstArg->getType() << FirstArg->getSourceRange(); 4678 return ExprError(); 4679 } 4680 4681 // Each of these builtins has one pointer argument, followed by some number of 4682 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4683 // that we ignore. Find out which row of BuiltinIndices to read from as well 4684 // as the number of fixed args. 4685 unsigned BuiltinID = FDecl->getBuiltinID(); 4686 unsigned BuiltinIndex, NumFixed = 1; 4687 bool WarnAboutSemanticsChange = false; 4688 switch (BuiltinID) { 4689 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4690 case Builtin::BI__sync_fetch_and_add: 4691 case Builtin::BI__sync_fetch_and_add_1: 4692 case Builtin::BI__sync_fetch_and_add_2: 4693 case Builtin::BI__sync_fetch_and_add_4: 4694 case Builtin::BI__sync_fetch_and_add_8: 4695 case Builtin::BI__sync_fetch_and_add_16: 4696 BuiltinIndex = 0; 4697 break; 4698 4699 case Builtin::BI__sync_fetch_and_sub: 4700 case Builtin::BI__sync_fetch_and_sub_1: 4701 case Builtin::BI__sync_fetch_and_sub_2: 4702 case Builtin::BI__sync_fetch_and_sub_4: 4703 case Builtin::BI__sync_fetch_and_sub_8: 4704 case Builtin::BI__sync_fetch_and_sub_16: 4705 BuiltinIndex = 1; 4706 break; 4707 4708 case Builtin::BI__sync_fetch_and_or: 4709 case Builtin::BI__sync_fetch_and_or_1: 4710 case Builtin::BI__sync_fetch_and_or_2: 4711 case Builtin::BI__sync_fetch_and_or_4: 4712 case Builtin::BI__sync_fetch_and_or_8: 4713 case Builtin::BI__sync_fetch_and_or_16: 4714 BuiltinIndex = 2; 4715 break; 4716 4717 case Builtin::BI__sync_fetch_and_and: 4718 case Builtin::BI__sync_fetch_and_and_1: 4719 case Builtin::BI__sync_fetch_and_and_2: 4720 case Builtin::BI__sync_fetch_and_and_4: 4721 case Builtin::BI__sync_fetch_and_and_8: 4722 case Builtin::BI__sync_fetch_and_and_16: 4723 BuiltinIndex = 3; 4724 break; 4725 4726 case Builtin::BI__sync_fetch_and_xor: 4727 case Builtin::BI__sync_fetch_and_xor_1: 4728 case Builtin::BI__sync_fetch_and_xor_2: 4729 case Builtin::BI__sync_fetch_and_xor_4: 4730 case Builtin::BI__sync_fetch_and_xor_8: 4731 case Builtin::BI__sync_fetch_and_xor_16: 4732 BuiltinIndex = 4; 4733 break; 4734 4735 case Builtin::BI__sync_fetch_and_nand: 4736 case Builtin::BI__sync_fetch_and_nand_1: 4737 case Builtin::BI__sync_fetch_and_nand_2: 4738 case Builtin::BI__sync_fetch_and_nand_4: 4739 case Builtin::BI__sync_fetch_and_nand_8: 4740 case Builtin::BI__sync_fetch_and_nand_16: 4741 BuiltinIndex = 5; 4742 WarnAboutSemanticsChange = true; 4743 break; 4744 4745 case Builtin::BI__sync_add_and_fetch: 4746 case Builtin::BI__sync_add_and_fetch_1: 4747 case Builtin::BI__sync_add_and_fetch_2: 4748 case Builtin::BI__sync_add_and_fetch_4: 4749 case Builtin::BI__sync_add_and_fetch_8: 4750 case Builtin::BI__sync_add_and_fetch_16: 4751 BuiltinIndex = 6; 4752 break; 4753 4754 case Builtin::BI__sync_sub_and_fetch: 4755 case Builtin::BI__sync_sub_and_fetch_1: 4756 case Builtin::BI__sync_sub_and_fetch_2: 4757 case Builtin::BI__sync_sub_and_fetch_4: 4758 case Builtin::BI__sync_sub_and_fetch_8: 4759 case Builtin::BI__sync_sub_and_fetch_16: 4760 BuiltinIndex = 7; 4761 break; 4762 4763 case Builtin::BI__sync_and_and_fetch: 4764 case Builtin::BI__sync_and_and_fetch_1: 4765 case Builtin::BI__sync_and_and_fetch_2: 4766 case Builtin::BI__sync_and_and_fetch_4: 4767 case Builtin::BI__sync_and_and_fetch_8: 4768 case Builtin::BI__sync_and_and_fetch_16: 4769 BuiltinIndex = 8; 4770 break; 4771 4772 case Builtin::BI__sync_or_and_fetch: 4773 case Builtin::BI__sync_or_and_fetch_1: 4774 case Builtin::BI__sync_or_and_fetch_2: 4775 case Builtin::BI__sync_or_and_fetch_4: 4776 case Builtin::BI__sync_or_and_fetch_8: 4777 case Builtin::BI__sync_or_and_fetch_16: 4778 BuiltinIndex = 9; 4779 break; 4780 4781 case Builtin::BI__sync_xor_and_fetch: 4782 case Builtin::BI__sync_xor_and_fetch_1: 4783 case Builtin::BI__sync_xor_and_fetch_2: 4784 case Builtin::BI__sync_xor_and_fetch_4: 4785 case Builtin::BI__sync_xor_and_fetch_8: 4786 case Builtin::BI__sync_xor_and_fetch_16: 4787 BuiltinIndex = 10; 4788 break; 4789 4790 case Builtin::BI__sync_nand_and_fetch: 4791 case Builtin::BI__sync_nand_and_fetch_1: 4792 case Builtin::BI__sync_nand_and_fetch_2: 4793 case Builtin::BI__sync_nand_and_fetch_4: 4794 case Builtin::BI__sync_nand_and_fetch_8: 4795 case Builtin::BI__sync_nand_and_fetch_16: 4796 BuiltinIndex = 11; 4797 WarnAboutSemanticsChange = true; 4798 break; 4799 4800 case Builtin::BI__sync_val_compare_and_swap: 4801 case Builtin::BI__sync_val_compare_and_swap_1: 4802 case Builtin::BI__sync_val_compare_and_swap_2: 4803 case Builtin::BI__sync_val_compare_and_swap_4: 4804 case Builtin::BI__sync_val_compare_and_swap_8: 4805 case Builtin::BI__sync_val_compare_and_swap_16: 4806 BuiltinIndex = 12; 4807 NumFixed = 2; 4808 break; 4809 4810 case Builtin::BI__sync_bool_compare_and_swap: 4811 case Builtin::BI__sync_bool_compare_and_swap_1: 4812 case Builtin::BI__sync_bool_compare_and_swap_2: 4813 case Builtin::BI__sync_bool_compare_and_swap_4: 4814 case Builtin::BI__sync_bool_compare_and_swap_8: 4815 case Builtin::BI__sync_bool_compare_and_swap_16: 4816 BuiltinIndex = 13; 4817 NumFixed = 2; 4818 ResultType = Context.BoolTy; 4819 break; 4820 4821 case Builtin::BI__sync_lock_test_and_set: 4822 case Builtin::BI__sync_lock_test_and_set_1: 4823 case Builtin::BI__sync_lock_test_and_set_2: 4824 case Builtin::BI__sync_lock_test_and_set_4: 4825 case Builtin::BI__sync_lock_test_and_set_8: 4826 case Builtin::BI__sync_lock_test_and_set_16: 4827 BuiltinIndex = 14; 4828 break; 4829 4830 case Builtin::BI__sync_lock_release: 4831 case Builtin::BI__sync_lock_release_1: 4832 case Builtin::BI__sync_lock_release_2: 4833 case Builtin::BI__sync_lock_release_4: 4834 case Builtin::BI__sync_lock_release_8: 4835 case Builtin::BI__sync_lock_release_16: 4836 BuiltinIndex = 15; 4837 NumFixed = 0; 4838 ResultType = Context.VoidTy; 4839 break; 4840 4841 case Builtin::BI__sync_swap: 4842 case Builtin::BI__sync_swap_1: 4843 case Builtin::BI__sync_swap_2: 4844 case Builtin::BI__sync_swap_4: 4845 case Builtin::BI__sync_swap_8: 4846 case Builtin::BI__sync_swap_16: 4847 BuiltinIndex = 16; 4848 break; 4849 } 4850 4851 // Now that we know how many fixed arguments we expect, first check that we 4852 // have at least that many. 4853 if (TheCall->getNumArgs() < 1+NumFixed) { 4854 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4855 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4856 << Callee->getSourceRange(); 4857 return ExprError(); 4858 } 4859 4860 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4861 << Callee->getSourceRange(); 4862 4863 if (WarnAboutSemanticsChange) { 4864 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4865 << Callee->getSourceRange(); 4866 } 4867 4868 // Get the decl for the concrete builtin from this, we can tell what the 4869 // concrete integer type we should convert to is. 4870 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4871 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4872 FunctionDecl *NewBuiltinDecl; 4873 if (NewBuiltinID == BuiltinID) 4874 NewBuiltinDecl = FDecl; 4875 else { 4876 // Perform builtin lookup to avoid redeclaring it. 4877 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4878 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4879 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4880 assert(Res.getFoundDecl()); 4881 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4882 if (!NewBuiltinDecl) 4883 return ExprError(); 4884 } 4885 4886 // The first argument --- the pointer --- has a fixed type; we 4887 // deduce the types of the rest of the arguments accordingly. Walk 4888 // the remaining arguments, converting them to the deduced value type. 4889 for (unsigned i = 0; i != NumFixed; ++i) { 4890 ExprResult Arg = TheCall->getArg(i+1); 4891 4892 // GCC does an implicit conversion to the pointer or integer ValType. This 4893 // can fail in some cases (1i -> int**), check for this error case now. 4894 // Initialize the argument. 4895 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4896 ValType, /*consume*/ false); 4897 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4898 if (Arg.isInvalid()) 4899 return ExprError(); 4900 4901 // Okay, we have something that *can* be converted to the right type. Check 4902 // to see if there is a potentially weird extension going on here. This can 4903 // happen when you do an atomic operation on something like an char* and 4904 // pass in 42. The 42 gets converted to char. This is even more strange 4905 // for things like 45.123 -> char, etc. 4906 // FIXME: Do this check. 4907 TheCall->setArg(i+1, Arg.get()); 4908 } 4909 4910 // Create a new DeclRefExpr to refer to the new decl. 4911 DeclRefExpr *NewDRE = DeclRefExpr::Create( 4912 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 4913 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 4914 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 4915 4916 // Set the callee in the CallExpr. 4917 // FIXME: This loses syntactic information. 4918 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4919 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4920 CK_BuiltinFnToFnPtr); 4921 TheCall->setCallee(PromotedCall.get()); 4922 4923 // Change the result type of the call to match the original value type. This 4924 // is arbitrary, but the codegen for these builtins ins design to handle it 4925 // gracefully. 4926 TheCall->setType(ResultType); 4927 4928 return TheCallResult; 4929 } 4930 4931 /// SemaBuiltinNontemporalOverloaded - We have a call to 4932 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 4933 /// overloaded function based on the pointer type of its last argument. 4934 /// 4935 /// This function goes through and does final semantic checking for these 4936 /// builtins. 4937 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4938 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4939 DeclRefExpr *DRE = 4940 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4941 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4942 unsigned BuiltinID = FDecl->getBuiltinID(); 4943 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4944 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4945 "Unexpected nontemporal load/store builtin!"); 4946 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4947 unsigned numArgs = isStore ? 2 : 1; 4948 4949 // Ensure that we have the proper number of arguments. 4950 if (checkArgCount(*this, TheCall, numArgs)) 4951 return ExprError(); 4952 4953 // Inspect the last argument of the nontemporal builtin. This should always 4954 // be a pointer type, from which we imply the type of the memory access. 4955 // Because it is a pointer type, we don't have to worry about any implicit 4956 // casts here. 4957 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4958 ExprResult PointerArgResult = 4959 DefaultFunctionArrayLvalueConversion(PointerArg); 4960 4961 if (PointerArgResult.isInvalid()) 4962 return ExprError(); 4963 PointerArg = PointerArgResult.get(); 4964 TheCall->setArg(numArgs - 1, PointerArg); 4965 4966 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4967 if (!pointerType) { 4968 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 4969 << PointerArg->getType() << PointerArg->getSourceRange(); 4970 return ExprError(); 4971 } 4972 4973 QualType ValType = pointerType->getPointeeType(); 4974 4975 // Strip any qualifiers off ValType. 4976 ValType = ValType.getUnqualifiedType(); 4977 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4978 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4979 !ValType->isVectorType()) { 4980 Diag(DRE->getBeginLoc(), 4981 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4982 << PointerArg->getType() << PointerArg->getSourceRange(); 4983 return ExprError(); 4984 } 4985 4986 if (!isStore) { 4987 TheCall->setType(ValType); 4988 return TheCallResult; 4989 } 4990 4991 ExprResult ValArg = TheCall->getArg(0); 4992 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4993 Context, ValType, /*consume*/ false); 4994 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4995 if (ValArg.isInvalid()) 4996 return ExprError(); 4997 4998 TheCall->setArg(0, ValArg.get()); 4999 TheCall->setType(Context.VoidTy); 5000 return TheCallResult; 5001 } 5002 5003 /// CheckObjCString - Checks that the argument to the builtin 5004 /// CFString constructor is correct 5005 /// Note: It might also make sense to do the UTF-16 conversion here (would 5006 /// simplify the backend). 5007 bool Sema::CheckObjCString(Expr *Arg) { 5008 Arg = Arg->IgnoreParenCasts(); 5009 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5010 5011 if (!Literal || !Literal->isAscii()) { 5012 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5013 << Arg->getSourceRange(); 5014 return true; 5015 } 5016 5017 if (Literal->containsNonAsciiOrNull()) { 5018 StringRef String = Literal->getString(); 5019 unsigned NumBytes = String.size(); 5020 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5021 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5022 llvm::UTF16 *ToPtr = &ToBuf[0]; 5023 5024 llvm::ConversionResult Result = 5025 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5026 ToPtr + NumBytes, llvm::strictConversion); 5027 // Check for conversion failure. 5028 if (Result != llvm::conversionOK) 5029 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5030 << Arg->getSourceRange(); 5031 } 5032 return false; 5033 } 5034 5035 /// CheckObjCString - Checks that the format string argument to the os_log() 5036 /// and os_trace() functions is correct, and converts it to const char *. 5037 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5038 Arg = Arg->IgnoreParenCasts(); 5039 auto *Literal = dyn_cast<StringLiteral>(Arg); 5040 if (!Literal) { 5041 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5042 Literal = ObjcLiteral->getString(); 5043 } 5044 } 5045 5046 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5047 return ExprError( 5048 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5049 << Arg->getSourceRange()); 5050 } 5051 5052 ExprResult Result(Literal); 5053 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5054 InitializedEntity Entity = 5055 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5056 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5057 return Result; 5058 } 5059 5060 /// Check that the user is calling the appropriate va_start builtin for the 5061 /// target and calling convention. 5062 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5063 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5064 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5065 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5066 TT.getArch() == llvm::Triple::aarch64_32); 5067 bool IsWindows = TT.isOSWindows(); 5068 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5069 if (IsX64 || IsAArch64) { 5070 CallingConv CC = CC_C; 5071 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5072 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5073 if (IsMSVAStart) { 5074 // Don't allow this in System V ABI functions. 5075 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5076 return S.Diag(Fn->getBeginLoc(), 5077 diag::err_ms_va_start_used_in_sysv_function); 5078 } else { 5079 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5080 // On x64 Windows, don't allow this in System V ABI functions. 5081 // (Yes, that means there's no corresponding way to support variadic 5082 // System V ABI functions on Windows.) 5083 if ((IsWindows && CC == CC_X86_64SysV) || 5084 (!IsWindows && CC == CC_Win64)) 5085 return S.Diag(Fn->getBeginLoc(), 5086 diag::err_va_start_used_in_wrong_abi_function) 5087 << !IsWindows; 5088 } 5089 return false; 5090 } 5091 5092 if (IsMSVAStart) 5093 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5094 return false; 5095 } 5096 5097 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5098 ParmVarDecl **LastParam = nullptr) { 5099 // Determine whether the current function, block, or obj-c method is variadic 5100 // and get its parameter list. 5101 bool IsVariadic = false; 5102 ArrayRef<ParmVarDecl *> Params; 5103 DeclContext *Caller = S.CurContext; 5104 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5105 IsVariadic = Block->isVariadic(); 5106 Params = Block->parameters(); 5107 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5108 IsVariadic = FD->isVariadic(); 5109 Params = FD->parameters(); 5110 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5111 IsVariadic = MD->isVariadic(); 5112 // FIXME: This isn't correct for methods (results in bogus warning). 5113 Params = MD->parameters(); 5114 } else if (isa<CapturedDecl>(Caller)) { 5115 // We don't support va_start in a CapturedDecl. 5116 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5117 return true; 5118 } else { 5119 // This must be some other declcontext that parses exprs. 5120 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5121 return true; 5122 } 5123 5124 if (!IsVariadic) { 5125 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5126 return true; 5127 } 5128 5129 if (LastParam) 5130 *LastParam = Params.empty() ? nullptr : Params.back(); 5131 5132 return false; 5133 } 5134 5135 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5136 /// for validity. Emit an error and return true on failure; return false 5137 /// on success. 5138 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5139 Expr *Fn = TheCall->getCallee(); 5140 5141 if (checkVAStartABI(*this, BuiltinID, Fn)) 5142 return true; 5143 5144 if (TheCall->getNumArgs() > 2) { 5145 Diag(TheCall->getArg(2)->getBeginLoc(), 5146 diag::err_typecheck_call_too_many_args) 5147 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5148 << Fn->getSourceRange() 5149 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5150 (*(TheCall->arg_end() - 1))->getEndLoc()); 5151 return true; 5152 } 5153 5154 if (TheCall->getNumArgs() < 2) { 5155 return Diag(TheCall->getEndLoc(), 5156 diag::err_typecheck_call_too_few_args_at_least) 5157 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5158 } 5159 5160 // Type-check the first argument normally. 5161 if (checkBuiltinArgument(*this, TheCall, 0)) 5162 return true; 5163 5164 // Check that the current function is variadic, and get its last parameter. 5165 ParmVarDecl *LastParam; 5166 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5167 return true; 5168 5169 // Verify that the second argument to the builtin is the last argument of the 5170 // current function or method. 5171 bool SecondArgIsLastNamedArgument = false; 5172 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5173 5174 // These are valid if SecondArgIsLastNamedArgument is false after the next 5175 // block. 5176 QualType Type; 5177 SourceLocation ParamLoc; 5178 bool IsCRegister = false; 5179 5180 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5181 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5182 SecondArgIsLastNamedArgument = PV == LastParam; 5183 5184 Type = PV->getType(); 5185 ParamLoc = PV->getLocation(); 5186 IsCRegister = 5187 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5188 } 5189 } 5190 5191 if (!SecondArgIsLastNamedArgument) 5192 Diag(TheCall->getArg(1)->getBeginLoc(), 5193 diag::warn_second_arg_of_va_start_not_last_named_param); 5194 else if (IsCRegister || Type->isReferenceType() || 5195 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5196 // Promotable integers are UB, but enumerations need a bit of 5197 // extra checking to see what their promotable type actually is. 5198 if (!Type->isPromotableIntegerType()) 5199 return false; 5200 if (!Type->isEnumeralType()) 5201 return true; 5202 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5203 return !(ED && 5204 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5205 }()) { 5206 unsigned Reason = 0; 5207 if (Type->isReferenceType()) Reason = 1; 5208 else if (IsCRegister) Reason = 2; 5209 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5210 Diag(ParamLoc, diag::note_parameter_type) << Type; 5211 } 5212 5213 TheCall->setType(Context.VoidTy); 5214 return false; 5215 } 5216 5217 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5218 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5219 // const char *named_addr); 5220 5221 Expr *Func = Call->getCallee(); 5222 5223 if (Call->getNumArgs() < 3) 5224 return Diag(Call->getEndLoc(), 5225 diag::err_typecheck_call_too_few_args_at_least) 5226 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5227 5228 // Type-check the first argument normally. 5229 if (checkBuiltinArgument(*this, Call, 0)) 5230 return true; 5231 5232 // Check that the current function is variadic. 5233 if (checkVAStartIsInVariadicFunction(*this, Func)) 5234 return true; 5235 5236 // __va_start on Windows does not validate the parameter qualifiers 5237 5238 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5239 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5240 5241 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5242 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5243 5244 const QualType &ConstCharPtrTy = 5245 Context.getPointerType(Context.CharTy.withConst()); 5246 if (!Arg1Ty->isPointerType() || 5247 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5248 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5249 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5250 << 0 /* qualifier difference */ 5251 << 3 /* parameter mismatch */ 5252 << 2 << Arg1->getType() << ConstCharPtrTy; 5253 5254 const QualType SizeTy = Context.getSizeType(); 5255 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5256 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5257 << Arg2->getType() << SizeTy << 1 /* different class */ 5258 << 0 /* qualifier difference */ 5259 << 3 /* parameter mismatch */ 5260 << 3 << Arg2->getType() << SizeTy; 5261 5262 return false; 5263 } 5264 5265 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5266 /// friends. This is declared to take (...), so we have to check everything. 5267 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5268 if (TheCall->getNumArgs() < 2) 5269 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5270 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5271 if (TheCall->getNumArgs() > 2) 5272 return Diag(TheCall->getArg(2)->getBeginLoc(), 5273 diag::err_typecheck_call_too_many_args) 5274 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5275 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5276 (*(TheCall->arg_end() - 1))->getEndLoc()); 5277 5278 ExprResult OrigArg0 = TheCall->getArg(0); 5279 ExprResult OrigArg1 = TheCall->getArg(1); 5280 5281 // Do standard promotions between the two arguments, returning their common 5282 // type. 5283 QualType Res = UsualArithmeticConversions( 5284 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5285 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5286 return true; 5287 5288 // Make sure any conversions are pushed back into the call; this is 5289 // type safe since unordered compare builtins are declared as "_Bool 5290 // foo(...)". 5291 TheCall->setArg(0, OrigArg0.get()); 5292 TheCall->setArg(1, OrigArg1.get()); 5293 5294 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5295 return false; 5296 5297 // If the common type isn't a real floating type, then the arguments were 5298 // invalid for this operation. 5299 if (Res.isNull() || !Res->isRealFloatingType()) 5300 return Diag(OrigArg0.get()->getBeginLoc(), 5301 diag::err_typecheck_call_invalid_ordered_compare) 5302 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5303 << SourceRange(OrigArg0.get()->getBeginLoc(), 5304 OrigArg1.get()->getEndLoc()); 5305 5306 return false; 5307 } 5308 5309 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5310 /// __builtin_isnan and friends. This is declared to take (...), so we have 5311 /// to check everything. We expect the last argument to be a floating point 5312 /// value. 5313 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5314 if (TheCall->getNumArgs() < NumArgs) 5315 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5316 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5317 if (TheCall->getNumArgs() > NumArgs) 5318 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5319 diag::err_typecheck_call_too_many_args) 5320 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5321 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5322 (*(TheCall->arg_end() - 1))->getEndLoc()); 5323 5324 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5325 // on all preceding parameters just being int. Try all of those. 5326 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5327 Expr *Arg = TheCall->getArg(i); 5328 5329 if (Arg->isTypeDependent()) 5330 return false; 5331 5332 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5333 5334 if (Res.isInvalid()) 5335 return true; 5336 TheCall->setArg(i, Res.get()); 5337 } 5338 5339 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5340 5341 if (OrigArg->isTypeDependent()) 5342 return false; 5343 5344 // Usual Unary Conversions will convert half to float, which we want for 5345 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5346 // type how it is, but do normal L->Rvalue conversions. 5347 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5348 OrigArg = UsualUnaryConversions(OrigArg).get(); 5349 else 5350 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5351 TheCall->setArg(NumArgs - 1, OrigArg); 5352 5353 // This operation requires a non-_Complex floating-point number. 5354 if (!OrigArg->getType()->isRealFloatingType()) 5355 return Diag(OrigArg->getBeginLoc(), 5356 diag::err_typecheck_call_invalid_unary_fp) 5357 << OrigArg->getType() << OrigArg->getSourceRange(); 5358 5359 return false; 5360 } 5361 5362 // Customized Sema Checking for VSX builtins that have the following signature: 5363 // vector [...] builtinName(vector [...], vector [...], const int); 5364 // Which takes the same type of vectors (any legal vector type) for the first 5365 // two arguments and takes compile time constant for the third argument. 5366 // Example builtins are : 5367 // vector double vec_xxpermdi(vector double, vector double, int); 5368 // vector short vec_xxsldwi(vector short, vector short, int); 5369 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5370 unsigned ExpectedNumArgs = 3; 5371 if (TheCall->getNumArgs() < ExpectedNumArgs) 5372 return Diag(TheCall->getEndLoc(), 5373 diag::err_typecheck_call_too_few_args_at_least) 5374 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5375 << TheCall->getSourceRange(); 5376 5377 if (TheCall->getNumArgs() > ExpectedNumArgs) 5378 return Diag(TheCall->getEndLoc(), 5379 diag::err_typecheck_call_too_many_args_at_most) 5380 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5381 << TheCall->getSourceRange(); 5382 5383 // Check the third argument is a compile time constant 5384 llvm::APSInt Value; 5385 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5386 return Diag(TheCall->getBeginLoc(), 5387 diag::err_vsx_builtin_nonconstant_argument) 5388 << 3 /* argument index */ << TheCall->getDirectCallee() 5389 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5390 TheCall->getArg(2)->getEndLoc()); 5391 5392 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5393 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5394 5395 // Check the type of argument 1 and argument 2 are vectors. 5396 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5397 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5398 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5399 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5400 << TheCall->getDirectCallee() 5401 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5402 TheCall->getArg(1)->getEndLoc()); 5403 } 5404 5405 // Check the first two arguments are the same type. 5406 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5407 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5408 << TheCall->getDirectCallee() 5409 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5410 TheCall->getArg(1)->getEndLoc()); 5411 } 5412 5413 // When default clang type checking is turned off and the customized type 5414 // checking is used, the returning type of the function must be explicitly 5415 // set. Otherwise it is _Bool by default. 5416 TheCall->setType(Arg1Ty); 5417 5418 return false; 5419 } 5420 5421 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5422 // This is declared to take (...), so we have to check everything. 5423 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5424 if (TheCall->getNumArgs() < 2) 5425 return ExprError(Diag(TheCall->getEndLoc(), 5426 diag::err_typecheck_call_too_few_args_at_least) 5427 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5428 << TheCall->getSourceRange()); 5429 5430 // Determine which of the following types of shufflevector we're checking: 5431 // 1) unary, vector mask: (lhs, mask) 5432 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5433 QualType resType = TheCall->getArg(0)->getType(); 5434 unsigned numElements = 0; 5435 5436 if (!TheCall->getArg(0)->isTypeDependent() && 5437 !TheCall->getArg(1)->isTypeDependent()) { 5438 QualType LHSType = TheCall->getArg(0)->getType(); 5439 QualType RHSType = TheCall->getArg(1)->getType(); 5440 5441 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5442 return ExprError( 5443 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5444 << TheCall->getDirectCallee() 5445 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5446 TheCall->getArg(1)->getEndLoc())); 5447 5448 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5449 unsigned numResElements = TheCall->getNumArgs() - 2; 5450 5451 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5452 // with mask. If so, verify that RHS is an integer vector type with the 5453 // same number of elts as lhs. 5454 if (TheCall->getNumArgs() == 2) { 5455 if (!RHSType->hasIntegerRepresentation() || 5456 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5457 return ExprError(Diag(TheCall->getBeginLoc(), 5458 diag::err_vec_builtin_incompatible_vector) 5459 << TheCall->getDirectCallee() 5460 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5461 TheCall->getArg(1)->getEndLoc())); 5462 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5463 return ExprError(Diag(TheCall->getBeginLoc(), 5464 diag::err_vec_builtin_incompatible_vector) 5465 << TheCall->getDirectCallee() 5466 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5467 TheCall->getArg(1)->getEndLoc())); 5468 } else if (numElements != numResElements) { 5469 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5470 resType = Context.getVectorType(eltType, numResElements, 5471 VectorType::GenericVector); 5472 } 5473 } 5474 5475 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5476 if (TheCall->getArg(i)->isTypeDependent() || 5477 TheCall->getArg(i)->isValueDependent()) 5478 continue; 5479 5480 llvm::APSInt Result(32); 5481 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5482 return ExprError(Diag(TheCall->getBeginLoc(), 5483 diag::err_shufflevector_nonconstant_argument) 5484 << TheCall->getArg(i)->getSourceRange()); 5485 5486 // Allow -1 which will be translated to undef in the IR. 5487 if (Result.isSigned() && Result.isAllOnesValue()) 5488 continue; 5489 5490 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5491 return ExprError(Diag(TheCall->getBeginLoc(), 5492 diag::err_shufflevector_argument_too_large) 5493 << TheCall->getArg(i)->getSourceRange()); 5494 } 5495 5496 SmallVector<Expr*, 32> exprs; 5497 5498 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5499 exprs.push_back(TheCall->getArg(i)); 5500 TheCall->setArg(i, nullptr); 5501 } 5502 5503 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5504 TheCall->getCallee()->getBeginLoc(), 5505 TheCall->getRParenLoc()); 5506 } 5507 5508 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5509 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5510 SourceLocation BuiltinLoc, 5511 SourceLocation RParenLoc) { 5512 ExprValueKind VK = VK_RValue; 5513 ExprObjectKind OK = OK_Ordinary; 5514 QualType DstTy = TInfo->getType(); 5515 QualType SrcTy = E->getType(); 5516 5517 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5518 return ExprError(Diag(BuiltinLoc, 5519 diag::err_convertvector_non_vector) 5520 << E->getSourceRange()); 5521 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5522 return ExprError(Diag(BuiltinLoc, 5523 diag::err_convertvector_non_vector_type)); 5524 5525 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5526 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5527 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5528 if (SrcElts != DstElts) 5529 return ExprError(Diag(BuiltinLoc, 5530 diag::err_convertvector_incompatible_vector) 5531 << E->getSourceRange()); 5532 } 5533 5534 return new (Context) 5535 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5536 } 5537 5538 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5539 // This is declared to take (const void*, ...) and can take two 5540 // optional constant int args. 5541 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5542 unsigned NumArgs = TheCall->getNumArgs(); 5543 5544 if (NumArgs > 3) 5545 return Diag(TheCall->getEndLoc(), 5546 diag::err_typecheck_call_too_many_args_at_most) 5547 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5548 5549 // Argument 0 is checked for us and the remaining arguments must be 5550 // constant integers. 5551 for (unsigned i = 1; i != NumArgs; ++i) 5552 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5553 return true; 5554 5555 return false; 5556 } 5557 5558 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5559 // __assume does not evaluate its arguments, and should warn if its argument 5560 // has side effects. 5561 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5562 Expr *Arg = TheCall->getArg(0); 5563 if (Arg->isInstantiationDependent()) return false; 5564 5565 if (Arg->HasSideEffects(Context)) 5566 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5567 << Arg->getSourceRange() 5568 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5569 5570 return false; 5571 } 5572 5573 /// Handle __builtin_alloca_with_align. This is declared 5574 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5575 /// than 8. 5576 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5577 // The alignment must be a constant integer. 5578 Expr *Arg = TheCall->getArg(1); 5579 5580 // We can't check the value of a dependent argument. 5581 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5582 if (const auto *UE = 5583 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5584 if (UE->getKind() == UETT_AlignOf || 5585 UE->getKind() == UETT_PreferredAlignOf) 5586 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5587 << Arg->getSourceRange(); 5588 5589 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5590 5591 if (!Result.isPowerOf2()) 5592 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5593 << Arg->getSourceRange(); 5594 5595 if (Result < Context.getCharWidth()) 5596 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5597 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5598 5599 if (Result > std::numeric_limits<int32_t>::max()) 5600 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5601 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5602 } 5603 5604 return false; 5605 } 5606 5607 /// Handle __builtin_assume_aligned. This is declared 5608 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5609 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5610 unsigned NumArgs = TheCall->getNumArgs(); 5611 5612 if (NumArgs > 3) 5613 return Diag(TheCall->getEndLoc(), 5614 diag::err_typecheck_call_too_many_args_at_most) 5615 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5616 5617 // The alignment must be a constant integer. 5618 Expr *Arg = TheCall->getArg(1); 5619 5620 // We can't check the value of a dependent argument. 5621 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5622 llvm::APSInt Result; 5623 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5624 return true; 5625 5626 if (!Result.isPowerOf2()) 5627 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5628 << Arg->getSourceRange(); 5629 5630 if (Result > Sema::MaximumAlignment) 5631 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5632 << Arg->getSourceRange() << Sema::MaximumAlignment; 5633 } 5634 5635 if (NumArgs > 2) { 5636 ExprResult Arg(TheCall->getArg(2)); 5637 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5638 Context.getSizeType(), false); 5639 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5640 if (Arg.isInvalid()) return true; 5641 TheCall->setArg(2, Arg.get()); 5642 } 5643 5644 return false; 5645 } 5646 5647 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5648 unsigned BuiltinID = 5649 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5650 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5651 5652 unsigned NumArgs = TheCall->getNumArgs(); 5653 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5654 if (NumArgs < NumRequiredArgs) { 5655 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5656 << 0 /* function call */ << NumRequiredArgs << NumArgs 5657 << TheCall->getSourceRange(); 5658 } 5659 if (NumArgs >= NumRequiredArgs + 0x100) { 5660 return Diag(TheCall->getEndLoc(), 5661 diag::err_typecheck_call_too_many_args_at_most) 5662 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5663 << TheCall->getSourceRange(); 5664 } 5665 unsigned i = 0; 5666 5667 // For formatting call, check buffer arg. 5668 if (!IsSizeCall) { 5669 ExprResult Arg(TheCall->getArg(i)); 5670 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5671 Context, Context.VoidPtrTy, false); 5672 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5673 if (Arg.isInvalid()) 5674 return true; 5675 TheCall->setArg(i, Arg.get()); 5676 i++; 5677 } 5678 5679 // Check string literal arg. 5680 unsigned FormatIdx = i; 5681 { 5682 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5683 if (Arg.isInvalid()) 5684 return true; 5685 TheCall->setArg(i, Arg.get()); 5686 i++; 5687 } 5688 5689 // Make sure variadic args are scalar. 5690 unsigned FirstDataArg = i; 5691 while (i < NumArgs) { 5692 ExprResult Arg = DefaultVariadicArgumentPromotion( 5693 TheCall->getArg(i), VariadicFunction, nullptr); 5694 if (Arg.isInvalid()) 5695 return true; 5696 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5697 if (ArgSize.getQuantity() >= 0x100) { 5698 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5699 << i << (int)ArgSize.getQuantity() << 0xff 5700 << TheCall->getSourceRange(); 5701 } 5702 TheCall->setArg(i, Arg.get()); 5703 i++; 5704 } 5705 5706 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5707 // call to avoid duplicate diagnostics. 5708 if (!IsSizeCall) { 5709 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5710 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5711 bool Success = CheckFormatArguments( 5712 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5713 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5714 CheckedVarArgs); 5715 if (!Success) 5716 return true; 5717 } 5718 5719 if (IsSizeCall) { 5720 TheCall->setType(Context.getSizeType()); 5721 } else { 5722 TheCall->setType(Context.VoidPtrTy); 5723 } 5724 return false; 5725 } 5726 5727 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5728 /// TheCall is a constant expression. 5729 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5730 llvm::APSInt &Result) { 5731 Expr *Arg = TheCall->getArg(ArgNum); 5732 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5733 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5734 5735 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5736 5737 if (!Arg->isIntegerConstantExpr(Result, Context)) 5738 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5739 << FDecl->getDeclName() << Arg->getSourceRange(); 5740 5741 return false; 5742 } 5743 5744 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5745 /// TheCall is a constant expression in the range [Low, High]. 5746 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5747 int Low, int High, bool RangeIsError) { 5748 if (isConstantEvaluated()) 5749 return false; 5750 llvm::APSInt Result; 5751 5752 // We can't check the value of a dependent argument. 5753 Expr *Arg = TheCall->getArg(ArgNum); 5754 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5755 return false; 5756 5757 // Check constant-ness first. 5758 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5759 return true; 5760 5761 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5762 if (RangeIsError) 5763 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5764 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5765 else 5766 // Defer the warning until we know if the code will be emitted so that 5767 // dead code can ignore this. 5768 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5769 PDiag(diag::warn_argument_invalid_range) 5770 << Result.toString(10) << Low << High 5771 << Arg->getSourceRange()); 5772 } 5773 5774 return false; 5775 } 5776 5777 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5778 /// TheCall is a constant expression is a multiple of Num.. 5779 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5780 unsigned Num) { 5781 llvm::APSInt Result; 5782 5783 // We can't check the value of a dependent argument. 5784 Expr *Arg = TheCall->getArg(ArgNum); 5785 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5786 return false; 5787 5788 // Check constant-ness first. 5789 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5790 return true; 5791 5792 if (Result.getSExtValue() % Num != 0) 5793 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5794 << Num << Arg->getSourceRange(); 5795 5796 return false; 5797 } 5798 5799 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 5800 /// constant expression representing a power of 2. 5801 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5802 llvm::APSInt Result; 5803 5804 // We can't check the value of a dependent argument. 5805 Expr *Arg = TheCall->getArg(ArgNum); 5806 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5807 return false; 5808 5809 // Check constant-ness first. 5810 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5811 return true; 5812 5813 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 5814 // and only if x is a power of 2. 5815 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 5816 return false; 5817 5818 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 5819 << Arg->getSourceRange(); 5820 } 5821 5822 static bool IsShiftedByte(llvm::APSInt Value) { 5823 if (Value.isNegative()) 5824 return false; 5825 5826 // Check if it's a shifted byte, by shifting it down 5827 while (true) { 5828 // If the value fits in the bottom byte, the check passes. 5829 if (Value < 0x100) 5830 return true; 5831 5832 // Otherwise, if the value has _any_ bits in the bottom byte, the check 5833 // fails. 5834 if ((Value & 0xFF) != 0) 5835 return false; 5836 5837 // If the bottom 8 bits are all 0, but something above that is nonzero, 5838 // then shifting the value right by 8 bits won't affect whether it's a 5839 // shifted byte or not. So do that, and go round again. 5840 Value >>= 8; 5841 } 5842 } 5843 5844 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 5845 /// a constant expression representing an arbitrary byte value shifted left by 5846 /// a multiple of 8 bits. 5847 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 5848 unsigned ArgBits) { 5849 llvm::APSInt Result; 5850 5851 // We can't check the value of a dependent argument. 5852 Expr *Arg = TheCall->getArg(ArgNum); 5853 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5854 return false; 5855 5856 // Check constant-ness first. 5857 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5858 return true; 5859 5860 // Truncate to the given size. 5861 Result = Result.getLoBits(ArgBits); 5862 Result.setIsUnsigned(true); 5863 5864 if (IsShiftedByte(Result)) 5865 return false; 5866 5867 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 5868 << Arg->getSourceRange(); 5869 } 5870 5871 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 5872 /// TheCall is a constant expression representing either a shifted byte value, 5873 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 5874 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 5875 /// Arm MVE intrinsics. 5876 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 5877 int ArgNum, 5878 unsigned ArgBits) { 5879 llvm::APSInt Result; 5880 5881 // We can't check the value of a dependent argument. 5882 Expr *Arg = TheCall->getArg(ArgNum); 5883 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5884 return false; 5885 5886 // Check constant-ness first. 5887 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5888 return true; 5889 5890 // Truncate to the given size. 5891 Result = Result.getLoBits(ArgBits); 5892 Result.setIsUnsigned(true); 5893 5894 // Check to see if it's in either of the required forms. 5895 if (IsShiftedByte(Result) || 5896 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 5897 return false; 5898 5899 return Diag(TheCall->getBeginLoc(), 5900 diag::err_argument_not_shifted_byte_or_xxff) 5901 << Arg->getSourceRange(); 5902 } 5903 5904 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 5905 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 5906 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 5907 if (checkArgCount(*this, TheCall, 2)) 5908 return true; 5909 Expr *Arg0 = TheCall->getArg(0); 5910 Expr *Arg1 = TheCall->getArg(1); 5911 5912 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5913 if (FirstArg.isInvalid()) 5914 return true; 5915 QualType FirstArgType = FirstArg.get()->getType(); 5916 if (!FirstArgType->isAnyPointerType()) 5917 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5918 << "first" << FirstArgType << Arg0->getSourceRange(); 5919 TheCall->setArg(0, FirstArg.get()); 5920 5921 ExprResult SecArg = DefaultLvalueConversion(Arg1); 5922 if (SecArg.isInvalid()) 5923 return true; 5924 QualType SecArgType = SecArg.get()->getType(); 5925 if (!SecArgType->isIntegerType()) 5926 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 5927 << "second" << SecArgType << Arg1->getSourceRange(); 5928 5929 // Derive the return type from the pointer argument. 5930 TheCall->setType(FirstArgType); 5931 return false; 5932 } 5933 5934 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 5935 if (checkArgCount(*this, TheCall, 2)) 5936 return true; 5937 5938 Expr *Arg0 = TheCall->getArg(0); 5939 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5940 if (FirstArg.isInvalid()) 5941 return true; 5942 QualType FirstArgType = FirstArg.get()->getType(); 5943 if (!FirstArgType->isAnyPointerType()) 5944 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5945 << "first" << FirstArgType << Arg0->getSourceRange(); 5946 TheCall->setArg(0, FirstArg.get()); 5947 5948 // Derive the return type from the pointer argument. 5949 TheCall->setType(FirstArgType); 5950 5951 // Second arg must be an constant in range [0,15] 5952 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 5953 } 5954 5955 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 5956 if (checkArgCount(*this, TheCall, 2)) 5957 return true; 5958 Expr *Arg0 = TheCall->getArg(0); 5959 Expr *Arg1 = TheCall->getArg(1); 5960 5961 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5962 if (FirstArg.isInvalid()) 5963 return true; 5964 QualType FirstArgType = FirstArg.get()->getType(); 5965 if (!FirstArgType->isAnyPointerType()) 5966 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5967 << "first" << FirstArgType << Arg0->getSourceRange(); 5968 5969 QualType SecArgType = Arg1->getType(); 5970 if (!SecArgType->isIntegerType()) 5971 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 5972 << "second" << SecArgType << Arg1->getSourceRange(); 5973 TheCall->setType(Context.IntTy); 5974 return false; 5975 } 5976 5977 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 5978 BuiltinID == AArch64::BI__builtin_arm_stg) { 5979 if (checkArgCount(*this, TheCall, 1)) 5980 return true; 5981 Expr *Arg0 = TheCall->getArg(0); 5982 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5983 if (FirstArg.isInvalid()) 5984 return true; 5985 5986 QualType FirstArgType = FirstArg.get()->getType(); 5987 if (!FirstArgType->isAnyPointerType()) 5988 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 5989 << "first" << FirstArgType << Arg0->getSourceRange(); 5990 TheCall->setArg(0, FirstArg.get()); 5991 5992 // Derive the return type from the pointer argument. 5993 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 5994 TheCall->setType(FirstArgType); 5995 return false; 5996 } 5997 5998 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 5999 Expr *ArgA = TheCall->getArg(0); 6000 Expr *ArgB = TheCall->getArg(1); 6001 6002 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6003 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6004 6005 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6006 return true; 6007 6008 QualType ArgTypeA = ArgExprA.get()->getType(); 6009 QualType ArgTypeB = ArgExprB.get()->getType(); 6010 6011 auto isNull = [&] (Expr *E) -> bool { 6012 return E->isNullPointerConstant( 6013 Context, Expr::NPC_ValueDependentIsNotNull); }; 6014 6015 // argument should be either a pointer or null 6016 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6017 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6018 << "first" << ArgTypeA << ArgA->getSourceRange(); 6019 6020 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6021 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6022 << "second" << ArgTypeB << ArgB->getSourceRange(); 6023 6024 // Ensure Pointee types are compatible 6025 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6026 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6027 QualType pointeeA = ArgTypeA->getPointeeType(); 6028 QualType pointeeB = ArgTypeB->getPointeeType(); 6029 if (!Context.typesAreCompatible( 6030 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6031 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6032 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6033 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6034 << ArgB->getSourceRange(); 6035 } 6036 } 6037 6038 // at least one argument should be pointer type 6039 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6040 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6041 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6042 6043 if (isNull(ArgA)) // adopt type of the other pointer 6044 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6045 6046 if (isNull(ArgB)) 6047 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6048 6049 TheCall->setArg(0, ArgExprA.get()); 6050 TheCall->setArg(1, ArgExprB.get()); 6051 TheCall->setType(Context.LongLongTy); 6052 return false; 6053 } 6054 assert(false && "Unhandled ARM MTE intrinsic"); 6055 return true; 6056 } 6057 6058 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6059 /// TheCall is an ARM/AArch64 special register string literal. 6060 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6061 int ArgNum, unsigned ExpectedFieldNum, 6062 bool AllowName) { 6063 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6064 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6065 BuiltinID == ARM::BI__builtin_arm_rsr || 6066 BuiltinID == ARM::BI__builtin_arm_rsrp || 6067 BuiltinID == ARM::BI__builtin_arm_wsr || 6068 BuiltinID == ARM::BI__builtin_arm_wsrp; 6069 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6070 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6071 BuiltinID == AArch64::BI__builtin_arm_rsr || 6072 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6073 BuiltinID == AArch64::BI__builtin_arm_wsr || 6074 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6075 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6076 6077 // We can't check the value of a dependent argument. 6078 Expr *Arg = TheCall->getArg(ArgNum); 6079 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6080 return false; 6081 6082 // Check if the argument is a string literal. 6083 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6084 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6085 << Arg->getSourceRange(); 6086 6087 // Check the type of special register given. 6088 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6089 SmallVector<StringRef, 6> Fields; 6090 Reg.split(Fields, ":"); 6091 6092 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6093 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6094 << Arg->getSourceRange(); 6095 6096 // If the string is the name of a register then we cannot check that it is 6097 // valid here but if the string is of one the forms described in ACLE then we 6098 // can check that the supplied fields are integers and within the valid 6099 // ranges. 6100 if (Fields.size() > 1) { 6101 bool FiveFields = Fields.size() == 5; 6102 6103 bool ValidString = true; 6104 if (IsARMBuiltin) { 6105 ValidString &= Fields[0].startswith_lower("cp") || 6106 Fields[0].startswith_lower("p"); 6107 if (ValidString) 6108 Fields[0] = 6109 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6110 6111 ValidString &= Fields[2].startswith_lower("c"); 6112 if (ValidString) 6113 Fields[2] = Fields[2].drop_front(1); 6114 6115 if (FiveFields) { 6116 ValidString &= Fields[3].startswith_lower("c"); 6117 if (ValidString) 6118 Fields[3] = Fields[3].drop_front(1); 6119 } 6120 } 6121 6122 SmallVector<int, 5> Ranges; 6123 if (FiveFields) 6124 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6125 else 6126 Ranges.append({15, 7, 15}); 6127 6128 for (unsigned i=0; i<Fields.size(); ++i) { 6129 int IntField; 6130 ValidString &= !Fields[i].getAsInteger(10, IntField); 6131 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6132 } 6133 6134 if (!ValidString) 6135 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6136 << Arg->getSourceRange(); 6137 } else if (IsAArch64Builtin && Fields.size() == 1) { 6138 // If the register name is one of those that appear in the condition below 6139 // and the special register builtin being used is one of the write builtins, 6140 // then we require that the argument provided for writing to the register 6141 // is an integer constant expression. This is because it will be lowered to 6142 // an MSR (immediate) instruction, so we need to know the immediate at 6143 // compile time. 6144 if (TheCall->getNumArgs() != 2) 6145 return false; 6146 6147 std::string RegLower = Reg.lower(); 6148 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6149 RegLower != "pan" && RegLower != "uao") 6150 return false; 6151 6152 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6153 } 6154 6155 return false; 6156 } 6157 6158 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6159 /// This checks that the target supports __builtin_longjmp and 6160 /// that val is a constant 1. 6161 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6162 if (!Context.getTargetInfo().hasSjLjLowering()) 6163 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6164 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6165 6166 Expr *Arg = TheCall->getArg(1); 6167 llvm::APSInt Result; 6168 6169 // TODO: This is less than ideal. Overload this to take a value. 6170 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6171 return true; 6172 6173 if (Result != 1) 6174 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6175 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6176 6177 return false; 6178 } 6179 6180 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6181 /// This checks that the target supports __builtin_setjmp. 6182 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6183 if (!Context.getTargetInfo().hasSjLjLowering()) 6184 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6185 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6186 return false; 6187 } 6188 6189 namespace { 6190 6191 class UncoveredArgHandler { 6192 enum { Unknown = -1, AllCovered = -2 }; 6193 6194 signed FirstUncoveredArg = Unknown; 6195 SmallVector<const Expr *, 4> DiagnosticExprs; 6196 6197 public: 6198 UncoveredArgHandler() = default; 6199 6200 bool hasUncoveredArg() const { 6201 return (FirstUncoveredArg >= 0); 6202 } 6203 6204 unsigned getUncoveredArg() const { 6205 assert(hasUncoveredArg() && "no uncovered argument"); 6206 return FirstUncoveredArg; 6207 } 6208 6209 void setAllCovered() { 6210 // A string has been found with all arguments covered, so clear out 6211 // the diagnostics. 6212 DiagnosticExprs.clear(); 6213 FirstUncoveredArg = AllCovered; 6214 } 6215 6216 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6217 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6218 6219 // Don't update if a previous string covers all arguments. 6220 if (FirstUncoveredArg == AllCovered) 6221 return; 6222 6223 // UncoveredArgHandler tracks the highest uncovered argument index 6224 // and with it all the strings that match this index. 6225 if (NewFirstUncoveredArg == FirstUncoveredArg) 6226 DiagnosticExprs.push_back(StrExpr); 6227 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6228 DiagnosticExprs.clear(); 6229 DiagnosticExprs.push_back(StrExpr); 6230 FirstUncoveredArg = NewFirstUncoveredArg; 6231 } 6232 } 6233 6234 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6235 }; 6236 6237 enum StringLiteralCheckType { 6238 SLCT_NotALiteral, 6239 SLCT_UncheckedLiteral, 6240 SLCT_CheckedLiteral 6241 }; 6242 6243 } // namespace 6244 6245 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6246 BinaryOperatorKind BinOpKind, 6247 bool AddendIsRight) { 6248 unsigned BitWidth = Offset.getBitWidth(); 6249 unsigned AddendBitWidth = Addend.getBitWidth(); 6250 // There might be negative interim results. 6251 if (Addend.isUnsigned()) { 6252 Addend = Addend.zext(++AddendBitWidth); 6253 Addend.setIsSigned(true); 6254 } 6255 // Adjust the bit width of the APSInts. 6256 if (AddendBitWidth > BitWidth) { 6257 Offset = Offset.sext(AddendBitWidth); 6258 BitWidth = AddendBitWidth; 6259 } else if (BitWidth > AddendBitWidth) { 6260 Addend = Addend.sext(BitWidth); 6261 } 6262 6263 bool Ov = false; 6264 llvm::APSInt ResOffset = Offset; 6265 if (BinOpKind == BO_Add) 6266 ResOffset = Offset.sadd_ov(Addend, Ov); 6267 else { 6268 assert(AddendIsRight && BinOpKind == BO_Sub && 6269 "operator must be add or sub with addend on the right"); 6270 ResOffset = Offset.ssub_ov(Addend, Ov); 6271 } 6272 6273 // We add an offset to a pointer here so we should support an offset as big as 6274 // possible. 6275 if (Ov) { 6276 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6277 "index (intermediate) result too big"); 6278 Offset = Offset.sext(2 * BitWidth); 6279 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6280 return; 6281 } 6282 6283 Offset = ResOffset; 6284 } 6285 6286 namespace { 6287 6288 // This is a wrapper class around StringLiteral to support offsetted string 6289 // literals as format strings. It takes the offset into account when returning 6290 // the string and its length or the source locations to display notes correctly. 6291 class FormatStringLiteral { 6292 const StringLiteral *FExpr; 6293 int64_t Offset; 6294 6295 public: 6296 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6297 : FExpr(fexpr), Offset(Offset) {} 6298 6299 StringRef getString() const { 6300 return FExpr->getString().drop_front(Offset); 6301 } 6302 6303 unsigned getByteLength() const { 6304 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6305 } 6306 6307 unsigned getLength() const { return FExpr->getLength() - Offset; } 6308 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6309 6310 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6311 6312 QualType getType() const { return FExpr->getType(); } 6313 6314 bool isAscii() const { return FExpr->isAscii(); } 6315 bool isWide() const { return FExpr->isWide(); } 6316 bool isUTF8() const { return FExpr->isUTF8(); } 6317 bool isUTF16() const { return FExpr->isUTF16(); } 6318 bool isUTF32() const { return FExpr->isUTF32(); } 6319 bool isPascal() const { return FExpr->isPascal(); } 6320 6321 SourceLocation getLocationOfByte( 6322 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6323 const TargetInfo &Target, unsigned *StartToken = nullptr, 6324 unsigned *StartTokenByteOffset = nullptr) const { 6325 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6326 StartToken, StartTokenByteOffset); 6327 } 6328 6329 SourceLocation getBeginLoc() const LLVM_READONLY { 6330 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6331 } 6332 6333 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6334 }; 6335 6336 } // namespace 6337 6338 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6339 const Expr *OrigFormatExpr, 6340 ArrayRef<const Expr *> Args, 6341 bool HasVAListArg, unsigned format_idx, 6342 unsigned firstDataArg, 6343 Sema::FormatStringType Type, 6344 bool inFunctionCall, 6345 Sema::VariadicCallType CallType, 6346 llvm::SmallBitVector &CheckedVarArgs, 6347 UncoveredArgHandler &UncoveredArg, 6348 bool IgnoreStringsWithoutSpecifiers); 6349 6350 // Determine if an expression is a string literal or constant string. 6351 // If this function returns false on the arguments to a function expecting a 6352 // format string, we will usually need to emit a warning. 6353 // True string literals are then checked by CheckFormatString. 6354 static StringLiteralCheckType 6355 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6356 bool HasVAListArg, unsigned format_idx, 6357 unsigned firstDataArg, Sema::FormatStringType Type, 6358 Sema::VariadicCallType CallType, bool InFunctionCall, 6359 llvm::SmallBitVector &CheckedVarArgs, 6360 UncoveredArgHandler &UncoveredArg, 6361 llvm::APSInt Offset, 6362 bool IgnoreStringsWithoutSpecifiers = false) { 6363 if (S.isConstantEvaluated()) 6364 return SLCT_NotALiteral; 6365 tryAgain: 6366 assert(Offset.isSigned() && "invalid offset"); 6367 6368 if (E->isTypeDependent() || E->isValueDependent()) 6369 return SLCT_NotALiteral; 6370 6371 E = E->IgnoreParenCasts(); 6372 6373 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6374 // Technically -Wformat-nonliteral does not warn about this case. 6375 // The behavior of printf and friends in this case is implementation 6376 // dependent. Ideally if the format string cannot be null then 6377 // it should have a 'nonnull' attribute in the function prototype. 6378 return SLCT_UncheckedLiteral; 6379 6380 switch (E->getStmtClass()) { 6381 case Stmt::BinaryConditionalOperatorClass: 6382 case Stmt::ConditionalOperatorClass: { 6383 // The expression is a literal if both sub-expressions were, and it was 6384 // completely checked only if both sub-expressions were checked. 6385 const AbstractConditionalOperator *C = 6386 cast<AbstractConditionalOperator>(E); 6387 6388 // Determine whether it is necessary to check both sub-expressions, for 6389 // example, because the condition expression is a constant that can be 6390 // evaluated at compile time. 6391 bool CheckLeft = true, CheckRight = true; 6392 6393 bool Cond; 6394 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6395 S.isConstantEvaluated())) { 6396 if (Cond) 6397 CheckRight = false; 6398 else 6399 CheckLeft = false; 6400 } 6401 6402 // We need to maintain the offsets for the right and the left hand side 6403 // separately to check if every possible indexed expression is a valid 6404 // string literal. They might have different offsets for different string 6405 // literals in the end. 6406 StringLiteralCheckType Left; 6407 if (!CheckLeft) 6408 Left = SLCT_UncheckedLiteral; 6409 else { 6410 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6411 HasVAListArg, format_idx, firstDataArg, 6412 Type, CallType, InFunctionCall, 6413 CheckedVarArgs, UncoveredArg, Offset, 6414 IgnoreStringsWithoutSpecifiers); 6415 if (Left == SLCT_NotALiteral || !CheckRight) { 6416 return Left; 6417 } 6418 } 6419 6420 StringLiteralCheckType Right = checkFormatStringExpr( 6421 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6422 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6423 IgnoreStringsWithoutSpecifiers); 6424 6425 return (CheckLeft && Left < Right) ? Left : Right; 6426 } 6427 6428 case Stmt::ImplicitCastExprClass: 6429 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6430 goto tryAgain; 6431 6432 case Stmt::OpaqueValueExprClass: 6433 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6434 E = src; 6435 goto tryAgain; 6436 } 6437 return SLCT_NotALiteral; 6438 6439 case Stmt::PredefinedExprClass: 6440 // While __func__, etc., are technically not string literals, they 6441 // cannot contain format specifiers and thus are not a security 6442 // liability. 6443 return SLCT_UncheckedLiteral; 6444 6445 case Stmt::DeclRefExprClass: { 6446 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6447 6448 // As an exception, do not flag errors for variables binding to 6449 // const string literals. 6450 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6451 bool isConstant = false; 6452 QualType T = DR->getType(); 6453 6454 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6455 isConstant = AT->getElementType().isConstant(S.Context); 6456 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6457 isConstant = T.isConstant(S.Context) && 6458 PT->getPointeeType().isConstant(S.Context); 6459 } else if (T->isObjCObjectPointerType()) { 6460 // In ObjC, there is usually no "const ObjectPointer" type, 6461 // so don't check if the pointee type is constant. 6462 isConstant = T.isConstant(S.Context); 6463 } 6464 6465 if (isConstant) { 6466 if (const Expr *Init = VD->getAnyInitializer()) { 6467 // Look through initializers like const char c[] = { "foo" } 6468 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6469 if (InitList->isStringLiteralInit()) 6470 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6471 } 6472 return checkFormatStringExpr(S, Init, Args, 6473 HasVAListArg, format_idx, 6474 firstDataArg, Type, CallType, 6475 /*InFunctionCall*/ false, CheckedVarArgs, 6476 UncoveredArg, Offset); 6477 } 6478 } 6479 6480 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6481 // special check to see if the format string is a function parameter 6482 // of the function calling the printf function. If the function 6483 // has an attribute indicating it is a printf-like function, then we 6484 // should suppress warnings concerning non-literals being used in a call 6485 // to a vprintf function. For example: 6486 // 6487 // void 6488 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6489 // va_list ap; 6490 // va_start(ap, fmt); 6491 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6492 // ... 6493 // } 6494 if (HasVAListArg) { 6495 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6496 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6497 int PVIndex = PV->getFunctionScopeIndex() + 1; 6498 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6499 // adjust for implicit parameter 6500 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6501 if (MD->isInstance()) 6502 ++PVIndex; 6503 // We also check if the formats are compatible. 6504 // We can't pass a 'scanf' string to a 'printf' function. 6505 if (PVIndex == PVFormat->getFormatIdx() && 6506 Type == S.GetFormatStringType(PVFormat)) 6507 return SLCT_UncheckedLiteral; 6508 } 6509 } 6510 } 6511 } 6512 } 6513 6514 return SLCT_NotALiteral; 6515 } 6516 6517 case Stmt::CallExprClass: 6518 case Stmt::CXXMemberCallExprClass: { 6519 const CallExpr *CE = cast<CallExpr>(E); 6520 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6521 bool IsFirst = true; 6522 StringLiteralCheckType CommonResult; 6523 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6524 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6525 StringLiteralCheckType Result = checkFormatStringExpr( 6526 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6527 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6528 IgnoreStringsWithoutSpecifiers); 6529 if (IsFirst) { 6530 CommonResult = Result; 6531 IsFirst = false; 6532 } 6533 } 6534 if (!IsFirst) 6535 return CommonResult; 6536 6537 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6538 unsigned BuiltinID = FD->getBuiltinID(); 6539 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6540 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6541 const Expr *Arg = CE->getArg(0); 6542 return checkFormatStringExpr(S, Arg, Args, 6543 HasVAListArg, format_idx, 6544 firstDataArg, Type, CallType, 6545 InFunctionCall, CheckedVarArgs, 6546 UncoveredArg, Offset, 6547 IgnoreStringsWithoutSpecifiers); 6548 } 6549 } 6550 } 6551 6552 return SLCT_NotALiteral; 6553 } 6554 case Stmt::ObjCMessageExprClass: { 6555 const auto *ME = cast<ObjCMessageExpr>(E); 6556 if (const auto *MD = ME->getMethodDecl()) { 6557 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6558 // As a special case heuristic, if we're using the method -[NSBundle 6559 // localizedStringForKey:value:table:], ignore any key strings that lack 6560 // format specifiers. The idea is that if the key doesn't have any 6561 // format specifiers then its probably just a key to map to the 6562 // localized strings. If it does have format specifiers though, then its 6563 // likely that the text of the key is the format string in the 6564 // programmer's language, and should be checked. 6565 const ObjCInterfaceDecl *IFace; 6566 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6567 IFace->getIdentifier()->isStr("NSBundle") && 6568 MD->getSelector().isKeywordSelector( 6569 {"localizedStringForKey", "value", "table"})) { 6570 IgnoreStringsWithoutSpecifiers = true; 6571 } 6572 6573 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6574 return checkFormatStringExpr( 6575 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6576 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6577 IgnoreStringsWithoutSpecifiers); 6578 } 6579 } 6580 6581 return SLCT_NotALiteral; 6582 } 6583 case Stmt::ObjCStringLiteralClass: 6584 case Stmt::StringLiteralClass: { 6585 const StringLiteral *StrE = nullptr; 6586 6587 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6588 StrE = ObjCFExpr->getString(); 6589 else 6590 StrE = cast<StringLiteral>(E); 6591 6592 if (StrE) { 6593 if (Offset.isNegative() || Offset > StrE->getLength()) { 6594 // TODO: It would be better to have an explicit warning for out of 6595 // bounds literals. 6596 return SLCT_NotALiteral; 6597 } 6598 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6599 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6600 firstDataArg, Type, InFunctionCall, CallType, 6601 CheckedVarArgs, UncoveredArg, 6602 IgnoreStringsWithoutSpecifiers); 6603 return SLCT_CheckedLiteral; 6604 } 6605 6606 return SLCT_NotALiteral; 6607 } 6608 case Stmt::BinaryOperatorClass: { 6609 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6610 6611 // A string literal + an int offset is still a string literal. 6612 if (BinOp->isAdditiveOp()) { 6613 Expr::EvalResult LResult, RResult; 6614 6615 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6616 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6617 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6618 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6619 6620 if (LIsInt != RIsInt) { 6621 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6622 6623 if (LIsInt) { 6624 if (BinOpKind == BO_Add) { 6625 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6626 E = BinOp->getRHS(); 6627 goto tryAgain; 6628 } 6629 } else { 6630 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6631 E = BinOp->getLHS(); 6632 goto tryAgain; 6633 } 6634 } 6635 } 6636 6637 return SLCT_NotALiteral; 6638 } 6639 case Stmt::UnaryOperatorClass: { 6640 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6641 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6642 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6643 Expr::EvalResult IndexResult; 6644 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6645 Expr::SE_NoSideEffects, 6646 S.isConstantEvaluated())) { 6647 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6648 /*RHS is int*/ true); 6649 E = ASE->getBase(); 6650 goto tryAgain; 6651 } 6652 } 6653 6654 return SLCT_NotALiteral; 6655 } 6656 6657 default: 6658 return SLCT_NotALiteral; 6659 } 6660 } 6661 6662 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6663 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6664 .Case("scanf", FST_Scanf) 6665 .Cases("printf", "printf0", FST_Printf) 6666 .Cases("NSString", "CFString", FST_NSString) 6667 .Case("strftime", FST_Strftime) 6668 .Case("strfmon", FST_Strfmon) 6669 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6670 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6671 .Case("os_trace", FST_OSLog) 6672 .Case("os_log", FST_OSLog) 6673 .Default(FST_Unknown); 6674 } 6675 6676 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6677 /// functions) for correct use of format strings. 6678 /// Returns true if a format string has been fully checked. 6679 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6680 ArrayRef<const Expr *> Args, 6681 bool IsCXXMember, 6682 VariadicCallType CallType, 6683 SourceLocation Loc, SourceRange Range, 6684 llvm::SmallBitVector &CheckedVarArgs) { 6685 FormatStringInfo FSI; 6686 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6687 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6688 FSI.FirstDataArg, GetFormatStringType(Format), 6689 CallType, Loc, Range, CheckedVarArgs); 6690 return false; 6691 } 6692 6693 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6694 bool HasVAListArg, unsigned format_idx, 6695 unsigned firstDataArg, FormatStringType Type, 6696 VariadicCallType CallType, 6697 SourceLocation Loc, SourceRange Range, 6698 llvm::SmallBitVector &CheckedVarArgs) { 6699 // CHECK: printf/scanf-like function is called with no format string. 6700 if (format_idx >= Args.size()) { 6701 Diag(Loc, diag::warn_missing_format_string) << Range; 6702 return false; 6703 } 6704 6705 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6706 6707 // CHECK: format string is not a string literal. 6708 // 6709 // Dynamically generated format strings are difficult to 6710 // automatically vet at compile time. Requiring that format strings 6711 // are string literals: (1) permits the checking of format strings by 6712 // the compiler and thereby (2) can practically remove the source of 6713 // many format string exploits. 6714 6715 // Format string can be either ObjC string (e.g. @"%d") or 6716 // C string (e.g. "%d") 6717 // ObjC string uses the same format specifiers as C string, so we can use 6718 // the same format string checking logic for both ObjC and C strings. 6719 UncoveredArgHandler UncoveredArg; 6720 StringLiteralCheckType CT = 6721 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6722 format_idx, firstDataArg, Type, CallType, 6723 /*IsFunctionCall*/ true, CheckedVarArgs, 6724 UncoveredArg, 6725 /*no string offset*/ llvm::APSInt(64, false) = 0); 6726 6727 // Generate a diagnostic where an uncovered argument is detected. 6728 if (UncoveredArg.hasUncoveredArg()) { 6729 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6730 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6731 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6732 } 6733 6734 if (CT != SLCT_NotALiteral) 6735 // Literal format string found, check done! 6736 return CT == SLCT_CheckedLiteral; 6737 6738 // Strftime is particular as it always uses a single 'time' argument, 6739 // so it is safe to pass a non-literal string. 6740 if (Type == FST_Strftime) 6741 return false; 6742 6743 // Do not emit diag when the string param is a macro expansion and the 6744 // format is either NSString or CFString. This is a hack to prevent 6745 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6746 // which are usually used in place of NS and CF string literals. 6747 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6748 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6749 return false; 6750 6751 // If there are no arguments specified, warn with -Wformat-security, otherwise 6752 // warn only with -Wformat-nonliteral. 6753 if (Args.size() == firstDataArg) { 6754 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6755 << OrigFormatExpr->getSourceRange(); 6756 switch (Type) { 6757 default: 6758 break; 6759 case FST_Kprintf: 6760 case FST_FreeBSDKPrintf: 6761 case FST_Printf: 6762 Diag(FormatLoc, diag::note_format_security_fixit) 6763 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6764 break; 6765 case FST_NSString: 6766 Diag(FormatLoc, diag::note_format_security_fixit) 6767 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6768 break; 6769 } 6770 } else { 6771 Diag(FormatLoc, diag::warn_format_nonliteral) 6772 << OrigFormatExpr->getSourceRange(); 6773 } 6774 return false; 6775 } 6776 6777 namespace { 6778 6779 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6780 protected: 6781 Sema &S; 6782 const FormatStringLiteral *FExpr; 6783 const Expr *OrigFormatExpr; 6784 const Sema::FormatStringType FSType; 6785 const unsigned FirstDataArg; 6786 const unsigned NumDataArgs; 6787 const char *Beg; // Start of format string. 6788 const bool HasVAListArg; 6789 ArrayRef<const Expr *> Args; 6790 unsigned FormatIdx; 6791 llvm::SmallBitVector CoveredArgs; 6792 bool usesPositionalArgs = false; 6793 bool atFirstArg = true; 6794 bool inFunctionCall; 6795 Sema::VariadicCallType CallType; 6796 llvm::SmallBitVector &CheckedVarArgs; 6797 UncoveredArgHandler &UncoveredArg; 6798 6799 public: 6800 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6801 const Expr *origFormatExpr, 6802 const Sema::FormatStringType type, unsigned firstDataArg, 6803 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6804 ArrayRef<const Expr *> Args, unsigned formatIdx, 6805 bool inFunctionCall, Sema::VariadicCallType callType, 6806 llvm::SmallBitVector &CheckedVarArgs, 6807 UncoveredArgHandler &UncoveredArg) 6808 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6809 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6810 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6811 inFunctionCall(inFunctionCall), CallType(callType), 6812 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6813 CoveredArgs.resize(numDataArgs); 6814 CoveredArgs.reset(); 6815 } 6816 6817 void DoneProcessing(); 6818 6819 void HandleIncompleteSpecifier(const char *startSpecifier, 6820 unsigned specifierLen) override; 6821 6822 void HandleInvalidLengthModifier( 6823 const analyze_format_string::FormatSpecifier &FS, 6824 const analyze_format_string::ConversionSpecifier &CS, 6825 const char *startSpecifier, unsigned specifierLen, 6826 unsigned DiagID); 6827 6828 void HandleNonStandardLengthModifier( 6829 const analyze_format_string::FormatSpecifier &FS, 6830 const char *startSpecifier, unsigned specifierLen); 6831 6832 void HandleNonStandardConversionSpecifier( 6833 const analyze_format_string::ConversionSpecifier &CS, 6834 const char *startSpecifier, unsigned specifierLen); 6835 6836 void HandlePosition(const char *startPos, unsigned posLen) override; 6837 6838 void HandleInvalidPosition(const char *startSpecifier, 6839 unsigned specifierLen, 6840 analyze_format_string::PositionContext p) override; 6841 6842 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6843 6844 void HandleNullChar(const char *nullCharacter) override; 6845 6846 template <typename Range> 6847 static void 6848 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6849 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6850 bool IsStringLocation, Range StringRange, 6851 ArrayRef<FixItHint> Fixit = None); 6852 6853 protected: 6854 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6855 const char *startSpec, 6856 unsigned specifierLen, 6857 const char *csStart, unsigned csLen); 6858 6859 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6860 const char *startSpec, 6861 unsigned specifierLen); 6862 6863 SourceRange getFormatStringRange(); 6864 CharSourceRange getSpecifierRange(const char *startSpecifier, 6865 unsigned specifierLen); 6866 SourceLocation getLocationOfByte(const char *x); 6867 6868 const Expr *getDataArg(unsigned i) const; 6869 6870 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6871 const analyze_format_string::ConversionSpecifier &CS, 6872 const char *startSpecifier, unsigned specifierLen, 6873 unsigned argIndex); 6874 6875 template <typename Range> 6876 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6877 bool IsStringLocation, Range StringRange, 6878 ArrayRef<FixItHint> Fixit = None); 6879 }; 6880 6881 } // namespace 6882 6883 SourceRange CheckFormatHandler::getFormatStringRange() { 6884 return OrigFormatExpr->getSourceRange(); 6885 } 6886 6887 CharSourceRange CheckFormatHandler:: 6888 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6889 SourceLocation Start = getLocationOfByte(startSpecifier); 6890 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6891 6892 // Advance the end SourceLocation by one due to half-open ranges. 6893 End = End.getLocWithOffset(1); 6894 6895 return CharSourceRange::getCharRange(Start, End); 6896 } 6897 6898 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6899 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6900 S.getLangOpts(), S.Context.getTargetInfo()); 6901 } 6902 6903 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6904 unsigned specifierLen){ 6905 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6906 getLocationOfByte(startSpecifier), 6907 /*IsStringLocation*/true, 6908 getSpecifierRange(startSpecifier, specifierLen)); 6909 } 6910 6911 void CheckFormatHandler::HandleInvalidLengthModifier( 6912 const analyze_format_string::FormatSpecifier &FS, 6913 const analyze_format_string::ConversionSpecifier &CS, 6914 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6915 using namespace analyze_format_string; 6916 6917 const LengthModifier &LM = FS.getLengthModifier(); 6918 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6919 6920 // See if we know how to fix this length modifier. 6921 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6922 if (FixedLM) { 6923 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6924 getLocationOfByte(LM.getStart()), 6925 /*IsStringLocation*/true, 6926 getSpecifierRange(startSpecifier, specifierLen)); 6927 6928 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6929 << FixedLM->toString() 6930 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6931 6932 } else { 6933 FixItHint Hint; 6934 if (DiagID == diag::warn_format_nonsensical_length) 6935 Hint = FixItHint::CreateRemoval(LMRange); 6936 6937 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6938 getLocationOfByte(LM.getStart()), 6939 /*IsStringLocation*/true, 6940 getSpecifierRange(startSpecifier, specifierLen), 6941 Hint); 6942 } 6943 } 6944 6945 void CheckFormatHandler::HandleNonStandardLengthModifier( 6946 const analyze_format_string::FormatSpecifier &FS, 6947 const char *startSpecifier, unsigned specifierLen) { 6948 using namespace analyze_format_string; 6949 6950 const LengthModifier &LM = FS.getLengthModifier(); 6951 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6952 6953 // See if we know how to fix this length modifier. 6954 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6955 if (FixedLM) { 6956 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6957 << LM.toString() << 0, 6958 getLocationOfByte(LM.getStart()), 6959 /*IsStringLocation*/true, 6960 getSpecifierRange(startSpecifier, specifierLen)); 6961 6962 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6963 << FixedLM->toString() 6964 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6965 6966 } else { 6967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6968 << LM.toString() << 0, 6969 getLocationOfByte(LM.getStart()), 6970 /*IsStringLocation*/true, 6971 getSpecifierRange(startSpecifier, specifierLen)); 6972 } 6973 } 6974 6975 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6976 const analyze_format_string::ConversionSpecifier &CS, 6977 const char *startSpecifier, unsigned specifierLen) { 6978 using namespace analyze_format_string; 6979 6980 // See if we know how to fix this conversion specifier. 6981 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6982 if (FixedCS) { 6983 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6984 << CS.toString() << /*conversion specifier*/1, 6985 getLocationOfByte(CS.getStart()), 6986 /*IsStringLocation*/true, 6987 getSpecifierRange(startSpecifier, specifierLen)); 6988 6989 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6990 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6991 << FixedCS->toString() 6992 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6993 } else { 6994 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6995 << CS.toString() << /*conversion specifier*/1, 6996 getLocationOfByte(CS.getStart()), 6997 /*IsStringLocation*/true, 6998 getSpecifierRange(startSpecifier, specifierLen)); 6999 } 7000 } 7001 7002 void CheckFormatHandler::HandlePosition(const char *startPos, 7003 unsigned posLen) { 7004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7005 getLocationOfByte(startPos), 7006 /*IsStringLocation*/true, 7007 getSpecifierRange(startPos, posLen)); 7008 } 7009 7010 void 7011 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7012 analyze_format_string::PositionContext p) { 7013 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7014 << (unsigned) p, 7015 getLocationOfByte(startPos), /*IsStringLocation*/true, 7016 getSpecifierRange(startPos, posLen)); 7017 } 7018 7019 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7020 unsigned posLen) { 7021 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7022 getLocationOfByte(startPos), 7023 /*IsStringLocation*/true, 7024 getSpecifierRange(startPos, posLen)); 7025 } 7026 7027 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7028 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7029 // The presence of a null character is likely an error. 7030 EmitFormatDiagnostic( 7031 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7032 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7033 getFormatStringRange()); 7034 } 7035 } 7036 7037 // Note that this may return NULL if there was an error parsing or building 7038 // one of the argument expressions. 7039 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7040 return Args[FirstDataArg + i]; 7041 } 7042 7043 void CheckFormatHandler::DoneProcessing() { 7044 // Does the number of data arguments exceed the number of 7045 // format conversions in the format string? 7046 if (!HasVAListArg) { 7047 // Find any arguments that weren't covered. 7048 CoveredArgs.flip(); 7049 signed notCoveredArg = CoveredArgs.find_first(); 7050 if (notCoveredArg >= 0) { 7051 assert((unsigned)notCoveredArg < NumDataArgs); 7052 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7053 } else { 7054 UncoveredArg.setAllCovered(); 7055 } 7056 } 7057 } 7058 7059 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7060 const Expr *ArgExpr) { 7061 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7062 "Invalid state"); 7063 7064 if (!ArgExpr) 7065 return; 7066 7067 SourceLocation Loc = ArgExpr->getBeginLoc(); 7068 7069 if (S.getSourceManager().isInSystemMacro(Loc)) 7070 return; 7071 7072 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7073 for (auto E : DiagnosticExprs) 7074 PDiag << E->getSourceRange(); 7075 7076 CheckFormatHandler::EmitFormatDiagnostic( 7077 S, IsFunctionCall, DiagnosticExprs[0], 7078 PDiag, Loc, /*IsStringLocation*/false, 7079 DiagnosticExprs[0]->getSourceRange()); 7080 } 7081 7082 bool 7083 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7084 SourceLocation Loc, 7085 const char *startSpec, 7086 unsigned specifierLen, 7087 const char *csStart, 7088 unsigned csLen) { 7089 bool keepGoing = true; 7090 if (argIndex < NumDataArgs) { 7091 // Consider the argument coverered, even though the specifier doesn't 7092 // make sense. 7093 CoveredArgs.set(argIndex); 7094 } 7095 else { 7096 // If argIndex exceeds the number of data arguments we 7097 // don't issue a warning because that is just a cascade of warnings (and 7098 // they may have intended '%%' anyway). We don't want to continue processing 7099 // the format string after this point, however, as we will like just get 7100 // gibberish when trying to match arguments. 7101 keepGoing = false; 7102 } 7103 7104 StringRef Specifier(csStart, csLen); 7105 7106 // If the specifier in non-printable, it could be the first byte of a UTF-8 7107 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7108 // hex value. 7109 std::string CodePointStr; 7110 if (!llvm::sys::locale::isPrint(*csStart)) { 7111 llvm::UTF32 CodePoint; 7112 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7113 const llvm::UTF8 *E = 7114 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7115 llvm::ConversionResult Result = 7116 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7117 7118 if (Result != llvm::conversionOK) { 7119 unsigned char FirstChar = *csStart; 7120 CodePoint = (llvm::UTF32)FirstChar; 7121 } 7122 7123 llvm::raw_string_ostream OS(CodePointStr); 7124 if (CodePoint < 256) 7125 OS << "\\x" << llvm::format("%02x", CodePoint); 7126 else if (CodePoint <= 0xFFFF) 7127 OS << "\\u" << llvm::format("%04x", CodePoint); 7128 else 7129 OS << "\\U" << llvm::format("%08x", CodePoint); 7130 OS.flush(); 7131 Specifier = CodePointStr; 7132 } 7133 7134 EmitFormatDiagnostic( 7135 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7136 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7137 7138 return keepGoing; 7139 } 7140 7141 void 7142 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7143 const char *startSpec, 7144 unsigned specifierLen) { 7145 EmitFormatDiagnostic( 7146 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7147 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7148 } 7149 7150 bool 7151 CheckFormatHandler::CheckNumArgs( 7152 const analyze_format_string::FormatSpecifier &FS, 7153 const analyze_format_string::ConversionSpecifier &CS, 7154 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7155 7156 if (argIndex >= NumDataArgs) { 7157 PartialDiagnostic PDiag = FS.usesPositionalArg() 7158 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7159 << (argIndex+1) << NumDataArgs) 7160 : S.PDiag(diag::warn_printf_insufficient_data_args); 7161 EmitFormatDiagnostic( 7162 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7163 getSpecifierRange(startSpecifier, specifierLen)); 7164 7165 // Since more arguments than conversion tokens are given, by extension 7166 // all arguments are covered, so mark this as so. 7167 UncoveredArg.setAllCovered(); 7168 return false; 7169 } 7170 return true; 7171 } 7172 7173 template<typename Range> 7174 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7175 SourceLocation Loc, 7176 bool IsStringLocation, 7177 Range StringRange, 7178 ArrayRef<FixItHint> FixIt) { 7179 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7180 Loc, IsStringLocation, StringRange, FixIt); 7181 } 7182 7183 /// If the format string is not within the function call, emit a note 7184 /// so that the function call and string are in diagnostic messages. 7185 /// 7186 /// \param InFunctionCall if true, the format string is within the function 7187 /// call and only one diagnostic message will be produced. Otherwise, an 7188 /// extra note will be emitted pointing to location of the format string. 7189 /// 7190 /// \param ArgumentExpr the expression that is passed as the format string 7191 /// argument in the function call. Used for getting locations when two 7192 /// diagnostics are emitted. 7193 /// 7194 /// \param PDiag the callee should already have provided any strings for the 7195 /// diagnostic message. This function only adds locations and fixits 7196 /// to diagnostics. 7197 /// 7198 /// \param Loc primary location for diagnostic. If two diagnostics are 7199 /// required, one will be at Loc and a new SourceLocation will be created for 7200 /// the other one. 7201 /// 7202 /// \param IsStringLocation if true, Loc points to the format string should be 7203 /// used for the note. Otherwise, Loc points to the argument list and will 7204 /// be used with PDiag. 7205 /// 7206 /// \param StringRange some or all of the string to highlight. This is 7207 /// templated so it can accept either a CharSourceRange or a SourceRange. 7208 /// 7209 /// \param FixIt optional fix it hint for the format string. 7210 template <typename Range> 7211 void CheckFormatHandler::EmitFormatDiagnostic( 7212 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7213 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7214 Range StringRange, ArrayRef<FixItHint> FixIt) { 7215 if (InFunctionCall) { 7216 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7217 D << StringRange; 7218 D << FixIt; 7219 } else { 7220 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7221 << ArgumentExpr->getSourceRange(); 7222 7223 const Sema::SemaDiagnosticBuilder &Note = 7224 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7225 diag::note_format_string_defined); 7226 7227 Note << StringRange; 7228 Note << FixIt; 7229 } 7230 } 7231 7232 //===--- CHECK: Printf format string checking ------------------------------===// 7233 7234 namespace { 7235 7236 class CheckPrintfHandler : public CheckFormatHandler { 7237 public: 7238 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7239 const Expr *origFormatExpr, 7240 const Sema::FormatStringType type, unsigned firstDataArg, 7241 unsigned numDataArgs, bool isObjC, const char *beg, 7242 bool hasVAListArg, ArrayRef<const Expr *> Args, 7243 unsigned formatIdx, bool inFunctionCall, 7244 Sema::VariadicCallType CallType, 7245 llvm::SmallBitVector &CheckedVarArgs, 7246 UncoveredArgHandler &UncoveredArg) 7247 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7248 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7249 inFunctionCall, CallType, CheckedVarArgs, 7250 UncoveredArg) {} 7251 7252 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7253 7254 /// Returns true if '%@' specifiers are allowed in the format string. 7255 bool allowsObjCArg() const { 7256 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7257 FSType == Sema::FST_OSTrace; 7258 } 7259 7260 bool HandleInvalidPrintfConversionSpecifier( 7261 const analyze_printf::PrintfSpecifier &FS, 7262 const char *startSpecifier, 7263 unsigned specifierLen) override; 7264 7265 void handleInvalidMaskType(StringRef MaskType) override; 7266 7267 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7268 const char *startSpecifier, 7269 unsigned specifierLen) override; 7270 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7271 const char *StartSpecifier, 7272 unsigned SpecifierLen, 7273 const Expr *E); 7274 7275 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7276 const char *startSpecifier, unsigned specifierLen); 7277 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7278 const analyze_printf::OptionalAmount &Amt, 7279 unsigned type, 7280 const char *startSpecifier, unsigned specifierLen); 7281 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7282 const analyze_printf::OptionalFlag &flag, 7283 const char *startSpecifier, unsigned specifierLen); 7284 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7285 const analyze_printf::OptionalFlag &ignoredFlag, 7286 const analyze_printf::OptionalFlag &flag, 7287 const char *startSpecifier, unsigned specifierLen); 7288 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7289 const Expr *E); 7290 7291 void HandleEmptyObjCModifierFlag(const char *startFlag, 7292 unsigned flagLen) override; 7293 7294 void HandleInvalidObjCModifierFlag(const char *startFlag, 7295 unsigned flagLen) override; 7296 7297 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7298 const char *flagsEnd, 7299 const char *conversionPosition) 7300 override; 7301 }; 7302 7303 } // namespace 7304 7305 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7306 const analyze_printf::PrintfSpecifier &FS, 7307 const char *startSpecifier, 7308 unsigned specifierLen) { 7309 const analyze_printf::PrintfConversionSpecifier &CS = 7310 FS.getConversionSpecifier(); 7311 7312 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7313 getLocationOfByte(CS.getStart()), 7314 startSpecifier, specifierLen, 7315 CS.getStart(), CS.getLength()); 7316 } 7317 7318 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7319 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7320 } 7321 7322 bool CheckPrintfHandler::HandleAmount( 7323 const analyze_format_string::OptionalAmount &Amt, 7324 unsigned k, const char *startSpecifier, 7325 unsigned specifierLen) { 7326 if (Amt.hasDataArgument()) { 7327 if (!HasVAListArg) { 7328 unsigned argIndex = Amt.getArgIndex(); 7329 if (argIndex >= NumDataArgs) { 7330 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7331 << k, 7332 getLocationOfByte(Amt.getStart()), 7333 /*IsStringLocation*/true, 7334 getSpecifierRange(startSpecifier, specifierLen)); 7335 // Don't do any more checking. We will just emit 7336 // spurious errors. 7337 return false; 7338 } 7339 7340 // Type check the data argument. It should be an 'int'. 7341 // Although not in conformance with C99, we also allow the argument to be 7342 // an 'unsigned int' as that is a reasonably safe case. GCC also 7343 // doesn't emit a warning for that case. 7344 CoveredArgs.set(argIndex); 7345 const Expr *Arg = getDataArg(argIndex); 7346 if (!Arg) 7347 return false; 7348 7349 QualType T = Arg->getType(); 7350 7351 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7352 assert(AT.isValid()); 7353 7354 if (!AT.matchesType(S.Context, T)) { 7355 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7356 << k << AT.getRepresentativeTypeName(S.Context) 7357 << T << Arg->getSourceRange(), 7358 getLocationOfByte(Amt.getStart()), 7359 /*IsStringLocation*/true, 7360 getSpecifierRange(startSpecifier, specifierLen)); 7361 // Don't do any more checking. We will just emit 7362 // spurious errors. 7363 return false; 7364 } 7365 } 7366 } 7367 return true; 7368 } 7369 7370 void CheckPrintfHandler::HandleInvalidAmount( 7371 const analyze_printf::PrintfSpecifier &FS, 7372 const analyze_printf::OptionalAmount &Amt, 7373 unsigned type, 7374 const char *startSpecifier, 7375 unsigned specifierLen) { 7376 const analyze_printf::PrintfConversionSpecifier &CS = 7377 FS.getConversionSpecifier(); 7378 7379 FixItHint fixit = 7380 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7381 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7382 Amt.getConstantLength())) 7383 : FixItHint(); 7384 7385 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7386 << type << CS.toString(), 7387 getLocationOfByte(Amt.getStart()), 7388 /*IsStringLocation*/true, 7389 getSpecifierRange(startSpecifier, specifierLen), 7390 fixit); 7391 } 7392 7393 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7394 const analyze_printf::OptionalFlag &flag, 7395 const char *startSpecifier, 7396 unsigned specifierLen) { 7397 // Warn about pointless flag with a fixit removal. 7398 const analyze_printf::PrintfConversionSpecifier &CS = 7399 FS.getConversionSpecifier(); 7400 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7401 << flag.toString() << CS.toString(), 7402 getLocationOfByte(flag.getPosition()), 7403 /*IsStringLocation*/true, 7404 getSpecifierRange(startSpecifier, specifierLen), 7405 FixItHint::CreateRemoval( 7406 getSpecifierRange(flag.getPosition(), 1))); 7407 } 7408 7409 void CheckPrintfHandler::HandleIgnoredFlag( 7410 const analyze_printf::PrintfSpecifier &FS, 7411 const analyze_printf::OptionalFlag &ignoredFlag, 7412 const analyze_printf::OptionalFlag &flag, 7413 const char *startSpecifier, 7414 unsigned specifierLen) { 7415 // Warn about ignored flag with a fixit removal. 7416 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7417 << ignoredFlag.toString() << flag.toString(), 7418 getLocationOfByte(ignoredFlag.getPosition()), 7419 /*IsStringLocation*/true, 7420 getSpecifierRange(startSpecifier, specifierLen), 7421 FixItHint::CreateRemoval( 7422 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7423 } 7424 7425 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7426 unsigned flagLen) { 7427 // Warn about an empty flag. 7428 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7429 getLocationOfByte(startFlag), 7430 /*IsStringLocation*/true, 7431 getSpecifierRange(startFlag, flagLen)); 7432 } 7433 7434 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7435 unsigned flagLen) { 7436 // Warn about an invalid flag. 7437 auto Range = getSpecifierRange(startFlag, flagLen); 7438 StringRef flag(startFlag, flagLen); 7439 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7440 getLocationOfByte(startFlag), 7441 /*IsStringLocation*/true, 7442 Range, FixItHint::CreateRemoval(Range)); 7443 } 7444 7445 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7446 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7447 // Warn about using '[...]' without a '@' conversion. 7448 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7449 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7450 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7451 getLocationOfByte(conversionPosition), 7452 /*IsStringLocation*/true, 7453 Range, FixItHint::CreateRemoval(Range)); 7454 } 7455 7456 // Determines if the specified is a C++ class or struct containing 7457 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7458 // "c_str()"). 7459 template<typename MemberKind> 7460 static llvm::SmallPtrSet<MemberKind*, 1> 7461 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7462 const RecordType *RT = Ty->getAs<RecordType>(); 7463 llvm::SmallPtrSet<MemberKind*, 1> Results; 7464 7465 if (!RT) 7466 return Results; 7467 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7468 if (!RD || !RD->getDefinition()) 7469 return Results; 7470 7471 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7472 Sema::LookupMemberName); 7473 R.suppressDiagnostics(); 7474 7475 // We just need to include all members of the right kind turned up by the 7476 // filter, at this point. 7477 if (S.LookupQualifiedName(R, RT->getDecl())) 7478 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7479 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7480 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7481 Results.insert(FK); 7482 } 7483 return Results; 7484 } 7485 7486 /// Check if we could call '.c_str()' on an object. 7487 /// 7488 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7489 /// allow the call, or if it would be ambiguous). 7490 bool Sema::hasCStrMethod(const Expr *E) { 7491 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7492 7493 MethodSet Results = 7494 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7495 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7496 MI != ME; ++MI) 7497 if ((*MI)->getMinRequiredArguments() == 0) 7498 return true; 7499 return false; 7500 } 7501 7502 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7503 // better diagnostic if so. AT is assumed to be valid. 7504 // Returns true when a c_str() conversion method is found. 7505 bool CheckPrintfHandler::checkForCStrMembers( 7506 const analyze_printf::ArgType &AT, const Expr *E) { 7507 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7508 7509 MethodSet Results = 7510 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7511 7512 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7513 MI != ME; ++MI) { 7514 const CXXMethodDecl *Method = *MI; 7515 if (Method->getMinRequiredArguments() == 0 && 7516 AT.matchesType(S.Context, Method->getReturnType())) { 7517 // FIXME: Suggest parens if the expression needs them. 7518 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7519 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7520 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7521 return true; 7522 } 7523 } 7524 7525 return false; 7526 } 7527 7528 bool 7529 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7530 &FS, 7531 const char *startSpecifier, 7532 unsigned specifierLen) { 7533 using namespace analyze_format_string; 7534 using namespace analyze_printf; 7535 7536 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7537 7538 if (FS.consumesDataArgument()) { 7539 if (atFirstArg) { 7540 atFirstArg = false; 7541 usesPositionalArgs = FS.usesPositionalArg(); 7542 } 7543 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7544 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7545 startSpecifier, specifierLen); 7546 return false; 7547 } 7548 } 7549 7550 // First check if the field width, precision, and conversion specifier 7551 // have matching data arguments. 7552 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7553 startSpecifier, specifierLen)) { 7554 return false; 7555 } 7556 7557 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7558 startSpecifier, specifierLen)) { 7559 return false; 7560 } 7561 7562 if (!CS.consumesDataArgument()) { 7563 // FIXME: Technically specifying a precision or field width here 7564 // makes no sense. Worth issuing a warning at some point. 7565 return true; 7566 } 7567 7568 // Consume the argument. 7569 unsigned argIndex = FS.getArgIndex(); 7570 if (argIndex < NumDataArgs) { 7571 // The check to see if the argIndex is valid will come later. 7572 // We set the bit here because we may exit early from this 7573 // function if we encounter some other error. 7574 CoveredArgs.set(argIndex); 7575 } 7576 7577 // FreeBSD kernel extensions. 7578 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7579 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7580 // We need at least two arguments. 7581 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7582 return false; 7583 7584 // Claim the second argument. 7585 CoveredArgs.set(argIndex + 1); 7586 7587 // Type check the first argument (int for %b, pointer for %D) 7588 const Expr *Ex = getDataArg(argIndex); 7589 const analyze_printf::ArgType &AT = 7590 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7591 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7592 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7593 EmitFormatDiagnostic( 7594 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7595 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7596 << false << Ex->getSourceRange(), 7597 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7598 getSpecifierRange(startSpecifier, specifierLen)); 7599 7600 // Type check the second argument (char * for both %b and %D) 7601 Ex = getDataArg(argIndex + 1); 7602 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7603 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7604 EmitFormatDiagnostic( 7605 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7606 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7607 << false << Ex->getSourceRange(), 7608 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7609 getSpecifierRange(startSpecifier, specifierLen)); 7610 7611 return true; 7612 } 7613 7614 // Check for using an Objective-C specific conversion specifier 7615 // in a non-ObjC literal. 7616 if (!allowsObjCArg() && CS.isObjCArg()) { 7617 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7618 specifierLen); 7619 } 7620 7621 // %P can only be used with os_log. 7622 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7623 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7624 specifierLen); 7625 } 7626 7627 // %n is not allowed with os_log. 7628 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7629 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7630 getLocationOfByte(CS.getStart()), 7631 /*IsStringLocation*/ false, 7632 getSpecifierRange(startSpecifier, specifierLen)); 7633 7634 return true; 7635 } 7636 7637 // Only scalars are allowed for os_trace. 7638 if (FSType == Sema::FST_OSTrace && 7639 (CS.getKind() == ConversionSpecifier::PArg || 7640 CS.getKind() == ConversionSpecifier::sArg || 7641 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7642 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7643 specifierLen); 7644 } 7645 7646 // Check for use of public/private annotation outside of os_log(). 7647 if (FSType != Sema::FST_OSLog) { 7648 if (FS.isPublic().isSet()) { 7649 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7650 << "public", 7651 getLocationOfByte(FS.isPublic().getPosition()), 7652 /*IsStringLocation*/ false, 7653 getSpecifierRange(startSpecifier, specifierLen)); 7654 } 7655 if (FS.isPrivate().isSet()) { 7656 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7657 << "private", 7658 getLocationOfByte(FS.isPrivate().getPosition()), 7659 /*IsStringLocation*/ false, 7660 getSpecifierRange(startSpecifier, specifierLen)); 7661 } 7662 } 7663 7664 // Check for invalid use of field width 7665 if (!FS.hasValidFieldWidth()) { 7666 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7667 startSpecifier, specifierLen); 7668 } 7669 7670 // Check for invalid use of precision 7671 if (!FS.hasValidPrecision()) { 7672 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7673 startSpecifier, specifierLen); 7674 } 7675 7676 // Precision is mandatory for %P specifier. 7677 if (CS.getKind() == ConversionSpecifier::PArg && 7678 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7679 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7680 getLocationOfByte(startSpecifier), 7681 /*IsStringLocation*/ false, 7682 getSpecifierRange(startSpecifier, specifierLen)); 7683 } 7684 7685 // Check each flag does not conflict with any other component. 7686 if (!FS.hasValidThousandsGroupingPrefix()) 7687 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7688 if (!FS.hasValidLeadingZeros()) 7689 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7690 if (!FS.hasValidPlusPrefix()) 7691 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7692 if (!FS.hasValidSpacePrefix()) 7693 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7694 if (!FS.hasValidAlternativeForm()) 7695 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7696 if (!FS.hasValidLeftJustified()) 7697 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7698 7699 // Check that flags are not ignored by another flag 7700 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7701 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7702 startSpecifier, specifierLen); 7703 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7704 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7705 startSpecifier, specifierLen); 7706 7707 // Check the length modifier is valid with the given conversion specifier. 7708 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7709 S.getLangOpts())) 7710 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7711 diag::warn_format_nonsensical_length); 7712 else if (!FS.hasStandardLengthModifier()) 7713 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7714 else if (!FS.hasStandardLengthConversionCombination()) 7715 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7716 diag::warn_format_non_standard_conversion_spec); 7717 7718 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7719 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7720 7721 // The remaining checks depend on the data arguments. 7722 if (HasVAListArg) 7723 return true; 7724 7725 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7726 return false; 7727 7728 const Expr *Arg = getDataArg(argIndex); 7729 if (!Arg) 7730 return true; 7731 7732 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7733 } 7734 7735 static bool requiresParensToAddCast(const Expr *E) { 7736 // FIXME: We should have a general way to reason about operator 7737 // precedence and whether parens are actually needed here. 7738 // Take care of a few common cases where they aren't. 7739 const Expr *Inside = E->IgnoreImpCasts(); 7740 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7741 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7742 7743 switch (Inside->getStmtClass()) { 7744 case Stmt::ArraySubscriptExprClass: 7745 case Stmt::CallExprClass: 7746 case Stmt::CharacterLiteralClass: 7747 case Stmt::CXXBoolLiteralExprClass: 7748 case Stmt::DeclRefExprClass: 7749 case Stmt::FloatingLiteralClass: 7750 case Stmt::IntegerLiteralClass: 7751 case Stmt::MemberExprClass: 7752 case Stmt::ObjCArrayLiteralClass: 7753 case Stmt::ObjCBoolLiteralExprClass: 7754 case Stmt::ObjCBoxedExprClass: 7755 case Stmt::ObjCDictionaryLiteralClass: 7756 case Stmt::ObjCEncodeExprClass: 7757 case Stmt::ObjCIvarRefExprClass: 7758 case Stmt::ObjCMessageExprClass: 7759 case Stmt::ObjCPropertyRefExprClass: 7760 case Stmt::ObjCStringLiteralClass: 7761 case Stmt::ObjCSubscriptRefExprClass: 7762 case Stmt::ParenExprClass: 7763 case Stmt::StringLiteralClass: 7764 case Stmt::UnaryOperatorClass: 7765 return false; 7766 default: 7767 return true; 7768 } 7769 } 7770 7771 static std::pair<QualType, StringRef> 7772 shouldNotPrintDirectly(const ASTContext &Context, 7773 QualType IntendedTy, 7774 const Expr *E) { 7775 // Use a 'while' to peel off layers of typedefs. 7776 QualType TyTy = IntendedTy; 7777 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7778 StringRef Name = UserTy->getDecl()->getName(); 7779 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7780 .Case("CFIndex", Context.getNSIntegerType()) 7781 .Case("NSInteger", Context.getNSIntegerType()) 7782 .Case("NSUInteger", Context.getNSUIntegerType()) 7783 .Case("SInt32", Context.IntTy) 7784 .Case("UInt32", Context.UnsignedIntTy) 7785 .Default(QualType()); 7786 7787 if (!CastTy.isNull()) 7788 return std::make_pair(CastTy, Name); 7789 7790 TyTy = UserTy->desugar(); 7791 } 7792 7793 // Strip parens if necessary. 7794 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7795 return shouldNotPrintDirectly(Context, 7796 PE->getSubExpr()->getType(), 7797 PE->getSubExpr()); 7798 7799 // If this is a conditional expression, then its result type is constructed 7800 // via usual arithmetic conversions and thus there might be no necessary 7801 // typedef sugar there. Recurse to operands to check for NSInteger & 7802 // Co. usage condition. 7803 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7804 QualType TrueTy, FalseTy; 7805 StringRef TrueName, FalseName; 7806 7807 std::tie(TrueTy, TrueName) = 7808 shouldNotPrintDirectly(Context, 7809 CO->getTrueExpr()->getType(), 7810 CO->getTrueExpr()); 7811 std::tie(FalseTy, FalseName) = 7812 shouldNotPrintDirectly(Context, 7813 CO->getFalseExpr()->getType(), 7814 CO->getFalseExpr()); 7815 7816 if (TrueTy == FalseTy) 7817 return std::make_pair(TrueTy, TrueName); 7818 else if (TrueTy.isNull()) 7819 return std::make_pair(FalseTy, FalseName); 7820 else if (FalseTy.isNull()) 7821 return std::make_pair(TrueTy, TrueName); 7822 } 7823 7824 return std::make_pair(QualType(), StringRef()); 7825 } 7826 7827 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7828 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7829 /// type do not count. 7830 static bool 7831 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7832 QualType From = ICE->getSubExpr()->getType(); 7833 QualType To = ICE->getType(); 7834 // It's an integer promotion if the destination type is the promoted 7835 // source type. 7836 if (ICE->getCastKind() == CK_IntegralCast && 7837 From->isPromotableIntegerType() && 7838 S.Context.getPromotedIntegerType(From) == To) 7839 return true; 7840 // Look through vector types, since we do default argument promotion for 7841 // those in OpenCL. 7842 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7843 From = VecTy->getElementType(); 7844 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7845 To = VecTy->getElementType(); 7846 // It's a floating promotion if the source type is a lower rank. 7847 return ICE->getCastKind() == CK_FloatingCast && 7848 S.Context.getFloatingTypeOrder(From, To) < 0; 7849 } 7850 7851 bool 7852 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7853 const char *StartSpecifier, 7854 unsigned SpecifierLen, 7855 const Expr *E) { 7856 using namespace analyze_format_string; 7857 using namespace analyze_printf; 7858 7859 // Now type check the data expression that matches the 7860 // format specifier. 7861 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7862 if (!AT.isValid()) 7863 return true; 7864 7865 QualType ExprTy = E->getType(); 7866 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7867 ExprTy = TET->getUnderlyingExpr()->getType(); 7868 } 7869 7870 // Diagnose attempts to print a boolean value as a character. Unlike other 7871 // -Wformat diagnostics, this is fine from a type perspective, but it still 7872 // doesn't make sense. 7873 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 7874 E->isKnownToHaveBooleanValue()) { 7875 const CharSourceRange &CSR = 7876 getSpecifierRange(StartSpecifier, SpecifierLen); 7877 SmallString<4> FSString; 7878 llvm::raw_svector_ostream os(FSString); 7879 FS.toString(os); 7880 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 7881 << FSString, 7882 E->getExprLoc(), false, CSR); 7883 return true; 7884 } 7885 7886 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 7887 if (Match == analyze_printf::ArgType::Match) 7888 return true; 7889 7890 // Look through argument promotions for our error message's reported type. 7891 // This includes the integral and floating promotions, but excludes array 7892 // and function pointer decay (seeing that an argument intended to be a 7893 // string has type 'char [6]' is probably more confusing than 'char *') and 7894 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7896 if (isArithmeticArgumentPromotion(S, ICE)) { 7897 E = ICE->getSubExpr(); 7898 ExprTy = E->getType(); 7899 7900 // Check if we didn't match because of an implicit cast from a 'char' 7901 // or 'short' to an 'int'. This is done because printf is a varargs 7902 // function. 7903 if (ICE->getType() == S.Context.IntTy || 7904 ICE->getType() == S.Context.UnsignedIntTy) { 7905 // All further checking is done on the subexpression 7906 const analyze_printf::ArgType::MatchKind ImplicitMatch = 7907 AT.matchesType(S.Context, ExprTy); 7908 if (ImplicitMatch == analyze_printf::ArgType::Match) 7909 return true; 7910 if (ImplicitMatch == ArgType::NoMatchPedantic || 7911 ImplicitMatch == ArgType::NoMatchTypeConfusion) 7912 Match = ImplicitMatch; 7913 } 7914 } 7915 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7916 // Special case for 'a', which has type 'int' in C. 7917 // Note, however, that we do /not/ want to treat multibyte constants like 7918 // 'MooV' as characters! This form is deprecated but still exists. 7919 if (ExprTy == S.Context.IntTy) 7920 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 7921 ExprTy = S.Context.CharTy; 7922 } 7923 7924 // Look through enums to their underlying type. 7925 bool IsEnum = false; 7926 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7927 ExprTy = EnumTy->getDecl()->getIntegerType(); 7928 IsEnum = true; 7929 } 7930 7931 // %C in an Objective-C context prints a unichar, not a wchar_t. 7932 // If the argument is an integer of some kind, believe the %C and suggest 7933 // a cast instead of changing the conversion specifier. 7934 QualType IntendedTy = ExprTy; 7935 if (isObjCContext() && 7936 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7937 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7938 !ExprTy->isCharType()) { 7939 // 'unichar' is defined as a typedef of unsigned short, but we should 7940 // prefer using the typedef if it is visible. 7941 IntendedTy = S.Context.UnsignedShortTy; 7942 7943 // While we are here, check if the value is an IntegerLiteral that happens 7944 // to be within the valid range. 7945 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7946 const llvm::APInt &V = IL->getValue(); 7947 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7948 return true; 7949 } 7950 7951 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7952 Sema::LookupOrdinaryName); 7953 if (S.LookupName(Result, S.getCurScope())) { 7954 NamedDecl *ND = Result.getFoundDecl(); 7955 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7956 if (TD->getUnderlyingType() == IntendedTy) 7957 IntendedTy = S.Context.getTypedefType(TD); 7958 } 7959 } 7960 } 7961 7962 // Special-case some of Darwin's platform-independence types by suggesting 7963 // casts to primitive types that are known to be large enough. 7964 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7965 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7966 QualType CastTy; 7967 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7968 if (!CastTy.isNull()) { 7969 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7970 // (long in ASTContext). Only complain to pedants. 7971 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7972 (AT.isSizeT() || AT.isPtrdiffT()) && 7973 AT.matchesType(S.Context, CastTy)) 7974 Match = ArgType::NoMatchPedantic; 7975 IntendedTy = CastTy; 7976 ShouldNotPrintDirectly = true; 7977 } 7978 } 7979 7980 // We may be able to offer a FixItHint if it is a supported type. 7981 PrintfSpecifier fixedFS = FS; 7982 bool Success = 7983 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7984 7985 if (Success) { 7986 // Get the fix string from the fixed format specifier 7987 SmallString<16> buf; 7988 llvm::raw_svector_ostream os(buf); 7989 fixedFS.toString(os); 7990 7991 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7992 7993 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 7994 unsigned Diag; 7995 switch (Match) { 7996 case ArgType::Match: llvm_unreachable("expected non-matching"); 7997 case ArgType::NoMatchPedantic: 7998 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 7999 break; 8000 case ArgType::NoMatchTypeConfusion: 8001 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8002 break; 8003 case ArgType::NoMatch: 8004 Diag = diag::warn_format_conversion_argument_type_mismatch; 8005 break; 8006 } 8007 8008 // In this case, the specifier is wrong and should be changed to match 8009 // the argument. 8010 EmitFormatDiagnostic(S.PDiag(Diag) 8011 << AT.getRepresentativeTypeName(S.Context) 8012 << IntendedTy << IsEnum << E->getSourceRange(), 8013 E->getBeginLoc(), 8014 /*IsStringLocation*/ false, SpecRange, 8015 FixItHint::CreateReplacement(SpecRange, os.str())); 8016 } else { 8017 // The canonical type for formatting this value is different from the 8018 // actual type of the expression. (This occurs, for example, with Darwin's 8019 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8020 // should be printed as 'long' for 64-bit compatibility.) 8021 // Rather than emitting a normal format/argument mismatch, we want to 8022 // add a cast to the recommended type (and correct the format string 8023 // if necessary). 8024 SmallString<16> CastBuf; 8025 llvm::raw_svector_ostream CastFix(CastBuf); 8026 CastFix << "("; 8027 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8028 CastFix << ")"; 8029 8030 SmallVector<FixItHint,4> Hints; 8031 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8032 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8033 8034 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8035 // If there's already a cast present, just replace it. 8036 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8037 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8038 8039 } else if (!requiresParensToAddCast(E)) { 8040 // If the expression has high enough precedence, 8041 // just write the C-style cast. 8042 Hints.push_back( 8043 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8044 } else { 8045 // Otherwise, add parens around the expression as well as the cast. 8046 CastFix << "("; 8047 Hints.push_back( 8048 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8049 8050 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8051 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8052 } 8053 8054 if (ShouldNotPrintDirectly) { 8055 // The expression has a type that should not be printed directly. 8056 // We extract the name from the typedef because we don't want to show 8057 // the underlying type in the diagnostic. 8058 StringRef Name; 8059 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8060 Name = TypedefTy->getDecl()->getName(); 8061 else 8062 Name = CastTyName; 8063 unsigned Diag = Match == ArgType::NoMatchPedantic 8064 ? diag::warn_format_argument_needs_cast_pedantic 8065 : diag::warn_format_argument_needs_cast; 8066 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8067 << E->getSourceRange(), 8068 E->getBeginLoc(), /*IsStringLocation=*/false, 8069 SpecRange, Hints); 8070 } else { 8071 // In this case, the expression could be printed using a different 8072 // specifier, but we've decided that the specifier is probably correct 8073 // and we should cast instead. Just use the normal warning message. 8074 EmitFormatDiagnostic( 8075 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8076 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8077 << E->getSourceRange(), 8078 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8079 } 8080 } 8081 } else { 8082 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8083 SpecifierLen); 8084 // Since the warning for passing non-POD types to variadic functions 8085 // was deferred until now, we emit a warning for non-POD 8086 // arguments here. 8087 switch (S.isValidVarArgType(ExprTy)) { 8088 case Sema::VAK_Valid: 8089 case Sema::VAK_ValidInCXX11: { 8090 unsigned Diag; 8091 switch (Match) { 8092 case ArgType::Match: llvm_unreachable("expected non-matching"); 8093 case ArgType::NoMatchPedantic: 8094 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8095 break; 8096 case ArgType::NoMatchTypeConfusion: 8097 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8098 break; 8099 case ArgType::NoMatch: 8100 Diag = diag::warn_format_conversion_argument_type_mismatch; 8101 break; 8102 } 8103 8104 EmitFormatDiagnostic( 8105 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8106 << IsEnum << CSR << E->getSourceRange(), 8107 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8108 break; 8109 } 8110 case Sema::VAK_Undefined: 8111 case Sema::VAK_MSVCUndefined: 8112 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8113 << S.getLangOpts().CPlusPlus11 << ExprTy 8114 << CallType 8115 << AT.getRepresentativeTypeName(S.Context) << CSR 8116 << E->getSourceRange(), 8117 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8118 checkForCStrMembers(AT, E); 8119 break; 8120 8121 case Sema::VAK_Invalid: 8122 if (ExprTy->isObjCObjectType()) 8123 EmitFormatDiagnostic( 8124 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8125 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8126 << AT.getRepresentativeTypeName(S.Context) << CSR 8127 << E->getSourceRange(), 8128 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8129 else 8130 // FIXME: If this is an initializer list, suggest removing the braces 8131 // or inserting a cast to the target type. 8132 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8133 << isa<InitListExpr>(E) << ExprTy << CallType 8134 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8135 break; 8136 } 8137 8138 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8139 "format string specifier index out of range"); 8140 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8141 } 8142 8143 return true; 8144 } 8145 8146 //===--- CHECK: Scanf format string checking ------------------------------===// 8147 8148 namespace { 8149 8150 class CheckScanfHandler : public CheckFormatHandler { 8151 public: 8152 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8153 const Expr *origFormatExpr, Sema::FormatStringType type, 8154 unsigned firstDataArg, unsigned numDataArgs, 8155 const char *beg, bool hasVAListArg, 8156 ArrayRef<const Expr *> Args, unsigned formatIdx, 8157 bool inFunctionCall, Sema::VariadicCallType CallType, 8158 llvm::SmallBitVector &CheckedVarArgs, 8159 UncoveredArgHandler &UncoveredArg) 8160 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8161 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8162 inFunctionCall, CallType, CheckedVarArgs, 8163 UncoveredArg) {} 8164 8165 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8166 const char *startSpecifier, 8167 unsigned specifierLen) override; 8168 8169 bool HandleInvalidScanfConversionSpecifier( 8170 const analyze_scanf::ScanfSpecifier &FS, 8171 const char *startSpecifier, 8172 unsigned specifierLen) override; 8173 8174 void HandleIncompleteScanList(const char *start, const char *end) override; 8175 }; 8176 8177 } // namespace 8178 8179 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8180 const char *end) { 8181 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8182 getLocationOfByte(end), /*IsStringLocation*/true, 8183 getSpecifierRange(start, end - start)); 8184 } 8185 8186 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8187 const analyze_scanf::ScanfSpecifier &FS, 8188 const char *startSpecifier, 8189 unsigned specifierLen) { 8190 const analyze_scanf::ScanfConversionSpecifier &CS = 8191 FS.getConversionSpecifier(); 8192 8193 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8194 getLocationOfByte(CS.getStart()), 8195 startSpecifier, specifierLen, 8196 CS.getStart(), CS.getLength()); 8197 } 8198 8199 bool CheckScanfHandler::HandleScanfSpecifier( 8200 const analyze_scanf::ScanfSpecifier &FS, 8201 const char *startSpecifier, 8202 unsigned specifierLen) { 8203 using namespace analyze_scanf; 8204 using namespace analyze_format_string; 8205 8206 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8207 8208 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8209 // be used to decide if we are using positional arguments consistently. 8210 if (FS.consumesDataArgument()) { 8211 if (atFirstArg) { 8212 atFirstArg = false; 8213 usesPositionalArgs = FS.usesPositionalArg(); 8214 } 8215 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8216 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8217 startSpecifier, specifierLen); 8218 return false; 8219 } 8220 } 8221 8222 // Check if the field with is non-zero. 8223 const OptionalAmount &Amt = FS.getFieldWidth(); 8224 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8225 if (Amt.getConstantAmount() == 0) { 8226 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8227 Amt.getConstantLength()); 8228 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8229 getLocationOfByte(Amt.getStart()), 8230 /*IsStringLocation*/true, R, 8231 FixItHint::CreateRemoval(R)); 8232 } 8233 } 8234 8235 if (!FS.consumesDataArgument()) { 8236 // FIXME: Technically specifying a precision or field width here 8237 // makes no sense. Worth issuing a warning at some point. 8238 return true; 8239 } 8240 8241 // Consume the argument. 8242 unsigned argIndex = FS.getArgIndex(); 8243 if (argIndex < NumDataArgs) { 8244 // The check to see if the argIndex is valid will come later. 8245 // We set the bit here because we may exit early from this 8246 // function if we encounter some other error. 8247 CoveredArgs.set(argIndex); 8248 } 8249 8250 // Check the length modifier is valid with the given conversion specifier. 8251 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8252 S.getLangOpts())) 8253 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8254 diag::warn_format_nonsensical_length); 8255 else if (!FS.hasStandardLengthModifier()) 8256 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8257 else if (!FS.hasStandardLengthConversionCombination()) 8258 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8259 diag::warn_format_non_standard_conversion_spec); 8260 8261 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8262 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8263 8264 // The remaining checks depend on the data arguments. 8265 if (HasVAListArg) 8266 return true; 8267 8268 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8269 return false; 8270 8271 // Check that the argument type matches the format specifier. 8272 const Expr *Ex = getDataArg(argIndex); 8273 if (!Ex) 8274 return true; 8275 8276 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8277 8278 if (!AT.isValid()) { 8279 return true; 8280 } 8281 8282 analyze_format_string::ArgType::MatchKind Match = 8283 AT.matchesType(S.Context, Ex->getType()); 8284 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8285 if (Match == analyze_format_string::ArgType::Match) 8286 return true; 8287 8288 ScanfSpecifier fixedFS = FS; 8289 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8290 S.getLangOpts(), S.Context); 8291 8292 unsigned Diag = 8293 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8294 : diag::warn_format_conversion_argument_type_mismatch; 8295 8296 if (Success) { 8297 // Get the fix string from the fixed format specifier. 8298 SmallString<128> buf; 8299 llvm::raw_svector_ostream os(buf); 8300 fixedFS.toString(os); 8301 8302 EmitFormatDiagnostic( 8303 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8304 << Ex->getType() << false << Ex->getSourceRange(), 8305 Ex->getBeginLoc(), 8306 /*IsStringLocation*/ false, 8307 getSpecifierRange(startSpecifier, specifierLen), 8308 FixItHint::CreateReplacement( 8309 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8310 } else { 8311 EmitFormatDiagnostic(S.PDiag(Diag) 8312 << AT.getRepresentativeTypeName(S.Context) 8313 << Ex->getType() << false << Ex->getSourceRange(), 8314 Ex->getBeginLoc(), 8315 /*IsStringLocation*/ false, 8316 getSpecifierRange(startSpecifier, specifierLen)); 8317 } 8318 8319 return true; 8320 } 8321 8322 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8323 const Expr *OrigFormatExpr, 8324 ArrayRef<const Expr *> Args, 8325 bool HasVAListArg, unsigned format_idx, 8326 unsigned firstDataArg, 8327 Sema::FormatStringType Type, 8328 bool inFunctionCall, 8329 Sema::VariadicCallType CallType, 8330 llvm::SmallBitVector &CheckedVarArgs, 8331 UncoveredArgHandler &UncoveredArg, 8332 bool IgnoreStringsWithoutSpecifiers) { 8333 // CHECK: is the format string a wide literal? 8334 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8335 CheckFormatHandler::EmitFormatDiagnostic( 8336 S, inFunctionCall, Args[format_idx], 8337 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8338 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8339 return; 8340 } 8341 8342 // Str - The format string. NOTE: this is NOT null-terminated! 8343 StringRef StrRef = FExpr->getString(); 8344 const char *Str = StrRef.data(); 8345 // Account for cases where the string literal is truncated in a declaration. 8346 const ConstantArrayType *T = 8347 S.Context.getAsConstantArrayType(FExpr->getType()); 8348 assert(T && "String literal not of constant array type!"); 8349 size_t TypeSize = T->getSize().getZExtValue(); 8350 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8351 const unsigned numDataArgs = Args.size() - firstDataArg; 8352 8353 if (IgnoreStringsWithoutSpecifiers && 8354 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8355 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8356 return; 8357 8358 // Emit a warning if the string literal is truncated and does not contain an 8359 // embedded null character. 8360 if (TypeSize <= StrRef.size() && 8361 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8362 CheckFormatHandler::EmitFormatDiagnostic( 8363 S, inFunctionCall, Args[format_idx], 8364 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8365 FExpr->getBeginLoc(), 8366 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8367 return; 8368 } 8369 8370 // CHECK: empty format string? 8371 if (StrLen == 0 && numDataArgs > 0) { 8372 CheckFormatHandler::EmitFormatDiagnostic( 8373 S, inFunctionCall, Args[format_idx], 8374 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8375 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8376 return; 8377 } 8378 8379 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8380 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8381 Type == Sema::FST_OSTrace) { 8382 CheckPrintfHandler H( 8383 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8384 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8385 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8386 CheckedVarArgs, UncoveredArg); 8387 8388 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8389 S.getLangOpts(), 8390 S.Context.getTargetInfo(), 8391 Type == Sema::FST_FreeBSDKPrintf)) 8392 H.DoneProcessing(); 8393 } else if (Type == Sema::FST_Scanf) { 8394 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8395 numDataArgs, Str, HasVAListArg, Args, format_idx, 8396 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8397 8398 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8399 S.getLangOpts(), 8400 S.Context.getTargetInfo())) 8401 H.DoneProcessing(); 8402 } // TODO: handle other formats 8403 } 8404 8405 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8406 // Str - The format string. NOTE: this is NOT null-terminated! 8407 StringRef StrRef = FExpr->getString(); 8408 const char *Str = StrRef.data(); 8409 // Account for cases where the string literal is truncated in a declaration. 8410 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8411 assert(T && "String literal not of constant array type!"); 8412 size_t TypeSize = T->getSize().getZExtValue(); 8413 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8414 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8415 getLangOpts(), 8416 Context.getTargetInfo()); 8417 } 8418 8419 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8420 8421 // Returns the related absolute value function that is larger, of 0 if one 8422 // does not exist. 8423 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8424 switch (AbsFunction) { 8425 default: 8426 return 0; 8427 8428 case Builtin::BI__builtin_abs: 8429 return Builtin::BI__builtin_labs; 8430 case Builtin::BI__builtin_labs: 8431 return Builtin::BI__builtin_llabs; 8432 case Builtin::BI__builtin_llabs: 8433 return 0; 8434 8435 case Builtin::BI__builtin_fabsf: 8436 return Builtin::BI__builtin_fabs; 8437 case Builtin::BI__builtin_fabs: 8438 return Builtin::BI__builtin_fabsl; 8439 case Builtin::BI__builtin_fabsl: 8440 return 0; 8441 8442 case Builtin::BI__builtin_cabsf: 8443 return Builtin::BI__builtin_cabs; 8444 case Builtin::BI__builtin_cabs: 8445 return Builtin::BI__builtin_cabsl; 8446 case Builtin::BI__builtin_cabsl: 8447 return 0; 8448 8449 case Builtin::BIabs: 8450 return Builtin::BIlabs; 8451 case Builtin::BIlabs: 8452 return Builtin::BIllabs; 8453 case Builtin::BIllabs: 8454 return 0; 8455 8456 case Builtin::BIfabsf: 8457 return Builtin::BIfabs; 8458 case Builtin::BIfabs: 8459 return Builtin::BIfabsl; 8460 case Builtin::BIfabsl: 8461 return 0; 8462 8463 case Builtin::BIcabsf: 8464 return Builtin::BIcabs; 8465 case Builtin::BIcabs: 8466 return Builtin::BIcabsl; 8467 case Builtin::BIcabsl: 8468 return 0; 8469 } 8470 } 8471 8472 // Returns the argument type of the absolute value function. 8473 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8474 unsigned AbsType) { 8475 if (AbsType == 0) 8476 return QualType(); 8477 8478 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8479 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8480 if (Error != ASTContext::GE_None) 8481 return QualType(); 8482 8483 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8484 if (!FT) 8485 return QualType(); 8486 8487 if (FT->getNumParams() != 1) 8488 return QualType(); 8489 8490 return FT->getParamType(0); 8491 } 8492 8493 // Returns the best absolute value function, or zero, based on type and 8494 // current absolute value function. 8495 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8496 unsigned AbsFunctionKind) { 8497 unsigned BestKind = 0; 8498 uint64_t ArgSize = Context.getTypeSize(ArgType); 8499 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8500 Kind = getLargerAbsoluteValueFunction(Kind)) { 8501 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8502 if (Context.getTypeSize(ParamType) >= ArgSize) { 8503 if (BestKind == 0) 8504 BestKind = Kind; 8505 else if (Context.hasSameType(ParamType, ArgType)) { 8506 BestKind = Kind; 8507 break; 8508 } 8509 } 8510 } 8511 return BestKind; 8512 } 8513 8514 enum AbsoluteValueKind { 8515 AVK_Integer, 8516 AVK_Floating, 8517 AVK_Complex 8518 }; 8519 8520 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8521 if (T->isIntegralOrEnumerationType()) 8522 return AVK_Integer; 8523 if (T->isRealFloatingType()) 8524 return AVK_Floating; 8525 if (T->isAnyComplexType()) 8526 return AVK_Complex; 8527 8528 llvm_unreachable("Type not integer, floating, or complex"); 8529 } 8530 8531 // Changes the absolute value function to a different type. Preserves whether 8532 // the function is a builtin. 8533 static unsigned changeAbsFunction(unsigned AbsKind, 8534 AbsoluteValueKind ValueKind) { 8535 switch (ValueKind) { 8536 case AVK_Integer: 8537 switch (AbsKind) { 8538 default: 8539 return 0; 8540 case Builtin::BI__builtin_fabsf: 8541 case Builtin::BI__builtin_fabs: 8542 case Builtin::BI__builtin_fabsl: 8543 case Builtin::BI__builtin_cabsf: 8544 case Builtin::BI__builtin_cabs: 8545 case Builtin::BI__builtin_cabsl: 8546 return Builtin::BI__builtin_abs; 8547 case Builtin::BIfabsf: 8548 case Builtin::BIfabs: 8549 case Builtin::BIfabsl: 8550 case Builtin::BIcabsf: 8551 case Builtin::BIcabs: 8552 case Builtin::BIcabsl: 8553 return Builtin::BIabs; 8554 } 8555 case AVK_Floating: 8556 switch (AbsKind) { 8557 default: 8558 return 0; 8559 case Builtin::BI__builtin_abs: 8560 case Builtin::BI__builtin_labs: 8561 case Builtin::BI__builtin_llabs: 8562 case Builtin::BI__builtin_cabsf: 8563 case Builtin::BI__builtin_cabs: 8564 case Builtin::BI__builtin_cabsl: 8565 return Builtin::BI__builtin_fabsf; 8566 case Builtin::BIabs: 8567 case Builtin::BIlabs: 8568 case Builtin::BIllabs: 8569 case Builtin::BIcabsf: 8570 case Builtin::BIcabs: 8571 case Builtin::BIcabsl: 8572 return Builtin::BIfabsf; 8573 } 8574 case AVK_Complex: 8575 switch (AbsKind) { 8576 default: 8577 return 0; 8578 case Builtin::BI__builtin_abs: 8579 case Builtin::BI__builtin_labs: 8580 case Builtin::BI__builtin_llabs: 8581 case Builtin::BI__builtin_fabsf: 8582 case Builtin::BI__builtin_fabs: 8583 case Builtin::BI__builtin_fabsl: 8584 return Builtin::BI__builtin_cabsf; 8585 case Builtin::BIabs: 8586 case Builtin::BIlabs: 8587 case Builtin::BIllabs: 8588 case Builtin::BIfabsf: 8589 case Builtin::BIfabs: 8590 case Builtin::BIfabsl: 8591 return Builtin::BIcabsf; 8592 } 8593 } 8594 llvm_unreachable("Unable to convert function"); 8595 } 8596 8597 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8598 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8599 if (!FnInfo) 8600 return 0; 8601 8602 switch (FDecl->getBuiltinID()) { 8603 default: 8604 return 0; 8605 case Builtin::BI__builtin_abs: 8606 case Builtin::BI__builtin_fabs: 8607 case Builtin::BI__builtin_fabsf: 8608 case Builtin::BI__builtin_fabsl: 8609 case Builtin::BI__builtin_labs: 8610 case Builtin::BI__builtin_llabs: 8611 case Builtin::BI__builtin_cabs: 8612 case Builtin::BI__builtin_cabsf: 8613 case Builtin::BI__builtin_cabsl: 8614 case Builtin::BIabs: 8615 case Builtin::BIlabs: 8616 case Builtin::BIllabs: 8617 case Builtin::BIfabs: 8618 case Builtin::BIfabsf: 8619 case Builtin::BIfabsl: 8620 case Builtin::BIcabs: 8621 case Builtin::BIcabsf: 8622 case Builtin::BIcabsl: 8623 return FDecl->getBuiltinID(); 8624 } 8625 llvm_unreachable("Unknown Builtin type"); 8626 } 8627 8628 // If the replacement is valid, emit a note with replacement function. 8629 // Additionally, suggest including the proper header if not already included. 8630 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8631 unsigned AbsKind, QualType ArgType) { 8632 bool EmitHeaderHint = true; 8633 const char *HeaderName = nullptr; 8634 const char *FunctionName = nullptr; 8635 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8636 FunctionName = "std::abs"; 8637 if (ArgType->isIntegralOrEnumerationType()) { 8638 HeaderName = "cstdlib"; 8639 } else if (ArgType->isRealFloatingType()) { 8640 HeaderName = "cmath"; 8641 } else { 8642 llvm_unreachable("Invalid Type"); 8643 } 8644 8645 // Lookup all std::abs 8646 if (NamespaceDecl *Std = S.getStdNamespace()) { 8647 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8648 R.suppressDiagnostics(); 8649 S.LookupQualifiedName(R, Std); 8650 8651 for (const auto *I : R) { 8652 const FunctionDecl *FDecl = nullptr; 8653 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8654 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8655 } else { 8656 FDecl = dyn_cast<FunctionDecl>(I); 8657 } 8658 if (!FDecl) 8659 continue; 8660 8661 // Found std::abs(), check that they are the right ones. 8662 if (FDecl->getNumParams() != 1) 8663 continue; 8664 8665 // Check that the parameter type can handle the argument. 8666 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8667 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8668 S.Context.getTypeSize(ArgType) <= 8669 S.Context.getTypeSize(ParamType)) { 8670 // Found a function, don't need the header hint. 8671 EmitHeaderHint = false; 8672 break; 8673 } 8674 } 8675 } 8676 } else { 8677 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8678 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8679 8680 if (HeaderName) { 8681 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8682 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8683 R.suppressDiagnostics(); 8684 S.LookupName(R, S.getCurScope()); 8685 8686 if (R.isSingleResult()) { 8687 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8688 if (FD && FD->getBuiltinID() == AbsKind) { 8689 EmitHeaderHint = false; 8690 } else { 8691 return; 8692 } 8693 } else if (!R.empty()) { 8694 return; 8695 } 8696 } 8697 } 8698 8699 S.Diag(Loc, diag::note_replace_abs_function) 8700 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8701 8702 if (!HeaderName) 8703 return; 8704 8705 if (!EmitHeaderHint) 8706 return; 8707 8708 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8709 << FunctionName; 8710 } 8711 8712 template <std::size_t StrLen> 8713 static bool IsStdFunction(const FunctionDecl *FDecl, 8714 const char (&Str)[StrLen]) { 8715 if (!FDecl) 8716 return false; 8717 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8718 return false; 8719 if (!FDecl->isInStdNamespace()) 8720 return false; 8721 8722 return true; 8723 } 8724 8725 // Warn when using the wrong abs() function. 8726 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8727 const FunctionDecl *FDecl) { 8728 if (Call->getNumArgs() != 1) 8729 return; 8730 8731 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8732 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8733 if (AbsKind == 0 && !IsStdAbs) 8734 return; 8735 8736 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8737 QualType ParamType = Call->getArg(0)->getType(); 8738 8739 // Unsigned types cannot be negative. Suggest removing the absolute value 8740 // function call. 8741 if (ArgType->isUnsignedIntegerType()) { 8742 const char *FunctionName = 8743 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8744 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8745 Diag(Call->getExprLoc(), diag::note_remove_abs) 8746 << FunctionName 8747 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8748 return; 8749 } 8750 8751 // Taking the absolute value of a pointer is very suspicious, they probably 8752 // wanted to index into an array, dereference a pointer, call a function, etc. 8753 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8754 unsigned DiagType = 0; 8755 if (ArgType->isFunctionType()) 8756 DiagType = 1; 8757 else if (ArgType->isArrayType()) 8758 DiagType = 2; 8759 8760 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8761 return; 8762 } 8763 8764 // std::abs has overloads which prevent most of the absolute value problems 8765 // from occurring. 8766 if (IsStdAbs) 8767 return; 8768 8769 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8770 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8771 8772 // The argument and parameter are the same kind. Check if they are the right 8773 // size. 8774 if (ArgValueKind == ParamValueKind) { 8775 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8776 return; 8777 8778 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8779 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8780 << FDecl << ArgType << ParamType; 8781 8782 if (NewAbsKind == 0) 8783 return; 8784 8785 emitReplacement(*this, Call->getExprLoc(), 8786 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8787 return; 8788 } 8789 8790 // ArgValueKind != ParamValueKind 8791 // The wrong type of absolute value function was used. Attempt to find the 8792 // proper one. 8793 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8794 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8795 if (NewAbsKind == 0) 8796 return; 8797 8798 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8799 << FDecl << ParamValueKind << ArgValueKind; 8800 8801 emitReplacement(*this, Call->getExprLoc(), 8802 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8803 } 8804 8805 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8806 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8807 const FunctionDecl *FDecl) { 8808 if (!Call || !FDecl) return; 8809 8810 // Ignore template specializations and macros. 8811 if (inTemplateInstantiation()) return; 8812 if (Call->getExprLoc().isMacroID()) return; 8813 8814 // Only care about the one template argument, two function parameter std::max 8815 if (Call->getNumArgs() != 2) return; 8816 if (!IsStdFunction(FDecl, "max")) return; 8817 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8818 if (!ArgList) return; 8819 if (ArgList->size() != 1) return; 8820 8821 // Check that template type argument is unsigned integer. 8822 const auto& TA = ArgList->get(0); 8823 if (TA.getKind() != TemplateArgument::Type) return; 8824 QualType ArgType = TA.getAsType(); 8825 if (!ArgType->isUnsignedIntegerType()) return; 8826 8827 // See if either argument is a literal zero. 8828 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8829 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8830 if (!MTE) return false; 8831 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 8832 if (!Num) return false; 8833 if (Num->getValue() != 0) return false; 8834 return true; 8835 }; 8836 8837 const Expr *FirstArg = Call->getArg(0); 8838 const Expr *SecondArg = Call->getArg(1); 8839 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8840 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8841 8842 // Only warn when exactly one argument is zero. 8843 if (IsFirstArgZero == IsSecondArgZero) return; 8844 8845 SourceRange FirstRange = FirstArg->getSourceRange(); 8846 SourceRange SecondRange = SecondArg->getSourceRange(); 8847 8848 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8849 8850 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8851 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8852 8853 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8854 SourceRange RemovalRange; 8855 if (IsFirstArgZero) { 8856 RemovalRange = SourceRange(FirstRange.getBegin(), 8857 SecondRange.getBegin().getLocWithOffset(-1)); 8858 } else { 8859 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8860 SecondRange.getEnd()); 8861 } 8862 8863 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8864 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8865 << FixItHint::CreateRemoval(RemovalRange); 8866 } 8867 8868 //===--- CHECK: Standard memory functions ---------------------------------===// 8869 8870 /// Takes the expression passed to the size_t parameter of functions 8871 /// such as memcmp, strncat, etc and warns if it's a comparison. 8872 /// 8873 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8874 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8875 IdentifierInfo *FnName, 8876 SourceLocation FnLoc, 8877 SourceLocation RParenLoc) { 8878 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8879 if (!Size) 8880 return false; 8881 8882 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8883 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8884 return false; 8885 8886 SourceRange SizeRange = Size->getSourceRange(); 8887 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8888 << SizeRange << FnName; 8889 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8890 << FnName 8891 << FixItHint::CreateInsertion( 8892 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8893 << FixItHint::CreateRemoval(RParenLoc); 8894 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8895 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8896 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8897 ")"); 8898 8899 return true; 8900 } 8901 8902 /// Determine whether the given type is or contains a dynamic class type 8903 /// (e.g., whether it has a vtable). 8904 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8905 bool &IsContained) { 8906 // Look through array types while ignoring qualifiers. 8907 const Type *Ty = T->getBaseElementTypeUnsafe(); 8908 IsContained = false; 8909 8910 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8911 RD = RD ? RD->getDefinition() : nullptr; 8912 if (!RD || RD->isInvalidDecl()) 8913 return nullptr; 8914 8915 if (RD->isDynamicClass()) 8916 return RD; 8917 8918 // Check all the fields. If any bases were dynamic, the class is dynamic. 8919 // It's impossible for a class to transitively contain itself by value, so 8920 // infinite recursion is impossible. 8921 for (auto *FD : RD->fields()) { 8922 bool SubContained; 8923 if (const CXXRecordDecl *ContainedRD = 8924 getContainedDynamicClass(FD->getType(), SubContained)) { 8925 IsContained = true; 8926 return ContainedRD; 8927 } 8928 } 8929 8930 return nullptr; 8931 } 8932 8933 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8934 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8935 if (Unary->getKind() == UETT_SizeOf) 8936 return Unary; 8937 return nullptr; 8938 } 8939 8940 /// If E is a sizeof expression, returns its argument expression, 8941 /// otherwise returns NULL. 8942 static const Expr *getSizeOfExprArg(const Expr *E) { 8943 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8944 if (!SizeOf->isArgumentType()) 8945 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8946 return nullptr; 8947 } 8948 8949 /// If E is a sizeof expression, returns its argument type. 8950 static QualType getSizeOfArgType(const Expr *E) { 8951 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8952 return SizeOf->getTypeOfArgument(); 8953 return QualType(); 8954 } 8955 8956 namespace { 8957 8958 struct SearchNonTrivialToInitializeField 8959 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8960 using Super = 8961 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8962 8963 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8964 8965 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8966 SourceLocation SL) { 8967 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8968 asDerived().visitArray(PDIK, AT, SL); 8969 return; 8970 } 8971 8972 Super::visitWithKind(PDIK, FT, SL); 8973 } 8974 8975 void visitARCStrong(QualType FT, SourceLocation SL) { 8976 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8977 } 8978 void visitARCWeak(QualType FT, SourceLocation SL) { 8979 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8980 } 8981 void visitStruct(QualType FT, SourceLocation SL) { 8982 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8983 visit(FD->getType(), FD->getLocation()); 8984 } 8985 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8986 const ArrayType *AT, SourceLocation SL) { 8987 visit(getContext().getBaseElementType(AT), SL); 8988 } 8989 void visitTrivial(QualType FT, SourceLocation SL) {} 8990 8991 static void diag(QualType RT, const Expr *E, Sema &S) { 8992 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8993 } 8994 8995 ASTContext &getContext() { return S.getASTContext(); } 8996 8997 const Expr *E; 8998 Sema &S; 8999 }; 9000 9001 struct SearchNonTrivialToCopyField 9002 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9003 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9004 9005 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9006 9007 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9008 SourceLocation SL) { 9009 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9010 asDerived().visitArray(PCK, AT, SL); 9011 return; 9012 } 9013 9014 Super::visitWithKind(PCK, FT, SL); 9015 } 9016 9017 void visitARCStrong(QualType FT, SourceLocation SL) { 9018 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9019 } 9020 void visitARCWeak(QualType FT, SourceLocation SL) { 9021 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9022 } 9023 void visitStruct(QualType FT, SourceLocation SL) { 9024 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9025 visit(FD->getType(), FD->getLocation()); 9026 } 9027 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9028 SourceLocation SL) { 9029 visit(getContext().getBaseElementType(AT), SL); 9030 } 9031 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9032 SourceLocation SL) {} 9033 void visitTrivial(QualType FT, SourceLocation SL) {} 9034 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9035 9036 static void diag(QualType RT, const Expr *E, Sema &S) { 9037 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9038 } 9039 9040 ASTContext &getContext() { return S.getASTContext(); } 9041 9042 const Expr *E; 9043 Sema &S; 9044 }; 9045 9046 } 9047 9048 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9049 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9050 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9051 9052 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9053 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9054 return false; 9055 9056 return doesExprLikelyComputeSize(BO->getLHS()) || 9057 doesExprLikelyComputeSize(BO->getRHS()); 9058 } 9059 9060 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9061 } 9062 9063 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9064 /// 9065 /// \code 9066 /// #define MACRO 0 9067 /// foo(MACRO); 9068 /// foo(0); 9069 /// \endcode 9070 /// 9071 /// This should return true for the first call to foo, but not for the second 9072 /// (regardless of whether foo is a macro or function). 9073 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9074 SourceLocation CallLoc, 9075 SourceLocation ArgLoc) { 9076 if (!CallLoc.isMacroID()) 9077 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9078 9079 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9080 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9081 } 9082 9083 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9084 /// last two arguments transposed. 9085 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9086 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9087 return; 9088 9089 const Expr *SizeArg = 9090 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9091 9092 auto isLiteralZero = [](const Expr *E) { 9093 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9094 }; 9095 9096 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9097 SourceLocation CallLoc = Call->getRParenLoc(); 9098 SourceManager &SM = S.getSourceManager(); 9099 if (isLiteralZero(SizeArg) && 9100 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9101 9102 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9103 9104 // Some platforms #define bzero to __builtin_memset. See if this is the 9105 // case, and if so, emit a better diagnostic. 9106 if (BId == Builtin::BIbzero || 9107 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9108 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9109 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9110 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9111 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9112 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9113 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9114 } 9115 return; 9116 } 9117 9118 // If the second argument to a memset is a sizeof expression and the third 9119 // isn't, this is also likely an error. This should catch 9120 // 'memset(buf, sizeof(buf), 0xff)'. 9121 if (BId == Builtin::BImemset && 9122 doesExprLikelyComputeSize(Call->getArg(1)) && 9123 !doesExprLikelyComputeSize(Call->getArg(2))) { 9124 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9125 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9126 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9127 return; 9128 } 9129 } 9130 9131 /// Check for dangerous or invalid arguments to memset(). 9132 /// 9133 /// This issues warnings on known problematic, dangerous or unspecified 9134 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9135 /// function calls. 9136 /// 9137 /// \param Call The call expression to diagnose. 9138 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9139 unsigned BId, 9140 IdentifierInfo *FnName) { 9141 assert(BId != 0); 9142 9143 // It is possible to have a non-standard definition of memset. Validate 9144 // we have enough arguments, and if not, abort further checking. 9145 unsigned ExpectedNumArgs = 9146 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9147 if (Call->getNumArgs() < ExpectedNumArgs) 9148 return; 9149 9150 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9151 BId == Builtin::BIstrndup ? 1 : 2); 9152 unsigned LenArg = 9153 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9154 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9155 9156 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9157 Call->getBeginLoc(), Call->getRParenLoc())) 9158 return; 9159 9160 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9161 CheckMemaccessSize(*this, BId, Call); 9162 9163 // We have special checking when the length is a sizeof expression. 9164 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9165 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9166 llvm::FoldingSetNodeID SizeOfArgID; 9167 9168 // Although widely used, 'bzero' is not a standard function. Be more strict 9169 // with the argument types before allowing diagnostics and only allow the 9170 // form bzero(ptr, sizeof(...)). 9171 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9172 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9173 return; 9174 9175 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9176 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9177 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9178 9179 QualType DestTy = Dest->getType(); 9180 QualType PointeeTy; 9181 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9182 PointeeTy = DestPtrTy->getPointeeType(); 9183 9184 // Never warn about void type pointers. This can be used to suppress 9185 // false positives. 9186 if (PointeeTy->isVoidType()) 9187 continue; 9188 9189 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9190 // actually comparing the expressions for equality. Because computing the 9191 // expression IDs can be expensive, we only do this if the diagnostic is 9192 // enabled. 9193 if (SizeOfArg && 9194 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9195 SizeOfArg->getExprLoc())) { 9196 // We only compute IDs for expressions if the warning is enabled, and 9197 // cache the sizeof arg's ID. 9198 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9199 SizeOfArg->Profile(SizeOfArgID, Context, true); 9200 llvm::FoldingSetNodeID DestID; 9201 Dest->Profile(DestID, Context, true); 9202 if (DestID == SizeOfArgID) { 9203 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9204 // over sizeof(src) as well. 9205 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9206 StringRef ReadableName = FnName->getName(); 9207 9208 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9209 if (UnaryOp->getOpcode() == UO_AddrOf) 9210 ActionIdx = 1; // If its an address-of operator, just remove it. 9211 if (!PointeeTy->isIncompleteType() && 9212 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9213 ActionIdx = 2; // If the pointee's size is sizeof(char), 9214 // suggest an explicit length. 9215 9216 // If the function is defined as a builtin macro, do not show macro 9217 // expansion. 9218 SourceLocation SL = SizeOfArg->getExprLoc(); 9219 SourceRange DSR = Dest->getSourceRange(); 9220 SourceRange SSR = SizeOfArg->getSourceRange(); 9221 SourceManager &SM = getSourceManager(); 9222 9223 if (SM.isMacroArgExpansion(SL)) { 9224 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9225 SL = SM.getSpellingLoc(SL); 9226 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9227 SM.getSpellingLoc(DSR.getEnd())); 9228 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9229 SM.getSpellingLoc(SSR.getEnd())); 9230 } 9231 9232 DiagRuntimeBehavior(SL, SizeOfArg, 9233 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9234 << ReadableName 9235 << PointeeTy 9236 << DestTy 9237 << DSR 9238 << SSR); 9239 DiagRuntimeBehavior(SL, SizeOfArg, 9240 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9241 << ActionIdx 9242 << SSR); 9243 9244 break; 9245 } 9246 } 9247 9248 // Also check for cases where the sizeof argument is the exact same 9249 // type as the memory argument, and where it points to a user-defined 9250 // record type. 9251 if (SizeOfArgTy != QualType()) { 9252 if (PointeeTy->isRecordType() && 9253 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9254 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9255 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9256 << FnName << SizeOfArgTy << ArgIdx 9257 << PointeeTy << Dest->getSourceRange() 9258 << LenExpr->getSourceRange()); 9259 break; 9260 } 9261 } 9262 } else if (DestTy->isArrayType()) { 9263 PointeeTy = DestTy; 9264 } 9265 9266 if (PointeeTy == QualType()) 9267 continue; 9268 9269 // Always complain about dynamic classes. 9270 bool IsContained; 9271 if (const CXXRecordDecl *ContainedRD = 9272 getContainedDynamicClass(PointeeTy, IsContained)) { 9273 9274 unsigned OperationType = 0; 9275 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9276 // "overwritten" if we're warning about the destination for any call 9277 // but memcmp; otherwise a verb appropriate to the call. 9278 if (ArgIdx != 0 || IsCmp) { 9279 if (BId == Builtin::BImemcpy) 9280 OperationType = 1; 9281 else if(BId == Builtin::BImemmove) 9282 OperationType = 2; 9283 else if (IsCmp) 9284 OperationType = 3; 9285 } 9286 9287 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9288 PDiag(diag::warn_dyn_class_memaccess) 9289 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9290 << IsContained << ContainedRD << OperationType 9291 << Call->getCallee()->getSourceRange()); 9292 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9293 BId != Builtin::BImemset) 9294 DiagRuntimeBehavior( 9295 Dest->getExprLoc(), Dest, 9296 PDiag(diag::warn_arc_object_memaccess) 9297 << ArgIdx << FnName << PointeeTy 9298 << Call->getCallee()->getSourceRange()); 9299 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9300 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9301 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9302 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9303 PDiag(diag::warn_cstruct_memaccess) 9304 << ArgIdx << FnName << PointeeTy << 0); 9305 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9306 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9307 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9308 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9309 PDiag(diag::warn_cstruct_memaccess) 9310 << ArgIdx << FnName << PointeeTy << 1); 9311 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9312 } else { 9313 continue; 9314 } 9315 } else 9316 continue; 9317 9318 DiagRuntimeBehavior( 9319 Dest->getExprLoc(), Dest, 9320 PDiag(diag::note_bad_memaccess_silence) 9321 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9322 break; 9323 } 9324 } 9325 9326 // A little helper routine: ignore addition and subtraction of integer literals. 9327 // This intentionally does not ignore all integer constant expressions because 9328 // we don't want to remove sizeof(). 9329 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9330 Ex = Ex->IgnoreParenCasts(); 9331 9332 while (true) { 9333 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9334 if (!BO || !BO->isAdditiveOp()) 9335 break; 9336 9337 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9338 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9339 9340 if (isa<IntegerLiteral>(RHS)) 9341 Ex = LHS; 9342 else if (isa<IntegerLiteral>(LHS)) 9343 Ex = RHS; 9344 else 9345 break; 9346 } 9347 9348 return Ex; 9349 } 9350 9351 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9352 ASTContext &Context) { 9353 // Only handle constant-sized or VLAs, but not flexible members. 9354 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9355 // Only issue the FIXIT for arrays of size > 1. 9356 if (CAT->getSize().getSExtValue() <= 1) 9357 return false; 9358 } else if (!Ty->isVariableArrayType()) { 9359 return false; 9360 } 9361 return true; 9362 } 9363 9364 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9365 // be the size of the source, instead of the destination. 9366 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9367 IdentifierInfo *FnName) { 9368 9369 // Don't crash if the user has the wrong number of arguments 9370 unsigned NumArgs = Call->getNumArgs(); 9371 if ((NumArgs != 3) && (NumArgs != 4)) 9372 return; 9373 9374 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9375 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9376 const Expr *CompareWithSrc = nullptr; 9377 9378 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9379 Call->getBeginLoc(), Call->getRParenLoc())) 9380 return; 9381 9382 // Look for 'strlcpy(dst, x, sizeof(x))' 9383 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9384 CompareWithSrc = Ex; 9385 else { 9386 // Look for 'strlcpy(dst, x, strlen(x))' 9387 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9388 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9389 SizeCall->getNumArgs() == 1) 9390 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9391 } 9392 } 9393 9394 if (!CompareWithSrc) 9395 return; 9396 9397 // Determine if the argument to sizeof/strlen is equal to the source 9398 // argument. In principle there's all kinds of things you could do 9399 // here, for instance creating an == expression and evaluating it with 9400 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9401 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9402 if (!SrcArgDRE) 9403 return; 9404 9405 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9406 if (!CompareWithSrcDRE || 9407 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9408 return; 9409 9410 const Expr *OriginalSizeArg = Call->getArg(2); 9411 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9412 << OriginalSizeArg->getSourceRange() << FnName; 9413 9414 // Output a FIXIT hint if the destination is an array (rather than a 9415 // pointer to an array). This could be enhanced to handle some 9416 // pointers if we know the actual size, like if DstArg is 'array+2' 9417 // we could say 'sizeof(array)-2'. 9418 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9419 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9420 return; 9421 9422 SmallString<128> sizeString; 9423 llvm::raw_svector_ostream OS(sizeString); 9424 OS << "sizeof("; 9425 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9426 OS << ")"; 9427 9428 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9429 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9430 OS.str()); 9431 } 9432 9433 /// Check if two expressions refer to the same declaration. 9434 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9435 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9436 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9437 return D1->getDecl() == D2->getDecl(); 9438 return false; 9439 } 9440 9441 static const Expr *getStrlenExprArg(const Expr *E) { 9442 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9443 const FunctionDecl *FD = CE->getDirectCallee(); 9444 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9445 return nullptr; 9446 return CE->getArg(0)->IgnoreParenCasts(); 9447 } 9448 return nullptr; 9449 } 9450 9451 // Warn on anti-patterns as the 'size' argument to strncat. 9452 // The correct size argument should look like following: 9453 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9454 void Sema::CheckStrncatArguments(const CallExpr *CE, 9455 IdentifierInfo *FnName) { 9456 // Don't crash if the user has the wrong number of arguments. 9457 if (CE->getNumArgs() < 3) 9458 return; 9459 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9460 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9461 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9462 9463 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9464 CE->getRParenLoc())) 9465 return; 9466 9467 // Identify common expressions, which are wrongly used as the size argument 9468 // to strncat and may lead to buffer overflows. 9469 unsigned PatternType = 0; 9470 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9471 // - sizeof(dst) 9472 if (referToTheSameDecl(SizeOfArg, DstArg)) 9473 PatternType = 1; 9474 // - sizeof(src) 9475 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9476 PatternType = 2; 9477 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9478 if (BE->getOpcode() == BO_Sub) { 9479 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9480 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9481 // - sizeof(dst) - strlen(dst) 9482 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9483 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9484 PatternType = 1; 9485 // - sizeof(src) - (anything) 9486 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9487 PatternType = 2; 9488 } 9489 } 9490 9491 if (PatternType == 0) 9492 return; 9493 9494 // Generate the diagnostic. 9495 SourceLocation SL = LenArg->getBeginLoc(); 9496 SourceRange SR = LenArg->getSourceRange(); 9497 SourceManager &SM = getSourceManager(); 9498 9499 // If the function is defined as a builtin macro, do not show macro expansion. 9500 if (SM.isMacroArgExpansion(SL)) { 9501 SL = SM.getSpellingLoc(SL); 9502 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9503 SM.getSpellingLoc(SR.getEnd())); 9504 } 9505 9506 // Check if the destination is an array (rather than a pointer to an array). 9507 QualType DstTy = DstArg->getType(); 9508 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9509 Context); 9510 if (!isKnownSizeArray) { 9511 if (PatternType == 1) 9512 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9513 else 9514 Diag(SL, diag::warn_strncat_src_size) << SR; 9515 return; 9516 } 9517 9518 if (PatternType == 1) 9519 Diag(SL, diag::warn_strncat_large_size) << SR; 9520 else 9521 Diag(SL, diag::warn_strncat_src_size) << SR; 9522 9523 SmallString<128> sizeString; 9524 llvm::raw_svector_ostream OS(sizeString); 9525 OS << "sizeof("; 9526 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9527 OS << ") - "; 9528 OS << "strlen("; 9529 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9530 OS << ") - 1"; 9531 9532 Diag(SL, diag::note_strncat_wrong_size) 9533 << FixItHint::CreateReplacement(SR, OS.str()); 9534 } 9535 9536 void 9537 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9538 SourceLocation ReturnLoc, 9539 bool isObjCMethod, 9540 const AttrVec *Attrs, 9541 const FunctionDecl *FD) { 9542 // Check if the return value is null but should not be. 9543 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9544 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9545 CheckNonNullExpr(*this, RetValExp)) 9546 Diag(ReturnLoc, diag::warn_null_ret) 9547 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9548 9549 // C++11 [basic.stc.dynamic.allocation]p4: 9550 // If an allocation function declared with a non-throwing 9551 // exception-specification fails to allocate storage, it shall return 9552 // a null pointer. Any other allocation function that fails to allocate 9553 // storage shall indicate failure only by throwing an exception [...] 9554 if (FD) { 9555 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9556 if (Op == OO_New || Op == OO_Array_New) { 9557 const FunctionProtoType *Proto 9558 = FD->getType()->castAs<FunctionProtoType>(); 9559 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9560 CheckNonNullExpr(*this, RetValExp)) 9561 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9562 << FD << getLangOpts().CPlusPlus11; 9563 } 9564 } 9565 } 9566 9567 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9568 9569 /// Check for comparisons of floating point operands using != and ==. 9570 /// Issue a warning if these are no self-comparisons, as they are not likely 9571 /// to do what the programmer intended. 9572 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9573 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9574 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9575 9576 // Special case: check for x == x (which is OK). 9577 // Do not emit warnings for such cases. 9578 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9579 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9580 if (DRL->getDecl() == DRR->getDecl()) 9581 return; 9582 9583 // Special case: check for comparisons against literals that can be exactly 9584 // represented by APFloat. In such cases, do not emit a warning. This 9585 // is a heuristic: often comparison against such literals are used to 9586 // detect if a value in a variable has not changed. This clearly can 9587 // lead to false negatives. 9588 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9589 if (FLL->isExact()) 9590 return; 9591 } else 9592 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9593 if (FLR->isExact()) 9594 return; 9595 9596 // Check for comparisons with builtin types. 9597 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9598 if (CL->getBuiltinCallee()) 9599 return; 9600 9601 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9602 if (CR->getBuiltinCallee()) 9603 return; 9604 9605 // Emit the diagnostic. 9606 Diag(Loc, diag::warn_floatingpoint_eq) 9607 << LHS->getSourceRange() << RHS->getSourceRange(); 9608 } 9609 9610 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9611 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9612 9613 namespace { 9614 9615 /// Structure recording the 'active' range of an integer-valued 9616 /// expression. 9617 struct IntRange { 9618 /// The number of bits active in the int. 9619 unsigned Width; 9620 9621 /// True if the int is known not to have negative values. 9622 bool NonNegative; 9623 9624 IntRange(unsigned Width, bool NonNegative) 9625 : Width(Width), NonNegative(NonNegative) {} 9626 9627 /// Returns the range of the bool type. 9628 static IntRange forBoolType() { 9629 return IntRange(1, true); 9630 } 9631 9632 /// Returns the range of an opaque value of the given integral type. 9633 static IntRange forValueOfType(ASTContext &C, QualType T) { 9634 return forValueOfCanonicalType(C, 9635 T->getCanonicalTypeInternal().getTypePtr()); 9636 } 9637 9638 /// Returns the range of an opaque value of a canonical integral type. 9639 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9640 assert(T->isCanonicalUnqualified()); 9641 9642 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9643 T = VT->getElementType().getTypePtr(); 9644 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9645 T = CT->getElementType().getTypePtr(); 9646 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9647 T = AT->getValueType().getTypePtr(); 9648 9649 if (!C.getLangOpts().CPlusPlus) { 9650 // For enum types in C code, use the underlying datatype. 9651 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9652 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9653 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9654 // For enum types in C++, use the known bit width of the enumerators. 9655 EnumDecl *Enum = ET->getDecl(); 9656 // In C++11, enums can have a fixed underlying type. Use this type to 9657 // compute the range. 9658 if (Enum->isFixed()) { 9659 return IntRange(C.getIntWidth(QualType(T, 0)), 9660 !ET->isSignedIntegerOrEnumerationType()); 9661 } 9662 9663 unsigned NumPositive = Enum->getNumPositiveBits(); 9664 unsigned NumNegative = Enum->getNumNegativeBits(); 9665 9666 if (NumNegative == 0) 9667 return IntRange(NumPositive, true/*NonNegative*/); 9668 else 9669 return IntRange(std::max(NumPositive + 1, NumNegative), 9670 false/*NonNegative*/); 9671 } 9672 9673 const BuiltinType *BT = cast<BuiltinType>(T); 9674 assert(BT->isInteger()); 9675 9676 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9677 } 9678 9679 /// Returns the "target" range of a canonical integral type, i.e. 9680 /// the range of values expressible in the type. 9681 /// 9682 /// This matches forValueOfCanonicalType except that enums have the 9683 /// full range of their type, not the range of their enumerators. 9684 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9685 assert(T->isCanonicalUnqualified()); 9686 9687 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9688 T = VT->getElementType().getTypePtr(); 9689 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9690 T = CT->getElementType().getTypePtr(); 9691 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9692 T = AT->getValueType().getTypePtr(); 9693 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9694 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9695 9696 const BuiltinType *BT = cast<BuiltinType>(T); 9697 assert(BT->isInteger()); 9698 9699 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9700 } 9701 9702 /// Returns the supremum of two ranges: i.e. their conservative merge. 9703 static IntRange join(IntRange L, IntRange R) { 9704 return IntRange(std::max(L.Width, R.Width), 9705 L.NonNegative && R.NonNegative); 9706 } 9707 9708 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9709 static IntRange meet(IntRange L, IntRange R) { 9710 return IntRange(std::min(L.Width, R.Width), 9711 L.NonNegative || R.NonNegative); 9712 } 9713 }; 9714 9715 } // namespace 9716 9717 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9718 unsigned MaxWidth) { 9719 if (value.isSigned() && value.isNegative()) 9720 return IntRange(value.getMinSignedBits(), false); 9721 9722 if (value.getBitWidth() > MaxWidth) 9723 value = value.trunc(MaxWidth); 9724 9725 // isNonNegative() just checks the sign bit without considering 9726 // signedness. 9727 return IntRange(value.getActiveBits(), true); 9728 } 9729 9730 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9731 unsigned MaxWidth) { 9732 if (result.isInt()) 9733 return GetValueRange(C, result.getInt(), MaxWidth); 9734 9735 if (result.isVector()) { 9736 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9737 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9738 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9739 R = IntRange::join(R, El); 9740 } 9741 return R; 9742 } 9743 9744 if (result.isComplexInt()) { 9745 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9746 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9747 return IntRange::join(R, I); 9748 } 9749 9750 // This can happen with lossless casts to intptr_t of "based" lvalues. 9751 // Assume it might use arbitrary bits. 9752 // FIXME: The only reason we need to pass the type in here is to get 9753 // the sign right on this one case. It would be nice if APValue 9754 // preserved this. 9755 assert(result.isLValue() || result.isAddrLabelDiff()); 9756 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9757 } 9758 9759 static QualType GetExprType(const Expr *E) { 9760 QualType Ty = E->getType(); 9761 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9762 Ty = AtomicRHS->getValueType(); 9763 return Ty; 9764 } 9765 9766 /// Pseudo-evaluate the given integer expression, estimating the 9767 /// range of values it might take. 9768 /// 9769 /// \param MaxWidth - the width to which the value will be truncated 9770 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9771 bool InConstantContext) { 9772 E = E->IgnoreParens(); 9773 9774 // Try a full evaluation first. 9775 Expr::EvalResult result; 9776 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9777 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9778 9779 // I think we only want to look through implicit casts here; if the 9780 // user has an explicit widening cast, we should treat the value as 9781 // being of the new, wider type. 9782 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9783 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9784 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9785 9786 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9787 9788 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9789 CE->getCastKind() == CK_BooleanToSignedIntegral; 9790 9791 // Assume that non-integer casts can span the full range of the type. 9792 if (!isIntegerCast) 9793 return OutputTypeRange; 9794 9795 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9796 std::min(MaxWidth, OutputTypeRange.Width), 9797 InConstantContext); 9798 9799 // Bail out if the subexpr's range is as wide as the cast type. 9800 if (SubRange.Width >= OutputTypeRange.Width) 9801 return OutputTypeRange; 9802 9803 // Otherwise, we take the smaller width, and we're non-negative if 9804 // either the output type or the subexpr is. 9805 return IntRange(SubRange.Width, 9806 SubRange.NonNegative || OutputTypeRange.NonNegative); 9807 } 9808 9809 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9810 // If we can fold the condition, just take that operand. 9811 bool CondResult; 9812 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9813 return GetExprRange(C, 9814 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9815 MaxWidth, InConstantContext); 9816 9817 // Otherwise, conservatively merge. 9818 IntRange L = 9819 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9820 IntRange R = 9821 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9822 return IntRange::join(L, R); 9823 } 9824 9825 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9826 switch (BO->getOpcode()) { 9827 case BO_Cmp: 9828 llvm_unreachable("builtin <=> should have class type"); 9829 9830 // Boolean-valued operations are single-bit and positive. 9831 case BO_LAnd: 9832 case BO_LOr: 9833 case BO_LT: 9834 case BO_GT: 9835 case BO_LE: 9836 case BO_GE: 9837 case BO_EQ: 9838 case BO_NE: 9839 return IntRange::forBoolType(); 9840 9841 // The type of the assignments is the type of the LHS, so the RHS 9842 // is not necessarily the same type. 9843 case BO_MulAssign: 9844 case BO_DivAssign: 9845 case BO_RemAssign: 9846 case BO_AddAssign: 9847 case BO_SubAssign: 9848 case BO_XorAssign: 9849 case BO_OrAssign: 9850 // TODO: bitfields? 9851 return IntRange::forValueOfType(C, GetExprType(E)); 9852 9853 // Simple assignments just pass through the RHS, which will have 9854 // been coerced to the LHS type. 9855 case BO_Assign: 9856 // TODO: bitfields? 9857 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9858 9859 // Operations with opaque sources are black-listed. 9860 case BO_PtrMemD: 9861 case BO_PtrMemI: 9862 return IntRange::forValueOfType(C, GetExprType(E)); 9863 9864 // Bitwise-and uses the *infinum* of the two source ranges. 9865 case BO_And: 9866 case BO_AndAssign: 9867 return IntRange::meet( 9868 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 9869 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 9870 9871 // Left shift gets black-listed based on a judgement call. 9872 case BO_Shl: 9873 // ...except that we want to treat '1 << (blah)' as logically 9874 // positive. It's an important idiom. 9875 if (IntegerLiteral *I 9876 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9877 if (I->getValue() == 1) { 9878 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9879 return IntRange(R.Width, /*NonNegative*/ true); 9880 } 9881 } 9882 LLVM_FALLTHROUGH; 9883 9884 case BO_ShlAssign: 9885 return IntRange::forValueOfType(C, GetExprType(E)); 9886 9887 // Right shift by a constant can narrow its left argument. 9888 case BO_Shr: 9889 case BO_ShrAssign: { 9890 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9891 9892 // If the shift amount is a positive constant, drop the width by 9893 // that much. 9894 llvm::APSInt shift; 9895 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9896 shift.isNonNegative()) { 9897 unsigned zext = shift.getZExtValue(); 9898 if (zext >= L.Width) 9899 L.Width = (L.NonNegative ? 0 : 1); 9900 else 9901 L.Width -= zext; 9902 } 9903 9904 return L; 9905 } 9906 9907 // Comma acts as its right operand. 9908 case BO_Comma: 9909 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9910 9911 // Black-list pointer subtractions. 9912 case BO_Sub: 9913 if (BO->getLHS()->getType()->isPointerType()) 9914 return IntRange::forValueOfType(C, GetExprType(E)); 9915 break; 9916 9917 // The width of a division result is mostly determined by the size 9918 // of the LHS. 9919 case BO_Div: { 9920 // Don't 'pre-truncate' the operands. 9921 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9922 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 9923 9924 // If the divisor is constant, use that. 9925 llvm::APSInt divisor; 9926 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 9927 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 9928 if (log2 >= L.Width) 9929 L.Width = (L.NonNegative ? 0 : 1); 9930 else 9931 L.Width = std::min(L.Width - log2, MaxWidth); 9932 return L; 9933 } 9934 9935 // Otherwise, just use the LHS's width. 9936 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 9937 return IntRange(L.Width, L.NonNegative && R.NonNegative); 9938 } 9939 9940 // The result of a remainder can't be larger than the result of 9941 // either side. 9942 case BO_Rem: { 9943 // Don't 'pre-truncate' the operands. 9944 unsigned opWidth = C.getIntWidth(GetExprType(E)); 9945 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 9946 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 9947 9948 IntRange meet = IntRange::meet(L, R); 9949 meet.Width = std::min(meet.Width, MaxWidth); 9950 return meet; 9951 } 9952 9953 // The default behavior is okay for these. 9954 case BO_Mul: 9955 case BO_Add: 9956 case BO_Xor: 9957 case BO_Or: 9958 break; 9959 } 9960 9961 // The default case is to treat the operation as if it were closed 9962 // on the narrowest type that encompasses both operands. 9963 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9964 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9965 return IntRange::join(L, R); 9966 } 9967 9968 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 9969 switch (UO->getOpcode()) { 9970 // Boolean-valued operations are white-listed. 9971 case UO_LNot: 9972 return IntRange::forBoolType(); 9973 9974 // Operations with opaque sources are black-listed. 9975 case UO_Deref: 9976 case UO_AddrOf: // should be impossible 9977 return IntRange::forValueOfType(C, GetExprType(E)); 9978 9979 default: 9980 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 9981 } 9982 } 9983 9984 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 9985 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 9986 9987 if (const auto *BitField = E->getSourceBitField()) 9988 return IntRange(BitField->getBitWidthValue(C), 9989 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 9990 9991 return IntRange::forValueOfType(C, GetExprType(E)); 9992 } 9993 9994 static IntRange GetExprRange(ASTContext &C, const Expr *E, 9995 bool InConstantContext) { 9996 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 9997 } 9998 9999 /// Checks whether the given value, which currently has the given 10000 /// source semantics, has the same value when coerced through the 10001 /// target semantics. 10002 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10003 const llvm::fltSemantics &Src, 10004 const llvm::fltSemantics &Tgt) { 10005 llvm::APFloat truncated = value; 10006 10007 bool ignored; 10008 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10009 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10010 10011 return truncated.bitwiseIsEqual(value); 10012 } 10013 10014 /// Checks whether the given value, which currently has the given 10015 /// source semantics, has the same value when coerced through the 10016 /// target semantics. 10017 /// 10018 /// The value might be a vector of floats (or a complex number). 10019 static bool IsSameFloatAfterCast(const APValue &value, 10020 const llvm::fltSemantics &Src, 10021 const llvm::fltSemantics &Tgt) { 10022 if (value.isFloat()) 10023 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10024 10025 if (value.isVector()) { 10026 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10027 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10028 return false; 10029 return true; 10030 } 10031 10032 assert(value.isComplexFloat()); 10033 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10034 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10035 } 10036 10037 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10038 bool IsListInit = false); 10039 10040 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10041 // Suppress cases where we are comparing against an enum constant. 10042 if (const DeclRefExpr *DR = 10043 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10044 if (isa<EnumConstantDecl>(DR->getDecl())) 10045 return true; 10046 10047 // Suppress cases where the value is expanded from a macro, unless that macro 10048 // is how a language represents a boolean literal. This is the case in both C 10049 // and Objective-C. 10050 SourceLocation BeginLoc = E->getBeginLoc(); 10051 if (BeginLoc.isMacroID()) { 10052 StringRef MacroName = Lexer::getImmediateMacroName( 10053 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10054 return MacroName != "YES" && MacroName != "NO" && 10055 MacroName != "true" && MacroName != "false"; 10056 } 10057 10058 return false; 10059 } 10060 10061 static bool isKnownToHaveUnsignedValue(Expr *E) { 10062 return E->getType()->isIntegerType() && 10063 (!E->getType()->isSignedIntegerType() || 10064 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10065 } 10066 10067 namespace { 10068 /// The promoted range of values of a type. In general this has the 10069 /// following structure: 10070 /// 10071 /// |-----------| . . . |-----------| 10072 /// ^ ^ ^ ^ 10073 /// Min HoleMin HoleMax Max 10074 /// 10075 /// ... where there is only a hole if a signed type is promoted to unsigned 10076 /// (in which case Min and Max are the smallest and largest representable 10077 /// values). 10078 struct PromotedRange { 10079 // Min, or HoleMax if there is a hole. 10080 llvm::APSInt PromotedMin; 10081 // Max, or HoleMin if there is a hole. 10082 llvm::APSInt PromotedMax; 10083 10084 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10085 if (R.Width == 0) 10086 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10087 else if (R.Width >= BitWidth && !Unsigned) { 10088 // Promotion made the type *narrower*. This happens when promoting 10089 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10090 // Treat all values of 'signed int' as being in range for now. 10091 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10092 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10093 } else { 10094 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10095 .extOrTrunc(BitWidth); 10096 PromotedMin.setIsUnsigned(Unsigned); 10097 10098 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10099 .extOrTrunc(BitWidth); 10100 PromotedMax.setIsUnsigned(Unsigned); 10101 } 10102 } 10103 10104 // Determine whether this range is contiguous (has no hole). 10105 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10106 10107 // Where a constant value is within the range. 10108 enum ComparisonResult { 10109 LT = 0x1, 10110 LE = 0x2, 10111 GT = 0x4, 10112 GE = 0x8, 10113 EQ = 0x10, 10114 NE = 0x20, 10115 InRangeFlag = 0x40, 10116 10117 Less = LE | LT | NE, 10118 Min = LE | InRangeFlag, 10119 InRange = InRangeFlag, 10120 Max = GE | InRangeFlag, 10121 Greater = GE | GT | NE, 10122 10123 OnlyValue = LE | GE | EQ | InRangeFlag, 10124 InHole = NE 10125 }; 10126 10127 ComparisonResult compare(const llvm::APSInt &Value) const { 10128 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10129 Value.isUnsigned() == PromotedMin.isUnsigned()); 10130 if (!isContiguous()) { 10131 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10132 if (Value.isMinValue()) return Min; 10133 if (Value.isMaxValue()) return Max; 10134 if (Value >= PromotedMin) return InRange; 10135 if (Value <= PromotedMax) return InRange; 10136 return InHole; 10137 } 10138 10139 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10140 case -1: return Less; 10141 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10142 case 1: 10143 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10144 case -1: return InRange; 10145 case 0: return Max; 10146 case 1: return Greater; 10147 } 10148 } 10149 10150 llvm_unreachable("impossible compare result"); 10151 } 10152 10153 static llvm::Optional<StringRef> 10154 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10155 if (Op == BO_Cmp) { 10156 ComparisonResult LTFlag = LT, GTFlag = GT; 10157 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10158 10159 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10160 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10161 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10162 return llvm::None; 10163 } 10164 10165 ComparisonResult TrueFlag, FalseFlag; 10166 if (Op == BO_EQ) { 10167 TrueFlag = EQ; 10168 FalseFlag = NE; 10169 } else if (Op == BO_NE) { 10170 TrueFlag = NE; 10171 FalseFlag = EQ; 10172 } else { 10173 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10174 TrueFlag = LT; 10175 FalseFlag = GE; 10176 } else { 10177 TrueFlag = GT; 10178 FalseFlag = LE; 10179 } 10180 if (Op == BO_GE || Op == BO_LE) 10181 std::swap(TrueFlag, FalseFlag); 10182 } 10183 if (R & TrueFlag) 10184 return StringRef("true"); 10185 if (R & FalseFlag) 10186 return StringRef("false"); 10187 return llvm::None; 10188 } 10189 }; 10190 } 10191 10192 static bool HasEnumType(Expr *E) { 10193 // Strip off implicit integral promotions. 10194 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10195 if (ICE->getCastKind() != CK_IntegralCast && 10196 ICE->getCastKind() != CK_NoOp) 10197 break; 10198 E = ICE->getSubExpr(); 10199 } 10200 10201 return E->getType()->isEnumeralType(); 10202 } 10203 10204 static int classifyConstantValue(Expr *Constant) { 10205 // The values of this enumeration are used in the diagnostics 10206 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10207 enum ConstantValueKind { 10208 Miscellaneous = 0, 10209 LiteralTrue, 10210 LiteralFalse 10211 }; 10212 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10213 return BL->getValue() ? ConstantValueKind::LiteralTrue 10214 : ConstantValueKind::LiteralFalse; 10215 return ConstantValueKind::Miscellaneous; 10216 } 10217 10218 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10219 Expr *Constant, Expr *Other, 10220 const llvm::APSInt &Value, 10221 bool RhsConstant) { 10222 if (S.inTemplateInstantiation()) 10223 return false; 10224 10225 Expr *OriginalOther = Other; 10226 10227 Constant = Constant->IgnoreParenImpCasts(); 10228 Other = Other->IgnoreParenImpCasts(); 10229 10230 // Suppress warnings on tautological comparisons between values of the same 10231 // enumeration type. There are only two ways we could warn on this: 10232 // - If the constant is outside the range of representable values of 10233 // the enumeration. In such a case, we should warn about the cast 10234 // to enumeration type, not about the comparison. 10235 // - If the constant is the maximum / minimum in-range value. For an 10236 // enumeratin type, such comparisons can be meaningful and useful. 10237 if (Constant->getType()->isEnumeralType() && 10238 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10239 return false; 10240 10241 // TODO: Investigate using GetExprRange() to get tighter bounds 10242 // on the bit ranges. 10243 QualType OtherT = Other->getType(); 10244 if (const auto *AT = OtherT->getAs<AtomicType>()) 10245 OtherT = AT->getValueType(); 10246 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10247 10248 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10249 // (Namely, macOS). 10250 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10251 S.NSAPIObj->isObjCBOOLType(OtherT) && 10252 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10253 10254 // Whether we're treating Other as being a bool because of the form of 10255 // expression despite it having another type (typically 'int' in C). 10256 bool OtherIsBooleanDespiteType = 10257 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10258 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10259 OtherRange = IntRange::forBoolType(); 10260 10261 // Determine the promoted range of the other type and see if a comparison of 10262 // the constant against that range is tautological. 10263 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10264 Value.isUnsigned()); 10265 auto Cmp = OtherPromotedRange.compare(Value); 10266 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10267 if (!Result) 10268 return false; 10269 10270 // Suppress the diagnostic for an in-range comparison if the constant comes 10271 // from a macro or enumerator. We don't want to diagnose 10272 // 10273 // some_long_value <= INT_MAX 10274 // 10275 // when sizeof(int) == sizeof(long). 10276 bool InRange = Cmp & PromotedRange::InRangeFlag; 10277 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10278 return false; 10279 10280 // If this is a comparison to an enum constant, include that 10281 // constant in the diagnostic. 10282 const EnumConstantDecl *ED = nullptr; 10283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10284 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10285 10286 // Should be enough for uint128 (39 decimal digits) 10287 SmallString<64> PrettySourceValue; 10288 llvm::raw_svector_ostream OS(PrettySourceValue); 10289 if (ED) { 10290 OS << '\'' << *ED << "' (" << Value << ")"; 10291 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10292 Constant->IgnoreParenImpCasts())) { 10293 OS << (BL->getValue() ? "YES" : "NO"); 10294 } else { 10295 OS << Value; 10296 } 10297 10298 if (IsObjCSignedCharBool) { 10299 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10300 S.PDiag(diag::warn_tautological_compare_objc_bool) 10301 << OS.str() << *Result); 10302 return true; 10303 } 10304 10305 // FIXME: We use a somewhat different formatting for the in-range cases and 10306 // cases involving boolean values for historical reasons. We should pick a 10307 // consistent way of presenting these diagnostics. 10308 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10309 10310 S.DiagRuntimeBehavior( 10311 E->getOperatorLoc(), E, 10312 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10313 : diag::warn_tautological_bool_compare) 10314 << OS.str() << classifyConstantValue(Constant) << OtherT 10315 << OtherIsBooleanDespiteType << *Result 10316 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10317 } else { 10318 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10319 ? (HasEnumType(OriginalOther) 10320 ? diag::warn_unsigned_enum_always_true_comparison 10321 : diag::warn_unsigned_always_true_comparison) 10322 : diag::warn_tautological_constant_compare; 10323 10324 S.Diag(E->getOperatorLoc(), Diag) 10325 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10326 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10327 } 10328 10329 return true; 10330 } 10331 10332 /// Analyze the operands of the given comparison. Implements the 10333 /// fallback case from AnalyzeComparison. 10334 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10335 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10336 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10337 } 10338 10339 /// Implements -Wsign-compare. 10340 /// 10341 /// \param E the binary operator to check for warnings 10342 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10343 // The type the comparison is being performed in. 10344 QualType T = E->getLHS()->getType(); 10345 10346 // Only analyze comparison operators where both sides have been converted to 10347 // the same type. 10348 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10349 return AnalyzeImpConvsInComparison(S, E); 10350 10351 // Don't analyze value-dependent comparisons directly. 10352 if (E->isValueDependent()) 10353 return AnalyzeImpConvsInComparison(S, E); 10354 10355 Expr *LHS = E->getLHS(); 10356 Expr *RHS = E->getRHS(); 10357 10358 if (T->isIntegralType(S.Context)) { 10359 llvm::APSInt RHSValue; 10360 llvm::APSInt LHSValue; 10361 10362 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10363 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10364 10365 // We don't care about expressions whose result is a constant. 10366 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10367 return AnalyzeImpConvsInComparison(S, E); 10368 10369 // We only care about expressions where just one side is literal 10370 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10371 // Is the constant on the RHS or LHS? 10372 const bool RhsConstant = IsRHSIntegralLiteral; 10373 Expr *Const = RhsConstant ? RHS : LHS; 10374 Expr *Other = RhsConstant ? LHS : RHS; 10375 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10376 10377 // Check whether an integer constant comparison results in a value 10378 // of 'true' or 'false'. 10379 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10380 return AnalyzeImpConvsInComparison(S, E); 10381 } 10382 } 10383 10384 if (!T->hasUnsignedIntegerRepresentation()) { 10385 // We don't do anything special if this isn't an unsigned integral 10386 // comparison: we're only interested in integral comparisons, and 10387 // signed comparisons only happen in cases we don't care to warn about. 10388 return AnalyzeImpConvsInComparison(S, E); 10389 } 10390 10391 LHS = LHS->IgnoreParenImpCasts(); 10392 RHS = RHS->IgnoreParenImpCasts(); 10393 10394 if (!S.getLangOpts().CPlusPlus) { 10395 // Avoid warning about comparison of integers with different signs when 10396 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10397 // the type of `E`. 10398 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10399 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10400 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10401 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10402 } 10403 10404 // Check to see if one of the (unmodified) operands is of different 10405 // signedness. 10406 Expr *signedOperand, *unsignedOperand; 10407 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10408 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10409 "unsigned comparison between two signed integer expressions?"); 10410 signedOperand = LHS; 10411 unsignedOperand = RHS; 10412 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10413 signedOperand = RHS; 10414 unsignedOperand = LHS; 10415 } else { 10416 return AnalyzeImpConvsInComparison(S, E); 10417 } 10418 10419 // Otherwise, calculate the effective range of the signed operand. 10420 IntRange signedRange = 10421 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10422 10423 // Go ahead and analyze implicit conversions in the operands. Note 10424 // that we skip the implicit conversions on both sides. 10425 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10426 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10427 10428 // If the signed range is non-negative, -Wsign-compare won't fire. 10429 if (signedRange.NonNegative) 10430 return; 10431 10432 // For (in)equality comparisons, if the unsigned operand is a 10433 // constant which cannot collide with a overflowed signed operand, 10434 // then reinterpreting the signed operand as unsigned will not 10435 // change the result of the comparison. 10436 if (E->isEqualityOp()) { 10437 unsigned comparisonWidth = S.Context.getIntWidth(T); 10438 IntRange unsignedRange = 10439 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10440 10441 // We should never be unable to prove that the unsigned operand is 10442 // non-negative. 10443 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10444 10445 if (unsignedRange.Width < comparisonWidth) 10446 return; 10447 } 10448 10449 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10450 S.PDiag(diag::warn_mixed_sign_comparison) 10451 << LHS->getType() << RHS->getType() 10452 << LHS->getSourceRange() << RHS->getSourceRange()); 10453 } 10454 10455 /// Analyzes an attempt to assign the given value to a bitfield. 10456 /// 10457 /// Returns true if there was something fishy about the attempt. 10458 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10459 SourceLocation InitLoc) { 10460 assert(Bitfield->isBitField()); 10461 if (Bitfield->isInvalidDecl()) 10462 return false; 10463 10464 // White-list bool bitfields. 10465 QualType BitfieldType = Bitfield->getType(); 10466 if (BitfieldType->isBooleanType()) 10467 return false; 10468 10469 if (BitfieldType->isEnumeralType()) { 10470 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10471 // If the underlying enum type was not explicitly specified as an unsigned 10472 // type and the enum contain only positive values, MSVC++ will cause an 10473 // inconsistency by storing this as a signed type. 10474 if (S.getLangOpts().CPlusPlus11 && 10475 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10476 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10477 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10478 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10479 << BitfieldEnumDecl->getNameAsString(); 10480 } 10481 } 10482 10483 if (Bitfield->getType()->isBooleanType()) 10484 return false; 10485 10486 // Ignore value- or type-dependent expressions. 10487 if (Bitfield->getBitWidth()->isValueDependent() || 10488 Bitfield->getBitWidth()->isTypeDependent() || 10489 Init->isValueDependent() || 10490 Init->isTypeDependent()) 10491 return false; 10492 10493 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10494 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10495 10496 Expr::EvalResult Result; 10497 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10498 Expr::SE_AllowSideEffects)) { 10499 // The RHS is not constant. If the RHS has an enum type, make sure the 10500 // bitfield is wide enough to hold all the values of the enum without 10501 // truncation. 10502 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10503 EnumDecl *ED = EnumTy->getDecl(); 10504 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10505 10506 // Enum types are implicitly signed on Windows, so check if there are any 10507 // negative enumerators to see if the enum was intended to be signed or 10508 // not. 10509 bool SignedEnum = ED->getNumNegativeBits() > 0; 10510 10511 // Check for surprising sign changes when assigning enum values to a 10512 // bitfield of different signedness. If the bitfield is signed and we 10513 // have exactly the right number of bits to store this unsigned enum, 10514 // suggest changing the enum to an unsigned type. This typically happens 10515 // on Windows where unfixed enums always use an underlying type of 'int'. 10516 unsigned DiagID = 0; 10517 if (SignedEnum && !SignedBitfield) { 10518 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10519 } else if (SignedBitfield && !SignedEnum && 10520 ED->getNumPositiveBits() == FieldWidth) { 10521 DiagID = diag::warn_signed_bitfield_enum_conversion; 10522 } 10523 10524 if (DiagID) { 10525 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10526 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10527 SourceRange TypeRange = 10528 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10529 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10530 << SignedEnum << TypeRange; 10531 } 10532 10533 // Compute the required bitwidth. If the enum has negative values, we need 10534 // one more bit than the normal number of positive bits to represent the 10535 // sign bit. 10536 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10537 ED->getNumNegativeBits()) 10538 : ED->getNumPositiveBits(); 10539 10540 // Check the bitwidth. 10541 if (BitsNeeded > FieldWidth) { 10542 Expr *WidthExpr = Bitfield->getBitWidth(); 10543 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10544 << Bitfield << ED; 10545 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10546 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10547 } 10548 } 10549 10550 return false; 10551 } 10552 10553 llvm::APSInt Value = Result.Val.getInt(); 10554 10555 unsigned OriginalWidth = Value.getBitWidth(); 10556 10557 if (!Value.isSigned() || Value.isNegative()) 10558 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10559 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10560 OriginalWidth = Value.getMinSignedBits(); 10561 10562 if (OriginalWidth <= FieldWidth) 10563 return false; 10564 10565 // Compute the value which the bitfield will contain. 10566 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10567 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10568 10569 // Check whether the stored value is equal to the original value. 10570 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10571 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10572 return false; 10573 10574 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10575 // therefore don't strictly fit into a signed bitfield of width 1. 10576 if (FieldWidth == 1 && Value == 1) 10577 return false; 10578 10579 std::string PrettyValue = Value.toString(10); 10580 std::string PrettyTrunc = TruncatedValue.toString(10); 10581 10582 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10583 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10584 << Init->getSourceRange(); 10585 10586 return true; 10587 } 10588 10589 /// Analyze the given simple or compound assignment for warning-worthy 10590 /// operations. 10591 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10592 // Just recurse on the LHS. 10593 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10594 10595 // We want to recurse on the RHS as normal unless we're assigning to 10596 // a bitfield. 10597 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10598 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10599 E->getOperatorLoc())) { 10600 // Recurse, ignoring any implicit conversions on the RHS. 10601 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10602 E->getOperatorLoc()); 10603 } 10604 } 10605 10606 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10607 10608 // Diagnose implicitly sequentially-consistent atomic assignment. 10609 if (E->getLHS()->getType()->isAtomicType()) 10610 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10611 } 10612 10613 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10614 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10615 SourceLocation CContext, unsigned diag, 10616 bool pruneControlFlow = false) { 10617 if (pruneControlFlow) { 10618 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10619 S.PDiag(diag) 10620 << SourceType << T << E->getSourceRange() 10621 << SourceRange(CContext)); 10622 return; 10623 } 10624 S.Diag(E->getExprLoc(), diag) 10625 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10626 } 10627 10628 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10629 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10630 SourceLocation CContext, 10631 unsigned diag, bool pruneControlFlow = false) { 10632 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10633 } 10634 10635 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10636 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10637 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10638 } 10639 10640 static void adornObjCBoolConversionDiagWithTernaryFixit( 10641 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10642 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10643 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10644 Ignored = OVE->getSourceExpr(); 10645 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10646 isa<BinaryOperator>(Ignored) || 10647 isa<CXXOperatorCallExpr>(Ignored); 10648 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10649 if (NeedsParens) 10650 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10651 << FixItHint::CreateInsertion(EndLoc, ")"); 10652 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10653 } 10654 10655 /// Diagnose an implicit cast from a floating point value to an integer value. 10656 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10657 SourceLocation CContext) { 10658 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10659 const bool PruneWarnings = S.inTemplateInstantiation(); 10660 10661 Expr *InnerE = E->IgnoreParenImpCasts(); 10662 // We also want to warn on, e.g., "int i = -1.234" 10663 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10664 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10665 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10666 10667 const bool IsLiteral = 10668 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10669 10670 llvm::APFloat Value(0.0); 10671 bool IsConstant = 10672 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10673 if (!IsConstant) { 10674 if (isObjCSignedCharBool(S, T)) { 10675 return adornObjCBoolConversionDiagWithTernaryFixit( 10676 S, E, 10677 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10678 << E->getType()); 10679 } 10680 10681 return DiagnoseImpCast(S, E, T, CContext, 10682 diag::warn_impcast_float_integer, PruneWarnings); 10683 } 10684 10685 bool isExact = false; 10686 10687 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10688 T->hasUnsignedIntegerRepresentation()); 10689 llvm::APFloat::opStatus Result = Value.convertToInteger( 10690 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10691 10692 // FIXME: Force the precision of the source value down so we don't print 10693 // digits which are usually useless (we don't really care here if we 10694 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10695 // would automatically print the shortest representation, but it's a bit 10696 // tricky to implement. 10697 SmallString<16> PrettySourceValue; 10698 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10699 precision = (precision * 59 + 195) / 196; 10700 Value.toString(PrettySourceValue, precision); 10701 10702 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10703 return adornObjCBoolConversionDiagWithTernaryFixit( 10704 S, E, 10705 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10706 << PrettySourceValue); 10707 } 10708 10709 if (Result == llvm::APFloat::opOK && isExact) { 10710 if (IsLiteral) return; 10711 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10712 PruneWarnings); 10713 } 10714 10715 // Conversion of a floating-point value to a non-bool integer where the 10716 // integral part cannot be represented by the integer type is undefined. 10717 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10718 return DiagnoseImpCast( 10719 S, E, T, CContext, 10720 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10721 : diag::warn_impcast_float_to_integer_out_of_range, 10722 PruneWarnings); 10723 10724 unsigned DiagID = 0; 10725 if (IsLiteral) { 10726 // Warn on floating point literal to integer. 10727 DiagID = diag::warn_impcast_literal_float_to_integer; 10728 } else if (IntegerValue == 0) { 10729 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10730 return DiagnoseImpCast(S, E, T, CContext, 10731 diag::warn_impcast_float_integer, PruneWarnings); 10732 } 10733 // Warn on non-zero to zero conversion. 10734 DiagID = diag::warn_impcast_float_to_integer_zero; 10735 } else { 10736 if (IntegerValue.isUnsigned()) { 10737 if (!IntegerValue.isMaxValue()) { 10738 return DiagnoseImpCast(S, E, T, CContext, 10739 diag::warn_impcast_float_integer, PruneWarnings); 10740 } 10741 } else { // IntegerValue.isSigned() 10742 if (!IntegerValue.isMaxSignedValue() && 10743 !IntegerValue.isMinSignedValue()) { 10744 return DiagnoseImpCast(S, E, T, CContext, 10745 diag::warn_impcast_float_integer, PruneWarnings); 10746 } 10747 } 10748 // Warn on evaluatable floating point expression to integer conversion. 10749 DiagID = diag::warn_impcast_float_to_integer; 10750 } 10751 10752 SmallString<16> PrettyTargetValue; 10753 if (IsBool) 10754 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10755 else 10756 IntegerValue.toString(PrettyTargetValue); 10757 10758 if (PruneWarnings) { 10759 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10760 S.PDiag(DiagID) 10761 << E->getType() << T.getUnqualifiedType() 10762 << PrettySourceValue << PrettyTargetValue 10763 << E->getSourceRange() << SourceRange(CContext)); 10764 } else { 10765 S.Diag(E->getExprLoc(), DiagID) 10766 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10767 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10768 } 10769 } 10770 10771 /// Analyze the given compound assignment for the possible losing of 10772 /// floating-point precision. 10773 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10774 assert(isa<CompoundAssignOperator>(E) && 10775 "Must be compound assignment operation"); 10776 // Recurse on the LHS and RHS in here 10777 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10778 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10779 10780 if (E->getLHS()->getType()->isAtomicType()) 10781 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10782 10783 // Now check the outermost expression 10784 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10785 const auto *RBT = cast<CompoundAssignOperator>(E) 10786 ->getComputationResultType() 10787 ->getAs<BuiltinType>(); 10788 10789 // The below checks assume source is floating point. 10790 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10791 10792 // If source is floating point but target is an integer. 10793 if (ResultBT->isInteger()) 10794 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10795 E->getExprLoc(), diag::warn_impcast_float_integer); 10796 10797 if (!ResultBT->isFloatingPoint()) 10798 return; 10799 10800 // If both source and target are floating points, warn about losing precision. 10801 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10802 QualType(ResultBT, 0), QualType(RBT, 0)); 10803 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10804 // warn about dropping FP rank. 10805 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10806 diag::warn_impcast_float_result_precision); 10807 } 10808 10809 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10810 IntRange Range) { 10811 if (!Range.Width) return "0"; 10812 10813 llvm::APSInt ValueInRange = Value; 10814 ValueInRange.setIsSigned(!Range.NonNegative); 10815 ValueInRange = ValueInRange.trunc(Range.Width); 10816 return ValueInRange.toString(10); 10817 } 10818 10819 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10820 if (!isa<ImplicitCastExpr>(Ex)) 10821 return false; 10822 10823 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10824 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10825 const Type *Source = 10826 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10827 if (Target->isDependentType()) 10828 return false; 10829 10830 const BuiltinType *FloatCandidateBT = 10831 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10832 const Type *BoolCandidateType = ToBool ? Target : Source; 10833 10834 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10835 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10836 } 10837 10838 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10839 SourceLocation CC) { 10840 unsigned NumArgs = TheCall->getNumArgs(); 10841 for (unsigned i = 0; i < NumArgs; ++i) { 10842 Expr *CurrA = TheCall->getArg(i); 10843 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10844 continue; 10845 10846 bool IsSwapped = ((i > 0) && 10847 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10848 IsSwapped |= ((i < (NumArgs - 1)) && 10849 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10850 if (IsSwapped) { 10851 // Warn on this floating-point to bool conversion. 10852 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10853 CurrA->getType(), CC, 10854 diag::warn_impcast_floating_point_to_bool); 10855 } 10856 } 10857 } 10858 10859 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10860 SourceLocation CC) { 10861 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10862 E->getExprLoc())) 10863 return; 10864 10865 // Don't warn on functions which have return type nullptr_t. 10866 if (isa<CallExpr>(E)) 10867 return; 10868 10869 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10870 const Expr::NullPointerConstantKind NullKind = 10871 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10872 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10873 return; 10874 10875 // Return if target type is a safe conversion. 10876 if (T->isAnyPointerType() || T->isBlockPointerType() || 10877 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10878 return; 10879 10880 SourceLocation Loc = E->getSourceRange().getBegin(); 10881 10882 // Venture through the macro stacks to get to the source of macro arguments. 10883 // The new location is a better location than the complete location that was 10884 // passed in. 10885 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10886 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10887 10888 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10889 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10890 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10891 Loc, S.SourceMgr, S.getLangOpts()); 10892 if (MacroName == "NULL") 10893 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10894 } 10895 10896 // Only warn if the null and context location are in the same macro expansion. 10897 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10898 return; 10899 10900 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10901 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10902 << FixItHint::CreateReplacement(Loc, 10903 S.getFixItZeroLiteralForType(T, Loc)); 10904 } 10905 10906 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10907 ObjCArrayLiteral *ArrayLiteral); 10908 10909 static void 10910 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10911 ObjCDictionaryLiteral *DictionaryLiteral); 10912 10913 /// Check a single element within a collection literal against the 10914 /// target element type. 10915 static void checkObjCCollectionLiteralElement(Sema &S, 10916 QualType TargetElementType, 10917 Expr *Element, 10918 unsigned ElementKind) { 10919 // Skip a bitcast to 'id' or qualified 'id'. 10920 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 10921 if (ICE->getCastKind() == CK_BitCast && 10922 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 10923 Element = ICE->getSubExpr(); 10924 } 10925 10926 QualType ElementType = Element->getType(); 10927 ExprResult ElementResult(Element); 10928 if (ElementType->getAs<ObjCObjectPointerType>() && 10929 S.CheckSingleAssignmentConstraints(TargetElementType, 10930 ElementResult, 10931 false, false) 10932 != Sema::Compatible) { 10933 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 10934 << ElementType << ElementKind << TargetElementType 10935 << Element->getSourceRange(); 10936 } 10937 10938 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 10939 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 10940 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 10941 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 10942 } 10943 10944 /// Check an Objective-C array literal being converted to the given 10945 /// target type. 10946 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10947 ObjCArrayLiteral *ArrayLiteral) { 10948 if (!S.NSArrayDecl) 10949 return; 10950 10951 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10952 if (!TargetObjCPtr) 10953 return; 10954 10955 if (TargetObjCPtr->isUnspecialized() || 10956 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10957 != S.NSArrayDecl->getCanonicalDecl()) 10958 return; 10959 10960 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10961 if (TypeArgs.size() != 1) 10962 return; 10963 10964 QualType TargetElementType = TypeArgs[0]; 10965 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 10966 checkObjCCollectionLiteralElement(S, TargetElementType, 10967 ArrayLiteral->getElement(I), 10968 0); 10969 } 10970 } 10971 10972 /// Check an Objective-C dictionary literal being converted to the given 10973 /// target type. 10974 static void 10975 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10976 ObjCDictionaryLiteral *DictionaryLiteral) { 10977 if (!S.NSDictionaryDecl) 10978 return; 10979 10980 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 10981 if (!TargetObjCPtr) 10982 return; 10983 10984 if (TargetObjCPtr->isUnspecialized() || 10985 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 10986 != S.NSDictionaryDecl->getCanonicalDecl()) 10987 return; 10988 10989 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 10990 if (TypeArgs.size() != 2) 10991 return; 10992 10993 QualType TargetKeyType = TypeArgs[0]; 10994 QualType TargetObjectType = TypeArgs[1]; 10995 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 10996 auto Element = DictionaryLiteral->getKeyValueElement(I); 10997 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 10998 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 10999 } 11000 } 11001 11002 // Helper function to filter out cases for constant width constant conversion. 11003 // Don't warn on char array initialization or for non-decimal values. 11004 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11005 SourceLocation CC) { 11006 // If initializing from a constant, and the constant starts with '0', 11007 // then it is a binary, octal, or hexadecimal. Allow these constants 11008 // to fill all the bits, even if there is a sign change. 11009 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11010 const char FirstLiteralCharacter = 11011 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11012 if (FirstLiteralCharacter == '0') 11013 return false; 11014 } 11015 11016 // If the CC location points to a '{', and the type is char, then assume 11017 // assume it is an array initialization. 11018 if (CC.isValid() && T->isCharType()) { 11019 const char FirstContextCharacter = 11020 S.getSourceManager().getCharacterData(CC)[0]; 11021 if (FirstContextCharacter == '{') 11022 return false; 11023 } 11024 11025 return true; 11026 } 11027 11028 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11029 const auto *IL = dyn_cast<IntegerLiteral>(E); 11030 if (!IL) { 11031 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11032 if (UO->getOpcode() == UO_Minus) 11033 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11034 } 11035 } 11036 11037 return IL; 11038 } 11039 11040 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11041 E = E->IgnoreParenImpCasts(); 11042 SourceLocation ExprLoc = E->getExprLoc(); 11043 11044 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11045 BinaryOperator::Opcode Opc = BO->getOpcode(); 11046 Expr::EvalResult Result; 11047 // Do not diagnose unsigned shifts. 11048 if (Opc == BO_Shl) { 11049 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11050 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11051 if (LHS && LHS->getValue() == 0) 11052 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11053 else if (!E->isValueDependent() && LHS && RHS && 11054 RHS->getValue().isNonNegative() && 11055 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11056 S.Diag(ExprLoc, diag::warn_left_shift_always) 11057 << (Result.Val.getInt() != 0); 11058 else if (E->getType()->isSignedIntegerType()) 11059 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11060 } 11061 } 11062 11063 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11064 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11065 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11066 if (!LHS || !RHS) 11067 return; 11068 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11069 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11070 // Do not diagnose common idioms. 11071 return; 11072 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11073 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11074 } 11075 } 11076 11077 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11078 SourceLocation CC, 11079 bool *ICContext = nullptr, 11080 bool IsListInit = false) { 11081 if (E->isTypeDependent() || E->isValueDependent()) return; 11082 11083 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11084 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11085 if (Source == Target) return; 11086 if (Target->isDependentType()) return; 11087 11088 // If the conversion context location is invalid don't complain. We also 11089 // don't want to emit a warning if the issue occurs from the expansion of 11090 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11091 // delay this check as long as possible. Once we detect we are in that 11092 // scenario, we just return. 11093 if (CC.isInvalid()) 11094 return; 11095 11096 if (Source->isAtomicType()) 11097 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11098 11099 // Diagnose implicit casts to bool. 11100 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11101 if (isa<StringLiteral>(E)) 11102 // Warn on string literal to bool. Checks for string literals in logical 11103 // and expressions, for instance, assert(0 && "error here"), are 11104 // prevented by a check in AnalyzeImplicitConversions(). 11105 return DiagnoseImpCast(S, E, T, CC, 11106 diag::warn_impcast_string_literal_to_bool); 11107 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11108 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11109 // This covers the literal expressions that evaluate to Objective-C 11110 // objects. 11111 return DiagnoseImpCast(S, E, T, CC, 11112 diag::warn_impcast_objective_c_literal_to_bool); 11113 } 11114 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11115 // Warn on pointer to bool conversion that is always true. 11116 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11117 SourceRange(CC)); 11118 } 11119 } 11120 11121 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11122 // is a typedef for signed char (macOS), then that constant value has to be 1 11123 // or 0. 11124 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11125 Expr::EvalResult Result; 11126 if (E->EvaluateAsInt(Result, S.getASTContext(), 11127 Expr::SE_AllowSideEffects)) { 11128 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11129 adornObjCBoolConversionDiagWithTernaryFixit( 11130 S, E, 11131 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11132 << Result.Val.getInt().toString(10)); 11133 } 11134 return; 11135 } 11136 } 11137 11138 // Check implicit casts from Objective-C collection literals to specialized 11139 // collection types, e.g., NSArray<NSString *> *. 11140 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11141 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11142 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11143 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11144 11145 // Strip vector types. 11146 if (isa<VectorType>(Source)) { 11147 if (!isa<VectorType>(Target)) { 11148 if (S.SourceMgr.isInSystemMacro(CC)) 11149 return; 11150 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11151 } 11152 11153 // If the vector cast is cast between two vectors of the same size, it is 11154 // a bitcast, not a conversion. 11155 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11156 return; 11157 11158 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11159 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11160 } 11161 if (auto VecTy = dyn_cast<VectorType>(Target)) 11162 Target = VecTy->getElementType().getTypePtr(); 11163 11164 // Strip complex types. 11165 if (isa<ComplexType>(Source)) { 11166 if (!isa<ComplexType>(Target)) { 11167 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11168 return; 11169 11170 return DiagnoseImpCast(S, E, T, CC, 11171 S.getLangOpts().CPlusPlus 11172 ? diag::err_impcast_complex_scalar 11173 : diag::warn_impcast_complex_scalar); 11174 } 11175 11176 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11177 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11178 } 11179 11180 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11181 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11182 11183 // If the source is floating point... 11184 if (SourceBT && SourceBT->isFloatingPoint()) { 11185 // ...and the target is floating point... 11186 if (TargetBT && TargetBT->isFloatingPoint()) { 11187 // ...then warn if we're dropping FP rank. 11188 11189 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11190 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11191 if (Order > 0) { 11192 // Don't warn about float constants that are precisely 11193 // representable in the target type. 11194 Expr::EvalResult result; 11195 if (E->EvaluateAsRValue(result, S.Context)) { 11196 // Value might be a float, a float vector, or a float complex. 11197 if (IsSameFloatAfterCast(result.Val, 11198 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11199 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11200 return; 11201 } 11202 11203 if (S.SourceMgr.isInSystemMacro(CC)) 11204 return; 11205 11206 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11207 } 11208 // ... or possibly if we're increasing rank, too 11209 else if (Order < 0) { 11210 if (S.SourceMgr.isInSystemMacro(CC)) 11211 return; 11212 11213 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11214 } 11215 return; 11216 } 11217 11218 // If the target is integral, always warn. 11219 if (TargetBT && TargetBT->isInteger()) { 11220 if (S.SourceMgr.isInSystemMacro(CC)) 11221 return; 11222 11223 DiagnoseFloatingImpCast(S, E, T, CC); 11224 } 11225 11226 // Detect the case where a call result is converted from floating-point to 11227 // to bool, and the final argument to the call is converted from bool, to 11228 // discover this typo: 11229 // 11230 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11231 // 11232 // FIXME: This is an incredibly special case; is there some more general 11233 // way to detect this class of misplaced-parentheses bug? 11234 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11235 // Check last argument of function call to see if it is an 11236 // implicit cast from a type matching the type the result 11237 // is being cast to. 11238 CallExpr *CEx = cast<CallExpr>(E); 11239 if (unsigned NumArgs = CEx->getNumArgs()) { 11240 Expr *LastA = CEx->getArg(NumArgs - 1); 11241 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11242 if (isa<ImplicitCastExpr>(LastA) && 11243 InnerE->getType()->isBooleanType()) { 11244 // Warn on this floating-point to bool conversion 11245 DiagnoseImpCast(S, E, T, CC, 11246 diag::warn_impcast_floating_point_to_bool); 11247 } 11248 } 11249 } 11250 return; 11251 } 11252 11253 // Valid casts involving fixed point types should be accounted for here. 11254 if (Source->isFixedPointType()) { 11255 if (Target->isUnsaturatedFixedPointType()) { 11256 Expr::EvalResult Result; 11257 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11258 S.isConstantEvaluated())) { 11259 APFixedPoint Value = Result.Val.getFixedPoint(); 11260 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11261 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11262 if (Value > MaxVal || Value < MinVal) { 11263 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11264 S.PDiag(diag::warn_impcast_fixed_point_range) 11265 << Value.toString() << T 11266 << E->getSourceRange() 11267 << clang::SourceRange(CC)); 11268 return; 11269 } 11270 } 11271 } else if (Target->isIntegerType()) { 11272 Expr::EvalResult Result; 11273 if (!S.isConstantEvaluated() && 11274 E->EvaluateAsFixedPoint(Result, S.Context, 11275 Expr::SE_AllowSideEffects)) { 11276 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11277 11278 bool Overflowed; 11279 llvm::APSInt IntResult = FXResult.convertToInt( 11280 S.Context.getIntWidth(T), 11281 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11282 11283 if (Overflowed) { 11284 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11285 S.PDiag(diag::warn_impcast_fixed_point_range) 11286 << FXResult.toString() << T 11287 << E->getSourceRange() 11288 << clang::SourceRange(CC)); 11289 return; 11290 } 11291 } 11292 } 11293 } else if (Target->isUnsaturatedFixedPointType()) { 11294 if (Source->isIntegerType()) { 11295 Expr::EvalResult Result; 11296 if (!S.isConstantEvaluated() && 11297 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11298 llvm::APSInt Value = Result.Val.getInt(); 11299 11300 bool Overflowed; 11301 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11302 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11303 11304 if (Overflowed) { 11305 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11306 S.PDiag(diag::warn_impcast_fixed_point_range) 11307 << Value.toString(/*Radix=*/10) << T 11308 << E->getSourceRange() 11309 << clang::SourceRange(CC)); 11310 return; 11311 } 11312 } 11313 } 11314 } 11315 11316 // If we are casting an integer type to a floating point type without 11317 // initialization-list syntax, we might lose accuracy if the floating 11318 // point type has a narrower significand than the integer type. 11319 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11320 TargetBT->isFloatingType() && !IsListInit) { 11321 // Determine the number of precision bits in the source integer type. 11322 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11323 unsigned int SourcePrecision = SourceRange.Width; 11324 11325 // Determine the number of precision bits in the 11326 // target floating point type. 11327 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11328 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11329 11330 if (SourcePrecision > 0 && TargetPrecision > 0 && 11331 SourcePrecision > TargetPrecision) { 11332 11333 llvm::APSInt SourceInt; 11334 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11335 // If the source integer is a constant, convert it to the target 11336 // floating point type. Issue a warning if the value changes 11337 // during the whole conversion. 11338 llvm::APFloat TargetFloatValue( 11339 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11340 llvm::APFloat::opStatus ConversionStatus = 11341 TargetFloatValue.convertFromAPInt( 11342 SourceInt, SourceBT->isSignedInteger(), 11343 llvm::APFloat::rmNearestTiesToEven); 11344 11345 if (ConversionStatus != llvm::APFloat::opOK) { 11346 std::string PrettySourceValue = SourceInt.toString(10); 11347 SmallString<32> PrettyTargetValue; 11348 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11349 11350 S.DiagRuntimeBehavior( 11351 E->getExprLoc(), E, 11352 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11353 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11354 << E->getSourceRange() << clang::SourceRange(CC)); 11355 } 11356 } else { 11357 // Otherwise, the implicit conversion may lose precision. 11358 DiagnoseImpCast(S, E, T, CC, 11359 diag::warn_impcast_integer_float_precision); 11360 } 11361 } 11362 } 11363 11364 DiagnoseNullConversion(S, E, T, CC); 11365 11366 S.DiscardMisalignedMemberAddress(Target, E); 11367 11368 if (Target->isBooleanType()) 11369 DiagnoseIntInBoolContext(S, E); 11370 11371 if (!Source->isIntegerType() || !Target->isIntegerType()) 11372 return; 11373 11374 // TODO: remove this early return once the false positives for constant->bool 11375 // in templates, macros, etc, are reduced or removed. 11376 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11377 return; 11378 11379 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11380 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11381 return adornObjCBoolConversionDiagWithTernaryFixit( 11382 S, E, 11383 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11384 << E->getType()); 11385 } 11386 11387 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11388 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11389 11390 if (SourceRange.Width > TargetRange.Width) { 11391 // If the source is a constant, use a default-on diagnostic. 11392 // TODO: this should happen for bitfield stores, too. 11393 Expr::EvalResult Result; 11394 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11395 S.isConstantEvaluated())) { 11396 llvm::APSInt Value(32); 11397 Value = Result.Val.getInt(); 11398 11399 if (S.SourceMgr.isInSystemMacro(CC)) 11400 return; 11401 11402 std::string PrettySourceValue = Value.toString(10); 11403 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11404 11405 S.DiagRuntimeBehavior( 11406 E->getExprLoc(), E, 11407 S.PDiag(diag::warn_impcast_integer_precision_constant) 11408 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11409 << E->getSourceRange() << clang::SourceRange(CC)); 11410 return; 11411 } 11412 11413 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11414 if (S.SourceMgr.isInSystemMacro(CC)) 11415 return; 11416 11417 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11418 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11419 /* pruneControlFlow */ true); 11420 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11421 } 11422 11423 if (TargetRange.Width > SourceRange.Width) { 11424 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11425 if (UO->getOpcode() == UO_Minus) 11426 if (Source->isUnsignedIntegerType()) { 11427 if (Target->isUnsignedIntegerType()) 11428 return DiagnoseImpCast(S, E, T, CC, 11429 diag::warn_impcast_high_order_zero_bits); 11430 if (Target->isSignedIntegerType()) 11431 return DiagnoseImpCast(S, E, T, CC, 11432 diag::warn_impcast_nonnegative_result); 11433 } 11434 } 11435 11436 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11437 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11438 // Warn when doing a signed to signed conversion, warn if the positive 11439 // source value is exactly the width of the target type, which will 11440 // cause a negative value to be stored. 11441 11442 Expr::EvalResult Result; 11443 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11444 !S.SourceMgr.isInSystemMacro(CC)) { 11445 llvm::APSInt Value = Result.Val.getInt(); 11446 if (isSameWidthConstantConversion(S, E, T, CC)) { 11447 std::string PrettySourceValue = Value.toString(10); 11448 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11449 11450 S.DiagRuntimeBehavior( 11451 E->getExprLoc(), E, 11452 S.PDiag(diag::warn_impcast_integer_precision_constant) 11453 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11454 << E->getSourceRange() << clang::SourceRange(CC)); 11455 return; 11456 } 11457 } 11458 11459 // Fall through for non-constants to give a sign conversion warning. 11460 } 11461 11462 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11463 (!TargetRange.NonNegative && SourceRange.NonNegative && 11464 SourceRange.Width == TargetRange.Width)) { 11465 if (S.SourceMgr.isInSystemMacro(CC)) 11466 return; 11467 11468 unsigned DiagID = diag::warn_impcast_integer_sign; 11469 11470 // Traditionally, gcc has warned about this under -Wsign-compare. 11471 // We also want to warn about it in -Wconversion. 11472 // So if -Wconversion is off, use a completely identical diagnostic 11473 // in the sign-compare group. 11474 // The conditional-checking code will 11475 if (ICContext) { 11476 DiagID = diag::warn_impcast_integer_sign_conditional; 11477 *ICContext = true; 11478 } 11479 11480 return DiagnoseImpCast(S, E, T, CC, DiagID); 11481 } 11482 11483 // Diagnose conversions between different enumeration types. 11484 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11485 // type, to give us better diagnostics. 11486 QualType SourceType = E->getType(); 11487 if (!S.getLangOpts().CPlusPlus) { 11488 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11489 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11490 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11491 SourceType = S.Context.getTypeDeclType(Enum); 11492 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11493 } 11494 } 11495 11496 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11497 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11498 if (SourceEnum->getDecl()->hasNameForLinkage() && 11499 TargetEnum->getDecl()->hasNameForLinkage() && 11500 SourceEnum != TargetEnum) { 11501 if (S.SourceMgr.isInSystemMacro(CC)) 11502 return; 11503 11504 return DiagnoseImpCast(S, E, SourceType, T, CC, 11505 diag::warn_impcast_different_enum_types); 11506 } 11507 } 11508 11509 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11510 SourceLocation CC, QualType T); 11511 11512 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11513 SourceLocation CC, bool &ICContext) { 11514 E = E->IgnoreParenImpCasts(); 11515 11516 if (isa<ConditionalOperator>(E)) 11517 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11518 11519 AnalyzeImplicitConversions(S, E, CC); 11520 if (E->getType() != T) 11521 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11522 } 11523 11524 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11525 SourceLocation CC, QualType T) { 11526 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11527 11528 bool Suspicious = false; 11529 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11530 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11531 11532 if (T->isBooleanType()) 11533 DiagnoseIntInBoolContext(S, E); 11534 11535 // If -Wconversion would have warned about either of the candidates 11536 // for a signedness conversion to the context type... 11537 if (!Suspicious) return; 11538 11539 // ...but it's currently ignored... 11540 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11541 return; 11542 11543 // ...then check whether it would have warned about either of the 11544 // candidates for a signedness conversion to the condition type. 11545 if (E->getType() == T) return; 11546 11547 Suspicious = false; 11548 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11549 E->getType(), CC, &Suspicious); 11550 if (!Suspicious) 11551 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11552 E->getType(), CC, &Suspicious); 11553 } 11554 11555 /// Check conversion of given expression to boolean. 11556 /// Input argument E is a logical expression. 11557 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11558 if (S.getLangOpts().Bool) 11559 return; 11560 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11561 return; 11562 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11563 } 11564 11565 /// AnalyzeImplicitConversions - Find and report any interesting 11566 /// implicit conversions in the given expression. There are a couple 11567 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11568 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11569 bool IsListInit/*= false*/) { 11570 QualType T = OrigE->getType(); 11571 Expr *E = OrigE->IgnoreParenImpCasts(); 11572 11573 // Propagate whether we are in a C++ list initialization expression. 11574 // If so, we do not issue warnings for implicit int-float conversion 11575 // precision loss, because C++11 narrowing already handles it. 11576 IsListInit = 11577 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11578 11579 if (E->isTypeDependent() || E->isValueDependent()) 11580 return; 11581 11582 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 11583 if (UO->getOpcode() == UO_Not && 11584 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11585 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11586 << OrigE->getSourceRange() << T->isBooleanType() 11587 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11588 11589 // For conditional operators, we analyze the arguments as if they 11590 // were being fed directly into the output. 11591 if (isa<ConditionalOperator>(E)) { 11592 ConditionalOperator *CO = cast<ConditionalOperator>(E); 11593 CheckConditionalOperator(S, CO, CC, T); 11594 return; 11595 } 11596 11597 // Check implicit argument conversions for function calls. 11598 if (CallExpr *Call = dyn_cast<CallExpr>(E)) 11599 CheckImplicitArgumentConversions(S, Call, CC); 11600 11601 // Go ahead and check any implicit conversions we might have skipped. 11602 // The non-canonical typecheck is just an optimization; 11603 // CheckImplicitConversion will filter out dead implicit conversions. 11604 if (E->getType() != T) 11605 CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit); 11606 11607 // Now continue drilling into this expression. 11608 11609 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11610 // The bound subexpressions in a PseudoObjectExpr are not reachable 11611 // as transitive children. 11612 // FIXME: Use a more uniform representation for this. 11613 for (auto *SE : POE->semantics()) 11614 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11615 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 11616 } 11617 11618 // Skip past explicit casts. 11619 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11620 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11621 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11622 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11623 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 11624 } 11625 11626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11627 // Do a somewhat different check with comparison operators. 11628 if (BO->isComparisonOp()) 11629 return AnalyzeComparison(S, BO); 11630 11631 // And with simple assignments. 11632 if (BO->getOpcode() == BO_Assign) 11633 return AnalyzeAssignment(S, BO); 11634 // And with compound assignments. 11635 if (BO->isAssignmentOp()) 11636 return AnalyzeCompoundAssignment(S, BO); 11637 } 11638 11639 // These break the otherwise-useful invariant below. Fortunately, 11640 // we don't really need to recurse into them, because any internal 11641 // expressions should have been analyzed already when they were 11642 // built into statements. 11643 if (isa<StmtExpr>(E)) return; 11644 11645 // Don't descend into unevaluated contexts. 11646 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11647 11648 // Now just recurse over the expression's children. 11649 CC = E->getExprLoc(); 11650 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11651 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11652 for (Stmt *SubStmt : E->children()) { 11653 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11654 if (!ChildExpr) 11655 continue; 11656 11657 if (IsLogicalAndOperator && 11658 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11659 // Ignore checking string literals that are in logical and operators. 11660 // This is a common pattern for asserts. 11661 continue; 11662 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 11663 } 11664 11665 if (BO && BO->isLogicalOp()) { 11666 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11667 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11668 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11669 11670 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11671 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11672 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11673 } 11674 11675 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11676 if (U->getOpcode() == UO_LNot) { 11677 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11678 } else if (U->getOpcode() != UO_AddrOf) { 11679 if (U->getSubExpr()->getType()->isAtomicType()) 11680 S.Diag(U->getSubExpr()->getBeginLoc(), 11681 diag::warn_atomic_implicit_seq_cst); 11682 } 11683 } 11684 } 11685 11686 /// Diagnose integer type and any valid implicit conversion to it. 11687 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11688 // Taking into account implicit conversions, 11689 // allow any integer. 11690 if (!E->getType()->isIntegerType()) { 11691 S.Diag(E->getBeginLoc(), 11692 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11693 return true; 11694 } 11695 // Potentially emit standard warnings for implicit conversions if enabled 11696 // using -Wconversion. 11697 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11698 return false; 11699 } 11700 11701 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11702 // Returns true when emitting a warning about taking the address of a reference. 11703 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11704 const PartialDiagnostic &PD) { 11705 E = E->IgnoreParenImpCasts(); 11706 11707 const FunctionDecl *FD = nullptr; 11708 11709 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11710 if (!DRE->getDecl()->getType()->isReferenceType()) 11711 return false; 11712 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11713 if (!M->getMemberDecl()->getType()->isReferenceType()) 11714 return false; 11715 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11716 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11717 return false; 11718 FD = Call->getDirectCallee(); 11719 } else { 11720 return false; 11721 } 11722 11723 SemaRef.Diag(E->getExprLoc(), PD); 11724 11725 // If possible, point to location of function. 11726 if (FD) { 11727 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11728 } 11729 11730 return true; 11731 } 11732 11733 // Returns true if the SourceLocation is expanded from any macro body. 11734 // Returns false if the SourceLocation is invalid, is from not in a macro 11735 // expansion, or is from expanded from a top-level macro argument. 11736 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11737 if (Loc.isInvalid()) 11738 return false; 11739 11740 while (Loc.isMacroID()) { 11741 if (SM.isMacroBodyExpansion(Loc)) 11742 return true; 11743 Loc = SM.getImmediateMacroCallerLoc(Loc); 11744 } 11745 11746 return false; 11747 } 11748 11749 /// Diagnose pointers that are always non-null. 11750 /// \param E the expression containing the pointer 11751 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11752 /// compared to a null pointer 11753 /// \param IsEqual True when the comparison is equal to a null pointer 11754 /// \param Range Extra SourceRange to highlight in the diagnostic 11755 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11756 Expr::NullPointerConstantKind NullKind, 11757 bool IsEqual, SourceRange Range) { 11758 if (!E) 11759 return; 11760 11761 // Don't warn inside macros. 11762 if (E->getExprLoc().isMacroID()) { 11763 const SourceManager &SM = getSourceManager(); 11764 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11765 IsInAnyMacroBody(SM, Range.getBegin())) 11766 return; 11767 } 11768 E = E->IgnoreImpCasts(); 11769 11770 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11771 11772 if (isa<CXXThisExpr>(E)) { 11773 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11774 : diag::warn_this_bool_conversion; 11775 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11776 return; 11777 } 11778 11779 bool IsAddressOf = false; 11780 11781 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11782 if (UO->getOpcode() != UO_AddrOf) 11783 return; 11784 IsAddressOf = true; 11785 E = UO->getSubExpr(); 11786 } 11787 11788 if (IsAddressOf) { 11789 unsigned DiagID = IsCompare 11790 ? diag::warn_address_of_reference_null_compare 11791 : diag::warn_address_of_reference_bool_conversion; 11792 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11793 << IsEqual; 11794 if (CheckForReference(*this, E, PD)) { 11795 return; 11796 } 11797 } 11798 11799 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11800 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11801 std::string Str; 11802 llvm::raw_string_ostream S(Str); 11803 E->printPretty(S, nullptr, getPrintingPolicy()); 11804 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11805 : diag::warn_cast_nonnull_to_bool; 11806 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11807 << E->getSourceRange() << Range << IsEqual; 11808 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11809 }; 11810 11811 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11812 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11813 if (auto *Callee = Call->getDirectCallee()) { 11814 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11815 ComplainAboutNonnullParamOrCall(A); 11816 return; 11817 } 11818 } 11819 } 11820 11821 // Expect to find a single Decl. Skip anything more complicated. 11822 ValueDecl *D = nullptr; 11823 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11824 D = R->getDecl(); 11825 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11826 D = M->getMemberDecl(); 11827 } 11828 11829 // Weak Decls can be null. 11830 if (!D || D->isWeak()) 11831 return; 11832 11833 // Check for parameter decl with nonnull attribute 11834 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11835 if (getCurFunction() && 11836 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11837 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11838 ComplainAboutNonnullParamOrCall(A); 11839 return; 11840 } 11841 11842 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11843 // Skip function template not specialized yet. 11844 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11845 return; 11846 auto ParamIter = llvm::find(FD->parameters(), PV); 11847 assert(ParamIter != FD->param_end()); 11848 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11849 11850 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11851 if (!NonNull->args_size()) { 11852 ComplainAboutNonnullParamOrCall(NonNull); 11853 return; 11854 } 11855 11856 for (const ParamIdx &ArgNo : NonNull->args()) { 11857 if (ArgNo.getASTIndex() == ParamNo) { 11858 ComplainAboutNonnullParamOrCall(NonNull); 11859 return; 11860 } 11861 } 11862 } 11863 } 11864 } 11865 } 11866 11867 QualType T = D->getType(); 11868 const bool IsArray = T->isArrayType(); 11869 const bool IsFunction = T->isFunctionType(); 11870 11871 // Address of function is used to silence the function warning. 11872 if (IsAddressOf && IsFunction) { 11873 return; 11874 } 11875 11876 // Found nothing. 11877 if (!IsAddressOf && !IsFunction && !IsArray) 11878 return; 11879 11880 // Pretty print the expression for the diagnostic. 11881 std::string Str; 11882 llvm::raw_string_ostream S(Str); 11883 E->printPretty(S, nullptr, getPrintingPolicy()); 11884 11885 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11886 : diag::warn_impcast_pointer_to_bool; 11887 enum { 11888 AddressOf, 11889 FunctionPointer, 11890 ArrayPointer 11891 } DiagType; 11892 if (IsAddressOf) 11893 DiagType = AddressOf; 11894 else if (IsFunction) 11895 DiagType = FunctionPointer; 11896 else if (IsArray) 11897 DiagType = ArrayPointer; 11898 else 11899 llvm_unreachable("Could not determine diagnostic."); 11900 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11901 << Range << IsEqual; 11902 11903 if (!IsFunction) 11904 return; 11905 11906 // Suggest '&' to silence the function warning. 11907 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11908 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11909 11910 // Check to see if '()' fixit should be emitted. 11911 QualType ReturnType; 11912 UnresolvedSet<4> NonTemplateOverloads; 11913 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 11914 if (ReturnType.isNull()) 11915 return; 11916 11917 if (IsCompare) { 11918 // There are two cases here. If there is null constant, the only suggest 11919 // for a pointer return type. If the null is 0, then suggest if the return 11920 // type is a pointer or an integer type. 11921 if (!ReturnType->isPointerType()) { 11922 if (NullKind == Expr::NPCK_ZeroExpression || 11923 NullKind == Expr::NPCK_ZeroLiteral) { 11924 if (!ReturnType->isIntegerType()) 11925 return; 11926 } else { 11927 return; 11928 } 11929 } 11930 } else { // !IsCompare 11931 // For function to bool, only suggest if the function pointer has bool 11932 // return type. 11933 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 11934 return; 11935 } 11936 Diag(E->getExprLoc(), diag::note_function_to_function_call) 11937 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 11938 } 11939 11940 /// Diagnoses "dangerous" implicit conversions within the given 11941 /// expression (which is a full expression). Implements -Wconversion 11942 /// and -Wsign-compare. 11943 /// 11944 /// \param CC the "context" location of the implicit conversion, i.e. 11945 /// the most location of the syntactic entity requiring the implicit 11946 /// conversion 11947 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 11948 // Don't diagnose in unevaluated contexts. 11949 if (isUnevaluatedContext()) 11950 return; 11951 11952 // Don't diagnose for value- or type-dependent expressions. 11953 if (E->isTypeDependent() || E->isValueDependent()) 11954 return; 11955 11956 // Check for array bounds violations in cases where the check isn't triggered 11957 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 11958 // ArraySubscriptExpr is on the RHS of a variable initialization. 11959 CheckArrayAccess(E); 11960 11961 // This is not the right CC for (e.g.) a variable initialization. 11962 AnalyzeImplicitConversions(*this, E, CC); 11963 } 11964 11965 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 11966 /// Input argument E is a logical expression. 11967 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 11968 ::CheckBoolLikeConversion(*this, E, CC); 11969 } 11970 11971 /// Diagnose when expression is an integer constant expression and its evaluation 11972 /// results in integer overflow 11973 void Sema::CheckForIntOverflow (Expr *E) { 11974 // Use a work list to deal with nested struct initializers. 11975 SmallVector<Expr *, 2> Exprs(1, E); 11976 11977 do { 11978 Expr *OriginalE = Exprs.pop_back_val(); 11979 Expr *E = OriginalE->IgnoreParenCasts(); 11980 11981 if (isa<BinaryOperator>(E)) { 11982 E->EvaluateForOverflow(Context); 11983 continue; 11984 } 11985 11986 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 11987 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 11988 else if (isa<ObjCBoxedExpr>(OriginalE)) 11989 E->EvaluateForOverflow(Context); 11990 else if (auto Call = dyn_cast<CallExpr>(E)) 11991 Exprs.append(Call->arg_begin(), Call->arg_end()); 11992 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 11993 Exprs.append(Message->arg_begin(), Message->arg_end()); 11994 } while (!Exprs.empty()); 11995 } 11996 11997 namespace { 11998 11999 /// Visitor for expressions which looks for unsequenced operations on the 12000 /// same object. 12001 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12002 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12003 12004 /// A tree of sequenced regions within an expression. Two regions are 12005 /// unsequenced if one is an ancestor or a descendent of the other. When we 12006 /// finish processing an expression with sequencing, such as a comma 12007 /// expression, we fold its tree nodes into its parent, since they are 12008 /// unsequenced with respect to nodes we will visit later. 12009 class SequenceTree { 12010 struct Value { 12011 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12012 unsigned Parent : 31; 12013 unsigned Merged : 1; 12014 }; 12015 SmallVector<Value, 8> Values; 12016 12017 public: 12018 /// A region within an expression which may be sequenced with respect 12019 /// to some other region. 12020 class Seq { 12021 friend class SequenceTree; 12022 12023 unsigned Index; 12024 12025 explicit Seq(unsigned N) : Index(N) {} 12026 12027 public: 12028 Seq() : Index(0) {} 12029 }; 12030 12031 SequenceTree() { Values.push_back(Value(0)); } 12032 Seq root() const { return Seq(0); } 12033 12034 /// Create a new sequence of operations, which is an unsequenced 12035 /// subset of \p Parent. This sequence of operations is sequenced with 12036 /// respect to other children of \p Parent. 12037 Seq allocate(Seq Parent) { 12038 Values.push_back(Value(Parent.Index)); 12039 return Seq(Values.size() - 1); 12040 } 12041 12042 /// Merge a sequence of operations into its parent. 12043 void merge(Seq S) { 12044 Values[S.Index].Merged = true; 12045 } 12046 12047 /// Determine whether two operations are unsequenced. This operation 12048 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12049 /// should have been merged into its parent as appropriate. 12050 bool isUnsequenced(Seq Cur, Seq Old) { 12051 unsigned C = representative(Cur.Index); 12052 unsigned Target = representative(Old.Index); 12053 while (C >= Target) { 12054 if (C == Target) 12055 return true; 12056 C = Values[C].Parent; 12057 } 12058 return false; 12059 } 12060 12061 private: 12062 /// Pick a representative for a sequence. 12063 unsigned representative(unsigned K) { 12064 if (Values[K].Merged) 12065 // Perform path compression as we go. 12066 return Values[K].Parent = representative(Values[K].Parent); 12067 return K; 12068 } 12069 }; 12070 12071 /// An object for which we can track unsequenced uses. 12072 using Object = const NamedDecl *; 12073 12074 /// Different flavors of object usage which we track. We only track the 12075 /// least-sequenced usage of each kind. 12076 enum UsageKind { 12077 /// A read of an object. Multiple unsequenced reads are OK. 12078 UK_Use, 12079 12080 /// A modification of an object which is sequenced before the value 12081 /// computation of the expression, such as ++n in C++. 12082 UK_ModAsValue, 12083 12084 /// A modification of an object which is not sequenced before the value 12085 /// computation of the expression, such as n++. 12086 UK_ModAsSideEffect, 12087 12088 UK_Count = UK_ModAsSideEffect + 1 12089 }; 12090 12091 /// Bundle together a sequencing region and the expression corresponding 12092 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12093 struct Usage { 12094 const Expr *UsageExpr; 12095 SequenceTree::Seq Seq; 12096 12097 Usage() : UsageExpr(nullptr), Seq() {} 12098 }; 12099 12100 struct UsageInfo { 12101 Usage Uses[UK_Count]; 12102 12103 /// Have we issued a diagnostic for this object already? 12104 bool Diagnosed; 12105 12106 UsageInfo() : Uses(), Diagnosed(false) {} 12107 }; 12108 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12109 12110 Sema &SemaRef; 12111 12112 /// Sequenced regions within the expression. 12113 SequenceTree Tree; 12114 12115 /// Declaration modifications and references which we have seen. 12116 UsageInfoMap UsageMap; 12117 12118 /// The region we are currently within. 12119 SequenceTree::Seq Region; 12120 12121 /// Filled in with declarations which were modified as a side-effect 12122 /// (that is, post-increment operations). 12123 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12124 12125 /// Expressions to check later. We defer checking these to reduce 12126 /// stack usage. 12127 SmallVectorImpl<const Expr *> &WorkList; 12128 12129 /// RAII object wrapping the visitation of a sequenced subexpression of an 12130 /// expression. At the end of this process, the side-effects of the evaluation 12131 /// become sequenced with respect to the value computation of the result, so 12132 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12133 /// UK_ModAsValue. 12134 struct SequencedSubexpression { 12135 SequencedSubexpression(SequenceChecker &Self) 12136 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12137 Self.ModAsSideEffect = &ModAsSideEffect; 12138 } 12139 12140 ~SequencedSubexpression() { 12141 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12142 // Add a new usage with usage kind UK_ModAsValue, and then restore 12143 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12144 // the previous one was empty). 12145 UsageInfo &UI = Self.UsageMap[M.first]; 12146 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12147 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12148 SideEffectUsage = M.second; 12149 } 12150 Self.ModAsSideEffect = OldModAsSideEffect; 12151 } 12152 12153 SequenceChecker &Self; 12154 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12155 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12156 }; 12157 12158 /// RAII object wrapping the visitation of a subexpression which we might 12159 /// choose to evaluate as a constant. If any subexpression is evaluated and 12160 /// found to be non-constant, this allows us to suppress the evaluation of 12161 /// the outer expression. 12162 class EvaluationTracker { 12163 public: 12164 EvaluationTracker(SequenceChecker &Self) 12165 : Self(Self), Prev(Self.EvalTracker) { 12166 Self.EvalTracker = this; 12167 } 12168 12169 ~EvaluationTracker() { 12170 Self.EvalTracker = Prev; 12171 if (Prev) 12172 Prev->EvalOK &= EvalOK; 12173 } 12174 12175 bool evaluate(const Expr *E, bool &Result) { 12176 if (!EvalOK || E->isValueDependent()) 12177 return false; 12178 EvalOK = E->EvaluateAsBooleanCondition( 12179 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12180 return EvalOK; 12181 } 12182 12183 private: 12184 SequenceChecker &Self; 12185 EvaluationTracker *Prev; 12186 bool EvalOK = true; 12187 } *EvalTracker = nullptr; 12188 12189 /// Find the object which is produced by the specified expression, 12190 /// if any. 12191 Object getObject(const Expr *E, bool Mod) const { 12192 E = E->IgnoreParenCasts(); 12193 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12194 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12195 return getObject(UO->getSubExpr(), Mod); 12196 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12197 if (BO->getOpcode() == BO_Comma) 12198 return getObject(BO->getRHS(), Mod); 12199 if (Mod && BO->isAssignmentOp()) 12200 return getObject(BO->getLHS(), Mod); 12201 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12202 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12203 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12204 return ME->getMemberDecl(); 12205 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12206 // FIXME: If this is a reference, map through to its value. 12207 return DRE->getDecl(); 12208 return nullptr; 12209 } 12210 12211 /// Note that an object \p O was modified or used by an expression 12212 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12213 /// the object \p O as obtained via the \p UsageMap. 12214 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12215 // Get the old usage for the given object and usage kind. 12216 Usage &U = UI.Uses[UK]; 12217 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12218 // If we have a modification as side effect and are in a sequenced 12219 // subexpression, save the old Usage so that we can restore it later 12220 // in SequencedSubexpression::~SequencedSubexpression. 12221 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12222 ModAsSideEffect->push_back(std::make_pair(O, U)); 12223 // Then record the new usage with the current sequencing region. 12224 U.UsageExpr = UsageExpr; 12225 U.Seq = Region; 12226 } 12227 } 12228 12229 /// Check whether a modification or use of an object \p O in an expression 12230 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12231 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12232 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12233 /// usage and false we are checking for a mod-use unsequenced usage. 12234 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12235 UsageKind OtherKind, bool IsModMod) { 12236 if (UI.Diagnosed) 12237 return; 12238 12239 const Usage &U = UI.Uses[OtherKind]; 12240 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12241 return; 12242 12243 const Expr *Mod = U.UsageExpr; 12244 const Expr *ModOrUse = UsageExpr; 12245 if (OtherKind == UK_Use) 12246 std::swap(Mod, ModOrUse); 12247 12248 SemaRef.DiagRuntimeBehavior( 12249 Mod->getExprLoc(), {Mod, ModOrUse}, 12250 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12251 : diag::warn_unsequenced_mod_use) 12252 << O << SourceRange(ModOrUse->getExprLoc())); 12253 UI.Diagnosed = true; 12254 } 12255 12256 // A note on note{Pre, Post}{Use, Mod}: 12257 // 12258 // (It helps to follow the algorithm with an expression such as 12259 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12260 // operations before C++17 and both are well-defined in C++17). 12261 // 12262 // When visiting a node which uses/modify an object we first call notePreUse 12263 // or notePreMod before visiting its sub-expression(s). At this point the 12264 // children of the current node have not yet been visited and so the eventual 12265 // uses/modifications resulting from the children of the current node have not 12266 // been recorded yet. 12267 // 12268 // We then visit the children of the current node. After that notePostUse or 12269 // notePostMod is called. These will 1) detect an unsequenced modification 12270 // as side effect (as in "k++ + k") and 2) add a new usage with the 12271 // appropriate usage kind. 12272 // 12273 // We also have to be careful that some operation sequences modification as 12274 // side effect as well (for example: || or ,). To account for this we wrap 12275 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12276 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12277 // which record usages which are modifications as side effect, and then 12278 // downgrade them (or more accurately restore the previous usage which was a 12279 // modification as side effect) when exiting the scope of the sequenced 12280 // subexpression. 12281 12282 void notePreUse(Object O, const Expr *UseExpr) { 12283 UsageInfo &UI = UsageMap[O]; 12284 // Uses conflict with other modifications. 12285 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12286 } 12287 12288 void notePostUse(Object O, const Expr *UseExpr) { 12289 UsageInfo &UI = UsageMap[O]; 12290 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12291 /*IsModMod=*/false); 12292 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12293 } 12294 12295 void notePreMod(Object O, const Expr *ModExpr) { 12296 UsageInfo &UI = UsageMap[O]; 12297 // Modifications conflict with other modifications and with uses. 12298 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12299 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12300 } 12301 12302 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12303 UsageInfo &UI = UsageMap[O]; 12304 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12305 /*IsModMod=*/true); 12306 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12307 } 12308 12309 public: 12310 SequenceChecker(Sema &S, const Expr *E, 12311 SmallVectorImpl<const Expr *> &WorkList) 12312 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12313 Visit(E); 12314 // Silence a -Wunused-private-field since WorkList is now unused. 12315 // TODO: Evaluate if it can be used, and if not remove it. 12316 (void)this->WorkList; 12317 } 12318 12319 void VisitStmt(const Stmt *S) { 12320 // Skip all statements which aren't expressions for now. 12321 } 12322 12323 void VisitExpr(const Expr *E) { 12324 // By default, just recurse to evaluated subexpressions. 12325 Base::VisitStmt(E); 12326 } 12327 12328 void VisitCastExpr(const CastExpr *E) { 12329 Object O = Object(); 12330 if (E->getCastKind() == CK_LValueToRValue) 12331 O = getObject(E->getSubExpr(), false); 12332 12333 if (O) 12334 notePreUse(O, E); 12335 VisitExpr(E); 12336 if (O) 12337 notePostUse(O, E); 12338 } 12339 12340 void VisitSequencedExpressions(const Expr *SequencedBefore, 12341 const Expr *SequencedAfter) { 12342 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12343 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12344 SequenceTree::Seq OldRegion = Region; 12345 12346 { 12347 SequencedSubexpression SeqBefore(*this); 12348 Region = BeforeRegion; 12349 Visit(SequencedBefore); 12350 } 12351 12352 Region = AfterRegion; 12353 Visit(SequencedAfter); 12354 12355 Region = OldRegion; 12356 12357 Tree.merge(BeforeRegion); 12358 Tree.merge(AfterRegion); 12359 } 12360 12361 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12362 // C++17 [expr.sub]p1: 12363 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12364 // expression E1 is sequenced before the expression E2. 12365 if (SemaRef.getLangOpts().CPlusPlus17) 12366 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12367 else { 12368 Visit(ASE->getLHS()); 12369 Visit(ASE->getRHS()); 12370 } 12371 } 12372 12373 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12374 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12375 void VisitBinPtrMem(const BinaryOperator *BO) { 12376 // C++17 [expr.mptr.oper]p4: 12377 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12378 // the expression E1 is sequenced before the expression E2. 12379 if (SemaRef.getLangOpts().CPlusPlus17) 12380 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12381 else { 12382 Visit(BO->getLHS()); 12383 Visit(BO->getRHS()); 12384 } 12385 } 12386 12387 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12388 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12389 void VisitBinShlShr(const BinaryOperator *BO) { 12390 // C++17 [expr.shift]p4: 12391 // The expression E1 is sequenced before the expression E2. 12392 if (SemaRef.getLangOpts().CPlusPlus17) 12393 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12394 else { 12395 Visit(BO->getLHS()); 12396 Visit(BO->getRHS()); 12397 } 12398 } 12399 12400 void VisitBinComma(const BinaryOperator *BO) { 12401 // C++11 [expr.comma]p1: 12402 // Every value computation and side effect associated with the left 12403 // expression is sequenced before every value computation and side 12404 // effect associated with the right expression. 12405 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12406 } 12407 12408 void VisitBinAssign(const BinaryOperator *BO) { 12409 SequenceTree::Seq RHSRegion; 12410 SequenceTree::Seq LHSRegion; 12411 if (SemaRef.getLangOpts().CPlusPlus17) { 12412 RHSRegion = Tree.allocate(Region); 12413 LHSRegion = Tree.allocate(Region); 12414 } else { 12415 RHSRegion = Region; 12416 LHSRegion = Region; 12417 } 12418 SequenceTree::Seq OldRegion = Region; 12419 12420 // C++11 [expr.ass]p1: 12421 // [...] the assignment is sequenced after the value computation 12422 // of the right and left operands, [...] 12423 // 12424 // so check it before inspecting the operands and update the 12425 // map afterwards. 12426 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12427 if (O) 12428 notePreMod(O, BO); 12429 12430 if (SemaRef.getLangOpts().CPlusPlus17) { 12431 // C++17 [expr.ass]p1: 12432 // [...] The right operand is sequenced before the left operand. [...] 12433 { 12434 SequencedSubexpression SeqBefore(*this); 12435 Region = RHSRegion; 12436 Visit(BO->getRHS()); 12437 } 12438 12439 Region = LHSRegion; 12440 Visit(BO->getLHS()); 12441 12442 if (O && isa<CompoundAssignOperator>(BO)) 12443 notePostUse(O, BO); 12444 12445 } else { 12446 // C++11 does not specify any sequencing between the LHS and RHS. 12447 Region = LHSRegion; 12448 Visit(BO->getLHS()); 12449 12450 if (O && isa<CompoundAssignOperator>(BO)) 12451 notePostUse(O, BO); 12452 12453 Region = RHSRegion; 12454 Visit(BO->getRHS()); 12455 } 12456 12457 // C++11 [expr.ass]p1: 12458 // the assignment is sequenced [...] before the value computation of the 12459 // assignment expression. 12460 // C11 6.5.16/3 has no such rule. 12461 Region = OldRegion; 12462 if (O) 12463 notePostMod(O, BO, 12464 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12465 : UK_ModAsSideEffect); 12466 if (SemaRef.getLangOpts().CPlusPlus17) { 12467 Tree.merge(RHSRegion); 12468 Tree.merge(LHSRegion); 12469 } 12470 } 12471 12472 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12473 VisitBinAssign(CAO); 12474 } 12475 12476 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12477 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12478 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12479 Object O = getObject(UO->getSubExpr(), true); 12480 if (!O) 12481 return VisitExpr(UO); 12482 12483 notePreMod(O, UO); 12484 Visit(UO->getSubExpr()); 12485 // C++11 [expr.pre.incr]p1: 12486 // the expression ++x is equivalent to x+=1 12487 notePostMod(O, UO, 12488 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12489 : UK_ModAsSideEffect); 12490 } 12491 12492 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12493 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12494 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12495 Object O = getObject(UO->getSubExpr(), true); 12496 if (!O) 12497 return VisitExpr(UO); 12498 12499 notePreMod(O, UO); 12500 Visit(UO->getSubExpr()); 12501 notePostMod(O, UO, UK_ModAsSideEffect); 12502 } 12503 12504 void VisitBinLOr(const BinaryOperator *BO) { 12505 // C++11 [expr.log.or]p2: 12506 // If the second expression is evaluated, every value computation and 12507 // side effect associated with the first expression is sequenced before 12508 // every value computation and side effect associated with the 12509 // second expression. 12510 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12511 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12512 SequenceTree::Seq OldRegion = Region; 12513 12514 EvaluationTracker Eval(*this); 12515 { 12516 SequencedSubexpression Sequenced(*this); 12517 Region = LHSRegion; 12518 Visit(BO->getLHS()); 12519 } 12520 12521 // C++11 [expr.log.or]p1: 12522 // [...] the second operand is not evaluated if the first operand 12523 // evaluates to true. 12524 bool EvalResult = false; 12525 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12526 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12527 if (ShouldVisitRHS) { 12528 Region = RHSRegion; 12529 Visit(BO->getRHS()); 12530 } 12531 12532 Region = OldRegion; 12533 Tree.merge(LHSRegion); 12534 Tree.merge(RHSRegion); 12535 } 12536 12537 void VisitBinLAnd(const BinaryOperator *BO) { 12538 // C++11 [expr.log.and]p2: 12539 // If the second expression is evaluated, every value computation and 12540 // side effect associated with the first expression is sequenced before 12541 // every value computation and side effect associated with the 12542 // second expression. 12543 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12544 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12545 SequenceTree::Seq OldRegion = Region; 12546 12547 EvaluationTracker Eval(*this); 12548 { 12549 SequencedSubexpression Sequenced(*this); 12550 Region = LHSRegion; 12551 Visit(BO->getLHS()); 12552 } 12553 12554 // C++11 [expr.log.and]p1: 12555 // [...] the second operand is not evaluated if the first operand is false. 12556 bool EvalResult = false; 12557 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12558 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12559 if (ShouldVisitRHS) { 12560 Region = RHSRegion; 12561 Visit(BO->getRHS()); 12562 } 12563 12564 Region = OldRegion; 12565 Tree.merge(LHSRegion); 12566 Tree.merge(RHSRegion); 12567 } 12568 12569 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12570 // C++11 [expr.cond]p1: 12571 // [...] Every value computation and side effect associated with the first 12572 // expression is sequenced before every value computation and side effect 12573 // associated with the second or third expression. 12574 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12575 12576 // No sequencing is specified between the true and false expression. 12577 // However since exactly one of both is going to be evaluated we can 12578 // consider them to be sequenced. This is needed to avoid warning on 12579 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12580 // both the true and false expressions because we can't evaluate x. 12581 // This will still allow us to detect an expression like (pre C++17) 12582 // "(x ? y += 1 : y += 2) = y". 12583 // 12584 // We don't wrap the visitation of the true and false expression with 12585 // SequencedSubexpression because we don't want to downgrade modifications 12586 // as side effect in the true and false expressions after the visition 12587 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12588 // not warn between the two "y++", but we should warn between the "y++" 12589 // and the "y". 12590 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12591 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12592 SequenceTree::Seq OldRegion = Region; 12593 12594 EvaluationTracker Eval(*this); 12595 { 12596 SequencedSubexpression Sequenced(*this); 12597 Region = ConditionRegion; 12598 Visit(CO->getCond()); 12599 } 12600 12601 // C++11 [expr.cond]p1: 12602 // [...] The first expression is contextually converted to bool (Clause 4). 12603 // It is evaluated and if it is true, the result of the conditional 12604 // expression is the value of the second expression, otherwise that of the 12605 // third expression. Only one of the second and third expressions is 12606 // evaluated. [...] 12607 bool EvalResult = false; 12608 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12609 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12610 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12611 if (ShouldVisitTrueExpr) { 12612 Region = TrueRegion; 12613 Visit(CO->getTrueExpr()); 12614 } 12615 if (ShouldVisitFalseExpr) { 12616 Region = FalseRegion; 12617 Visit(CO->getFalseExpr()); 12618 } 12619 12620 Region = OldRegion; 12621 Tree.merge(ConditionRegion); 12622 Tree.merge(TrueRegion); 12623 Tree.merge(FalseRegion); 12624 } 12625 12626 void VisitCallExpr(const CallExpr *CE) { 12627 // C++11 [intro.execution]p15: 12628 // When calling a function [...], every value computation and side effect 12629 // associated with any argument expression, or with the postfix expression 12630 // designating the called function, is sequenced before execution of every 12631 // expression or statement in the body of the function [and thus before 12632 // the value computation of its result]. 12633 SequencedSubexpression Sequenced(*this); 12634 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12635 [&] { Base::VisitCallExpr(CE); }); 12636 12637 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12638 } 12639 12640 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12641 // This is a call, so all subexpressions are sequenced before the result. 12642 SequencedSubexpression Sequenced(*this); 12643 12644 if (!CCE->isListInitialization()) 12645 return VisitExpr(CCE); 12646 12647 // In C++11, list initializations are sequenced. 12648 SmallVector<SequenceTree::Seq, 32> Elts; 12649 SequenceTree::Seq Parent = Region; 12650 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12651 E = CCE->arg_end(); 12652 I != E; ++I) { 12653 Region = Tree.allocate(Parent); 12654 Elts.push_back(Region); 12655 Visit(*I); 12656 } 12657 12658 // Forget that the initializers are sequenced. 12659 Region = Parent; 12660 for (unsigned I = 0; I < Elts.size(); ++I) 12661 Tree.merge(Elts[I]); 12662 } 12663 12664 void VisitInitListExpr(const InitListExpr *ILE) { 12665 if (!SemaRef.getLangOpts().CPlusPlus11) 12666 return VisitExpr(ILE); 12667 12668 // In C++11, list initializations are sequenced. 12669 SmallVector<SequenceTree::Seq, 32> Elts; 12670 SequenceTree::Seq Parent = Region; 12671 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12672 const Expr *E = ILE->getInit(I); 12673 if (!E) 12674 continue; 12675 Region = Tree.allocate(Parent); 12676 Elts.push_back(Region); 12677 Visit(E); 12678 } 12679 12680 // Forget that the initializers are sequenced. 12681 Region = Parent; 12682 for (unsigned I = 0; I < Elts.size(); ++I) 12683 Tree.merge(Elts[I]); 12684 } 12685 }; 12686 12687 } // namespace 12688 12689 void Sema::CheckUnsequencedOperations(const Expr *E) { 12690 SmallVector<const Expr *, 8> WorkList; 12691 WorkList.push_back(E); 12692 while (!WorkList.empty()) { 12693 const Expr *Item = WorkList.pop_back_val(); 12694 SequenceChecker(*this, Item, WorkList); 12695 } 12696 } 12697 12698 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12699 bool IsConstexpr) { 12700 llvm::SaveAndRestore<bool> ConstantContext( 12701 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12702 CheckImplicitConversions(E, CheckLoc); 12703 if (!E->isInstantiationDependent()) 12704 CheckUnsequencedOperations(E); 12705 if (!IsConstexpr && !E->isValueDependent()) 12706 CheckForIntOverflow(E); 12707 DiagnoseMisalignedMembers(); 12708 } 12709 12710 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12711 FieldDecl *BitField, 12712 Expr *Init) { 12713 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12714 } 12715 12716 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12717 SourceLocation Loc) { 12718 if (!PType->isVariablyModifiedType()) 12719 return; 12720 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12721 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12722 return; 12723 } 12724 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12725 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12726 return; 12727 } 12728 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12729 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12730 return; 12731 } 12732 12733 const ArrayType *AT = S.Context.getAsArrayType(PType); 12734 if (!AT) 12735 return; 12736 12737 if (AT->getSizeModifier() != ArrayType::Star) { 12738 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12739 return; 12740 } 12741 12742 S.Diag(Loc, diag::err_array_star_in_function_definition); 12743 } 12744 12745 /// CheckParmsForFunctionDef - Check that the parameters of the given 12746 /// function are appropriate for the definition of a function. This 12747 /// takes care of any checks that cannot be performed on the 12748 /// declaration itself, e.g., that the types of each of the function 12749 /// parameters are complete. 12750 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12751 bool CheckParameterNames) { 12752 bool HasInvalidParm = false; 12753 for (ParmVarDecl *Param : Parameters) { 12754 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12755 // function declarator that is part of a function definition of 12756 // that function shall not have incomplete type. 12757 // 12758 // This is also C++ [dcl.fct]p6. 12759 if (!Param->isInvalidDecl() && 12760 RequireCompleteType(Param->getLocation(), Param->getType(), 12761 diag::err_typecheck_decl_incomplete_type)) { 12762 Param->setInvalidDecl(); 12763 HasInvalidParm = true; 12764 } 12765 12766 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12767 // declaration of each parameter shall include an identifier. 12768 if (CheckParameterNames && 12769 Param->getIdentifier() == nullptr && 12770 !Param->isImplicit() && 12771 !getLangOpts().CPlusPlus) 12772 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12773 12774 // C99 6.7.5.3p12: 12775 // If the function declarator is not part of a definition of that 12776 // function, parameters may have incomplete type and may use the [*] 12777 // notation in their sequences of declarator specifiers to specify 12778 // variable length array types. 12779 QualType PType = Param->getOriginalType(); 12780 // FIXME: This diagnostic should point the '[*]' if source-location 12781 // information is added for it. 12782 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12783 12784 // If the parameter is a c++ class type and it has to be destructed in the 12785 // callee function, declare the destructor so that it can be called by the 12786 // callee function. Do not perform any direct access check on the dtor here. 12787 if (!Param->isInvalidDecl()) { 12788 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12789 if (!ClassDecl->isInvalidDecl() && 12790 !ClassDecl->hasIrrelevantDestructor() && 12791 !ClassDecl->isDependentContext() && 12792 ClassDecl->isParamDestroyedInCallee()) { 12793 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12794 MarkFunctionReferenced(Param->getLocation(), Destructor); 12795 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12796 } 12797 } 12798 } 12799 12800 // Parameters with the pass_object_size attribute only need to be marked 12801 // constant at function definitions. Because we lack information about 12802 // whether we're on a declaration or definition when we're instantiating the 12803 // attribute, we need to check for constness here. 12804 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12805 if (!Param->getType().isConstQualified()) 12806 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12807 << Attr->getSpelling() << 1; 12808 12809 // Check for parameter names shadowing fields from the class. 12810 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12811 // The owning context for the parameter should be the function, but we 12812 // want to see if this function's declaration context is a record. 12813 DeclContext *DC = Param->getDeclContext(); 12814 if (DC && DC->isFunctionOrMethod()) { 12815 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12816 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12817 RD, /*DeclIsField*/ false); 12818 } 12819 } 12820 } 12821 12822 return HasInvalidParm; 12823 } 12824 12825 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12826 /// or MemberExpr. 12827 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12828 ASTContext &Context) { 12829 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12830 return Context.getDeclAlign(DRE->getDecl()); 12831 12832 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12833 return Context.getDeclAlign(ME->getMemberDecl()); 12834 12835 return TypeAlign; 12836 } 12837 12838 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12839 /// pointer cast increases the alignment requirements. 12840 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12841 // This is actually a lot of work to potentially be doing on every 12842 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12843 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12844 return; 12845 12846 // Ignore dependent types. 12847 if (T->isDependentType() || Op->getType()->isDependentType()) 12848 return; 12849 12850 // Require that the destination be a pointer type. 12851 const PointerType *DestPtr = T->getAs<PointerType>(); 12852 if (!DestPtr) return; 12853 12854 // If the destination has alignment 1, we're done. 12855 QualType DestPointee = DestPtr->getPointeeType(); 12856 if (DestPointee->isIncompleteType()) return; 12857 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12858 if (DestAlign.isOne()) return; 12859 12860 // Require that the source be a pointer type. 12861 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12862 if (!SrcPtr) return; 12863 QualType SrcPointee = SrcPtr->getPointeeType(); 12864 12865 // Whitelist casts from cv void*. We already implicitly 12866 // whitelisted casts to cv void*, since they have alignment 1. 12867 // Also whitelist casts involving incomplete types, which implicitly 12868 // includes 'void'. 12869 if (SrcPointee->isIncompleteType()) return; 12870 12871 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12872 12873 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12874 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12875 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12876 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12877 if (UO->getOpcode() == UO_AddrOf) 12878 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12879 } 12880 12881 if (SrcAlign >= DestAlign) return; 12882 12883 Diag(TRange.getBegin(), diag::warn_cast_align) 12884 << Op->getType() << T 12885 << static_cast<unsigned>(SrcAlign.getQuantity()) 12886 << static_cast<unsigned>(DestAlign.getQuantity()) 12887 << TRange << Op->getSourceRange(); 12888 } 12889 12890 /// Check whether this array fits the idiom of a size-one tail padded 12891 /// array member of a struct. 12892 /// 12893 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12894 /// commonly used to emulate flexible arrays in C89 code. 12895 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12896 const NamedDecl *ND) { 12897 if (Size != 1 || !ND) return false; 12898 12899 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12900 if (!FD) return false; 12901 12902 // Don't consider sizes resulting from macro expansions or template argument 12903 // substitution to form C89 tail-padded arrays. 12904 12905 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12906 while (TInfo) { 12907 TypeLoc TL = TInfo->getTypeLoc(); 12908 // Look through typedefs. 12909 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 12910 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 12911 TInfo = TDL->getTypeSourceInfo(); 12912 continue; 12913 } 12914 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 12915 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 12916 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 12917 return false; 12918 } 12919 break; 12920 } 12921 12922 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 12923 if (!RD) return false; 12924 if (RD->isUnion()) return false; 12925 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12926 if (!CRD->isStandardLayout()) return false; 12927 } 12928 12929 // See if this is the last field decl in the record. 12930 const Decl *D = FD; 12931 while ((D = D->getNextDeclInContext())) 12932 if (isa<FieldDecl>(D)) 12933 return false; 12934 return true; 12935 } 12936 12937 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12938 const ArraySubscriptExpr *ASE, 12939 bool AllowOnePastEnd, bool IndexNegated) { 12940 // Already diagnosed by the constant evaluator. 12941 if (isConstantEvaluated()) 12942 return; 12943 12944 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 12945 if (IndexExpr->isValueDependent()) 12946 return; 12947 12948 const Type *EffectiveType = 12949 BaseExpr->getType()->getPointeeOrArrayElementType(); 12950 BaseExpr = BaseExpr->IgnoreParenCasts(); 12951 const ConstantArrayType *ArrayTy = 12952 Context.getAsConstantArrayType(BaseExpr->getType()); 12953 12954 if (!ArrayTy) 12955 return; 12956 12957 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 12958 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 12959 return; 12960 12961 Expr::EvalResult Result; 12962 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 12963 return; 12964 12965 llvm::APSInt index = Result.Val.getInt(); 12966 if (IndexNegated) 12967 index = -index; 12968 12969 const NamedDecl *ND = nullptr; 12970 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 12971 ND = DRE->getDecl(); 12972 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 12973 ND = ME->getMemberDecl(); 12974 12975 if (index.isUnsigned() || !index.isNegative()) { 12976 // It is possible that the type of the base expression after 12977 // IgnoreParenCasts is incomplete, even though the type of the base 12978 // expression before IgnoreParenCasts is complete (see PR39746 for an 12979 // example). In this case we have no information about whether the array 12980 // access exceeds the array bounds. However we can still diagnose an array 12981 // access which precedes the array bounds. 12982 if (BaseType->isIncompleteType()) 12983 return; 12984 12985 llvm::APInt size = ArrayTy->getSize(); 12986 if (!size.isStrictlyPositive()) 12987 return; 12988 12989 if (BaseType != EffectiveType) { 12990 // Make sure we're comparing apples to apples when comparing index to size 12991 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 12992 uint64_t array_typesize = Context.getTypeSize(BaseType); 12993 // Handle ptrarith_typesize being zero, such as when casting to void* 12994 if (!ptrarith_typesize) ptrarith_typesize = 1; 12995 if (ptrarith_typesize != array_typesize) { 12996 // There's a cast to a different size type involved 12997 uint64_t ratio = array_typesize / ptrarith_typesize; 12998 // TODO: Be smarter about handling cases where array_typesize is not a 12999 // multiple of ptrarith_typesize 13000 if (ptrarith_typesize * ratio == array_typesize) 13001 size *= llvm::APInt(size.getBitWidth(), ratio); 13002 } 13003 } 13004 13005 if (size.getBitWidth() > index.getBitWidth()) 13006 index = index.zext(size.getBitWidth()); 13007 else if (size.getBitWidth() < index.getBitWidth()) 13008 size = size.zext(index.getBitWidth()); 13009 13010 // For array subscripting the index must be less than size, but for pointer 13011 // arithmetic also allow the index (offset) to be equal to size since 13012 // computing the next address after the end of the array is legal and 13013 // commonly done e.g. in C++ iterators and range-based for loops. 13014 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13015 return; 13016 13017 // Also don't warn for arrays of size 1 which are members of some 13018 // structure. These are often used to approximate flexible arrays in C89 13019 // code. 13020 if (IsTailPaddedMemberArray(*this, size, ND)) 13021 return; 13022 13023 // Suppress the warning if the subscript expression (as identified by the 13024 // ']' location) and the index expression are both from macro expansions 13025 // within a system header. 13026 if (ASE) { 13027 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13028 ASE->getRBracketLoc()); 13029 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13030 SourceLocation IndexLoc = 13031 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13032 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13033 return; 13034 } 13035 } 13036 13037 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13038 if (ASE) 13039 DiagID = diag::warn_array_index_exceeds_bounds; 13040 13041 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13042 PDiag(DiagID) << index.toString(10, true) 13043 << size.toString(10, true) 13044 << (unsigned)size.getLimitedValue(~0U) 13045 << IndexExpr->getSourceRange()); 13046 } else { 13047 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13048 if (!ASE) { 13049 DiagID = diag::warn_ptr_arith_precedes_bounds; 13050 if (index.isNegative()) index = -index; 13051 } 13052 13053 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13054 PDiag(DiagID) << index.toString(10, true) 13055 << IndexExpr->getSourceRange()); 13056 } 13057 13058 if (!ND) { 13059 // Try harder to find a NamedDecl to point at in the note. 13060 while (const ArraySubscriptExpr *ASE = 13061 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13062 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13063 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13064 ND = DRE->getDecl(); 13065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13066 ND = ME->getMemberDecl(); 13067 } 13068 13069 if (ND) 13070 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13071 PDiag(diag::note_array_declared_here) 13072 << ND->getDeclName()); 13073 } 13074 13075 void Sema::CheckArrayAccess(const Expr *expr) { 13076 int AllowOnePastEnd = 0; 13077 while (expr) { 13078 expr = expr->IgnoreParenImpCasts(); 13079 switch (expr->getStmtClass()) { 13080 case Stmt::ArraySubscriptExprClass: { 13081 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13082 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13083 AllowOnePastEnd > 0); 13084 expr = ASE->getBase(); 13085 break; 13086 } 13087 case Stmt::MemberExprClass: { 13088 expr = cast<MemberExpr>(expr)->getBase(); 13089 break; 13090 } 13091 case Stmt::OMPArraySectionExprClass: { 13092 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13093 if (ASE->getLowerBound()) 13094 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13095 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13096 return; 13097 } 13098 case Stmt::UnaryOperatorClass: { 13099 // Only unwrap the * and & unary operators 13100 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13101 expr = UO->getSubExpr(); 13102 switch (UO->getOpcode()) { 13103 case UO_AddrOf: 13104 AllowOnePastEnd++; 13105 break; 13106 case UO_Deref: 13107 AllowOnePastEnd--; 13108 break; 13109 default: 13110 return; 13111 } 13112 break; 13113 } 13114 case Stmt::ConditionalOperatorClass: { 13115 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13116 if (const Expr *lhs = cond->getLHS()) 13117 CheckArrayAccess(lhs); 13118 if (const Expr *rhs = cond->getRHS()) 13119 CheckArrayAccess(rhs); 13120 return; 13121 } 13122 case Stmt::CXXOperatorCallExprClass: { 13123 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13124 for (const auto *Arg : OCE->arguments()) 13125 CheckArrayAccess(Arg); 13126 return; 13127 } 13128 default: 13129 return; 13130 } 13131 } 13132 } 13133 13134 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13135 13136 namespace { 13137 13138 struct RetainCycleOwner { 13139 VarDecl *Variable = nullptr; 13140 SourceRange Range; 13141 SourceLocation Loc; 13142 bool Indirect = false; 13143 13144 RetainCycleOwner() = default; 13145 13146 void setLocsFrom(Expr *e) { 13147 Loc = e->getExprLoc(); 13148 Range = e->getSourceRange(); 13149 } 13150 }; 13151 13152 } // namespace 13153 13154 /// Consider whether capturing the given variable can possibly lead to 13155 /// a retain cycle. 13156 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13157 // In ARC, it's captured strongly iff the variable has __strong 13158 // lifetime. In MRR, it's captured strongly if the variable is 13159 // __block and has an appropriate type. 13160 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13161 return false; 13162 13163 owner.Variable = var; 13164 if (ref) 13165 owner.setLocsFrom(ref); 13166 return true; 13167 } 13168 13169 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13170 while (true) { 13171 e = e->IgnoreParens(); 13172 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13173 switch (cast->getCastKind()) { 13174 case CK_BitCast: 13175 case CK_LValueBitCast: 13176 case CK_LValueToRValue: 13177 case CK_ARCReclaimReturnedObject: 13178 e = cast->getSubExpr(); 13179 continue; 13180 13181 default: 13182 return false; 13183 } 13184 } 13185 13186 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13187 ObjCIvarDecl *ivar = ref->getDecl(); 13188 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13189 return false; 13190 13191 // Try to find a retain cycle in the base. 13192 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13193 return false; 13194 13195 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13196 owner.Indirect = true; 13197 return true; 13198 } 13199 13200 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13201 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13202 if (!var) return false; 13203 return considerVariable(var, ref, owner); 13204 } 13205 13206 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13207 if (member->isArrow()) return false; 13208 13209 // Don't count this as an indirect ownership. 13210 e = member->getBase(); 13211 continue; 13212 } 13213 13214 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13215 // Only pay attention to pseudo-objects on property references. 13216 ObjCPropertyRefExpr *pre 13217 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13218 ->IgnoreParens()); 13219 if (!pre) return false; 13220 if (pre->isImplicitProperty()) return false; 13221 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13222 if (!property->isRetaining() && 13223 !(property->getPropertyIvarDecl() && 13224 property->getPropertyIvarDecl()->getType() 13225 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13226 return false; 13227 13228 owner.Indirect = true; 13229 if (pre->isSuperReceiver()) { 13230 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13231 if (!owner.Variable) 13232 return false; 13233 owner.Loc = pre->getLocation(); 13234 owner.Range = pre->getSourceRange(); 13235 return true; 13236 } 13237 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13238 ->getSourceExpr()); 13239 continue; 13240 } 13241 13242 // Array ivars? 13243 13244 return false; 13245 } 13246 } 13247 13248 namespace { 13249 13250 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13251 ASTContext &Context; 13252 VarDecl *Variable; 13253 Expr *Capturer = nullptr; 13254 bool VarWillBeReased = false; 13255 13256 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13257 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13258 Context(Context), Variable(variable) {} 13259 13260 void VisitDeclRefExpr(DeclRefExpr *ref) { 13261 if (ref->getDecl() == Variable && !Capturer) 13262 Capturer = ref; 13263 } 13264 13265 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13266 if (Capturer) return; 13267 Visit(ref->getBase()); 13268 if (Capturer && ref->isFreeIvar()) 13269 Capturer = ref; 13270 } 13271 13272 void VisitBlockExpr(BlockExpr *block) { 13273 // Look inside nested blocks 13274 if (block->getBlockDecl()->capturesVariable(Variable)) 13275 Visit(block->getBlockDecl()->getBody()); 13276 } 13277 13278 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13279 if (Capturer) return; 13280 if (OVE->getSourceExpr()) 13281 Visit(OVE->getSourceExpr()); 13282 } 13283 13284 void VisitBinaryOperator(BinaryOperator *BinOp) { 13285 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13286 return; 13287 Expr *LHS = BinOp->getLHS(); 13288 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13289 if (DRE->getDecl() != Variable) 13290 return; 13291 if (Expr *RHS = BinOp->getRHS()) { 13292 RHS = RHS->IgnoreParenCasts(); 13293 llvm::APSInt Value; 13294 VarWillBeReased = 13295 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13296 } 13297 } 13298 } 13299 }; 13300 13301 } // namespace 13302 13303 /// Check whether the given argument is a block which captures a 13304 /// variable. 13305 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13306 assert(owner.Variable && owner.Loc.isValid()); 13307 13308 e = e->IgnoreParenCasts(); 13309 13310 // Look through [^{...} copy] and Block_copy(^{...}). 13311 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13312 Selector Cmd = ME->getSelector(); 13313 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13314 e = ME->getInstanceReceiver(); 13315 if (!e) 13316 return nullptr; 13317 e = e->IgnoreParenCasts(); 13318 } 13319 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13320 if (CE->getNumArgs() == 1) { 13321 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13322 if (Fn) { 13323 const IdentifierInfo *FnI = Fn->getIdentifier(); 13324 if (FnI && FnI->isStr("_Block_copy")) { 13325 e = CE->getArg(0)->IgnoreParenCasts(); 13326 } 13327 } 13328 } 13329 } 13330 13331 BlockExpr *block = dyn_cast<BlockExpr>(e); 13332 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13333 return nullptr; 13334 13335 FindCaptureVisitor visitor(S.Context, owner.Variable); 13336 visitor.Visit(block->getBlockDecl()->getBody()); 13337 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13338 } 13339 13340 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13341 RetainCycleOwner &owner) { 13342 assert(capturer); 13343 assert(owner.Variable && owner.Loc.isValid()); 13344 13345 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13346 << owner.Variable << capturer->getSourceRange(); 13347 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13348 << owner.Indirect << owner.Range; 13349 } 13350 13351 /// Check for a keyword selector that starts with the word 'add' or 13352 /// 'set'. 13353 static bool isSetterLikeSelector(Selector sel) { 13354 if (sel.isUnarySelector()) return false; 13355 13356 StringRef str = sel.getNameForSlot(0); 13357 while (!str.empty() && str.front() == '_') str = str.substr(1); 13358 if (str.startswith("set")) 13359 str = str.substr(3); 13360 else if (str.startswith("add")) { 13361 // Specially whitelist 'addOperationWithBlock:'. 13362 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13363 return false; 13364 str = str.substr(3); 13365 } 13366 else 13367 return false; 13368 13369 if (str.empty()) return true; 13370 return !isLowercase(str.front()); 13371 } 13372 13373 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13374 ObjCMessageExpr *Message) { 13375 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13376 Message->getReceiverInterface(), 13377 NSAPI::ClassId_NSMutableArray); 13378 if (!IsMutableArray) { 13379 return None; 13380 } 13381 13382 Selector Sel = Message->getSelector(); 13383 13384 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13385 S.NSAPIObj->getNSArrayMethodKind(Sel); 13386 if (!MKOpt) { 13387 return None; 13388 } 13389 13390 NSAPI::NSArrayMethodKind MK = *MKOpt; 13391 13392 switch (MK) { 13393 case NSAPI::NSMutableArr_addObject: 13394 case NSAPI::NSMutableArr_insertObjectAtIndex: 13395 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13396 return 0; 13397 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13398 return 1; 13399 13400 default: 13401 return None; 13402 } 13403 13404 return None; 13405 } 13406 13407 static 13408 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13409 ObjCMessageExpr *Message) { 13410 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13411 Message->getReceiverInterface(), 13412 NSAPI::ClassId_NSMutableDictionary); 13413 if (!IsMutableDictionary) { 13414 return None; 13415 } 13416 13417 Selector Sel = Message->getSelector(); 13418 13419 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13420 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13421 if (!MKOpt) { 13422 return None; 13423 } 13424 13425 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13426 13427 switch (MK) { 13428 case NSAPI::NSMutableDict_setObjectForKey: 13429 case NSAPI::NSMutableDict_setValueForKey: 13430 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13431 return 0; 13432 13433 default: 13434 return None; 13435 } 13436 13437 return None; 13438 } 13439 13440 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13441 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13442 Message->getReceiverInterface(), 13443 NSAPI::ClassId_NSMutableSet); 13444 13445 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13446 Message->getReceiverInterface(), 13447 NSAPI::ClassId_NSMutableOrderedSet); 13448 if (!IsMutableSet && !IsMutableOrderedSet) { 13449 return None; 13450 } 13451 13452 Selector Sel = Message->getSelector(); 13453 13454 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13455 if (!MKOpt) { 13456 return None; 13457 } 13458 13459 NSAPI::NSSetMethodKind MK = *MKOpt; 13460 13461 switch (MK) { 13462 case NSAPI::NSMutableSet_addObject: 13463 case NSAPI::NSOrderedSet_setObjectAtIndex: 13464 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13465 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13466 return 0; 13467 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13468 return 1; 13469 } 13470 13471 return None; 13472 } 13473 13474 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13475 if (!Message->isInstanceMessage()) { 13476 return; 13477 } 13478 13479 Optional<int> ArgOpt; 13480 13481 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13482 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13483 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13484 return; 13485 } 13486 13487 int ArgIndex = *ArgOpt; 13488 13489 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13490 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13491 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13492 } 13493 13494 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13495 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13496 if (ArgRE->isObjCSelfExpr()) { 13497 Diag(Message->getSourceRange().getBegin(), 13498 diag::warn_objc_circular_container) 13499 << ArgRE->getDecl() << StringRef("'super'"); 13500 } 13501 } 13502 } else { 13503 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13504 13505 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13506 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13507 } 13508 13509 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13510 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13511 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13512 ValueDecl *Decl = ReceiverRE->getDecl(); 13513 Diag(Message->getSourceRange().getBegin(), 13514 diag::warn_objc_circular_container) 13515 << Decl << Decl; 13516 if (!ArgRE->isObjCSelfExpr()) { 13517 Diag(Decl->getLocation(), 13518 diag::note_objc_circular_container_declared_here) 13519 << Decl; 13520 } 13521 } 13522 } 13523 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13524 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13525 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13526 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13527 Diag(Message->getSourceRange().getBegin(), 13528 diag::warn_objc_circular_container) 13529 << Decl << Decl; 13530 Diag(Decl->getLocation(), 13531 diag::note_objc_circular_container_declared_here) 13532 << Decl; 13533 } 13534 } 13535 } 13536 } 13537 } 13538 13539 /// Check a message send to see if it's likely to cause a retain cycle. 13540 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13541 // Only check instance methods whose selector looks like a setter. 13542 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13543 return; 13544 13545 // Try to find a variable that the receiver is strongly owned by. 13546 RetainCycleOwner owner; 13547 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13548 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13549 return; 13550 } else { 13551 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13552 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13553 owner.Loc = msg->getSuperLoc(); 13554 owner.Range = msg->getSuperLoc(); 13555 } 13556 13557 // Check whether the receiver is captured by any of the arguments. 13558 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13559 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13560 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13561 // noescape blocks should not be retained by the method. 13562 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13563 continue; 13564 return diagnoseRetainCycle(*this, capturer, owner); 13565 } 13566 } 13567 } 13568 13569 /// Check a property assign to see if it's likely to cause a retain cycle. 13570 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13571 RetainCycleOwner owner; 13572 if (!findRetainCycleOwner(*this, receiver, owner)) 13573 return; 13574 13575 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13576 diagnoseRetainCycle(*this, capturer, owner); 13577 } 13578 13579 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13580 RetainCycleOwner Owner; 13581 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13582 return; 13583 13584 // Because we don't have an expression for the variable, we have to set the 13585 // location explicitly here. 13586 Owner.Loc = Var->getLocation(); 13587 Owner.Range = Var->getSourceRange(); 13588 13589 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13590 diagnoseRetainCycle(*this, Capturer, Owner); 13591 } 13592 13593 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13594 Expr *RHS, bool isProperty) { 13595 // Check if RHS is an Objective-C object literal, which also can get 13596 // immediately zapped in a weak reference. Note that we explicitly 13597 // allow ObjCStringLiterals, since those are designed to never really die. 13598 RHS = RHS->IgnoreParenImpCasts(); 13599 13600 // This enum needs to match with the 'select' in 13601 // warn_objc_arc_literal_assign (off-by-1). 13602 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13603 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13604 return false; 13605 13606 S.Diag(Loc, diag::warn_arc_literal_assign) 13607 << (unsigned) Kind 13608 << (isProperty ? 0 : 1) 13609 << RHS->getSourceRange(); 13610 13611 return true; 13612 } 13613 13614 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13615 Qualifiers::ObjCLifetime LT, 13616 Expr *RHS, bool isProperty) { 13617 // Strip off any implicit cast added to get to the one ARC-specific. 13618 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13619 if (cast->getCastKind() == CK_ARCConsumeObject) { 13620 S.Diag(Loc, diag::warn_arc_retained_assign) 13621 << (LT == Qualifiers::OCL_ExplicitNone) 13622 << (isProperty ? 0 : 1) 13623 << RHS->getSourceRange(); 13624 return true; 13625 } 13626 RHS = cast->getSubExpr(); 13627 } 13628 13629 if (LT == Qualifiers::OCL_Weak && 13630 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13631 return true; 13632 13633 return false; 13634 } 13635 13636 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13637 QualType LHS, Expr *RHS) { 13638 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13639 13640 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13641 return false; 13642 13643 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13644 return true; 13645 13646 return false; 13647 } 13648 13649 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13650 Expr *LHS, Expr *RHS) { 13651 QualType LHSType; 13652 // PropertyRef on LHS type need be directly obtained from 13653 // its declaration as it has a PseudoType. 13654 ObjCPropertyRefExpr *PRE 13655 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13656 if (PRE && !PRE->isImplicitProperty()) { 13657 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13658 if (PD) 13659 LHSType = PD->getType(); 13660 } 13661 13662 if (LHSType.isNull()) 13663 LHSType = LHS->getType(); 13664 13665 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13666 13667 if (LT == Qualifiers::OCL_Weak) { 13668 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13669 getCurFunction()->markSafeWeakUse(LHS); 13670 } 13671 13672 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13673 return; 13674 13675 // FIXME. Check for other life times. 13676 if (LT != Qualifiers::OCL_None) 13677 return; 13678 13679 if (PRE) { 13680 if (PRE->isImplicitProperty()) 13681 return; 13682 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13683 if (!PD) 13684 return; 13685 13686 unsigned Attributes = PD->getPropertyAttributes(); 13687 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13688 // when 'assign' attribute was not explicitly specified 13689 // by user, ignore it and rely on property type itself 13690 // for lifetime info. 13691 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13692 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13693 LHSType->isObjCRetainableType()) 13694 return; 13695 13696 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13697 if (cast->getCastKind() == CK_ARCConsumeObject) { 13698 Diag(Loc, diag::warn_arc_retained_property_assign) 13699 << RHS->getSourceRange(); 13700 return; 13701 } 13702 RHS = cast->getSubExpr(); 13703 } 13704 } 13705 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13706 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13707 return; 13708 } 13709 } 13710 } 13711 13712 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13713 13714 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13715 SourceLocation StmtLoc, 13716 const NullStmt *Body) { 13717 // Do not warn if the body is a macro that expands to nothing, e.g: 13718 // 13719 // #define CALL(x) 13720 // if (condition) 13721 // CALL(0); 13722 if (Body->hasLeadingEmptyMacro()) 13723 return false; 13724 13725 // Get line numbers of statement and body. 13726 bool StmtLineInvalid; 13727 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13728 &StmtLineInvalid); 13729 if (StmtLineInvalid) 13730 return false; 13731 13732 bool BodyLineInvalid; 13733 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13734 &BodyLineInvalid); 13735 if (BodyLineInvalid) 13736 return false; 13737 13738 // Warn if null statement and body are on the same line. 13739 if (StmtLine != BodyLine) 13740 return false; 13741 13742 return true; 13743 } 13744 13745 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13746 const Stmt *Body, 13747 unsigned DiagID) { 13748 // Since this is a syntactic check, don't emit diagnostic for template 13749 // instantiations, this just adds noise. 13750 if (CurrentInstantiationScope) 13751 return; 13752 13753 // The body should be a null statement. 13754 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13755 if (!NBody) 13756 return; 13757 13758 // Do the usual checks. 13759 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13760 return; 13761 13762 Diag(NBody->getSemiLoc(), DiagID); 13763 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13764 } 13765 13766 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13767 const Stmt *PossibleBody) { 13768 assert(!CurrentInstantiationScope); // Ensured by caller 13769 13770 SourceLocation StmtLoc; 13771 const Stmt *Body; 13772 unsigned DiagID; 13773 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13774 StmtLoc = FS->getRParenLoc(); 13775 Body = FS->getBody(); 13776 DiagID = diag::warn_empty_for_body; 13777 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13778 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13779 Body = WS->getBody(); 13780 DiagID = diag::warn_empty_while_body; 13781 } else 13782 return; // Neither `for' nor `while'. 13783 13784 // The body should be a null statement. 13785 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13786 if (!NBody) 13787 return; 13788 13789 // Skip expensive checks if diagnostic is disabled. 13790 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13791 return; 13792 13793 // Do the usual checks. 13794 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13795 return; 13796 13797 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13798 // noise level low, emit diagnostics only if for/while is followed by a 13799 // CompoundStmt, e.g.: 13800 // for (int i = 0; i < n; i++); 13801 // { 13802 // a(i); 13803 // } 13804 // or if for/while is followed by a statement with more indentation 13805 // than for/while itself: 13806 // for (int i = 0; i < n; i++); 13807 // a(i); 13808 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13809 if (!ProbableTypo) { 13810 bool BodyColInvalid; 13811 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13812 PossibleBody->getBeginLoc(), &BodyColInvalid); 13813 if (BodyColInvalid) 13814 return; 13815 13816 bool StmtColInvalid; 13817 unsigned StmtCol = 13818 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13819 if (StmtColInvalid) 13820 return; 13821 13822 if (BodyCol > StmtCol) 13823 ProbableTypo = true; 13824 } 13825 13826 if (ProbableTypo) { 13827 Diag(NBody->getSemiLoc(), DiagID); 13828 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13829 } 13830 } 13831 13832 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13833 13834 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13835 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13836 SourceLocation OpLoc) { 13837 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13838 return; 13839 13840 if (inTemplateInstantiation()) 13841 return; 13842 13843 // Strip parens and casts away. 13844 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13845 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13846 13847 // Check for a call expression 13848 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13849 if (!CE || CE->getNumArgs() != 1) 13850 return; 13851 13852 // Check for a call to std::move 13853 if (!CE->isCallToStdMove()) 13854 return; 13855 13856 // Get argument from std::move 13857 RHSExpr = CE->getArg(0); 13858 13859 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13860 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13861 13862 // Two DeclRefExpr's, check that the decls are the same. 13863 if (LHSDeclRef && RHSDeclRef) { 13864 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13865 return; 13866 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13867 RHSDeclRef->getDecl()->getCanonicalDecl()) 13868 return; 13869 13870 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13871 << LHSExpr->getSourceRange() 13872 << RHSExpr->getSourceRange(); 13873 return; 13874 } 13875 13876 // Member variables require a different approach to check for self moves. 13877 // MemberExpr's are the same if every nested MemberExpr refers to the same 13878 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13879 // the base Expr's are CXXThisExpr's. 13880 const Expr *LHSBase = LHSExpr; 13881 const Expr *RHSBase = RHSExpr; 13882 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13883 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13884 if (!LHSME || !RHSME) 13885 return; 13886 13887 while (LHSME && RHSME) { 13888 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13889 RHSME->getMemberDecl()->getCanonicalDecl()) 13890 return; 13891 13892 LHSBase = LHSME->getBase(); 13893 RHSBase = RHSME->getBase(); 13894 LHSME = dyn_cast<MemberExpr>(LHSBase); 13895 RHSME = dyn_cast<MemberExpr>(RHSBase); 13896 } 13897 13898 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13899 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13900 if (LHSDeclRef && RHSDeclRef) { 13901 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13902 return; 13903 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13904 RHSDeclRef->getDecl()->getCanonicalDecl()) 13905 return; 13906 13907 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13908 << LHSExpr->getSourceRange() 13909 << RHSExpr->getSourceRange(); 13910 return; 13911 } 13912 13913 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 13914 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13915 << LHSExpr->getSourceRange() 13916 << RHSExpr->getSourceRange(); 13917 } 13918 13919 //===--- Layout compatibility ----------------------------------------------// 13920 13921 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 13922 13923 /// Check if two enumeration types are layout-compatible. 13924 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 13925 // C++11 [dcl.enum] p8: 13926 // Two enumeration types are layout-compatible if they have the same 13927 // underlying type. 13928 return ED1->isComplete() && ED2->isComplete() && 13929 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 13930 } 13931 13932 /// Check if two fields are layout-compatible. 13933 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 13934 FieldDecl *Field2) { 13935 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 13936 return false; 13937 13938 if (Field1->isBitField() != Field2->isBitField()) 13939 return false; 13940 13941 if (Field1->isBitField()) { 13942 // Make sure that the bit-fields are the same length. 13943 unsigned Bits1 = Field1->getBitWidthValue(C); 13944 unsigned Bits2 = Field2->getBitWidthValue(C); 13945 13946 if (Bits1 != Bits2) 13947 return false; 13948 } 13949 13950 return true; 13951 } 13952 13953 /// Check if two standard-layout structs are layout-compatible. 13954 /// (C++11 [class.mem] p17) 13955 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 13956 RecordDecl *RD2) { 13957 // If both records are C++ classes, check that base classes match. 13958 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 13959 // If one of records is a CXXRecordDecl we are in C++ mode, 13960 // thus the other one is a CXXRecordDecl, too. 13961 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 13962 // Check number of base classes. 13963 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 13964 return false; 13965 13966 // Check the base classes. 13967 for (CXXRecordDecl::base_class_const_iterator 13968 Base1 = D1CXX->bases_begin(), 13969 BaseEnd1 = D1CXX->bases_end(), 13970 Base2 = D2CXX->bases_begin(); 13971 Base1 != BaseEnd1; 13972 ++Base1, ++Base2) { 13973 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 13974 return false; 13975 } 13976 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 13977 // If only RD2 is a C++ class, it should have zero base classes. 13978 if (D2CXX->getNumBases() > 0) 13979 return false; 13980 } 13981 13982 // Check the fields. 13983 RecordDecl::field_iterator Field2 = RD2->field_begin(), 13984 Field2End = RD2->field_end(), 13985 Field1 = RD1->field_begin(), 13986 Field1End = RD1->field_end(); 13987 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 13988 if (!isLayoutCompatible(C, *Field1, *Field2)) 13989 return false; 13990 } 13991 if (Field1 != Field1End || Field2 != Field2End) 13992 return false; 13993 13994 return true; 13995 } 13996 13997 /// Check if two standard-layout unions are layout-compatible. 13998 /// (C++11 [class.mem] p18) 13999 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14000 RecordDecl *RD2) { 14001 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14002 for (auto *Field2 : RD2->fields()) 14003 UnmatchedFields.insert(Field2); 14004 14005 for (auto *Field1 : RD1->fields()) { 14006 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14007 I = UnmatchedFields.begin(), 14008 E = UnmatchedFields.end(); 14009 14010 for ( ; I != E; ++I) { 14011 if (isLayoutCompatible(C, Field1, *I)) { 14012 bool Result = UnmatchedFields.erase(*I); 14013 (void) Result; 14014 assert(Result); 14015 break; 14016 } 14017 } 14018 if (I == E) 14019 return false; 14020 } 14021 14022 return UnmatchedFields.empty(); 14023 } 14024 14025 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14026 RecordDecl *RD2) { 14027 if (RD1->isUnion() != RD2->isUnion()) 14028 return false; 14029 14030 if (RD1->isUnion()) 14031 return isLayoutCompatibleUnion(C, RD1, RD2); 14032 else 14033 return isLayoutCompatibleStruct(C, RD1, RD2); 14034 } 14035 14036 /// Check if two types are layout-compatible in C++11 sense. 14037 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14038 if (T1.isNull() || T2.isNull()) 14039 return false; 14040 14041 // C++11 [basic.types] p11: 14042 // If two types T1 and T2 are the same type, then T1 and T2 are 14043 // layout-compatible types. 14044 if (C.hasSameType(T1, T2)) 14045 return true; 14046 14047 T1 = T1.getCanonicalType().getUnqualifiedType(); 14048 T2 = T2.getCanonicalType().getUnqualifiedType(); 14049 14050 const Type::TypeClass TC1 = T1->getTypeClass(); 14051 const Type::TypeClass TC2 = T2->getTypeClass(); 14052 14053 if (TC1 != TC2) 14054 return false; 14055 14056 if (TC1 == Type::Enum) { 14057 return isLayoutCompatible(C, 14058 cast<EnumType>(T1)->getDecl(), 14059 cast<EnumType>(T2)->getDecl()); 14060 } else if (TC1 == Type::Record) { 14061 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14062 return false; 14063 14064 return isLayoutCompatible(C, 14065 cast<RecordType>(T1)->getDecl(), 14066 cast<RecordType>(T2)->getDecl()); 14067 } 14068 14069 return false; 14070 } 14071 14072 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14073 14074 /// Given a type tag expression find the type tag itself. 14075 /// 14076 /// \param TypeExpr Type tag expression, as it appears in user's code. 14077 /// 14078 /// \param VD Declaration of an identifier that appears in a type tag. 14079 /// 14080 /// \param MagicValue Type tag magic value. 14081 /// 14082 /// \param isConstantEvaluated wether the evalaution should be performed in 14083 14084 /// constant context. 14085 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14086 const ValueDecl **VD, uint64_t *MagicValue, 14087 bool isConstantEvaluated) { 14088 while(true) { 14089 if (!TypeExpr) 14090 return false; 14091 14092 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14093 14094 switch (TypeExpr->getStmtClass()) { 14095 case Stmt::UnaryOperatorClass: { 14096 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14097 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14098 TypeExpr = UO->getSubExpr(); 14099 continue; 14100 } 14101 return false; 14102 } 14103 14104 case Stmt::DeclRefExprClass: { 14105 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14106 *VD = DRE->getDecl(); 14107 return true; 14108 } 14109 14110 case Stmt::IntegerLiteralClass: { 14111 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14112 llvm::APInt MagicValueAPInt = IL->getValue(); 14113 if (MagicValueAPInt.getActiveBits() <= 64) { 14114 *MagicValue = MagicValueAPInt.getZExtValue(); 14115 return true; 14116 } else 14117 return false; 14118 } 14119 14120 case Stmt::BinaryConditionalOperatorClass: 14121 case Stmt::ConditionalOperatorClass: { 14122 const AbstractConditionalOperator *ACO = 14123 cast<AbstractConditionalOperator>(TypeExpr); 14124 bool Result; 14125 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14126 isConstantEvaluated)) { 14127 if (Result) 14128 TypeExpr = ACO->getTrueExpr(); 14129 else 14130 TypeExpr = ACO->getFalseExpr(); 14131 continue; 14132 } 14133 return false; 14134 } 14135 14136 case Stmt::BinaryOperatorClass: { 14137 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14138 if (BO->getOpcode() == BO_Comma) { 14139 TypeExpr = BO->getRHS(); 14140 continue; 14141 } 14142 return false; 14143 } 14144 14145 default: 14146 return false; 14147 } 14148 } 14149 } 14150 14151 /// Retrieve the C type corresponding to type tag TypeExpr. 14152 /// 14153 /// \param TypeExpr Expression that specifies a type tag. 14154 /// 14155 /// \param MagicValues Registered magic values. 14156 /// 14157 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14158 /// kind. 14159 /// 14160 /// \param TypeInfo Information about the corresponding C type. 14161 /// 14162 /// \param isConstantEvaluated wether the evalaution should be performed in 14163 /// constant context. 14164 /// 14165 /// \returns true if the corresponding C type was found. 14166 static bool GetMatchingCType( 14167 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14168 const ASTContext &Ctx, 14169 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14170 *MagicValues, 14171 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14172 bool isConstantEvaluated) { 14173 FoundWrongKind = false; 14174 14175 // Variable declaration that has type_tag_for_datatype attribute. 14176 const ValueDecl *VD = nullptr; 14177 14178 uint64_t MagicValue; 14179 14180 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14181 return false; 14182 14183 if (VD) { 14184 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14185 if (I->getArgumentKind() != ArgumentKind) { 14186 FoundWrongKind = true; 14187 return false; 14188 } 14189 TypeInfo.Type = I->getMatchingCType(); 14190 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14191 TypeInfo.MustBeNull = I->getMustBeNull(); 14192 return true; 14193 } 14194 return false; 14195 } 14196 14197 if (!MagicValues) 14198 return false; 14199 14200 llvm::DenseMap<Sema::TypeTagMagicValue, 14201 Sema::TypeTagData>::const_iterator I = 14202 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14203 if (I == MagicValues->end()) 14204 return false; 14205 14206 TypeInfo = I->second; 14207 return true; 14208 } 14209 14210 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14211 uint64_t MagicValue, QualType Type, 14212 bool LayoutCompatible, 14213 bool MustBeNull) { 14214 if (!TypeTagForDatatypeMagicValues) 14215 TypeTagForDatatypeMagicValues.reset( 14216 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14217 14218 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14219 (*TypeTagForDatatypeMagicValues)[Magic] = 14220 TypeTagData(Type, LayoutCompatible, MustBeNull); 14221 } 14222 14223 static bool IsSameCharType(QualType T1, QualType T2) { 14224 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14225 if (!BT1) 14226 return false; 14227 14228 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14229 if (!BT2) 14230 return false; 14231 14232 BuiltinType::Kind T1Kind = BT1->getKind(); 14233 BuiltinType::Kind T2Kind = BT2->getKind(); 14234 14235 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14236 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14237 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14238 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14239 } 14240 14241 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14242 const ArrayRef<const Expr *> ExprArgs, 14243 SourceLocation CallSiteLoc) { 14244 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14245 bool IsPointerAttr = Attr->getIsPointer(); 14246 14247 // Retrieve the argument representing the 'type_tag'. 14248 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14249 if (TypeTagIdxAST >= ExprArgs.size()) { 14250 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14251 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14252 return; 14253 } 14254 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14255 bool FoundWrongKind; 14256 TypeTagData TypeInfo; 14257 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14258 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14259 TypeInfo, isConstantEvaluated())) { 14260 if (FoundWrongKind) 14261 Diag(TypeTagExpr->getExprLoc(), 14262 diag::warn_type_tag_for_datatype_wrong_kind) 14263 << TypeTagExpr->getSourceRange(); 14264 return; 14265 } 14266 14267 // Retrieve the argument representing the 'arg_idx'. 14268 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14269 if (ArgumentIdxAST >= ExprArgs.size()) { 14270 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14271 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14272 return; 14273 } 14274 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14275 if (IsPointerAttr) { 14276 // Skip implicit cast of pointer to `void *' (as a function argument). 14277 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14278 if (ICE->getType()->isVoidPointerType() && 14279 ICE->getCastKind() == CK_BitCast) 14280 ArgumentExpr = ICE->getSubExpr(); 14281 } 14282 QualType ArgumentType = ArgumentExpr->getType(); 14283 14284 // Passing a `void*' pointer shouldn't trigger a warning. 14285 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14286 return; 14287 14288 if (TypeInfo.MustBeNull) { 14289 // Type tag with matching void type requires a null pointer. 14290 if (!ArgumentExpr->isNullPointerConstant(Context, 14291 Expr::NPC_ValueDependentIsNotNull)) { 14292 Diag(ArgumentExpr->getExprLoc(), 14293 diag::warn_type_safety_null_pointer_required) 14294 << ArgumentKind->getName() 14295 << ArgumentExpr->getSourceRange() 14296 << TypeTagExpr->getSourceRange(); 14297 } 14298 return; 14299 } 14300 14301 QualType RequiredType = TypeInfo.Type; 14302 if (IsPointerAttr) 14303 RequiredType = Context.getPointerType(RequiredType); 14304 14305 bool mismatch = false; 14306 if (!TypeInfo.LayoutCompatible) { 14307 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14308 14309 // C++11 [basic.fundamental] p1: 14310 // Plain char, signed char, and unsigned char are three distinct types. 14311 // 14312 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14313 // char' depending on the current char signedness mode. 14314 if (mismatch) 14315 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14316 RequiredType->getPointeeType())) || 14317 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14318 mismatch = false; 14319 } else 14320 if (IsPointerAttr) 14321 mismatch = !isLayoutCompatible(Context, 14322 ArgumentType->getPointeeType(), 14323 RequiredType->getPointeeType()); 14324 else 14325 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14326 14327 if (mismatch) 14328 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14329 << ArgumentType << ArgumentKind 14330 << TypeInfo.LayoutCompatible << RequiredType 14331 << ArgumentExpr->getSourceRange() 14332 << TypeTagExpr->getSourceRange(); 14333 } 14334 14335 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14336 CharUnits Alignment) { 14337 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14338 } 14339 14340 void Sema::DiagnoseMisalignedMembers() { 14341 for (MisalignedMember &m : MisalignedMembers) { 14342 const NamedDecl *ND = m.RD; 14343 if (ND->getName().empty()) { 14344 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14345 ND = TD; 14346 } 14347 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14348 << m.MD << ND << m.E->getSourceRange(); 14349 } 14350 MisalignedMembers.clear(); 14351 } 14352 14353 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14354 E = E->IgnoreParens(); 14355 if (!T->isPointerType() && !T->isIntegerType()) 14356 return; 14357 if (isa<UnaryOperator>(E) && 14358 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14359 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14360 if (isa<MemberExpr>(Op)) { 14361 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14362 if (MA != MisalignedMembers.end() && 14363 (T->isIntegerType() || 14364 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14365 Context.getTypeAlignInChars( 14366 T->getPointeeType()) <= MA->Alignment)))) 14367 MisalignedMembers.erase(MA); 14368 } 14369 } 14370 } 14371 14372 void Sema::RefersToMemberWithReducedAlignment( 14373 Expr *E, 14374 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14375 Action) { 14376 const auto *ME = dyn_cast<MemberExpr>(E); 14377 if (!ME) 14378 return; 14379 14380 // No need to check expressions with an __unaligned-qualified type. 14381 if (E->getType().getQualifiers().hasUnaligned()) 14382 return; 14383 14384 // For a chain of MemberExpr like "a.b.c.d" this list 14385 // will keep FieldDecl's like [d, c, b]. 14386 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14387 const MemberExpr *TopME = nullptr; 14388 bool AnyIsPacked = false; 14389 do { 14390 QualType BaseType = ME->getBase()->getType(); 14391 if (BaseType->isDependentType()) 14392 return; 14393 if (ME->isArrow()) 14394 BaseType = BaseType->getPointeeType(); 14395 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14396 if (RD->isInvalidDecl()) 14397 return; 14398 14399 ValueDecl *MD = ME->getMemberDecl(); 14400 auto *FD = dyn_cast<FieldDecl>(MD); 14401 // We do not care about non-data members. 14402 if (!FD || FD->isInvalidDecl()) 14403 return; 14404 14405 AnyIsPacked = 14406 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14407 ReverseMemberChain.push_back(FD); 14408 14409 TopME = ME; 14410 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14411 } while (ME); 14412 assert(TopME && "We did not compute a topmost MemberExpr!"); 14413 14414 // Not the scope of this diagnostic. 14415 if (!AnyIsPacked) 14416 return; 14417 14418 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14419 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14420 // TODO: The innermost base of the member expression may be too complicated. 14421 // For now, just disregard these cases. This is left for future 14422 // improvement. 14423 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14424 return; 14425 14426 // Alignment expected by the whole expression. 14427 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14428 14429 // No need to do anything else with this case. 14430 if (ExpectedAlignment.isOne()) 14431 return; 14432 14433 // Synthesize offset of the whole access. 14434 CharUnits Offset; 14435 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14436 I++) { 14437 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14438 } 14439 14440 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14441 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14442 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14443 14444 // The base expression of the innermost MemberExpr may give 14445 // stronger guarantees than the class containing the member. 14446 if (DRE && !TopME->isArrow()) { 14447 const ValueDecl *VD = DRE->getDecl(); 14448 if (!VD->getType()->isReferenceType()) 14449 CompleteObjectAlignment = 14450 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14451 } 14452 14453 // Check if the synthesized offset fulfills the alignment. 14454 if (Offset % ExpectedAlignment != 0 || 14455 // It may fulfill the offset it but the effective alignment may still be 14456 // lower than the expected expression alignment. 14457 CompleteObjectAlignment < ExpectedAlignment) { 14458 // If this happens, we want to determine a sensible culprit of this. 14459 // Intuitively, watching the chain of member expressions from right to 14460 // left, we start with the required alignment (as required by the field 14461 // type) but some packed attribute in that chain has reduced the alignment. 14462 // It may happen that another packed structure increases it again. But if 14463 // we are here such increase has not been enough. So pointing the first 14464 // FieldDecl that either is packed or else its RecordDecl is, 14465 // seems reasonable. 14466 FieldDecl *FD = nullptr; 14467 CharUnits Alignment; 14468 for (FieldDecl *FDI : ReverseMemberChain) { 14469 if (FDI->hasAttr<PackedAttr>() || 14470 FDI->getParent()->hasAttr<PackedAttr>()) { 14471 FD = FDI; 14472 Alignment = std::min( 14473 Context.getTypeAlignInChars(FD->getType()), 14474 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14475 break; 14476 } 14477 } 14478 assert(FD && "We did not find a packed FieldDecl!"); 14479 Action(E, FD->getParent(), FD, Alignment); 14480 } 14481 } 14482 14483 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14484 using namespace std::placeholders; 14485 14486 RefersToMemberWithReducedAlignment( 14487 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14488 _2, _3, _4)); 14489 } 14490