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 clang::Expr *SizeOp = TheCall->getArg(2); 1653 // We warn about copying to or from `nullptr` pointers when `size` is 1654 // greater than 0. When `size` is value dependent we cannot evaluate its 1655 // value so we bail out. 1656 if (SizeOp->isValueDependent()) 1657 break; 1658 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1659 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1660 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1661 } 1662 break; 1663 } 1664 #define BUILTIN(ID, TYPE, ATTRS) 1665 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1666 case Builtin::BI##ID: \ 1667 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1668 #include "clang/Basic/Builtins.def" 1669 case Builtin::BI__annotation: 1670 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1671 return ExprError(); 1672 break; 1673 case Builtin::BI__builtin_annotation: 1674 if (SemaBuiltinAnnotation(*this, TheCall)) 1675 return ExprError(); 1676 break; 1677 case Builtin::BI__builtin_addressof: 1678 if (SemaBuiltinAddressof(*this, TheCall)) 1679 return ExprError(); 1680 break; 1681 case Builtin::BI__builtin_is_aligned: 1682 case Builtin::BI__builtin_align_up: 1683 case Builtin::BI__builtin_align_down: 1684 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1685 return ExprError(); 1686 break; 1687 case Builtin::BI__builtin_add_overflow: 1688 case Builtin::BI__builtin_sub_overflow: 1689 case Builtin::BI__builtin_mul_overflow: 1690 if (SemaBuiltinOverflow(*this, TheCall)) 1691 return ExprError(); 1692 break; 1693 case Builtin::BI__builtin_operator_new: 1694 case Builtin::BI__builtin_operator_delete: { 1695 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1696 ExprResult Res = 1697 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1698 if (Res.isInvalid()) 1699 CorrectDelayedTyposInExpr(TheCallResult.get()); 1700 return Res; 1701 } 1702 case Builtin::BI__builtin_dump_struct: { 1703 // We first want to ensure we are called with 2 arguments 1704 if (checkArgCount(*this, TheCall, 2)) 1705 return ExprError(); 1706 // Ensure that the first argument is of type 'struct XX *' 1707 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1708 const QualType PtrArgType = PtrArg->getType(); 1709 if (!PtrArgType->isPointerType() || 1710 !PtrArgType->getPointeeType()->isRecordType()) { 1711 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1712 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1713 << "structure pointer"; 1714 return ExprError(); 1715 } 1716 1717 // Ensure that the second argument is of type 'FunctionType' 1718 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1719 const QualType FnPtrArgType = FnPtrArg->getType(); 1720 if (!FnPtrArgType->isPointerType()) { 1721 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1722 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1723 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1724 return ExprError(); 1725 } 1726 1727 const auto *FuncType = 1728 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1729 1730 if (!FuncType) { 1731 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1732 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1733 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1734 return ExprError(); 1735 } 1736 1737 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1738 if (!FT->getNumParams()) { 1739 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1740 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1741 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1742 return ExprError(); 1743 } 1744 QualType PT = FT->getParamType(0); 1745 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1746 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1747 !PT->getPointeeType().isConstQualified()) { 1748 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1749 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1750 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1751 return ExprError(); 1752 } 1753 } 1754 1755 TheCall->setType(Context.IntTy); 1756 break; 1757 } 1758 case Builtin::BI__builtin_preserve_access_index: 1759 if (SemaBuiltinPreserveAI(*this, TheCall)) 1760 return ExprError(); 1761 break; 1762 case Builtin::BI__builtin_call_with_static_chain: 1763 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1764 return ExprError(); 1765 break; 1766 case Builtin::BI__exception_code: 1767 case Builtin::BI_exception_code: 1768 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1769 diag::err_seh___except_block)) 1770 return ExprError(); 1771 break; 1772 case Builtin::BI__exception_info: 1773 case Builtin::BI_exception_info: 1774 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1775 diag::err_seh___except_filter)) 1776 return ExprError(); 1777 break; 1778 case Builtin::BI__GetExceptionInfo: 1779 if (checkArgCount(*this, TheCall, 1)) 1780 return ExprError(); 1781 1782 if (CheckCXXThrowOperand( 1783 TheCall->getBeginLoc(), 1784 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1785 TheCall)) 1786 return ExprError(); 1787 1788 TheCall->setType(Context.VoidPtrTy); 1789 break; 1790 // OpenCL v2.0, s6.13.16 - Pipe functions 1791 case Builtin::BIread_pipe: 1792 case Builtin::BIwrite_pipe: 1793 // Since those two functions are declared with var args, we need a semantic 1794 // check for the argument. 1795 if (SemaBuiltinRWPipe(*this, TheCall)) 1796 return ExprError(); 1797 break; 1798 case Builtin::BIreserve_read_pipe: 1799 case Builtin::BIreserve_write_pipe: 1800 case Builtin::BIwork_group_reserve_read_pipe: 1801 case Builtin::BIwork_group_reserve_write_pipe: 1802 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1803 return ExprError(); 1804 break; 1805 case Builtin::BIsub_group_reserve_read_pipe: 1806 case Builtin::BIsub_group_reserve_write_pipe: 1807 if (checkOpenCLSubgroupExt(*this, TheCall) || 1808 SemaBuiltinReserveRWPipe(*this, TheCall)) 1809 return ExprError(); 1810 break; 1811 case Builtin::BIcommit_read_pipe: 1812 case Builtin::BIcommit_write_pipe: 1813 case Builtin::BIwork_group_commit_read_pipe: 1814 case Builtin::BIwork_group_commit_write_pipe: 1815 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1816 return ExprError(); 1817 break; 1818 case Builtin::BIsub_group_commit_read_pipe: 1819 case Builtin::BIsub_group_commit_write_pipe: 1820 if (checkOpenCLSubgroupExt(*this, TheCall) || 1821 SemaBuiltinCommitRWPipe(*this, TheCall)) 1822 return ExprError(); 1823 break; 1824 case Builtin::BIget_pipe_num_packets: 1825 case Builtin::BIget_pipe_max_packets: 1826 if (SemaBuiltinPipePackets(*this, TheCall)) 1827 return ExprError(); 1828 break; 1829 case Builtin::BIto_global: 1830 case Builtin::BIto_local: 1831 case Builtin::BIto_private: 1832 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1833 return ExprError(); 1834 break; 1835 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1836 case Builtin::BIenqueue_kernel: 1837 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1838 return ExprError(); 1839 break; 1840 case Builtin::BIget_kernel_work_group_size: 1841 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1842 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1846 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1847 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1848 return ExprError(); 1849 break; 1850 case Builtin::BI__builtin_os_log_format: 1851 Cleanup.setExprNeedsCleanups(true); 1852 LLVM_FALLTHROUGH; 1853 case Builtin::BI__builtin_os_log_format_buffer_size: 1854 if (SemaBuiltinOSLogFormat(TheCall)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__builtin_frame_address: 1858 case Builtin::BI__builtin_return_address: 1859 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1860 return ExprError(); 1861 1862 // -Wframe-address warning if non-zero passed to builtin 1863 // return/frame address. 1864 Expr::EvalResult Result; 1865 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1866 Result.Val.getInt() != 0) 1867 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1868 << ((BuiltinID == Builtin::BI__builtin_return_address) 1869 ? "__builtin_return_address" 1870 : "__builtin_frame_address") 1871 << TheCall->getSourceRange(); 1872 break; 1873 } 1874 1875 // Since the target specific builtins for each arch overlap, only check those 1876 // of the arch we are compiling for. 1877 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1878 switch (Context.getTargetInfo().getTriple().getArch()) { 1879 case llvm::Triple::arm: 1880 case llvm::Triple::armeb: 1881 case llvm::Triple::thumb: 1882 case llvm::Triple::thumbeb: 1883 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1884 return ExprError(); 1885 break; 1886 case llvm::Triple::aarch64: 1887 case llvm::Triple::aarch64_32: 1888 case llvm::Triple::aarch64_be: 1889 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1890 return ExprError(); 1891 break; 1892 case llvm::Triple::bpfeb: 1893 case llvm::Triple::bpfel: 1894 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1895 return ExprError(); 1896 break; 1897 case llvm::Triple::hexagon: 1898 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1899 return ExprError(); 1900 break; 1901 case llvm::Triple::mips: 1902 case llvm::Triple::mipsel: 1903 case llvm::Triple::mips64: 1904 case llvm::Triple::mips64el: 1905 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1906 return ExprError(); 1907 break; 1908 case llvm::Triple::systemz: 1909 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1910 return ExprError(); 1911 break; 1912 case llvm::Triple::x86: 1913 case llvm::Triple::x86_64: 1914 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1915 return ExprError(); 1916 break; 1917 case llvm::Triple::ppc: 1918 case llvm::Triple::ppc64: 1919 case llvm::Triple::ppc64le: 1920 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1921 return ExprError(); 1922 break; 1923 default: 1924 break; 1925 } 1926 } 1927 1928 return TheCallResult; 1929 } 1930 1931 // Get the valid immediate range for the specified NEON type code. 1932 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1933 NeonTypeFlags Type(t); 1934 int IsQuad = ForceQuad ? true : Type.isQuad(); 1935 switch (Type.getEltType()) { 1936 case NeonTypeFlags::Int8: 1937 case NeonTypeFlags::Poly8: 1938 return shift ? 7 : (8 << IsQuad) - 1; 1939 case NeonTypeFlags::Int16: 1940 case NeonTypeFlags::Poly16: 1941 return shift ? 15 : (4 << IsQuad) - 1; 1942 case NeonTypeFlags::Int32: 1943 return shift ? 31 : (2 << IsQuad) - 1; 1944 case NeonTypeFlags::Int64: 1945 case NeonTypeFlags::Poly64: 1946 return shift ? 63 : (1 << IsQuad) - 1; 1947 case NeonTypeFlags::Poly128: 1948 return shift ? 127 : (1 << IsQuad) - 1; 1949 case NeonTypeFlags::Float16: 1950 assert(!shift && "cannot shift float types!"); 1951 return (4 << IsQuad) - 1; 1952 case NeonTypeFlags::Float32: 1953 assert(!shift && "cannot shift float types!"); 1954 return (2 << IsQuad) - 1; 1955 case NeonTypeFlags::Float64: 1956 assert(!shift && "cannot shift float types!"); 1957 return (1 << IsQuad) - 1; 1958 } 1959 llvm_unreachable("Invalid NeonTypeFlag!"); 1960 } 1961 1962 /// getNeonEltType - Return the QualType corresponding to the elements of 1963 /// the vector type specified by the NeonTypeFlags. This is used to check 1964 /// the pointer arguments for Neon load/store intrinsics. 1965 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1966 bool IsPolyUnsigned, bool IsInt64Long) { 1967 switch (Flags.getEltType()) { 1968 case NeonTypeFlags::Int8: 1969 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1970 case NeonTypeFlags::Int16: 1971 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1972 case NeonTypeFlags::Int32: 1973 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1974 case NeonTypeFlags::Int64: 1975 if (IsInt64Long) 1976 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1977 else 1978 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1979 : Context.LongLongTy; 1980 case NeonTypeFlags::Poly8: 1981 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1982 case NeonTypeFlags::Poly16: 1983 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1984 case NeonTypeFlags::Poly64: 1985 if (IsInt64Long) 1986 return Context.UnsignedLongTy; 1987 else 1988 return Context.UnsignedLongLongTy; 1989 case NeonTypeFlags::Poly128: 1990 break; 1991 case NeonTypeFlags::Float16: 1992 return Context.HalfTy; 1993 case NeonTypeFlags::Float32: 1994 return Context.FloatTy; 1995 case NeonTypeFlags::Float64: 1996 return Context.DoubleTy; 1997 } 1998 llvm_unreachable("Invalid NeonTypeFlag!"); 1999 } 2000 2001 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2002 // Range check SVE intrinsics that take immediate values. 2003 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2004 2005 switch (BuiltinID) { 2006 default: 2007 return false; 2008 #define GET_SVE_IMMEDIATE_CHECK 2009 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2010 #undef GET_SVE_IMMEDIATE_CHECK 2011 } 2012 2013 // Perform all the immediate checks for this builtin call. 2014 bool HasError = false; 2015 for (auto &I : ImmChecks) { 2016 int ArgNum, CheckTy, ElementSizeInBits; 2017 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2018 2019 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2020 2021 // Function that checks whether the operand (ArgNum) is an immediate 2022 // that is one of the predefined values. 2023 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2024 int ErrDiag) -> bool { 2025 // We can't check the value of a dependent argument. 2026 Expr *Arg = TheCall->getArg(ArgNum); 2027 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2028 return false; 2029 2030 // Check constant-ness first. 2031 llvm::APSInt Imm; 2032 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2033 return true; 2034 2035 if (!CheckImm(Imm.getSExtValue())) 2036 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2037 return false; 2038 }; 2039 2040 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2041 case SVETypeFlags::ImmCheck0_31: 2042 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2043 HasError = true; 2044 break; 2045 case SVETypeFlags::ImmCheck1_16: 2046 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2047 HasError = true; 2048 break; 2049 case SVETypeFlags::ImmCheck0_7: 2050 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2051 HasError = true; 2052 break; 2053 case SVETypeFlags::ImmCheckExtract: 2054 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2055 (2048 / ElementSizeInBits) - 1)) 2056 HasError = true; 2057 break; 2058 case SVETypeFlags::ImmCheckShiftRight: 2059 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2060 HasError = true; 2061 break; 2062 case SVETypeFlags::ImmCheckShiftRightNarrow: 2063 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2064 ElementSizeInBits / 2)) 2065 HasError = true; 2066 break; 2067 case SVETypeFlags::ImmCheckShiftLeft: 2068 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2069 ElementSizeInBits - 1)) 2070 HasError = true; 2071 break; 2072 case SVETypeFlags::ImmCheckLaneIndex: 2073 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2074 (128 / (1 * ElementSizeInBits)) - 1)) 2075 HasError = true; 2076 break; 2077 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2078 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2079 (128 / (2 * ElementSizeInBits)) - 1)) 2080 HasError = true; 2081 break; 2082 case SVETypeFlags::ImmCheckLaneIndexDot: 2083 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2084 (128 / (4 * ElementSizeInBits)) - 1)) 2085 HasError = true; 2086 break; 2087 case SVETypeFlags::ImmCheckComplexRot90_270: 2088 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2089 diag::err_rotation_argument_to_cadd)) 2090 HasError = true; 2091 break; 2092 case SVETypeFlags::ImmCheckComplexRotAll90: 2093 if (CheckImmediateInSet( 2094 [](int64_t V) { 2095 return V == 0 || V == 90 || V == 180 || V == 270; 2096 }, 2097 diag::err_rotation_argument_to_cmla)) 2098 HasError = true; 2099 break; 2100 } 2101 } 2102 2103 return HasError; 2104 } 2105 2106 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2107 llvm::APSInt Result; 2108 uint64_t mask = 0; 2109 unsigned TV = 0; 2110 int PtrArgNum = -1; 2111 bool HasConstPtr = false; 2112 switch (BuiltinID) { 2113 #define GET_NEON_OVERLOAD_CHECK 2114 #include "clang/Basic/arm_neon.inc" 2115 #include "clang/Basic/arm_fp16.inc" 2116 #undef GET_NEON_OVERLOAD_CHECK 2117 } 2118 2119 // For NEON intrinsics which are overloaded on vector element type, validate 2120 // the immediate which specifies which variant to emit. 2121 unsigned ImmArg = TheCall->getNumArgs()-1; 2122 if (mask) { 2123 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2124 return true; 2125 2126 TV = Result.getLimitedValue(64); 2127 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2128 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2129 << TheCall->getArg(ImmArg)->getSourceRange(); 2130 } 2131 2132 if (PtrArgNum >= 0) { 2133 // Check that pointer arguments have the specified type. 2134 Expr *Arg = TheCall->getArg(PtrArgNum); 2135 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2136 Arg = ICE->getSubExpr(); 2137 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2138 QualType RHSTy = RHS.get()->getType(); 2139 2140 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2141 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2142 Arch == llvm::Triple::aarch64_32 || 2143 Arch == llvm::Triple::aarch64_be; 2144 bool IsInt64Long = 2145 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2146 QualType EltTy = 2147 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2148 if (HasConstPtr) 2149 EltTy = EltTy.withConst(); 2150 QualType LHSTy = Context.getPointerType(EltTy); 2151 AssignConvertType ConvTy; 2152 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2153 if (RHS.isInvalid()) 2154 return true; 2155 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2156 RHS.get(), AA_Assigning)) 2157 return true; 2158 } 2159 2160 // For NEON intrinsics which take an immediate value as part of the 2161 // instruction, range check them here. 2162 unsigned i = 0, l = 0, u = 0; 2163 switch (BuiltinID) { 2164 default: 2165 return false; 2166 #define GET_NEON_IMMEDIATE_CHECK 2167 #include "clang/Basic/arm_neon.inc" 2168 #include "clang/Basic/arm_fp16.inc" 2169 #undef GET_NEON_IMMEDIATE_CHECK 2170 } 2171 2172 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2173 } 2174 2175 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2176 switch (BuiltinID) { 2177 default: 2178 return false; 2179 #include "clang/Basic/arm_mve_builtin_sema.inc" 2180 } 2181 } 2182 2183 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2184 bool Err = false; 2185 switch (BuiltinID) { 2186 default: 2187 return false; 2188 #include "clang/Basic/arm_cde_builtin_sema.inc" 2189 } 2190 2191 if (Err) 2192 return true; 2193 2194 return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true); 2195 } 2196 2197 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) { 2198 if (isConstantEvaluated()) 2199 return false; 2200 2201 // We can't check the value of a dependent argument. 2202 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2203 return false; 2204 2205 llvm::APSInt CoprocNoAP; 2206 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2207 (void)IsICE; 2208 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2209 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2210 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2211 2212 uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask(); 2213 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2214 2215 if (IsCDECoproc != WantCDE) 2216 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2217 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2218 2219 return false; 2220 } 2221 2222 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2223 unsigned MaxWidth) { 2224 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2225 BuiltinID == ARM::BI__builtin_arm_ldaex || 2226 BuiltinID == ARM::BI__builtin_arm_strex || 2227 BuiltinID == ARM::BI__builtin_arm_stlex || 2228 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2229 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2230 BuiltinID == AArch64::BI__builtin_arm_strex || 2231 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2232 "unexpected ARM builtin"); 2233 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2234 BuiltinID == ARM::BI__builtin_arm_ldaex || 2235 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2236 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2237 2238 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2239 2240 // Ensure that we have the proper number of arguments. 2241 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2242 return true; 2243 2244 // Inspect the pointer argument of the atomic builtin. This should always be 2245 // a pointer type, whose element is an integral scalar or pointer type. 2246 // Because it is a pointer type, we don't have to worry about any implicit 2247 // casts here. 2248 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2249 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2250 if (PointerArgRes.isInvalid()) 2251 return true; 2252 PointerArg = PointerArgRes.get(); 2253 2254 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2255 if (!pointerType) { 2256 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2257 << PointerArg->getType() << PointerArg->getSourceRange(); 2258 return true; 2259 } 2260 2261 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2262 // task is to insert the appropriate casts into the AST. First work out just 2263 // what the appropriate type is. 2264 QualType ValType = pointerType->getPointeeType(); 2265 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2266 if (IsLdrex) 2267 AddrType.addConst(); 2268 2269 // Issue a warning if the cast is dodgy. 2270 CastKind CastNeeded = CK_NoOp; 2271 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2272 CastNeeded = CK_BitCast; 2273 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2274 << PointerArg->getType() << Context.getPointerType(AddrType) 2275 << AA_Passing << PointerArg->getSourceRange(); 2276 } 2277 2278 // Finally, do the cast and replace the argument with the corrected version. 2279 AddrType = Context.getPointerType(AddrType); 2280 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2281 if (PointerArgRes.isInvalid()) 2282 return true; 2283 PointerArg = PointerArgRes.get(); 2284 2285 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2286 2287 // In general, we allow ints, floats and pointers to be loaded and stored. 2288 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2289 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2290 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2291 << PointerArg->getType() << PointerArg->getSourceRange(); 2292 return true; 2293 } 2294 2295 // But ARM doesn't have instructions to deal with 128-bit versions. 2296 if (Context.getTypeSize(ValType) > MaxWidth) { 2297 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2298 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2299 << PointerArg->getType() << PointerArg->getSourceRange(); 2300 return true; 2301 } 2302 2303 switch (ValType.getObjCLifetime()) { 2304 case Qualifiers::OCL_None: 2305 case Qualifiers::OCL_ExplicitNone: 2306 // okay 2307 break; 2308 2309 case Qualifiers::OCL_Weak: 2310 case Qualifiers::OCL_Strong: 2311 case Qualifiers::OCL_Autoreleasing: 2312 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2313 << ValType << PointerArg->getSourceRange(); 2314 return true; 2315 } 2316 2317 if (IsLdrex) { 2318 TheCall->setType(ValType); 2319 return false; 2320 } 2321 2322 // Initialize the argument to be stored. 2323 ExprResult ValArg = TheCall->getArg(0); 2324 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2325 Context, ValType, /*consume*/ false); 2326 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2327 if (ValArg.isInvalid()) 2328 return true; 2329 TheCall->setArg(0, ValArg.get()); 2330 2331 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2332 // but the custom checker bypasses all default analysis. 2333 TheCall->setType(Context.IntTy); 2334 return false; 2335 } 2336 2337 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2338 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2339 BuiltinID == ARM::BI__builtin_arm_ldaex || 2340 BuiltinID == ARM::BI__builtin_arm_strex || 2341 BuiltinID == ARM::BI__builtin_arm_stlex) { 2342 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2343 } 2344 2345 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2346 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2347 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2348 } 2349 2350 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2351 BuiltinID == ARM::BI__builtin_arm_wsr64) 2352 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2353 2354 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2355 BuiltinID == ARM::BI__builtin_arm_rsrp || 2356 BuiltinID == ARM::BI__builtin_arm_wsr || 2357 BuiltinID == ARM::BI__builtin_arm_wsrp) 2358 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2359 2360 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2361 return true; 2362 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2363 return true; 2364 if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall)) 2365 return true; 2366 2367 // For intrinsics which take an immediate value as part of the instruction, 2368 // range check them here. 2369 // FIXME: VFP Intrinsics should error if VFP not present. 2370 switch (BuiltinID) { 2371 default: return false; 2372 case ARM::BI__builtin_arm_ssat: 2373 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2374 case ARM::BI__builtin_arm_usat: 2375 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2376 case ARM::BI__builtin_arm_ssat16: 2377 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2378 case ARM::BI__builtin_arm_usat16: 2379 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2380 case ARM::BI__builtin_arm_vcvtr_f: 2381 case ARM::BI__builtin_arm_vcvtr_d: 2382 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2383 case ARM::BI__builtin_arm_dmb: 2384 case ARM::BI__builtin_arm_dsb: 2385 case ARM::BI__builtin_arm_isb: 2386 case ARM::BI__builtin_arm_dbg: 2387 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2388 case ARM::BI__builtin_arm_cdp: 2389 case ARM::BI__builtin_arm_cdp2: 2390 case ARM::BI__builtin_arm_mcr: 2391 case ARM::BI__builtin_arm_mcr2: 2392 case ARM::BI__builtin_arm_mrc: 2393 case ARM::BI__builtin_arm_mrc2: 2394 case ARM::BI__builtin_arm_mcrr: 2395 case ARM::BI__builtin_arm_mcrr2: 2396 case ARM::BI__builtin_arm_mrrc: 2397 case ARM::BI__builtin_arm_mrrc2: 2398 case ARM::BI__builtin_arm_ldc: 2399 case ARM::BI__builtin_arm_ldcl: 2400 case ARM::BI__builtin_arm_ldc2: 2401 case ARM::BI__builtin_arm_ldc2l: 2402 case ARM::BI__builtin_arm_stc: 2403 case ARM::BI__builtin_arm_stcl: 2404 case ARM::BI__builtin_arm_stc2: 2405 case ARM::BI__builtin_arm_stc2l: 2406 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2407 CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false); 2408 } 2409 } 2410 2411 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2412 CallExpr *TheCall) { 2413 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2414 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2415 BuiltinID == AArch64::BI__builtin_arm_strex || 2416 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2417 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2418 } 2419 2420 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2421 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2422 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2423 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2424 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2425 } 2426 2427 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2428 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2429 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2430 2431 // Memory Tagging Extensions (MTE) Intrinsics 2432 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2433 BuiltinID == AArch64::BI__builtin_arm_addg || 2434 BuiltinID == AArch64::BI__builtin_arm_gmi || 2435 BuiltinID == AArch64::BI__builtin_arm_ldg || 2436 BuiltinID == AArch64::BI__builtin_arm_stg || 2437 BuiltinID == AArch64::BI__builtin_arm_subp) { 2438 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2439 } 2440 2441 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2442 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2443 BuiltinID == AArch64::BI__builtin_arm_wsr || 2444 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2445 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2446 2447 // Only check the valid encoding range. Any constant in this range would be 2448 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2449 // an exception for incorrect registers. This matches MSVC behavior. 2450 if (BuiltinID == AArch64::BI_ReadStatusReg || 2451 BuiltinID == AArch64::BI_WriteStatusReg) 2452 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2453 2454 if (BuiltinID == AArch64::BI__getReg) 2455 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2456 2457 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2458 return true; 2459 2460 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2461 return true; 2462 2463 // For intrinsics which take an immediate value as part of the instruction, 2464 // range check them here. 2465 unsigned i = 0, l = 0, u = 0; 2466 switch (BuiltinID) { 2467 default: return false; 2468 case AArch64::BI__builtin_arm_dmb: 2469 case AArch64::BI__builtin_arm_dsb: 2470 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2471 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2472 } 2473 2474 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2475 } 2476 2477 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2478 CallExpr *TheCall) { 2479 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2480 "unexpected ARM builtin"); 2481 2482 if (checkArgCount(*this, TheCall, 2)) 2483 return true; 2484 2485 // The first argument needs to be a record field access. 2486 // If it is an array element access, we delay decision 2487 // to BPF backend to check whether the access is a 2488 // field access or not. 2489 Expr *Arg = TheCall->getArg(0); 2490 if (Arg->getType()->getAsPlaceholderType() || 2491 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2492 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2493 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2494 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2495 << 1 << Arg->getSourceRange(); 2496 return true; 2497 } 2498 2499 // The second argument needs to be a constant int 2500 llvm::APSInt Value; 2501 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2502 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2503 << 2 << Arg->getSourceRange(); 2504 return true; 2505 } 2506 2507 TheCall->setType(Context.UnsignedIntTy); 2508 return false; 2509 } 2510 2511 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2512 struct ArgInfo { 2513 uint8_t OpNum; 2514 bool IsSigned; 2515 uint8_t BitWidth; 2516 uint8_t Align; 2517 }; 2518 struct BuiltinInfo { 2519 unsigned BuiltinID; 2520 ArgInfo Infos[2]; 2521 }; 2522 2523 static BuiltinInfo Infos[] = { 2524 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2525 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2526 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2527 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2528 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2529 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2530 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2531 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2532 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2533 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2534 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2535 2536 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2537 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2538 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2539 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2540 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2541 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2542 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2543 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2544 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2545 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2546 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2547 2548 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2549 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2550 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2551 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2552 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2553 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2554 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2555 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2556 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2557 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2558 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2559 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2560 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2561 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2562 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2563 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2564 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2565 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2566 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2567 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2600 {{ 1, false, 6, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2608 {{ 1, false, 5, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2615 { 2, false, 5, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2617 { 2, false, 6, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2619 { 3, false, 5, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2621 { 3, false, 6, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2638 {{ 2, false, 4, 0 }, 2639 { 3, false, 5, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2641 {{ 2, false, 4, 0 }, 2642 { 3, false, 5, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2644 {{ 2, false, 4, 0 }, 2645 { 3, false, 5, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2647 {{ 2, false, 4, 0 }, 2648 { 3, false, 5, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2660 { 2, false, 5, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2662 { 2, false, 6, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2672 {{ 1, false, 4, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2675 {{ 1, false, 4, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2696 {{ 3, false, 1, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2701 {{ 3, false, 1, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2706 {{ 3, false, 1, 0 }} }, 2707 }; 2708 2709 // Use a dynamically initialized static to sort the table exactly once on 2710 // first run. 2711 static const bool SortOnce = 2712 (llvm::sort(Infos, 2713 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2714 return LHS.BuiltinID < RHS.BuiltinID; 2715 }), 2716 true); 2717 (void)SortOnce; 2718 2719 const BuiltinInfo *F = llvm::partition_point( 2720 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2721 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2722 return false; 2723 2724 bool Error = false; 2725 2726 for (const ArgInfo &A : F->Infos) { 2727 // Ignore empty ArgInfo elements. 2728 if (A.BitWidth == 0) 2729 continue; 2730 2731 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2732 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2733 if (!A.Align) { 2734 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2735 } else { 2736 unsigned M = 1 << A.Align; 2737 Min *= M; 2738 Max *= M; 2739 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2740 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2741 } 2742 } 2743 return Error; 2744 } 2745 2746 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2747 CallExpr *TheCall) { 2748 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2749 } 2750 2751 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2752 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2753 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2754 } 2755 2756 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2757 const TargetInfo &TI = Context.getTargetInfo(); 2758 2759 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2760 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2761 if (!TI.hasFeature("dsp")) 2762 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2763 } 2764 2765 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2766 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2767 if (!TI.hasFeature("dspr2")) 2768 return Diag(TheCall->getBeginLoc(), 2769 diag::err_mips_builtin_requires_dspr2); 2770 } 2771 2772 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2773 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2774 if (!TI.hasFeature("msa")) 2775 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2776 } 2777 2778 return false; 2779 } 2780 2781 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2782 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2783 // ordering for DSP is unspecified. MSA is ordered by the data format used 2784 // by the underlying instruction i.e., df/m, df/n and then by size. 2785 // 2786 // FIXME: The size tests here should instead be tablegen'd along with the 2787 // definitions from include/clang/Basic/BuiltinsMips.def. 2788 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2789 // be too. 2790 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2791 unsigned i = 0, l = 0, u = 0, m = 0; 2792 switch (BuiltinID) { 2793 default: return false; 2794 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2795 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2796 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2797 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2798 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2799 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2800 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2801 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2802 // df/m field. 2803 // These intrinsics take an unsigned 3 bit immediate. 2804 case Mips::BI__builtin_msa_bclri_b: 2805 case Mips::BI__builtin_msa_bnegi_b: 2806 case Mips::BI__builtin_msa_bseti_b: 2807 case Mips::BI__builtin_msa_sat_s_b: 2808 case Mips::BI__builtin_msa_sat_u_b: 2809 case Mips::BI__builtin_msa_slli_b: 2810 case Mips::BI__builtin_msa_srai_b: 2811 case Mips::BI__builtin_msa_srari_b: 2812 case Mips::BI__builtin_msa_srli_b: 2813 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2814 case Mips::BI__builtin_msa_binsli_b: 2815 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2816 // These intrinsics take an unsigned 4 bit immediate. 2817 case Mips::BI__builtin_msa_bclri_h: 2818 case Mips::BI__builtin_msa_bnegi_h: 2819 case Mips::BI__builtin_msa_bseti_h: 2820 case Mips::BI__builtin_msa_sat_s_h: 2821 case Mips::BI__builtin_msa_sat_u_h: 2822 case Mips::BI__builtin_msa_slli_h: 2823 case Mips::BI__builtin_msa_srai_h: 2824 case Mips::BI__builtin_msa_srari_h: 2825 case Mips::BI__builtin_msa_srli_h: 2826 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2827 case Mips::BI__builtin_msa_binsli_h: 2828 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2829 // These intrinsics take an unsigned 5 bit immediate. 2830 // The first block of intrinsics actually have an unsigned 5 bit field, 2831 // not a df/n field. 2832 case Mips::BI__builtin_msa_cfcmsa: 2833 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2834 case Mips::BI__builtin_msa_clei_u_b: 2835 case Mips::BI__builtin_msa_clei_u_h: 2836 case Mips::BI__builtin_msa_clei_u_w: 2837 case Mips::BI__builtin_msa_clei_u_d: 2838 case Mips::BI__builtin_msa_clti_u_b: 2839 case Mips::BI__builtin_msa_clti_u_h: 2840 case Mips::BI__builtin_msa_clti_u_w: 2841 case Mips::BI__builtin_msa_clti_u_d: 2842 case Mips::BI__builtin_msa_maxi_u_b: 2843 case Mips::BI__builtin_msa_maxi_u_h: 2844 case Mips::BI__builtin_msa_maxi_u_w: 2845 case Mips::BI__builtin_msa_maxi_u_d: 2846 case Mips::BI__builtin_msa_mini_u_b: 2847 case Mips::BI__builtin_msa_mini_u_h: 2848 case Mips::BI__builtin_msa_mini_u_w: 2849 case Mips::BI__builtin_msa_mini_u_d: 2850 case Mips::BI__builtin_msa_addvi_b: 2851 case Mips::BI__builtin_msa_addvi_h: 2852 case Mips::BI__builtin_msa_addvi_w: 2853 case Mips::BI__builtin_msa_addvi_d: 2854 case Mips::BI__builtin_msa_bclri_w: 2855 case Mips::BI__builtin_msa_bnegi_w: 2856 case Mips::BI__builtin_msa_bseti_w: 2857 case Mips::BI__builtin_msa_sat_s_w: 2858 case Mips::BI__builtin_msa_sat_u_w: 2859 case Mips::BI__builtin_msa_slli_w: 2860 case Mips::BI__builtin_msa_srai_w: 2861 case Mips::BI__builtin_msa_srari_w: 2862 case Mips::BI__builtin_msa_srli_w: 2863 case Mips::BI__builtin_msa_srlri_w: 2864 case Mips::BI__builtin_msa_subvi_b: 2865 case Mips::BI__builtin_msa_subvi_h: 2866 case Mips::BI__builtin_msa_subvi_w: 2867 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2868 case Mips::BI__builtin_msa_binsli_w: 2869 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2870 // These intrinsics take an unsigned 6 bit immediate. 2871 case Mips::BI__builtin_msa_bclri_d: 2872 case Mips::BI__builtin_msa_bnegi_d: 2873 case Mips::BI__builtin_msa_bseti_d: 2874 case Mips::BI__builtin_msa_sat_s_d: 2875 case Mips::BI__builtin_msa_sat_u_d: 2876 case Mips::BI__builtin_msa_slli_d: 2877 case Mips::BI__builtin_msa_srai_d: 2878 case Mips::BI__builtin_msa_srari_d: 2879 case Mips::BI__builtin_msa_srli_d: 2880 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2881 case Mips::BI__builtin_msa_binsli_d: 2882 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2883 // These intrinsics take a signed 5 bit immediate. 2884 case Mips::BI__builtin_msa_ceqi_b: 2885 case Mips::BI__builtin_msa_ceqi_h: 2886 case Mips::BI__builtin_msa_ceqi_w: 2887 case Mips::BI__builtin_msa_ceqi_d: 2888 case Mips::BI__builtin_msa_clti_s_b: 2889 case Mips::BI__builtin_msa_clti_s_h: 2890 case Mips::BI__builtin_msa_clti_s_w: 2891 case Mips::BI__builtin_msa_clti_s_d: 2892 case Mips::BI__builtin_msa_clei_s_b: 2893 case Mips::BI__builtin_msa_clei_s_h: 2894 case Mips::BI__builtin_msa_clei_s_w: 2895 case Mips::BI__builtin_msa_clei_s_d: 2896 case Mips::BI__builtin_msa_maxi_s_b: 2897 case Mips::BI__builtin_msa_maxi_s_h: 2898 case Mips::BI__builtin_msa_maxi_s_w: 2899 case Mips::BI__builtin_msa_maxi_s_d: 2900 case Mips::BI__builtin_msa_mini_s_b: 2901 case Mips::BI__builtin_msa_mini_s_h: 2902 case Mips::BI__builtin_msa_mini_s_w: 2903 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2904 // These intrinsics take an unsigned 8 bit immediate. 2905 case Mips::BI__builtin_msa_andi_b: 2906 case Mips::BI__builtin_msa_nori_b: 2907 case Mips::BI__builtin_msa_ori_b: 2908 case Mips::BI__builtin_msa_shf_b: 2909 case Mips::BI__builtin_msa_shf_h: 2910 case Mips::BI__builtin_msa_shf_w: 2911 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2912 case Mips::BI__builtin_msa_bseli_b: 2913 case Mips::BI__builtin_msa_bmnzi_b: 2914 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2915 // df/n format 2916 // These intrinsics take an unsigned 4 bit immediate. 2917 case Mips::BI__builtin_msa_copy_s_b: 2918 case Mips::BI__builtin_msa_copy_u_b: 2919 case Mips::BI__builtin_msa_insve_b: 2920 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2921 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2922 // These intrinsics take an unsigned 3 bit immediate. 2923 case Mips::BI__builtin_msa_copy_s_h: 2924 case Mips::BI__builtin_msa_copy_u_h: 2925 case Mips::BI__builtin_msa_insve_h: 2926 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2927 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2928 // These intrinsics take an unsigned 2 bit immediate. 2929 case Mips::BI__builtin_msa_copy_s_w: 2930 case Mips::BI__builtin_msa_copy_u_w: 2931 case Mips::BI__builtin_msa_insve_w: 2932 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2933 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2934 // These intrinsics take an unsigned 1 bit immediate. 2935 case Mips::BI__builtin_msa_copy_s_d: 2936 case Mips::BI__builtin_msa_copy_u_d: 2937 case Mips::BI__builtin_msa_insve_d: 2938 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2939 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2940 // Memory offsets and immediate loads. 2941 // These intrinsics take a signed 10 bit immediate. 2942 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2943 case Mips::BI__builtin_msa_ldi_h: 2944 case Mips::BI__builtin_msa_ldi_w: 2945 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2946 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2947 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2948 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2949 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2950 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2951 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2952 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2953 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2954 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2955 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2956 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2957 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 2958 } 2959 2960 if (!m) 2961 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2962 2963 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2964 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2965 } 2966 2967 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2968 unsigned i = 0, l = 0, u = 0; 2969 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2970 BuiltinID == PPC::BI__builtin_divdeu || 2971 BuiltinID == PPC::BI__builtin_bpermd; 2972 bool IsTarget64Bit = Context.getTargetInfo() 2973 .getTypeWidth(Context 2974 .getTargetInfo() 2975 .getIntPtrType()) == 64; 2976 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2977 BuiltinID == PPC::BI__builtin_divweu || 2978 BuiltinID == PPC::BI__builtin_divde || 2979 BuiltinID == PPC::BI__builtin_divdeu; 2980 2981 if (Is64BitBltin && !IsTarget64Bit) 2982 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2983 << TheCall->getSourceRange(); 2984 2985 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2986 (BuiltinID == PPC::BI__builtin_bpermd && 2987 !Context.getTargetInfo().hasFeature("bpermd"))) 2988 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2989 << TheCall->getSourceRange(); 2990 2991 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2992 if (!Context.getTargetInfo().hasFeature("vsx")) 2993 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2994 << TheCall->getSourceRange(); 2995 return false; 2996 }; 2997 2998 switch (BuiltinID) { 2999 default: return false; 3000 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3001 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3004 case PPC::BI__builtin_altivec_dss: 3005 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3006 case PPC::BI__builtin_tbegin: 3007 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3008 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3009 case PPC::BI__builtin_tabortwc: 3010 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3011 case PPC::BI__builtin_tabortwci: 3012 case PPC::BI__builtin_tabortdci: 3013 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3014 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3015 case PPC::BI__builtin_altivec_dst: 3016 case PPC::BI__builtin_altivec_dstt: 3017 case PPC::BI__builtin_altivec_dstst: 3018 case PPC::BI__builtin_altivec_dststt: 3019 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3020 case PPC::BI__builtin_vsx_xxpermdi: 3021 case PPC::BI__builtin_vsx_xxsldwi: 3022 return SemaBuiltinVSX(TheCall); 3023 case PPC::BI__builtin_unpack_vector_int128: 3024 return SemaVSXCheck(TheCall) || 3025 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3026 case PPC::BI__builtin_pack_vector_int128: 3027 return SemaVSXCheck(TheCall); 3028 } 3029 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3030 } 3031 3032 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3033 CallExpr *TheCall) { 3034 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3035 Expr *Arg = TheCall->getArg(0); 3036 llvm::APSInt AbortCode(32); 3037 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3038 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3039 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3040 << Arg->getSourceRange(); 3041 } 3042 3043 // For intrinsics which take an immediate value as part of the instruction, 3044 // range check them here. 3045 unsigned i = 0, l = 0, u = 0; 3046 switch (BuiltinID) { 3047 default: return false; 3048 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3049 case SystemZ::BI__builtin_s390_verimb: 3050 case SystemZ::BI__builtin_s390_verimh: 3051 case SystemZ::BI__builtin_s390_verimf: 3052 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3053 case SystemZ::BI__builtin_s390_vfaeb: 3054 case SystemZ::BI__builtin_s390_vfaeh: 3055 case SystemZ::BI__builtin_s390_vfaef: 3056 case SystemZ::BI__builtin_s390_vfaebs: 3057 case SystemZ::BI__builtin_s390_vfaehs: 3058 case SystemZ::BI__builtin_s390_vfaefs: 3059 case SystemZ::BI__builtin_s390_vfaezb: 3060 case SystemZ::BI__builtin_s390_vfaezh: 3061 case SystemZ::BI__builtin_s390_vfaezf: 3062 case SystemZ::BI__builtin_s390_vfaezbs: 3063 case SystemZ::BI__builtin_s390_vfaezhs: 3064 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3065 case SystemZ::BI__builtin_s390_vfisb: 3066 case SystemZ::BI__builtin_s390_vfidb: 3067 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3068 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3069 case SystemZ::BI__builtin_s390_vftcisb: 3070 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3071 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3072 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3073 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3074 case SystemZ::BI__builtin_s390_vstrcb: 3075 case SystemZ::BI__builtin_s390_vstrch: 3076 case SystemZ::BI__builtin_s390_vstrcf: 3077 case SystemZ::BI__builtin_s390_vstrczb: 3078 case SystemZ::BI__builtin_s390_vstrczh: 3079 case SystemZ::BI__builtin_s390_vstrczf: 3080 case SystemZ::BI__builtin_s390_vstrcbs: 3081 case SystemZ::BI__builtin_s390_vstrchs: 3082 case SystemZ::BI__builtin_s390_vstrcfs: 3083 case SystemZ::BI__builtin_s390_vstrczbs: 3084 case SystemZ::BI__builtin_s390_vstrczhs: 3085 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3086 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3087 case SystemZ::BI__builtin_s390_vfminsb: 3088 case SystemZ::BI__builtin_s390_vfmaxsb: 3089 case SystemZ::BI__builtin_s390_vfmindb: 3090 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3091 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3092 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3093 } 3094 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3095 } 3096 3097 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3098 /// This checks that the target supports __builtin_cpu_supports and 3099 /// that the string argument is constant and valid. 3100 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3101 Expr *Arg = TheCall->getArg(0); 3102 3103 // Check if the argument is a string literal. 3104 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3105 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3106 << Arg->getSourceRange(); 3107 3108 // Check the contents of the string. 3109 StringRef Feature = 3110 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3111 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3112 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3113 << Arg->getSourceRange(); 3114 return false; 3115 } 3116 3117 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3118 /// This checks that the target supports __builtin_cpu_is and 3119 /// that the string argument is constant and valid. 3120 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3121 Expr *Arg = TheCall->getArg(0); 3122 3123 // Check if the argument is a string literal. 3124 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3125 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3126 << Arg->getSourceRange(); 3127 3128 // Check the contents of the string. 3129 StringRef Feature = 3130 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3131 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3132 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3133 << Arg->getSourceRange(); 3134 return false; 3135 } 3136 3137 // Check if the rounding mode is legal. 3138 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3139 // Indicates if this instruction has rounding control or just SAE. 3140 bool HasRC = false; 3141 3142 unsigned ArgNum = 0; 3143 switch (BuiltinID) { 3144 default: 3145 return false; 3146 case X86::BI__builtin_ia32_vcvttsd2si32: 3147 case X86::BI__builtin_ia32_vcvttsd2si64: 3148 case X86::BI__builtin_ia32_vcvttsd2usi32: 3149 case X86::BI__builtin_ia32_vcvttsd2usi64: 3150 case X86::BI__builtin_ia32_vcvttss2si32: 3151 case X86::BI__builtin_ia32_vcvttss2si64: 3152 case X86::BI__builtin_ia32_vcvttss2usi32: 3153 case X86::BI__builtin_ia32_vcvttss2usi64: 3154 ArgNum = 1; 3155 break; 3156 case X86::BI__builtin_ia32_maxpd512: 3157 case X86::BI__builtin_ia32_maxps512: 3158 case X86::BI__builtin_ia32_minpd512: 3159 case X86::BI__builtin_ia32_minps512: 3160 ArgNum = 2; 3161 break; 3162 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3163 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3164 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3165 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3166 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3167 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3168 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3169 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3170 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3171 case X86::BI__builtin_ia32_exp2pd_mask: 3172 case X86::BI__builtin_ia32_exp2ps_mask: 3173 case X86::BI__builtin_ia32_getexppd512_mask: 3174 case X86::BI__builtin_ia32_getexpps512_mask: 3175 case X86::BI__builtin_ia32_rcp28pd_mask: 3176 case X86::BI__builtin_ia32_rcp28ps_mask: 3177 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3178 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3179 case X86::BI__builtin_ia32_vcomisd: 3180 case X86::BI__builtin_ia32_vcomiss: 3181 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3182 ArgNum = 3; 3183 break; 3184 case X86::BI__builtin_ia32_cmppd512_mask: 3185 case X86::BI__builtin_ia32_cmpps512_mask: 3186 case X86::BI__builtin_ia32_cmpsd_mask: 3187 case X86::BI__builtin_ia32_cmpss_mask: 3188 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3189 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3190 case X86::BI__builtin_ia32_getexpss128_round_mask: 3191 case X86::BI__builtin_ia32_getmantpd512_mask: 3192 case X86::BI__builtin_ia32_getmantps512_mask: 3193 case X86::BI__builtin_ia32_maxsd_round_mask: 3194 case X86::BI__builtin_ia32_maxss_round_mask: 3195 case X86::BI__builtin_ia32_minsd_round_mask: 3196 case X86::BI__builtin_ia32_minss_round_mask: 3197 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3198 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3199 case X86::BI__builtin_ia32_reducepd512_mask: 3200 case X86::BI__builtin_ia32_reduceps512_mask: 3201 case X86::BI__builtin_ia32_rndscalepd_mask: 3202 case X86::BI__builtin_ia32_rndscaleps_mask: 3203 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3204 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3205 ArgNum = 4; 3206 break; 3207 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3208 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3209 case X86::BI__builtin_ia32_fixupimmps512_mask: 3210 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3211 case X86::BI__builtin_ia32_fixupimmsd_mask: 3212 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3213 case X86::BI__builtin_ia32_fixupimmss_mask: 3214 case X86::BI__builtin_ia32_fixupimmss_maskz: 3215 case X86::BI__builtin_ia32_getmantsd_round_mask: 3216 case X86::BI__builtin_ia32_getmantss_round_mask: 3217 case X86::BI__builtin_ia32_rangepd512_mask: 3218 case X86::BI__builtin_ia32_rangeps512_mask: 3219 case X86::BI__builtin_ia32_rangesd128_round_mask: 3220 case X86::BI__builtin_ia32_rangess128_round_mask: 3221 case X86::BI__builtin_ia32_reducesd_mask: 3222 case X86::BI__builtin_ia32_reducess_mask: 3223 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3224 case X86::BI__builtin_ia32_rndscaless_round_mask: 3225 ArgNum = 5; 3226 break; 3227 case X86::BI__builtin_ia32_vcvtsd2si64: 3228 case X86::BI__builtin_ia32_vcvtsd2si32: 3229 case X86::BI__builtin_ia32_vcvtsd2usi32: 3230 case X86::BI__builtin_ia32_vcvtsd2usi64: 3231 case X86::BI__builtin_ia32_vcvtss2si32: 3232 case X86::BI__builtin_ia32_vcvtss2si64: 3233 case X86::BI__builtin_ia32_vcvtss2usi32: 3234 case X86::BI__builtin_ia32_vcvtss2usi64: 3235 case X86::BI__builtin_ia32_sqrtpd512: 3236 case X86::BI__builtin_ia32_sqrtps512: 3237 ArgNum = 1; 3238 HasRC = true; 3239 break; 3240 case X86::BI__builtin_ia32_addpd512: 3241 case X86::BI__builtin_ia32_addps512: 3242 case X86::BI__builtin_ia32_divpd512: 3243 case X86::BI__builtin_ia32_divps512: 3244 case X86::BI__builtin_ia32_mulpd512: 3245 case X86::BI__builtin_ia32_mulps512: 3246 case X86::BI__builtin_ia32_subpd512: 3247 case X86::BI__builtin_ia32_subps512: 3248 case X86::BI__builtin_ia32_cvtsi2sd64: 3249 case X86::BI__builtin_ia32_cvtsi2ss32: 3250 case X86::BI__builtin_ia32_cvtsi2ss64: 3251 case X86::BI__builtin_ia32_cvtusi2sd64: 3252 case X86::BI__builtin_ia32_cvtusi2ss32: 3253 case X86::BI__builtin_ia32_cvtusi2ss64: 3254 ArgNum = 2; 3255 HasRC = true; 3256 break; 3257 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3258 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3259 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3260 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3261 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3262 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3263 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3264 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3265 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3266 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3267 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3268 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3269 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3270 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3271 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3272 ArgNum = 3; 3273 HasRC = true; 3274 break; 3275 case X86::BI__builtin_ia32_addss_round_mask: 3276 case X86::BI__builtin_ia32_addsd_round_mask: 3277 case X86::BI__builtin_ia32_divss_round_mask: 3278 case X86::BI__builtin_ia32_divsd_round_mask: 3279 case X86::BI__builtin_ia32_mulss_round_mask: 3280 case X86::BI__builtin_ia32_mulsd_round_mask: 3281 case X86::BI__builtin_ia32_subss_round_mask: 3282 case X86::BI__builtin_ia32_subsd_round_mask: 3283 case X86::BI__builtin_ia32_scalefpd512_mask: 3284 case X86::BI__builtin_ia32_scalefps512_mask: 3285 case X86::BI__builtin_ia32_scalefsd_round_mask: 3286 case X86::BI__builtin_ia32_scalefss_round_mask: 3287 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3288 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3289 case X86::BI__builtin_ia32_sqrtss_round_mask: 3290 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3291 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3292 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3293 case X86::BI__builtin_ia32_vfmaddss3_mask: 3294 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3295 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3296 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3297 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3298 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3299 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3300 case X86::BI__builtin_ia32_vfmaddps512_mask: 3301 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3302 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3303 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3304 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3305 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3306 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3307 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3308 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3309 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3310 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3311 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3312 ArgNum = 4; 3313 HasRC = true; 3314 break; 3315 } 3316 3317 llvm::APSInt Result; 3318 3319 // We can't check the value of a dependent argument. 3320 Expr *Arg = TheCall->getArg(ArgNum); 3321 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3322 return false; 3323 3324 // Check constant-ness first. 3325 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3326 return true; 3327 3328 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3329 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3330 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3331 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3332 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3333 Result == 8/*ROUND_NO_EXC*/ || 3334 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3335 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3336 return false; 3337 3338 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3339 << Arg->getSourceRange(); 3340 } 3341 3342 // Check if the gather/scatter scale is legal. 3343 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3344 CallExpr *TheCall) { 3345 unsigned ArgNum = 0; 3346 switch (BuiltinID) { 3347 default: 3348 return false; 3349 case X86::BI__builtin_ia32_gatherpfdpd: 3350 case X86::BI__builtin_ia32_gatherpfdps: 3351 case X86::BI__builtin_ia32_gatherpfqpd: 3352 case X86::BI__builtin_ia32_gatherpfqps: 3353 case X86::BI__builtin_ia32_scatterpfdpd: 3354 case X86::BI__builtin_ia32_scatterpfdps: 3355 case X86::BI__builtin_ia32_scatterpfqpd: 3356 case X86::BI__builtin_ia32_scatterpfqps: 3357 ArgNum = 3; 3358 break; 3359 case X86::BI__builtin_ia32_gatherd_pd: 3360 case X86::BI__builtin_ia32_gatherd_pd256: 3361 case X86::BI__builtin_ia32_gatherq_pd: 3362 case X86::BI__builtin_ia32_gatherq_pd256: 3363 case X86::BI__builtin_ia32_gatherd_ps: 3364 case X86::BI__builtin_ia32_gatherd_ps256: 3365 case X86::BI__builtin_ia32_gatherq_ps: 3366 case X86::BI__builtin_ia32_gatherq_ps256: 3367 case X86::BI__builtin_ia32_gatherd_q: 3368 case X86::BI__builtin_ia32_gatherd_q256: 3369 case X86::BI__builtin_ia32_gatherq_q: 3370 case X86::BI__builtin_ia32_gatherq_q256: 3371 case X86::BI__builtin_ia32_gatherd_d: 3372 case X86::BI__builtin_ia32_gatherd_d256: 3373 case X86::BI__builtin_ia32_gatherq_d: 3374 case X86::BI__builtin_ia32_gatherq_d256: 3375 case X86::BI__builtin_ia32_gather3div2df: 3376 case X86::BI__builtin_ia32_gather3div2di: 3377 case X86::BI__builtin_ia32_gather3div4df: 3378 case X86::BI__builtin_ia32_gather3div4di: 3379 case X86::BI__builtin_ia32_gather3div4sf: 3380 case X86::BI__builtin_ia32_gather3div4si: 3381 case X86::BI__builtin_ia32_gather3div8sf: 3382 case X86::BI__builtin_ia32_gather3div8si: 3383 case X86::BI__builtin_ia32_gather3siv2df: 3384 case X86::BI__builtin_ia32_gather3siv2di: 3385 case X86::BI__builtin_ia32_gather3siv4df: 3386 case X86::BI__builtin_ia32_gather3siv4di: 3387 case X86::BI__builtin_ia32_gather3siv4sf: 3388 case X86::BI__builtin_ia32_gather3siv4si: 3389 case X86::BI__builtin_ia32_gather3siv8sf: 3390 case X86::BI__builtin_ia32_gather3siv8si: 3391 case X86::BI__builtin_ia32_gathersiv8df: 3392 case X86::BI__builtin_ia32_gathersiv16sf: 3393 case X86::BI__builtin_ia32_gatherdiv8df: 3394 case X86::BI__builtin_ia32_gatherdiv16sf: 3395 case X86::BI__builtin_ia32_gathersiv8di: 3396 case X86::BI__builtin_ia32_gathersiv16si: 3397 case X86::BI__builtin_ia32_gatherdiv8di: 3398 case X86::BI__builtin_ia32_gatherdiv16si: 3399 case X86::BI__builtin_ia32_scatterdiv2df: 3400 case X86::BI__builtin_ia32_scatterdiv2di: 3401 case X86::BI__builtin_ia32_scatterdiv4df: 3402 case X86::BI__builtin_ia32_scatterdiv4di: 3403 case X86::BI__builtin_ia32_scatterdiv4sf: 3404 case X86::BI__builtin_ia32_scatterdiv4si: 3405 case X86::BI__builtin_ia32_scatterdiv8sf: 3406 case X86::BI__builtin_ia32_scatterdiv8si: 3407 case X86::BI__builtin_ia32_scattersiv2df: 3408 case X86::BI__builtin_ia32_scattersiv2di: 3409 case X86::BI__builtin_ia32_scattersiv4df: 3410 case X86::BI__builtin_ia32_scattersiv4di: 3411 case X86::BI__builtin_ia32_scattersiv4sf: 3412 case X86::BI__builtin_ia32_scattersiv4si: 3413 case X86::BI__builtin_ia32_scattersiv8sf: 3414 case X86::BI__builtin_ia32_scattersiv8si: 3415 case X86::BI__builtin_ia32_scattersiv8df: 3416 case X86::BI__builtin_ia32_scattersiv16sf: 3417 case X86::BI__builtin_ia32_scatterdiv8df: 3418 case X86::BI__builtin_ia32_scatterdiv16sf: 3419 case X86::BI__builtin_ia32_scattersiv8di: 3420 case X86::BI__builtin_ia32_scattersiv16si: 3421 case X86::BI__builtin_ia32_scatterdiv8di: 3422 case X86::BI__builtin_ia32_scatterdiv16si: 3423 ArgNum = 4; 3424 break; 3425 } 3426 3427 llvm::APSInt Result; 3428 3429 // We can't check the value of a dependent argument. 3430 Expr *Arg = TheCall->getArg(ArgNum); 3431 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3432 return false; 3433 3434 // Check constant-ness first. 3435 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3436 return true; 3437 3438 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3439 return false; 3440 3441 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3442 << Arg->getSourceRange(); 3443 } 3444 3445 static bool isX86_32Builtin(unsigned BuiltinID) { 3446 // These builtins only work on x86-32 targets. 3447 switch (BuiltinID) { 3448 case X86::BI__builtin_ia32_readeflags_u32: 3449 case X86::BI__builtin_ia32_writeeflags_u32: 3450 return true; 3451 } 3452 3453 return false; 3454 } 3455 3456 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3457 if (BuiltinID == X86::BI__builtin_cpu_supports) 3458 return SemaBuiltinCpuSupports(*this, TheCall); 3459 3460 if (BuiltinID == X86::BI__builtin_cpu_is) 3461 return SemaBuiltinCpuIs(*this, TheCall); 3462 3463 // Check for 32-bit only builtins on a 64-bit target. 3464 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3465 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3466 return Diag(TheCall->getCallee()->getBeginLoc(), 3467 diag::err_32_bit_builtin_64_bit_tgt); 3468 3469 // If the intrinsic has rounding or SAE make sure its valid. 3470 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3471 return true; 3472 3473 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3474 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3475 return true; 3476 3477 // For intrinsics which take an immediate value as part of the instruction, 3478 // range check them here. 3479 int i = 0, l = 0, u = 0; 3480 switch (BuiltinID) { 3481 default: 3482 return false; 3483 case X86::BI__builtin_ia32_vec_ext_v2si: 3484 case X86::BI__builtin_ia32_vec_ext_v2di: 3485 case X86::BI__builtin_ia32_vextractf128_pd256: 3486 case X86::BI__builtin_ia32_vextractf128_ps256: 3487 case X86::BI__builtin_ia32_vextractf128_si256: 3488 case X86::BI__builtin_ia32_extract128i256: 3489 case X86::BI__builtin_ia32_extractf64x4_mask: 3490 case X86::BI__builtin_ia32_extracti64x4_mask: 3491 case X86::BI__builtin_ia32_extractf32x8_mask: 3492 case X86::BI__builtin_ia32_extracti32x8_mask: 3493 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3494 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3495 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3496 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3497 i = 1; l = 0; u = 1; 3498 break; 3499 case X86::BI__builtin_ia32_vec_set_v2di: 3500 case X86::BI__builtin_ia32_vinsertf128_pd256: 3501 case X86::BI__builtin_ia32_vinsertf128_ps256: 3502 case X86::BI__builtin_ia32_vinsertf128_si256: 3503 case X86::BI__builtin_ia32_insert128i256: 3504 case X86::BI__builtin_ia32_insertf32x8: 3505 case X86::BI__builtin_ia32_inserti32x8: 3506 case X86::BI__builtin_ia32_insertf64x4: 3507 case X86::BI__builtin_ia32_inserti64x4: 3508 case X86::BI__builtin_ia32_insertf64x2_256: 3509 case X86::BI__builtin_ia32_inserti64x2_256: 3510 case X86::BI__builtin_ia32_insertf32x4_256: 3511 case X86::BI__builtin_ia32_inserti32x4_256: 3512 i = 2; l = 0; u = 1; 3513 break; 3514 case X86::BI__builtin_ia32_vpermilpd: 3515 case X86::BI__builtin_ia32_vec_ext_v4hi: 3516 case X86::BI__builtin_ia32_vec_ext_v4si: 3517 case X86::BI__builtin_ia32_vec_ext_v4sf: 3518 case X86::BI__builtin_ia32_vec_ext_v4di: 3519 case X86::BI__builtin_ia32_extractf32x4_mask: 3520 case X86::BI__builtin_ia32_extracti32x4_mask: 3521 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3522 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3523 i = 1; l = 0; u = 3; 3524 break; 3525 case X86::BI_mm_prefetch: 3526 case X86::BI__builtin_ia32_vec_ext_v8hi: 3527 case X86::BI__builtin_ia32_vec_ext_v8si: 3528 i = 1; l = 0; u = 7; 3529 break; 3530 case X86::BI__builtin_ia32_sha1rnds4: 3531 case X86::BI__builtin_ia32_blendpd: 3532 case X86::BI__builtin_ia32_shufpd: 3533 case X86::BI__builtin_ia32_vec_set_v4hi: 3534 case X86::BI__builtin_ia32_vec_set_v4si: 3535 case X86::BI__builtin_ia32_vec_set_v4di: 3536 case X86::BI__builtin_ia32_shuf_f32x4_256: 3537 case X86::BI__builtin_ia32_shuf_f64x2_256: 3538 case X86::BI__builtin_ia32_shuf_i32x4_256: 3539 case X86::BI__builtin_ia32_shuf_i64x2_256: 3540 case X86::BI__builtin_ia32_insertf64x2_512: 3541 case X86::BI__builtin_ia32_inserti64x2_512: 3542 case X86::BI__builtin_ia32_insertf32x4: 3543 case X86::BI__builtin_ia32_inserti32x4: 3544 i = 2; l = 0; u = 3; 3545 break; 3546 case X86::BI__builtin_ia32_vpermil2pd: 3547 case X86::BI__builtin_ia32_vpermil2pd256: 3548 case X86::BI__builtin_ia32_vpermil2ps: 3549 case X86::BI__builtin_ia32_vpermil2ps256: 3550 i = 3; l = 0; u = 3; 3551 break; 3552 case X86::BI__builtin_ia32_cmpb128_mask: 3553 case X86::BI__builtin_ia32_cmpw128_mask: 3554 case X86::BI__builtin_ia32_cmpd128_mask: 3555 case X86::BI__builtin_ia32_cmpq128_mask: 3556 case X86::BI__builtin_ia32_cmpb256_mask: 3557 case X86::BI__builtin_ia32_cmpw256_mask: 3558 case X86::BI__builtin_ia32_cmpd256_mask: 3559 case X86::BI__builtin_ia32_cmpq256_mask: 3560 case X86::BI__builtin_ia32_cmpb512_mask: 3561 case X86::BI__builtin_ia32_cmpw512_mask: 3562 case X86::BI__builtin_ia32_cmpd512_mask: 3563 case X86::BI__builtin_ia32_cmpq512_mask: 3564 case X86::BI__builtin_ia32_ucmpb128_mask: 3565 case X86::BI__builtin_ia32_ucmpw128_mask: 3566 case X86::BI__builtin_ia32_ucmpd128_mask: 3567 case X86::BI__builtin_ia32_ucmpq128_mask: 3568 case X86::BI__builtin_ia32_ucmpb256_mask: 3569 case X86::BI__builtin_ia32_ucmpw256_mask: 3570 case X86::BI__builtin_ia32_ucmpd256_mask: 3571 case X86::BI__builtin_ia32_ucmpq256_mask: 3572 case X86::BI__builtin_ia32_ucmpb512_mask: 3573 case X86::BI__builtin_ia32_ucmpw512_mask: 3574 case X86::BI__builtin_ia32_ucmpd512_mask: 3575 case X86::BI__builtin_ia32_ucmpq512_mask: 3576 case X86::BI__builtin_ia32_vpcomub: 3577 case X86::BI__builtin_ia32_vpcomuw: 3578 case X86::BI__builtin_ia32_vpcomud: 3579 case X86::BI__builtin_ia32_vpcomuq: 3580 case X86::BI__builtin_ia32_vpcomb: 3581 case X86::BI__builtin_ia32_vpcomw: 3582 case X86::BI__builtin_ia32_vpcomd: 3583 case X86::BI__builtin_ia32_vpcomq: 3584 case X86::BI__builtin_ia32_vec_set_v8hi: 3585 case X86::BI__builtin_ia32_vec_set_v8si: 3586 i = 2; l = 0; u = 7; 3587 break; 3588 case X86::BI__builtin_ia32_vpermilpd256: 3589 case X86::BI__builtin_ia32_roundps: 3590 case X86::BI__builtin_ia32_roundpd: 3591 case X86::BI__builtin_ia32_roundps256: 3592 case X86::BI__builtin_ia32_roundpd256: 3593 case X86::BI__builtin_ia32_getmantpd128_mask: 3594 case X86::BI__builtin_ia32_getmantpd256_mask: 3595 case X86::BI__builtin_ia32_getmantps128_mask: 3596 case X86::BI__builtin_ia32_getmantps256_mask: 3597 case X86::BI__builtin_ia32_getmantpd512_mask: 3598 case X86::BI__builtin_ia32_getmantps512_mask: 3599 case X86::BI__builtin_ia32_vec_ext_v16qi: 3600 case X86::BI__builtin_ia32_vec_ext_v16hi: 3601 i = 1; l = 0; u = 15; 3602 break; 3603 case X86::BI__builtin_ia32_pblendd128: 3604 case X86::BI__builtin_ia32_blendps: 3605 case X86::BI__builtin_ia32_blendpd256: 3606 case X86::BI__builtin_ia32_shufpd256: 3607 case X86::BI__builtin_ia32_roundss: 3608 case X86::BI__builtin_ia32_roundsd: 3609 case X86::BI__builtin_ia32_rangepd128_mask: 3610 case X86::BI__builtin_ia32_rangepd256_mask: 3611 case X86::BI__builtin_ia32_rangepd512_mask: 3612 case X86::BI__builtin_ia32_rangeps128_mask: 3613 case X86::BI__builtin_ia32_rangeps256_mask: 3614 case X86::BI__builtin_ia32_rangeps512_mask: 3615 case X86::BI__builtin_ia32_getmantsd_round_mask: 3616 case X86::BI__builtin_ia32_getmantss_round_mask: 3617 case X86::BI__builtin_ia32_vec_set_v16qi: 3618 case X86::BI__builtin_ia32_vec_set_v16hi: 3619 i = 2; l = 0; u = 15; 3620 break; 3621 case X86::BI__builtin_ia32_vec_ext_v32qi: 3622 i = 1; l = 0; u = 31; 3623 break; 3624 case X86::BI__builtin_ia32_cmpps: 3625 case X86::BI__builtin_ia32_cmpss: 3626 case X86::BI__builtin_ia32_cmppd: 3627 case X86::BI__builtin_ia32_cmpsd: 3628 case X86::BI__builtin_ia32_cmpps256: 3629 case X86::BI__builtin_ia32_cmppd256: 3630 case X86::BI__builtin_ia32_cmpps128_mask: 3631 case X86::BI__builtin_ia32_cmppd128_mask: 3632 case X86::BI__builtin_ia32_cmpps256_mask: 3633 case X86::BI__builtin_ia32_cmppd256_mask: 3634 case X86::BI__builtin_ia32_cmpps512_mask: 3635 case X86::BI__builtin_ia32_cmppd512_mask: 3636 case X86::BI__builtin_ia32_cmpsd_mask: 3637 case X86::BI__builtin_ia32_cmpss_mask: 3638 case X86::BI__builtin_ia32_vec_set_v32qi: 3639 i = 2; l = 0; u = 31; 3640 break; 3641 case X86::BI__builtin_ia32_permdf256: 3642 case X86::BI__builtin_ia32_permdi256: 3643 case X86::BI__builtin_ia32_permdf512: 3644 case X86::BI__builtin_ia32_permdi512: 3645 case X86::BI__builtin_ia32_vpermilps: 3646 case X86::BI__builtin_ia32_vpermilps256: 3647 case X86::BI__builtin_ia32_vpermilpd512: 3648 case X86::BI__builtin_ia32_vpermilps512: 3649 case X86::BI__builtin_ia32_pshufd: 3650 case X86::BI__builtin_ia32_pshufd256: 3651 case X86::BI__builtin_ia32_pshufd512: 3652 case X86::BI__builtin_ia32_pshufhw: 3653 case X86::BI__builtin_ia32_pshufhw256: 3654 case X86::BI__builtin_ia32_pshufhw512: 3655 case X86::BI__builtin_ia32_pshuflw: 3656 case X86::BI__builtin_ia32_pshuflw256: 3657 case X86::BI__builtin_ia32_pshuflw512: 3658 case X86::BI__builtin_ia32_vcvtps2ph: 3659 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3660 case X86::BI__builtin_ia32_vcvtps2ph256: 3661 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3662 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3663 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3664 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3665 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3666 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3667 case X86::BI__builtin_ia32_rndscaleps_mask: 3668 case X86::BI__builtin_ia32_rndscalepd_mask: 3669 case X86::BI__builtin_ia32_reducepd128_mask: 3670 case X86::BI__builtin_ia32_reducepd256_mask: 3671 case X86::BI__builtin_ia32_reducepd512_mask: 3672 case X86::BI__builtin_ia32_reduceps128_mask: 3673 case X86::BI__builtin_ia32_reduceps256_mask: 3674 case X86::BI__builtin_ia32_reduceps512_mask: 3675 case X86::BI__builtin_ia32_prold512: 3676 case X86::BI__builtin_ia32_prolq512: 3677 case X86::BI__builtin_ia32_prold128: 3678 case X86::BI__builtin_ia32_prold256: 3679 case X86::BI__builtin_ia32_prolq128: 3680 case X86::BI__builtin_ia32_prolq256: 3681 case X86::BI__builtin_ia32_prord512: 3682 case X86::BI__builtin_ia32_prorq512: 3683 case X86::BI__builtin_ia32_prord128: 3684 case X86::BI__builtin_ia32_prord256: 3685 case X86::BI__builtin_ia32_prorq128: 3686 case X86::BI__builtin_ia32_prorq256: 3687 case X86::BI__builtin_ia32_fpclasspd128_mask: 3688 case X86::BI__builtin_ia32_fpclasspd256_mask: 3689 case X86::BI__builtin_ia32_fpclassps128_mask: 3690 case X86::BI__builtin_ia32_fpclassps256_mask: 3691 case X86::BI__builtin_ia32_fpclassps512_mask: 3692 case X86::BI__builtin_ia32_fpclasspd512_mask: 3693 case X86::BI__builtin_ia32_fpclasssd_mask: 3694 case X86::BI__builtin_ia32_fpclassss_mask: 3695 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3696 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3697 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3698 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3699 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3700 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3701 case X86::BI__builtin_ia32_kshiftliqi: 3702 case X86::BI__builtin_ia32_kshiftlihi: 3703 case X86::BI__builtin_ia32_kshiftlisi: 3704 case X86::BI__builtin_ia32_kshiftlidi: 3705 case X86::BI__builtin_ia32_kshiftriqi: 3706 case X86::BI__builtin_ia32_kshiftrihi: 3707 case X86::BI__builtin_ia32_kshiftrisi: 3708 case X86::BI__builtin_ia32_kshiftridi: 3709 i = 1; l = 0; u = 255; 3710 break; 3711 case X86::BI__builtin_ia32_vperm2f128_pd256: 3712 case X86::BI__builtin_ia32_vperm2f128_ps256: 3713 case X86::BI__builtin_ia32_vperm2f128_si256: 3714 case X86::BI__builtin_ia32_permti256: 3715 case X86::BI__builtin_ia32_pblendw128: 3716 case X86::BI__builtin_ia32_pblendw256: 3717 case X86::BI__builtin_ia32_blendps256: 3718 case X86::BI__builtin_ia32_pblendd256: 3719 case X86::BI__builtin_ia32_palignr128: 3720 case X86::BI__builtin_ia32_palignr256: 3721 case X86::BI__builtin_ia32_palignr512: 3722 case X86::BI__builtin_ia32_alignq512: 3723 case X86::BI__builtin_ia32_alignd512: 3724 case X86::BI__builtin_ia32_alignd128: 3725 case X86::BI__builtin_ia32_alignd256: 3726 case X86::BI__builtin_ia32_alignq128: 3727 case X86::BI__builtin_ia32_alignq256: 3728 case X86::BI__builtin_ia32_vcomisd: 3729 case X86::BI__builtin_ia32_vcomiss: 3730 case X86::BI__builtin_ia32_shuf_f32x4: 3731 case X86::BI__builtin_ia32_shuf_f64x2: 3732 case X86::BI__builtin_ia32_shuf_i32x4: 3733 case X86::BI__builtin_ia32_shuf_i64x2: 3734 case X86::BI__builtin_ia32_shufpd512: 3735 case X86::BI__builtin_ia32_shufps: 3736 case X86::BI__builtin_ia32_shufps256: 3737 case X86::BI__builtin_ia32_shufps512: 3738 case X86::BI__builtin_ia32_dbpsadbw128: 3739 case X86::BI__builtin_ia32_dbpsadbw256: 3740 case X86::BI__builtin_ia32_dbpsadbw512: 3741 case X86::BI__builtin_ia32_vpshldd128: 3742 case X86::BI__builtin_ia32_vpshldd256: 3743 case X86::BI__builtin_ia32_vpshldd512: 3744 case X86::BI__builtin_ia32_vpshldq128: 3745 case X86::BI__builtin_ia32_vpshldq256: 3746 case X86::BI__builtin_ia32_vpshldq512: 3747 case X86::BI__builtin_ia32_vpshldw128: 3748 case X86::BI__builtin_ia32_vpshldw256: 3749 case X86::BI__builtin_ia32_vpshldw512: 3750 case X86::BI__builtin_ia32_vpshrdd128: 3751 case X86::BI__builtin_ia32_vpshrdd256: 3752 case X86::BI__builtin_ia32_vpshrdd512: 3753 case X86::BI__builtin_ia32_vpshrdq128: 3754 case X86::BI__builtin_ia32_vpshrdq256: 3755 case X86::BI__builtin_ia32_vpshrdq512: 3756 case X86::BI__builtin_ia32_vpshrdw128: 3757 case X86::BI__builtin_ia32_vpshrdw256: 3758 case X86::BI__builtin_ia32_vpshrdw512: 3759 i = 2; l = 0; u = 255; 3760 break; 3761 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3762 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3763 case X86::BI__builtin_ia32_fixupimmps512_mask: 3764 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3765 case X86::BI__builtin_ia32_fixupimmsd_mask: 3766 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3767 case X86::BI__builtin_ia32_fixupimmss_mask: 3768 case X86::BI__builtin_ia32_fixupimmss_maskz: 3769 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3770 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3771 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3772 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3773 case X86::BI__builtin_ia32_fixupimmps128_mask: 3774 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3775 case X86::BI__builtin_ia32_fixupimmps256_mask: 3776 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3777 case X86::BI__builtin_ia32_pternlogd512_mask: 3778 case X86::BI__builtin_ia32_pternlogd512_maskz: 3779 case X86::BI__builtin_ia32_pternlogq512_mask: 3780 case X86::BI__builtin_ia32_pternlogq512_maskz: 3781 case X86::BI__builtin_ia32_pternlogd128_mask: 3782 case X86::BI__builtin_ia32_pternlogd128_maskz: 3783 case X86::BI__builtin_ia32_pternlogd256_mask: 3784 case X86::BI__builtin_ia32_pternlogd256_maskz: 3785 case X86::BI__builtin_ia32_pternlogq128_mask: 3786 case X86::BI__builtin_ia32_pternlogq128_maskz: 3787 case X86::BI__builtin_ia32_pternlogq256_mask: 3788 case X86::BI__builtin_ia32_pternlogq256_maskz: 3789 i = 3; l = 0; u = 255; 3790 break; 3791 case X86::BI__builtin_ia32_gatherpfdpd: 3792 case X86::BI__builtin_ia32_gatherpfdps: 3793 case X86::BI__builtin_ia32_gatherpfqpd: 3794 case X86::BI__builtin_ia32_gatherpfqps: 3795 case X86::BI__builtin_ia32_scatterpfdpd: 3796 case X86::BI__builtin_ia32_scatterpfdps: 3797 case X86::BI__builtin_ia32_scatterpfqpd: 3798 case X86::BI__builtin_ia32_scatterpfqps: 3799 i = 4; l = 2; u = 3; 3800 break; 3801 case X86::BI__builtin_ia32_reducesd_mask: 3802 case X86::BI__builtin_ia32_reducess_mask: 3803 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3804 case X86::BI__builtin_ia32_rndscaless_round_mask: 3805 i = 4; l = 0; u = 255; 3806 break; 3807 } 3808 3809 // Note that we don't force a hard error on the range check here, allowing 3810 // template-generated or macro-generated dead code to potentially have out-of- 3811 // range values. These need to code generate, but don't need to necessarily 3812 // make any sense. We use a warning that defaults to an error. 3813 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3814 } 3815 3816 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3817 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3818 /// Returns true when the format fits the function and the FormatStringInfo has 3819 /// been populated. 3820 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3821 FormatStringInfo *FSI) { 3822 FSI->HasVAListArg = Format->getFirstArg() == 0; 3823 FSI->FormatIdx = Format->getFormatIdx() - 1; 3824 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3825 3826 // The way the format attribute works in GCC, the implicit this argument 3827 // of member functions is counted. However, it doesn't appear in our own 3828 // lists, so decrement format_idx in that case. 3829 if (IsCXXMember) { 3830 if(FSI->FormatIdx == 0) 3831 return false; 3832 --FSI->FormatIdx; 3833 if (FSI->FirstDataArg != 0) 3834 --FSI->FirstDataArg; 3835 } 3836 return true; 3837 } 3838 3839 /// Checks if a the given expression evaluates to null. 3840 /// 3841 /// Returns true if the value evaluates to null. 3842 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3843 // If the expression has non-null type, it doesn't evaluate to null. 3844 if (auto nullability 3845 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3846 if (*nullability == NullabilityKind::NonNull) 3847 return false; 3848 } 3849 3850 // As a special case, transparent unions initialized with zero are 3851 // considered null for the purposes of the nonnull attribute. 3852 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3853 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3854 if (const CompoundLiteralExpr *CLE = 3855 dyn_cast<CompoundLiteralExpr>(Expr)) 3856 if (const InitListExpr *ILE = 3857 dyn_cast<InitListExpr>(CLE->getInitializer())) 3858 Expr = ILE->getInit(0); 3859 } 3860 3861 bool Result; 3862 return (!Expr->isValueDependent() && 3863 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3864 !Result); 3865 } 3866 3867 static void CheckNonNullArgument(Sema &S, 3868 const Expr *ArgExpr, 3869 SourceLocation CallSiteLoc) { 3870 if (CheckNonNullExpr(S, ArgExpr)) 3871 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3872 S.PDiag(diag::warn_null_arg) 3873 << ArgExpr->getSourceRange()); 3874 } 3875 3876 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3877 FormatStringInfo FSI; 3878 if ((GetFormatStringType(Format) == FST_NSString) && 3879 getFormatStringInfo(Format, false, &FSI)) { 3880 Idx = FSI.FormatIdx; 3881 return true; 3882 } 3883 return false; 3884 } 3885 3886 /// Diagnose use of %s directive in an NSString which is being passed 3887 /// as formatting string to formatting method. 3888 static void 3889 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3890 const NamedDecl *FDecl, 3891 Expr **Args, 3892 unsigned NumArgs) { 3893 unsigned Idx = 0; 3894 bool Format = false; 3895 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3896 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3897 Idx = 2; 3898 Format = true; 3899 } 3900 else 3901 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3902 if (S.GetFormatNSStringIdx(I, Idx)) { 3903 Format = true; 3904 break; 3905 } 3906 } 3907 if (!Format || NumArgs <= Idx) 3908 return; 3909 const Expr *FormatExpr = Args[Idx]; 3910 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3911 FormatExpr = CSCE->getSubExpr(); 3912 const StringLiteral *FormatString; 3913 if (const ObjCStringLiteral *OSL = 3914 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3915 FormatString = OSL->getString(); 3916 else 3917 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3918 if (!FormatString) 3919 return; 3920 if (S.FormatStringHasSArg(FormatString)) { 3921 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3922 << "%s" << 1 << 1; 3923 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3924 << FDecl->getDeclName(); 3925 } 3926 } 3927 3928 /// Determine whether the given type has a non-null nullability annotation. 3929 static bool isNonNullType(ASTContext &ctx, QualType type) { 3930 if (auto nullability = type->getNullability(ctx)) 3931 return *nullability == NullabilityKind::NonNull; 3932 3933 return false; 3934 } 3935 3936 static void CheckNonNullArguments(Sema &S, 3937 const NamedDecl *FDecl, 3938 const FunctionProtoType *Proto, 3939 ArrayRef<const Expr *> Args, 3940 SourceLocation CallSiteLoc) { 3941 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3942 3943 // Already checked by by constant evaluator. 3944 if (S.isConstantEvaluated()) 3945 return; 3946 // Check the attributes attached to the method/function itself. 3947 llvm::SmallBitVector NonNullArgs; 3948 if (FDecl) { 3949 // Handle the nonnull attribute on the function/method declaration itself. 3950 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3951 if (!NonNull->args_size()) { 3952 // Easy case: all pointer arguments are nonnull. 3953 for (const auto *Arg : Args) 3954 if (S.isValidPointerAttrType(Arg->getType())) 3955 CheckNonNullArgument(S, Arg, CallSiteLoc); 3956 return; 3957 } 3958 3959 for (const ParamIdx &Idx : NonNull->args()) { 3960 unsigned IdxAST = Idx.getASTIndex(); 3961 if (IdxAST >= Args.size()) 3962 continue; 3963 if (NonNullArgs.empty()) 3964 NonNullArgs.resize(Args.size()); 3965 NonNullArgs.set(IdxAST); 3966 } 3967 } 3968 } 3969 3970 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3971 // Handle the nonnull attribute on the parameters of the 3972 // function/method. 3973 ArrayRef<ParmVarDecl*> parms; 3974 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3975 parms = FD->parameters(); 3976 else 3977 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3978 3979 unsigned ParamIndex = 0; 3980 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3981 I != E; ++I, ++ParamIndex) { 3982 const ParmVarDecl *PVD = *I; 3983 if (PVD->hasAttr<NonNullAttr>() || 3984 isNonNullType(S.Context, PVD->getType())) { 3985 if (NonNullArgs.empty()) 3986 NonNullArgs.resize(Args.size()); 3987 3988 NonNullArgs.set(ParamIndex); 3989 } 3990 } 3991 } else { 3992 // If we have a non-function, non-method declaration but no 3993 // function prototype, try to dig out the function prototype. 3994 if (!Proto) { 3995 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3996 QualType type = VD->getType().getNonReferenceType(); 3997 if (auto pointerType = type->getAs<PointerType>()) 3998 type = pointerType->getPointeeType(); 3999 else if (auto blockType = type->getAs<BlockPointerType>()) 4000 type = blockType->getPointeeType(); 4001 // FIXME: data member pointers? 4002 4003 // Dig out the function prototype, if there is one. 4004 Proto = type->getAs<FunctionProtoType>(); 4005 } 4006 } 4007 4008 // Fill in non-null argument information from the nullability 4009 // information on the parameter types (if we have them). 4010 if (Proto) { 4011 unsigned Index = 0; 4012 for (auto paramType : Proto->getParamTypes()) { 4013 if (isNonNullType(S.Context, paramType)) { 4014 if (NonNullArgs.empty()) 4015 NonNullArgs.resize(Args.size()); 4016 4017 NonNullArgs.set(Index); 4018 } 4019 4020 ++Index; 4021 } 4022 } 4023 } 4024 4025 // Check for non-null arguments. 4026 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4027 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4028 if (NonNullArgs[ArgIndex]) 4029 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4030 } 4031 } 4032 4033 /// Handles the checks for format strings, non-POD arguments to vararg 4034 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4035 /// attributes. 4036 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4037 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4038 bool IsMemberFunction, SourceLocation Loc, 4039 SourceRange Range, VariadicCallType CallType) { 4040 // FIXME: We should check as much as we can in the template definition. 4041 if (CurContext->isDependentContext()) 4042 return; 4043 4044 // Printf and scanf checking. 4045 llvm::SmallBitVector CheckedVarArgs; 4046 if (FDecl) { 4047 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4048 // Only create vector if there are format attributes. 4049 CheckedVarArgs.resize(Args.size()); 4050 4051 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4052 CheckedVarArgs); 4053 } 4054 } 4055 4056 // Refuse POD arguments that weren't caught by the format string 4057 // checks above. 4058 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4059 if (CallType != VariadicDoesNotApply && 4060 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4061 unsigned NumParams = Proto ? Proto->getNumParams() 4062 : FDecl && isa<FunctionDecl>(FDecl) 4063 ? cast<FunctionDecl>(FDecl)->getNumParams() 4064 : FDecl && isa<ObjCMethodDecl>(FDecl) 4065 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4066 : 0; 4067 4068 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4069 // Args[ArgIdx] can be null in malformed code. 4070 if (const Expr *Arg = Args[ArgIdx]) { 4071 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4072 checkVariadicArgument(Arg, CallType); 4073 } 4074 } 4075 } 4076 4077 if (FDecl || Proto) { 4078 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4079 4080 // Type safety checking. 4081 if (FDecl) { 4082 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4083 CheckArgumentWithTypeTag(I, Args, Loc); 4084 } 4085 } 4086 4087 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4088 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4089 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4090 if (!Arg->isValueDependent()) { 4091 Expr::EvalResult Align; 4092 if (Arg->EvaluateAsInt(Align, Context)) { 4093 const llvm::APSInt &I = Align.Val.getInt(); 4094 if (!I.isPowerOf2()) 4095 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4096 << Arg->getSourceRange(); 4097 4098 if (I > Sema::MaximumAlignment) 4099 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4100 << Arg->getSourceRange() << Sema::MaximumAlignment; 4101 } 4102 } 4103 } 4104 4105 if (FD) 4106 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4107 } 4108 4109 /// CheckConstructorCall - Check a constructor call for correctness and safety 4110 /// properties not enforced by the C type system. 4111 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4112 ArrayRef<const Expr *> Args, 4113 const FunctionProtoType *Proto, 4114 SourceLocation Loc) { 4115 VariadicCallType CallType = 4116 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4117 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4118 Loc, SourceRange(), CallType); 4119 } 4120 4121 /// CheckFunctionCall - Check a direct function call for various correctness 4122 /// and safety properties not strictly enforced by the C type system. 4123 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4124 const FunctionProtoType *Proto) { 4125 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4126 isa<CXXMethodDecl>(FDecl); 4127 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4128 IsMemberOperatorCall; 4129 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4130 TheCall->getCallee()); 4131 Expr** Args = TheCall->getArgs(); 4132 unsigned NumArgs = TheCall->getNumArgs(); 4133 4134 Expr *ImplicitThis = nullptr; 4135 if (IsMemberOperatorCall) { 4136 // If this is a call to a member operator, hide the first argument 4137 // from checkCall. 4138 // FIXME: Our choice of AST representation here is less than ideal. 4139 ImplicitThis = Args[0]; 4140 ++Args; 4141 --NumArgs; 4142 } else if (IsMemberFunction) 4143 ImplicitThis = 4144 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4145 4146 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4147 IsMemberFunction, TheCall->getRParenLoc(), 4148 TheCall->getCallee()->getSourceRange(), CallType); 4149 4150 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4151 // None of the checks below are needed for functions that don't have 4152 // simple names (e.g., C++ conversion functions). 4153 if (!FnInfo) 4154 return false; 4155 4156 CheckAbsoluteValueFunction(TheCall, FDecl); 4157 CheckMaxUnsignedZero(TheCall, FDecl); 4158 4159 if (getLangOpts().ObjC) 4160 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4161 4162 unsigned CMId = FDecl->getMemoryFunctionKind(); 4163 if (CMId == 0) 4164 return false; 4165 4166 // Handle memory setting and copying functions. 4167 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4168 CheckStrlcpycatArguments(TheCall, FnInfo); 4169 else if (CMId == Builtin::BIstrncat) 4170 CheckStrncatArguments(TheCall, FnInfo); 4171 else 4172 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4173 4174 return false; 4175 } 4176 4177 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4178 ArrayRef<const Expr *> Args) { 4179 VariadicCallType CallType = 4180 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4181 4182 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4183 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4184 CallType); 4185 4186 return false; 4187 } 4188 4189 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4190 const FunctionProtoType *Proto) { 4191 QualType Ty; 4192 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4193 Ty = V->getType().getNonReferenceType(); 4194 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4195 Ty = F->getType().getNonReferenceType(); 4196 else 4197 return false; 4198 4199 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4200 !Ty->isFunctionProtoType()) 4201 return false; 4202 4203 VariadicCallType CallType; 4204 if (!Proto || !Proto->isVariadic()) { 4205 CallType = VariadicDoesNotApply; 4206 } else if (Ty->isBlockPointerType()) { 4207 CallType = VariadicBlock; 4208 } else { // Ty->isFunctionPointerType() 4209 CallType = VariadicFunction; 4210 } 4211 4212 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4213 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4214 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4215 TheCall->getCallee()->getSourceRange(), CallType); 4216 4217 return false; 4218 } 4219 4220 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4221 /// such as function pointers returned from functions. 4222 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4223 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4224 TheCall->getCallee()); 4225 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4226 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4227 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4228 TheCall->getCallee()->getSourceRange(), CallType); 4229 4230 return false; 4231 } 4232 4233 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4234 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4235 return false; 4236 4237 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4238 switch (Op) { 4239 case AtomicExpr::AO__c11_atomic_init: 4240 case AtomicExpr::AO__opencl_atomic_init: 4241 llvm_unreachable("There is no ordering argument for an init"); 4242 4243 case AtomicExpr::AO__c11_atomic_load: 4244 case AtomicExpr::AO__opencl_atomic_load: 4245 case AtomicExpr::AO__atomic_load_n: 4246 case AtomicExpr::AO__atomic_load: 4247 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4248 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4249 4250 case AtomicExpr::AO__c11_atomic_store: 4251 case AtomicExpr::AO__opencl_atomic_store: 4252 case AtomicExpr::AO__atomic_store: 4253 case AtomicExpr::AO__atomic_store_n: 4254 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4255 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4256 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4257 4258 default: 4259 return true; 4260 } 4261 } 4262 4263 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4264 AtomicExpr::AtomicOp Op) { 4265 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4266 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4267 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4268 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4269 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4270 Op); 4271 } 4272 4273 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4274 SourceLocation RParenLoc, MultiExprArg Args, 4275 AtomicExpr::AtomicOp Op, 4276 AtomicArgumentOrder ArgOrder) { 4277 // All the non-OpenCL operations take one of the following forms. 4278 // The OpenCL operations take the __c11 forms with one extra argument for 4279 // synchronization scope. 4280 enum { 4281 // C __c11_atomic_init(A *, C) 4282 Init, 4283 4284 // C __c11_atomic_load(A *, int) 4285 Load, 4286 4287 // void __atomic_load(A *, CP, int) 4288 LoadCopy, 4289 4290 // void __atomic_store(A *, CP, int) 4291 Copy, 4292 4293 // C __c11_atomic_add(A *, M, int) 4294 Arithmetic, 4295 4296 // C __atomic_exchange_n(A *, CP, int) 4297 Xchg, 4298 4299 // void __atomic_exchange(A *, C *, CP, int) 4300 GNUXchg, 4301 4302 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4303 C11CmpXchg, 4304 4305 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4306 GNUCmpXchg 4307 } Form = Init; 4308 4309 const unsigned NumForm = GNUCmpXchg + 1; 4310 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4311 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4312 // where: 4313 // C is an appropriate type, 4314 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4315 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4316 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4317 // the int parameters are for orderings. 4318 4319 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4320 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4321 "need to update code for modified forms"); 4322 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4323 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4324 AtomicExpr::AO__atomic_load, 4325 "need to update code for modified C11 atomics"); 4326 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4327 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4328 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4329 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4330 IsOpenCL; 4331 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4332 Op == AtomicExpr::AO__atomic_store_n || 4333 Op == AtomicExpr::AO__atomic_exchange_n || 4334 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4335 bool IsAddSub = false; 4336 4337 switch (Op) { 4338 case AtomicExpr::AO__c11_atomic_init: 4339 case AtomicExpr::AO__opencl_atomic_init: 4340 Form = Init; 4341 break; 4342 4343 case AtomicExpr::AO__c11_atomic_load: 4344 case AtomicExpr::AO__opencl_atomic_load: 4345 case AtomicExpr::AO__atomic_load_n: 4346 Form = Load; 4347 break; 4348 4349 case AtomicExpr::AO__atomic_load: 4350 Form = LoadCopy; 4351 break; 4352 4353 case AtomicExpr::AO__c11_atomic_store: 4354 case AtomicExpr::AO__opencl_atomic_store: 4355 case AtomicExpr::AO__atomic_store: 4356 case AtomicExpr::AO__atomic_store_n: 4357 Form = Copy; 4358 break; 4359 4360 case AtomicExpr::AO__c11_atomic_fetch_add: 4361 case AtomicExpr::AO__c11_atomic_fetch_sub: 4362 case AtomicExpr::AO__opencl_atomic_fetch_add: 4363 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4364 case AtomicExpr::AO__atomic_fetch_add: 4365 case AtomicExpr::AO__atomic_fetch_sub: 4366 case AtomicExpr::AO__atomic_add_fetch: 4367 case AtomicExpr::AO__atomic_sub_fetch: 4368 IsAddSub = true; 4369 LLVM_FALLTHROUGH; 4370 case AtomicExpr::AO__c11_atomic_fetch_and: 4371 case AtomicExpr::AO__c11_atomic_fetch_or: 4372 case AtomicExpr::AO__c11_atomic_fetch_xor: 4373 case AtomicExpr::AO__opencl_atomic_fetch_and: 4374 case AtomicExpr::AO__opencl_atomic_fetch_or: 4375 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4376 case AtomicExpr::AO__atomic_fetch_and: 4377 case AtomicExpr::AO__atomic_fetch_or: 4378 case AtomicExpr::AO__atomic_fetch_xor: 4379 case AtomicExpr::AO__atomic_fetch_nand: 4380 case AtomicExpr::AO__atomic_and_fetch: 4381 case AtomicExpr::AO__atomic_or_fetch: 4382 case AtomicExpr::AO__atomic_xor_fetch: 4383 case AtomicExpr::AO__atomic_nand_fetch: 4384 case AtomicExpr::AO__c11_atomic_fetch_min: 4385 case AtomicExpr::AO__c11_atomic_fetch_max: 4386 case AtomicExpr::AO__opencl_atomic_fetch_min: 4387 case AtomicExpr::AO__opencl_atomic_fetch_max: 4388 case AtomicExpr::AO__atomic_min_fetch: 4389 case AtomicExpr::AO__atomic_max_fetch: 4390 case AtomicExpr::AO__atomic_fetch_min: 4391 case AtomicExpr::AO__atomic_fetch_max: 4392 Form = Arithmetic; 4393 break; 4394 4395 case AtomicExpr::AO__c11_atomic_exchange: 4396 case AtomicExpr::AO__opencl_atomic_exchange: 4397 case AtomicExpr::AO__atomic_exchange_n: 4398 Form = Xchg; 4399 break; 4400 4401 case AtomicExpr::AO__atomic_exchange: 4402 Form = GNUXchg; 4403 break; 4404 4405 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4406 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4407 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4408 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4409 Form = C11CmpXchg; 4410 break; 4411 4412 case AtomicExpr::AO__atomic_compare_exchange: 4413 case AtomicExpr::AO__atomic_compare_exchange_n: 4414 Form = GNUCmpXchg; 4415 break; 4416 } 4417 4418 unsigned AdjustedNumArgs = NumArgs[Form]; 4419 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4420 ++AdjustedNumArgs; 4421 // Check we have the right number of arguments. 4422 if (Args.size() < AdjustedNumArgs) { 4423 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4424 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4425 << ExprRange; 4426 return ExprError(); 4427 } else if (Args.size() > AdjustedNumArgs) { 4428 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4429 diag::err_typecheck_call_too_many_args) 4430 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4431 << ExprRange; 4432 return ExprError(); 4433 } 4434 4435 // Inspect the first argument of the atomic operation. 4436 Expr *Ptr = Args[0]; 4437 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4438 if (ConvertedPtr.isInvalid()) 4439 return ExprError(); 4440 4441 Ptr = ConvertedPtr.get(); 4442 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4443 if (!pointerType) { 4444 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4445 << Ptr->getType() << Ptr->getSourceRange(); 4446 return ExprError(); 4447 } 4448 4449 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4450 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4451 QualType ValType = AtomTy; // 'C' 4452 if (IsC11) { 4453 if (!AtomTy->isAtomicType()) { 4454 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4455 << Ptr->getType() << Ptr->getSourceRange(); 4456 return ExprError(); 4457 } 4458 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4459 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4460 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4461 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4462 << Ptr->getSourceRange(); 4463 return ExprError(); 4464 } 4465 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4466 } else if (Form != Load && Form != LoadCopy) { 4467 if (ValType.isConstQualified()) { 4468 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4469 << Ptr->getType() << Ptr->getSourceRange(); 4470 return ExprError(); 4471 } 4472 } 4473 4474 // For an arithmetic operation, the implied arithmetic must be well-formed. 4475 if (Form == Arithmetic) { 4476 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4477 if (IsAddSub && !ValType->isIntegerType() 4478 && !ValType->isPointerType()) { 4479 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4480 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4481 return ExprError(); 4482 } 4483 if (!IsAddSub && !ValType->isIntegerType()) { 4484 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4485 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4486 return ExprError(); 4487 } 4488 if (IsC11 && ValType->isPointerType() && 4489 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4490 diag::err_incomplete_type)) { 4491 return ExprError(); 4492 } 4493 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4494 // For __atomic_*_n operations, the value type must be a scalar integral or 4495 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4496 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4497 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4498 return ExprError(); 4499 } 4500 4501 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4502 !AtomTy->isScalarType()) { 4503 // For GNU atomics, require a trivially-copyable type. This is not part of 4504 // the GNU atomics specification, but we enforce it for sanity. 4505 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4506 << Ptr->getType() << Ptr->getSourceRange(); 4507 return ExprError(); 4508 } 4509 4510 switch (ValType.getObjCLifetime()) { 4511 case Qualifiers::OCL_None: 4512 case Qualifiers::OCL_ExplicitNone: 4513 // okay 4514 break; 4515 4516 case Qualifiers::OCL_Weak: 4517 case Qualifiers::OCL_Strong: 4518 case Qualifiers::OCL_Autoreleasing: 4519 // FIXME: Can this happen? By this point, ValType should be known 4520 // to be trivially copyable. 4521 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4522 << ValType << Ptr->getSourceRange(); 4523 return ExprError(); 4524 } 4525 4526 // All atomic operations have an overload which takes a pointer to a volatile 4527 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4528 // into the result or the other operands. Similarly atomic_load takes a 4529 // pointer to a const 'A'. 4530 ValType.removeLocalVolatile(); 4531 ValType.removeLocalConst(); 4532 QualType ResultType = ValType; 4533 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4534 Form == Init) 4535 ResultType = Context.VoidTy; 4536 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4537 ResultType = Context.BoolTy; 4538 4539 // The type of a parameter passed 'by value'. In the GNU atomics, such 4540 // arguments are actually passed as pointers. 4541 QualType ByValType = ValType; // 'CP' 4542 bool IsPassedByAddress = false; 4543 if (!IsC11 && !IsN) { 4544 ByValType = Ptr->getType(); 4545 IsPassedByAddress = true; 4546 } 4547 4548 SmallVector<Expr *, 5> APIOrderedArgs; 4549 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4550 APIOrderedArgs.push_back(Args[0]); 4551 switch (Form) { 4552 case Init: 4553 case Load: 4554 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4555 break; 4556 case LoadCopy: 4557 case Copy: 4558 case Arithmetic: 4559 case Xchg: 4560 APIOrderedArgs.push_back(Args[2]); // Val1 4561 APIOrderedArgs.push_back(Args[1]); // Order 4562 break; 4563 case GNUXchg: 4564 APIOrderedArgs.push_back(Args[2]); // Val1 4565 APIOrderedArgs.push_back(Args[3]); // Val2 4566 APIOrderedArgs.push_back(Args[1]); // Order 4567 break; 4568 case C11CmpXchg: 4569 APIOrderedArgs.push_back(Args[2]); // Val1 4570 APIOrderedArgs.push_back(Args[4]); // Val2 4571 APIOrderedArgs.push_back(Args[1]); // Order 4572 APIOrderedArgs.push_back(Args[3]); // OrderFail 4573 break; 4574 case GNUCmpXchg: 4575 APIOrderedArgs.push_back(Args[2]); // Val1 4576 APIOrderedArgs.push_back(Args[4]); // Val2 4577 APIOrderedArgs.push_back(Args[5]); // Weak 4578 APIOrderedArgs.push_back(Args[1]); // Order 4579 APIOrderedArgs.push_back(Args[3]); // OrderFail 4580 break; 4581 } 4582 } else 4583 APIOrderedArgs.append(Args.begin(), Args.end()); 4584 4585 // The first argument's non-CV pointer type is used to deduce the type of 4586 // subsequent arguments, except for: 4587 // - weak flag (always converted to bool) 4588 // - memory order (always converted to int) 4589 // - scope (always converted to int) 4590 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4591 QualType Ty; 4592 if (i < NumVals[Form] + 1) { 4593 switch (i) { 4594 case 0: 4595 // The first argument is always a pointer. It has a fixed type. 4596 // It is always dereferenced, a nullptr is undefined. 4597 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4598 // Nothing else to do: we already know all we want about this pointer. 4599 continue; 4600 case 1: 4601 // The second argument is the non-atomic operand. For arithmetic, this 4602 // is always passed by value, and for a compare_exchange it is always 4603 // passed by address. For the rest, GNU uses by-address and C11 uses 4604 // by-value. 4605 assert(Form != Load); 4606 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4607 Ty = ValType; 4608 else if (Form == Copy || Form == Xchg) { 4609 if (IsPassedByAddress) { 4610 // The value pointer is always dereferenced, a nullptr is undefined. 4611 CheckNonNullArgument(*this, APIOrderedArgs[i], 4612 ExprRange.getBegin()); 4613 } 4614 Ty = ByValType; 4615 } else if (Form == Arithmetic) 4616 Ty = Context.getPointerDiffType(); 4617 else { 4618 Expr *ValArg = APIOrderedArgs[i]; 4619 // The value pointer is always dereferenced, a nullptr is undefined. 4620 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4621 LangAS AS = LangAS::Default; 4622 // Keep address space of non-atomic pointer type. 4623 if (const PointerType *PtrTy = 4624 ValArg->getType()->getAs<PointerType>()) { 4625 AS = PtrTy->getPointeeType().getAddressSpace(); 4626 } 4627 Ty = Context.getPointerType( 4628 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4629 } 4630 break; 4631 case 2: 4632 // The third argument to compare_exchange / GNU exchange is the desired 4633 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4634 if (IsPassedByAddress) 4635 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4636 Ty = ByValType; 4637 break; 4638 case 3: 4639 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4640 Ty = Context.BoolTy; 4641 break; 4642 } 4643 } else { 4644 // The order(s) and scope are always converted to int. 4645 Ty = Context.IntTy; 4646 } 4647 4648 InitializedEntity Entity = 4649 InitializedEntity::InitializeParameter(Context, Ty, false); 4650 ExprResult Arg = APIOrderedArgs[i]; 4651 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4652 if (Arg.isInvalid()) 4653 return true; 4654 APIOrderedArgs[i] = Arg.get(); 4655 } 4656 4657 // Permute the arguments into a 'consistent' order. 4658 SmallVector<Expr*, 5> SubExprs; 4659 SubExprs.push_back(Ptr); 4660 switch (Form) { 4661 case Init: 4662 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4663 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4664 break; 4665 case Load: 4666 SubExprs.push_back(APIOrderedArgs[1]); // Order 4667 break; 4668 case LoadCopy: 4669 case Copy: 4670 case Arithmetic: 4671 case Xchg: 4672 SubExprs.push_back(APIOrderedArgs[2]); // Order 4673 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4674 break; 4675 case GNUXchg: 4676 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4677 SubExprs.push_back(APIOrderedArgs[3]); // Order 4678 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4679 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4680 break; 4681 case C11CmpXchg: 4682 SubExprs.push_back(APIOrderedArgs[3]); // Order 4683 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4684 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4685 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4686 break; 4687 case GNUCmpXchg: 4688 SubExprs.push_back(APIOrderedArgs[4]); // Order 4689 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4690 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4691 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4692 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4693 break; 4694 } 4695 4696 if (SubExprs.size() >= 2 && Form != Init) { 4697 llvm::APSInt Result(32); 4698 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4699 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4700 Diag(SubExprs[1]->getBeginLoc(), 4701 diag::warn_atomic_op_has_invalid_memory_order) 4702 << SubExprs[1]->getSourceRange(); 4703 } 4704 4705 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4706 auto *Scope = Args[Args.size() - 1]; 4707 llvm::APSInt Result(32); 4708 if (Scope->isIntegerConstantExpr(Result, Context) && 4709 !ScopeModel->isValid(Result.getZExtValue())) { 4710 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4711 << Scope->getSourceRange(); 4712 } 4713 SubExprs.push_back(Scope); 4714 } 4715 4716 AtomicExpr *AE = new (Context) 4717 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4718 4719 if ((Op == AtomicExpr::AO__c11_atomic_load || 4720 Op == AtomicExpr::AO__c11_atomic_store || 4721 Op == AtomicExpr::AO__opencl_atomic_load || 4722 Op == AtomicExpr::AO__opencl_atomic_store ) && 4723 Context.AtomicUsesUnsupportedLibcall(AE)) 4724 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4725 << ((Op == AtomicExpr::AO__c11_atomic_load || 4726 Op == AtomicExpr::AO__opencl_atomic_load) 4727 ? 0 4728 : 1); 4729 4730 return AE; 4731 } 4732 4733 /// checkBuiltinArgument - Given a call to a builtin function, perform 4734 /// normal type-checking on the given argument, updating the call in 4735 /// place. This is useful when a builtin function requires custom 4736 /// type-checking for some of its arguments but not necessarily all of 4737 /// them. 4738 /// 4739 /// Returns true on error. 4740 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4741 FunctionDecl *Fn = E->getDirectCallee(); 4742 assert(Fn && "builtin call without direct callee!"); 4743 4744 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4745 InitializedEntity Entity = 4746 InitializedEntity::InitializeParameter(S.Context, Param); 4747 4748 ExprResult Arg = E->getArg(0); 4749 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4750 if (Arg.isInvalid()) 4751 return true; 4752 4753 E->setArg(ArgIndex, Arg.get()); 4754 return false; 4755 } 4756 4757 /// We have a call to a function like __sync_fetch_and_add, which is an 4758 /// overloaded function based on the pointer type of its first argument. 4759 /// The main BuildCallExpr routines have already promoted the types of 4760 /// arguments because all of these calls are prototyped as void(...). 4761 /// 4762 /// This function goes through and does final semantic checking for these 4763 /// builtins, as well as generating any warnings. 4764 ExprResult 4765 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4766 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4767 Expr *Callee = TheCall->getCallee(); 4768 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4769 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4770 4771 // Ensure that we have at least one argument to do type inference from. 4772 if (TheCall->getNumArgs() < 1) { 4773 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4774 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4775 return ExprError(); 4776 } 4777 4778 // Inspect the first argument of the atomic builtin. This should always be 4779 // a pointer type, whose element is an integral scalar or pointer type. 4780 // Because it is a pointer type, we don't have to worry about any implicit 4781 // casts here. 4782 // FIXME: We don't allow floating point scalars as input. 4783 Expr *FirstArg = TheCall->getArg(0); 4784 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4785 if (FirstArgResult.isInvalid()) 4786 return ExprError(); 4787 FirstArg = FirstArgResult.get(); 4788 TheCall->setArg(0, FirstArg); 4789 4790 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4791 if (!pointerType) { 4792 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4793 << FirstArg->getType() << FirstArg->getSourceRange(); 4794 return ExprError(); 4795 } 4796 4797 QualType ValType = pointerType->getPointeeType(); 4798 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4799 !ValType->isBlockPointerType()) { 4800 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4801 << FirstArg->getType() << FirstArg->getSourceRange(); 4802 return ExprError(); 4803 } 4804 4805 if (ValType.isConstQualified()) { 4806 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4807 << FirstArg->getType() << FirstArg->getSourceRange(); 4808 return ExprError(); 4809 } 4810 4811 switch (ValType.getObjCLifetime()) { 4812 case Qualifiers::OCL_None: 4813 case Qualifiers::OCL_ExplicitNone: 4814 // okay 4815 break; 4816 4817 case Qualifiers::OCL_Weak: 4818 case Qualifiers::OCL_Strong: 4819 case Qualifiers::OCL_Autoreleasing: 4820 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4821 << ValType << FirstArg->getSourceRange(); 4822 return ExprError(); 4823 } 4824 4825 // Strip any qualifiers off ValType. 4826 ValType = ValType.getUnqualifiedType(); 4827 4828 // The majority of builtins return a value, but a few have special return 4829 // types, so allow them to override appropriately below. 4830 QualType ResultType = ValType; 4831 4832 // We need to figure out which concrete builtin this maps onto. For example, 4833 // __sync_fetch_and_add with a 2 byte object turns into 4834 // __sync_fetch_and_add_2. 4835 #define BUILTIN_ROW(x) \ 4836 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4837 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4838 4839 static const unsigned BuiltinIndices[][5] = { 4840 BUILTIN_ROW(__sync_fetch_and_add), 4841 BUILTIN_ROW(__sync_fetch_and_sub), 4842 BUILTIN_ROW(__sync_fetch_and_or), 4843 BUILTIN_ROW(__sync_fetch_and_and), 4844 BUILTIN_ROW(__sync_fetch_and_xor), 4845 BUILTIN_ROW(__sync_fetch_and_nand), 4846 4847 BUILTIN_ROW(__sync_add_and_fetch), 4848 BUILTIN_ROW(__sync_sub_and_fetch), 4849 BUILTIN_ROW(__sync_and_and_fetch), 4850 BUILTIN_ROW(__sync_or_and_fetch), 4851 BUILTIN_ROW(__sync_xor_and_fetch), 4852 BUILTIN_ROW(__sync_nand_and_fetch), 4853 4854 BUILTIN_ROW(__sync_val_compare_and_swap), 4855 BUILTIN_ROW(__sync_bool_compare_and_swap), 4856 BUILTIN_ROW(__sync_lock_test_and_set), 4857 BUILTIN_ROW(__sync_lock_release), 4858 BUILTIN_ROW(__sync_swap) 4859 }; 4860 #undef BUILTIN_ROW 4861 4862 // Determine the index of the size. 4863 unsigned SizeIndex; 4864 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4865 case 1: SizeIndex = 0; break; 4866 case 2: SizeIndex = 1; break; 4867 case 4: SizeIndex = 2; break; 4868 case 8: SizeIndex = 3; break; 4869 case 16: SizeIndex = 4; break; 4870 default: 4871 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4872 << FirstArg->getType() << FirstArg->getSourceRange(); 4873 return ExprError(); 4874 } 4875 4876 // Each of these builtins has one pointer argument, followed by some number of 4877 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4878 // that we ignore. Find out which row of BuiltinIndices to read from as well 4879 // as the number of fixed args. 4880 unsigned BuiltinID = FDecl->getBuiltinID(); 4881 unsigned BuiltinIndex, NumFixed = 1; 4882 bool WarnAboutSemanticsChange = false; 4883 switch (BuiltinID) { 4884 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4885 case Builtin::BI__sync_fetch_and_add: 4886 case Builtin::BI__sync_fetch_and_add_1: 4887 case Builtin::BI__sync_fetch_and_add_2: 4888 case Builtin::BI__sync_fetch_and_add_4: 4889 case Builtin::BI__sync_fetch_and_add_8: 4890 case Builtin::BI__sync_fetch_and_add_16: 4891 BuiltinIndex = 0; 4892 break; 4893 4894 case Builtin::BI__sync_fetch_and_sub: 4895 case Builtin::BI__sync_fetch_and_sub_1: 4896 case Builtin::BI__sync_fetch_and_sub_2: 4897 case Builtin::BI__sync_fetch_and_sub_4: 4898 case Builtin::BI__sync_fetch_and_sub_8: 4899 case Builtin::BI__sync_fetch_and_sub_16: 4900 BuiltinIndex = 1; 4901 break; 4902 4903 case Builtin::BI__sync_fetch_and_or: 4904 case Builtin::BI__sync_fetch_and_or_1: 4905 case Builtin::BI__sync_fetch_and_or_2: 4906 case Builtin::BI__sync_fetch_and_or_4: 4907 case Builtin::BI__sync_fetch_and_or_8: 4908 case Builtin::BI__sync_fetch_and_or_16: 4909 BuiltinIndex = 2; 4910 break; 4911 4912 case Builtin::BI__sync_fetch_and_and: 4913 case Builtin::BI__sync_fetch_and_and_1: 4914 case Builtin::BI__sync_fetch_and_and_2: 4915 case Builtin::BI__sync_fetch_and_and_4: 4916 case Builtin::BI__sync_fetch_and_and_8: 4917 case Builtin::BI__sync_fetch_and_and_16: 4918 BuiltinIndex = 3; 4919 break; 4920 4921 case Builtin::BI__sync_fetch_and_xor: 4922 case Builtin::BI__sync_fetch_and_xor_1: 4923 case Builtin::BI__sync_fetch_and_xor_2: 4924 case Builtin::BI__sync_fetch_and_xor_4: 4925 case Builtin::BI__sync_fetch_and_xor_8: 4926 case Builtin::BI__sync_fetch_and_xor_16: 4927 BuiltinIndex = 4; 4928 break; 4929 4930 case Builtin::BI__sync_fetch_and_nand: 4931 case Builtin::BI__sync_fetch_and_nand_1: 4932 case Builtin::BI__sync_fetch_and_nand_2: 4933 case Builtin::BI__sync_fetch_and_nand_4: 4934 case Builtin::BI__sync_fetch_and_nand_8: 4935 case Builtin::BI__sync_fetch_and_nand_16: 4936 BuiltinIndex = 5; 4937 WarnAboutSemanticsChange = true; 4938 break; 4939 4940 case Builtin::BI__sync_add_and_fetch: 4941 case Builtin::BI__sync_add_and_fetch_1: 4942 case Builtin::BI__sync_add_and_fetch_2: 4943 case Builtin::BI__sync_add_and_fetch_4: 4944 case Builtin::BI__sync_add_and_fetch_8: 4945 case Builtin::BI__sync_add_and_fetch_16: 4946 BuiltinIndex = 6; 4947 break; 4948 4949 case Builtin::BI__sync_sub_and_fetch: 4950 case Builtin::BI__sync_sub_and_fetch_1: 4951 case Builtin::BI__sync_sub_and_fetch_2: 4952 case Builtin::BI__sync_sub_and_fetch_4: 4953 case Builtin::BI__sync_sub_and_fetch_8: 4954 case Builtin::BI__sync_sub_and_fetch_16: 4955 BuiltinIndex = 7; 4956 break; 4957 4958 case Builtin::BI__sync_and_and_fetch: 4959 case Builtin::BI__sync_and_and_fetch_1: 4960 case Builtin::BI__sync_and_and_fetch_2: 4961 case Builtin::BI__sync_and_and_fetch_4: 4962 case Builtin::BI__sync_and_and_fetch_8: 4963 case Builtin::BI__sync_and_and_fetch_16: 4964 BuiltinIndex = 8; 4965 break; 4966 4967 case Builtin::BI__sync_or_and_fetch: 4968 case Builtin::BI__sync_or_and_fetch_1: 4969 case Builtin::BI__sync_or_and_fetch_2: 4970 case Builtin::BI__sync_or_and_fetch_4: 4971 case Builtin::BI__sync_or_and_fetch_8: 4972 case Builtin::BI__sync_or_and_fetch_16: 4973 BuiltinIndex = 9; 4974 break; 4975 4976 case Builtin::BI__sync_xor_and_fetch: 4977 case Builtin::BI__sync_xor_and_fetch_1: 4978 case Builtin::BI__sync_xor_and_fetch_2: 4979 case Builtin::BI__sync_xor_and_fetch_4: 4980 case Builtin::BI__sync_xor_and_fetch_8: 4981 case Builtin::BI__sync_xor_and_fetch_16: 4982 BuiltinIndex = 10; 4983 break; 4984 4985 case Builtin::BI__sync_nand_and_fetch: 4986 case Builtin::BI__sync_nand_and_fetch_1: 4987 case Builtin::BI__sync_nand_and_fetch_2: 4988 case Builtin::BI__sync_nand_and_fetch_4: 4989 case Builtin::BI__sync_nand_and_fetch_8: 4990 case Builtin::BI__sync_nand_and_fetch_16: 4991 BuiltinIndex = 11; 4992 WarnAboutSemanticsChange = true; 4993 break; 4994 4995 case Builtin::BI__sync_val_compare_and_swap: 4996 case Builtin::BI__sync_val_compare_and_swap_1: 4997 case Builtin::BI__sync_val_compare_and_swap_2: 4998 case Builtin::BI__sync_val_compare_and_swap_4: 4999 case Builtin::BI__sync_val_compare_and_swap_8: 5000 case Builtin::BI__sync_val_compare_and_swap_16: 5001 BuiltinIndex = 12; 5002 NumFixed = 2; 5003 break; 5004 5005 case Builtin::BI__sync_bool_compare_and_swap: 5006 case Builtin::BI__sync_bool_compare_and_swap_1: 5007 case Builtin::BI__sync_bool_compare_and_swap_2: 5008 case Builtin::BI__sync_bool_compare_and_swap_4: 5009 case Builtin::BI__sync_bool_compare_and_swap_8: 5010 case Builtin::BI__sync_bool_compare_and_swap_16: 5011 BuiltinIndex = 13; 5012 NumFixed = 2; 5013 ResultType = Context.BoolTy; 5014 break; 5015 5016 case Builtin::BI__sync_lock_test_and_set: 5017 case Builtin::BI__sync_lock_test_and_set_1: 5018 case Builtin::BI__sync_lock_test_and_set_2: 5019 case Builtin::BI__sync_lock_test_and_set_4: 5020 case Builtin::BI__sync_lock_test_and_set_8: 5021 case Builtin::BI__sync_lock_test_and_set_16: 5022 BuiltinIndex = 14; 5023 break; 5024 5025 case Builtin::BI__sync_lock_release: 5026 case Builtin::BI__sync_lock_release_1: 5027 case Builtin::BI__sync_lock_release_2: 5028 case Builtin::BI__sync_lock_release_4: 5029 case Builtin::BI__sync_lock_release_8: 5030 case Builtin::BI__sync_lock_release_16: 5031 BuiltinIndex = 15; 5032 NumFixed = 0; 5033 ResultType = Context.VoidTy; 5034 break; 5035 5036 case Builtin::BI__sync_swap: 5037 case Builtin::BI__sync_swap_1: 5038 case Builtin::BI__sync_swap_2: 5039 case Builtin::BI__sync_swap_4: 5040 case Builtin::BI__sync_swap_8: 5041 case Builtin::BI__sync_swap_16: 5042 BuiltinIndex = 16; 5043 break; 5044 } 5045 5046 // Now that we know how many fixed arguments we expect, first check that we 5047 // have at least that many. 5048 if (TheCall->getNumArgs() < 1+NumFixed) { 5049 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5050 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5051 << Callee->getSourceRange(); 5052 return ExprError(); 5053 } 5054 5055 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5056 << Callee->getSourceRange(); 5057 5058 if (WarnAboutSemanticsChange) { 5059 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5060 << Callee->getSourceRange(); 5061 } 5062 5063 // Get the decl for the concrete builtin from this, we can tell what the 5064 // concrete integer type we should convert to is. 5065 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5066 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5067 FunctionDecl *NewBuiltinDecl; 5068 if (NewBuiltinID == BuiltinID) 5069 NewBuiltinDecl = FDecl; 5070 else { 5071 // Perform builtin lookup to avoid redeclaring it. 5072 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5073 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5074 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5075 assert(Res.getFoundDecl()); 5076 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5077 if (!NewBuiltinDecl) 5078 return ExprError(); 5079 } 5080 5081 // The first argument --- the pointer --- has a fixed type; we 5082 // deduce the types of the rest of the arguments accordingly. Walk 5083 // the remaining arguments, converting them to the deduced value type. 5084 for (unsigned i = 0; i != NumFixed; ++i) { 5085 ExprResult Arg = TheCall->getArg(i+1); 5086 5087 // GCC does an implicit conversion to the pointer or integer ValType. This 5088 // can fail in some cases (1i -> int**), check for this error case now. 5089 // Initialize the argument. 5090 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5091 ValType, /*consume*/ false); 5092 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5093 if (Arg.isInvalid()) 5094 return ExprError(); 5095 5096 // Okay, we have something that *can* be converted to the right type. Check 5097 // to see if there is a potentially weird extension going on here. This can 5098 // happen when you do an atomic operation on something like an char* and 5099 // pass in 42. The 42 gets converted to char. This is even more strange 5100 // for things like 45.123 -> char, etc. 5101 // FIXME: Do this check. 5102 TheCall->setArg(i+1, Arg.get()); 5103 } 5104 5105 // Create a new DeclRefExpr to refer to the new decl. 5106 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5107 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5108 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5109 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5110 5111 // Set the callee in the CallExpr. 5112 // FIXME: This loses syntactic information. 5113 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5114 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5115 CK_BuiltinFnToFnPtr); 5116 TheCall->setCallee(PromotedCall.get()); 5117 5118 // Change the result type of the call to match the original value type. This 5119 // is arbitrary, but the codegen for these builtins ins design to handle it 5120 // gracefully. 5121 TheCall->setType(ResultType); 5122 5123 return TheCallResult; 5124 } 5125 5126 /// SemaBuiltinNontemporalOverloaded - We have a call to 5127 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5128 /// overloaded function based on the pointer type of its last argument. 5129 /// 5130 /// This function goes through and does final semantic checking for these 5131 /// builtins. 5132 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5133 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5134 DeclRefExpr *DRE = 5135 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5136 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5137 unsigned BuiltinID = FDecl->getBuiltinID(); 5138 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5139 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5140 "Unexpected nontemporal load/store builtin!"); 5141 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5142 unsigned numArgs = isStore ? 2 : 1; 5143 5144 // Ensure that we have the proper number of arguments. 5145 if (checkArgCount(*this, TheCall, numArgs)) 5146 return ExprError(); 5147 5148 // Inspect the last argument of the nontemporal builtin. This should always 5149 // be a pointer type, from which we imply the type of the memory access. 5150 // Because it is a pointer type, we don't have to worry about any implicit 5151 // casts here. 5152 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5153 ExprResult PointerArgResult = 5154 DefaultFunctionArrayLvalueConversion(PointerArg); 5155 5156 if (PointerArgResult.isInvalid()) 5157 return ExprError(); 5158 PointerArg = PointerArgResult.get(); 5159 TheCall->setArg(numArgs - 1, PointerArg); 5160 5161 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5162 if (!pointerType) { 5163 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5164 << PointerArg->getType() << PointerArg->getSourceRange(); 5165 return ExprError(); 5166 } 5167 5168 QualType ValType = pointerType->getPointeeType(); 5169 5170 // Strip any qualifiers off ValType. 5171 ValType = ValType.getUnqualifiedType(); 5172 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5173 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5174 !ValType->isVectorType()) { 5175 Diag(DRE->getBeginLoc(), 5176 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5177 << PointerArg->getType() << PointerArg->getSourceRange(); 5178 return ExprError(); 5179 } 5180 5181 if (!isStore) { 5182 TheCall->setType(ValType); 5183 return TheCallResult; 5184 } 5185 5186 ExprResult ValArg = TheCall->getArg(0); 5187 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5188 Context, ValType, /*consume*/ false); 5189 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5190 if (ValArg.isInvalid()) 5191 return ExprError(); 5192 5193 TheCall->setArg(0, ValArg.get()); 5194 TheCall->setType(Context.VoidTy); 5195 return TheCallResult; 5196 } 5197 5198 /// CheckObjCString - Checks that the argument to the builtin 5199 /// CFString constructor is correct 5200 /// Note: It might also make sense to do the UTF-16 conversion here (would 5201 /// simplify the backend). 5202 bool Sema::CheckObjCString(Expr *Arg) { 5203 Arg = Arg->IgnoreParenCasts(); 5204 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5205 5206 if (!Literal || !Literal->isAscii()) { 5207 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5208 << Arg->getSourceRange(); 5209 return true; 5210 } 5211 5212 if (Literal->containsNonAsciiOrNull()) { 5213 StringRef String = Literal->getString(); 5214 unsigned NumBytes = String.size(); 5215 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5216 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5217 llvm::UTF16 *ToPtr = &ToBuf[0]; 5218 5219 llvm::ConversionResult Result = 5220 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5221 ToPtr + NumBytes, llvm::strictConversion); 5222 // Check for conversion failure. 5223 if (Result != llvm::conversionOK) 5224 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5225 << Arg->getSourceRange(); 5226 } 5227 return false; 5228 } 5229 5230 /// CheckObjCString - Checks that the format string argument to the os_log() 5231 /// and os_trace() functions is correct, and converts it to const char *. 5232 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5233 Arg = Arg->IgnoreParenCasts(); 5234 auto *Literal = dyn_cast<StringLiteral>(Arg); 5235 if (!Literal) { 5236 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5237 Literal = ObjcLiteral->getString(); 5238 } 5239 } 5240 5241 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5242 return ExprError( 5243 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5244 << Arg->getSourceRange()); 5245 } 5246 5247 ExprResult Result(Literal); 5248 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5249 InitializedEntity Entity = 5250 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5251 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5252 return Result; 5253 } 5254 5255 /// Check that the user is calling the appropriate va_start builtin for the 5256 /// target and calling convention. 5257 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5258 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5259 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5260 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5261 TT.getArch() == llvm::Triple::aarch64_32); 5262 bool IsWindows = TT.isOSWindows(); 5263 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5264 if (IsX64 || IsAArch64) { 5265 CallingConv CC = CC_C; 5266 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5267 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5268 if (IsMSVAStart) { 5269 // Don't allow this in System V ABI functions. 5270 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5271 return S.Diag(Fn->getBeginLoc(), 5272 diag::err_ms_va_start_used_in_sysv_function); 5273 } else { 5274 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5275 // On x64 Windows, don't allow this in System V ABI functions. 5276 // (Yes, that means there's no corresponding way to support variadic 5277 // System V ABI functions on Windows.) 5278 if ((IsWindows && CC == CC_X86_64SysV) || 5279 (!IsWindows && CC == CC_Win64)) 5280 return S.Diag(Fn->getBeginLoc(), 5281 diag::err_va_start_used_in_wrong_abi_function) 5282 << !IsWindows; 5283 } 5284 return false; 5285 } 5286 5287 if (IsMSVAStart) 5288 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5289 return false; 5290 } 5291 5292 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5293 ParmVarDecl **LastParam = nullptr) { 5294 // Determine whether the current function, block, or obj-c method is variadic 5295 // and get its parameter list. 5296 bool IsVariadic = false; 5297 ArrayRef<ParmVarDecl *> Params; 5298 DeclContext *Caller = S.CurContext; 5299 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5300 IsVariadic = Block->isVariadic(); 5301 Params = Block->parameters(); 5302 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5303 IsVariadic = FD->isVariadic(); 5304 Params = FD->parameters(); 5305 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5306 IsVariadic = MD->isVariadic(); 5307 // FIXME: This isn't correct for methods (results in bogus warning). 5308 Params = MD->parameters(); 5309 } else if (isa<CapturedDecl>(Caller)) { 5310 // We don't support va_start in a CapturedDecl. 5311 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5312 return true; 5313 } else { 5314 // This must be some other declcontext that parses exprs. 5315 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5316 return true; 5317 } 5318 5319 if (!IsVariadic) { 5320 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5321 return true; 5322 } 5323 5324 if (LastParam) 5325 *LastParam = Params.empty() ? nullptr : Params.back(); 5326 5327 return false; 5328 } 5329 5330 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5331 /// for validity. Emit an error and return true on failure; return false 5332 /// on success. 5333 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5334 Expr *Fn = TheCall->getCallee(); 5335 5336 if (checkVAStartABI(*this, BuiltinID, Fn)) 5337 return true; 5338 5339 if (TheCall->getNumArgs() > 2) { 5340 Diag(TheCall->getArg(2)->getBeginLoc(), 5341 diag::err_typecheck_call_too_many_args) 5342 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5343 << Fn->getSourceRange() 5344 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5345 (*(TheCall->arg_end() - 1))->getEndLoc()); 5346 return true; 5347 } 5348 5349 if (TheCall->getNumArgs() < 2) { 5350 return Diag(TheCall->getEndLoc(), 5351 diag::err_typecheck_call_too_few_args_at_least) 5352 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5353 } 5354 5355 // Type-check the first argument normally. 5356 if (checkBuiltinArgument(*this, TheCall, 0)) 5357 return true; 5358 5359 // Check that the current function is variadic, and get its last parameter. 5360 ParmVarDecl *LastParam; 5361 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5362 return true; 5363 5364 // Verify that the second argument to the builtin is the last argument of the 5365 // current function or method. 5366 bool SecondArgIsLastNamedArgument = false; 5367 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5368 5369 // These are valid if SecondArgIsLastNamedArgument is false after the next 5370 // block. 5371 QualType Type; 5372 SourceLocation ParamLoc; 5373 bool IsCRegister = false; 5374 5375 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5376 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5377 SecondArgIsLastNamedArgument = PV == LastParam; 5378 5379 Type = PV->getType(); 5380 ParamLoc = PV->getLocation(); 5381 IsCRegister = 5382 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5383 } 5384 } 5385 5386 if (!SecondArgIsLastNamedArgument) 5387 Diag(TheCall->getArg(1)->getBeginLoc(), 5388 diag::warn_second_arg_of_va_start_not_last_named_param); 5389 else if (IsCRegister || Type->isReferenceType() || 5390 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5391 // Promotable integers are UB, but enumerations need a bit of 5392 // extra checking to see what their promotable type actually is. 5393 if (!Type->isPromotableIntegerType()) 5394 return false; 5395 if (!Type->isEnumeralType()) 5396 return true; 5397 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5398 return !(ED && 5399 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5400 }()) { 5401 unsigned Reason = 0; 5402 if (Type->isReferenceType()) Reason = 1; 5403 else if (IsCRegister) Reason = 2; 5404 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5405 Diag(ParamLoc, diag::note_parameter_type) << Type; 5406 } 5407 5408 TheCall->setType(Context.VoidTy); 5409 return false; 5410 } 5411 5412 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5413 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5414 // const char *named_addr); 5415 5416 Expr *Func = Call->getCallee(); 5417 5418 if (Call->getNumArgs() < 3) 5419 return Diag(Call->getEndLoc(), 5420 diag::err_typecheck_call_too_few_args_at_least) 5421 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5422 5423 // Type-check the first argument normally. 5424 if (checkBuiltinArgument(*this, Call, 0)) 5425 return true; 5426 5427 // Check that the current function is variadic. 5428 if (checkVAStartIsInVariadicFunction(*this, Func)) 5429 return true; 5430 5431 // __va_start on Windows does not validate the parameter qualifiers 5432 5433 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5434 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5435 5436 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5437 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5438 5439 const QualType &ConstCharPtrTy = 5440 Context.getPointerType(Context.CharTy.withConst()); 5441 if (!Arg1Ty->isPointerType() || 5442 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5443 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5444 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5445 << 0 /* qualifier difference */ 5446 << 3 /* parameter mismatch */ 5447 << 2 << Arg1->getType() << ConstCharPtrTy; 5448 5449 const QualType SizeTy = Context.getSizeType(); 5450 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5451 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5452 << Arg2->getType() << SizeTy << 1 /* different class */ 5453 << 0 /* qualifier difference */ 5454 << 3 /* parameter mismatch */ 5455 << 3 << Arg2->getType() << SizeTy; 5456 5457 return false; 5458 } 5459 5460 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5461 /// friends. This is declared to take (...), so we have to check everything. 5462 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5463 if (TheCall->getNumArgs() < 2) 5464 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5465 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5466 if (TheCall->getNumArgs() > 2) 5467 return Diag(TheCall->getArg(2)->getBeginLoc(), 5468 diag::err_typecheck_call_too_many_args) 5469 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5470 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5471 (*(TheCall->arg_end() - 1))->getEndLoc()); 5472 5473 ExprResult OrigArg0 = TheCall->getArg(0); 5474 ExprResult OrigArg1 = TheCall->getArg(1); 5475 5476 // Do standard promotions between the two arguments, returning their common 5477 // type. 5478 QualType Res = UsualArithmeticConversions( 5479 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5480 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5481 return true; 5482 5483 // Make sure any conversions are pushed back into the call; this is 5484 // type safe since unordered compare builtins are declared as "_Bool 5485 // foo(...)". 5486 TheCall->setArg(0, OrigArg0.get()); 5487 TheCall->setArg(1, OrigArg1.get()); 5488 5489 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5490 return false; 5491 5492 // If the common type isn't a real floating type, then the arguments were 5493 // invalid for this operation. 5494 if (Res.isNull() || !Res->isRealFloatingType()) 5495 return Diag(OrigArg0.get()->getBeginLoc(), 5496 diag::err_typecheck_call_invalid_ordered_compare) 5497 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5498 << SourceRange(OrigArg0.get()->getBeginLoc(), 5499 OrigArg1.get()->getEndLoc()); 5500 5501 return false; 5502 } 5503 5504 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5505 /// __builtin_isnan and friends. This is declared to take (...), so we have 5506 /// to check everything. We expect the last argument to be a floating point 5507 /// value. 5508 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5509 if (TheCall->getNumArgs() < NumArgs) 5510 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5511 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5512 if (TheCall->getNumArgs() > NumArgs) 5513 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5514 diag::err_typecheck_call_too_many_args) 5515 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5516 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5517 (*(TheCall->arg_end() - 1))->getEndLoc()); 5518 5519 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5520 // on all preceding parameters just being int. Try all of those. 5521 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5522 Expr *Arg = TheCall->getArg(i); 5523 5524 if (Arg->isTypeDependent()) 5525 return false; 5526 5527 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5528 5529 if (Res.isInvalid()) 5530 return true; 5531 TheCall->setArg(i, Res.get()); 5532 } 5533 5534 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5535 5536 if (OrigArg->isTypeDependent()) 5537 return false; 5538 5539 // Usual Unary Conversions will convert half to float, which we want for 5540 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5541 // type how it is, but do normal L->Rvalue conversions. 5542 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5543 OrigArg = UsualUnaryConversions(OrigArg).get(); 5544 else 5545 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5546 TheCall->setArg(NumArgs - 1, OrigArg); 5547 5548 // This operation requires a non-_Complex floating-point number. 5549 if (!OrigArg->getType()->isRealFloatingType()) 5550 return Diag(OrigArg->getBeginLoc(), 5551 diag::err_typecheck_call_invalid_unary_fp) 5552 << OrigArg->getType() << OrigArg->getSourceRange(); 5553 5554 return false; 5555 } 5556 5557 // Customized Sema Checking for VSX builtins that have the following signature: 5558 // vector [...] builtinName(vector [...], vector [...], const int); 5559 // Which takes the same type of vectors (any legal vector type) for the first 5560 // two arguments and takes compile time constant for the third argument. 5561 // Example builtins are : 5562 // vector double vec_xxpermdi(vector double, vector double, int); 5563 // vector short vec_xxsldwi(vector short, vector short, int); 5564 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5565 unsigned ExpectedNumArgs = 3; 5566 if (TheCall->getNumArgs() < ExpectedNumArgs) 5567 return Diag(TheCall->getEndLoc(), 5568 diag::err_typecheck_call_too_few_args_at_least) 5569 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5570 << TheCall->getSourceRange(); 5571 5572 if (TheCall->getNumArgs() > ExpectedNumArgs) 5573 return Diag(TheCall->getEndLoc(), 5574 diag::err_typecheck_call_too_many_args_at_most) 5575 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5576 << TheCall->getSourceRange(); 5577 5578 // Check the third argument is a compile time constant 5579 llvm::APSInt Value; 5580 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5581 return Diag(TheCall->getBeginLoc(), 5582 diag::err_vsx_builtin_nonconstant_argument) 5583 << 3 /* argument index */ << TheCall->getDirectCallee() 5584 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5585 TheCall->getArg(2)->getEndLoc()); 5586 5587 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5588 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5589 5590 // Check the type of argument 1 and argument 2 are vectors. 5591 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5592 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5593 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5594 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5595 << TheCall->getDirectCallee() 5596 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5597 TheCall->getArg(1)->getEndLoc()); 5598 } 5599 5600 // Check the first two arguments are the same type. 5601 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5602 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5603 << TheCall->getDirectCallee() 5604 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5605 TheCall->getArg(1)->getEndLoc()); 5606 } 5607 5608 // When default clang type checking is turned off and the customized type 5609 // checking is used, the returning type of the function must be explicitly 5610 // set. Otherwise it is _Bool by default. 5611 TheCall->setType(Arg1Ty); 5612 5613 return false; 5614 } 5615 5616 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5617 // This is declared to take (...), so we have to check everything. 5618 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5619 if (TheCall->getNumArgs() < 2) 5620 return ExprError(Diag(TheCall->getEndLoc(), 5621 diag::err_typecheck_call_too_few_args_at_least) 5622 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5623 << TheCall->getSourceRange()); 5624 5625 // Determine which of the following types of shufflevector we're checking: 5626 // 1) unary, vector mask: (lhs, mask) 5627 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5628 QualType resType = TheCall->getArg(0)->getType(); 5629 unsigned numElements = 0; 5630 5631 if (!TheCall->getArg(0)->isTypeDependent() && 5632 !TheCall->getArg(1)->isTypeDependent()) { 5633 QualType LHSType = TheCall->getArg(0)->getType(); 5634 QualType RHSType = TheCall->getArg(1)->getType(); 5635 5636 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5637 return ExprError( 5638 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5639 << TheCall->getDirectCallee() 5640 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5641 TheCall->getArg(1)->getEndLoc())); 5642 5643 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5644 unsigned numResElements = TheCall->getNumArgs() - 2; 5645 5646 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5647 // with mask. If so, verify that RHS is an integer vector type with the 5648 // same number of elts as lhs. 5649 if (TheCall->getNumArgs() == 2) { 5650 if (!RHSType->hasIntegerRepresentation() || 5651 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5652 return ExprError(Diag(TheCall->getBeginLoc(), 5653 diag::err_vec_builtin_incompatible_vector) 5654 << TheCall->getDirectCallee() 5655 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5656 TheCall->getArg(1)->getEndLoc())); 5657 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5658 return ExprError(Diag(TheCall->getBeginLoc(), 5659 diag::err_vec_builtin_incompatible_vector) 5660 << TheCall->getDirectCallee() 5661 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5662 TheCall->getArg(1)->getEndLoc())); 5663 } else if (numElements != numResElements) { 5664 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5665 resType = Context.getVectorType(eltType, numResElements, 5666 VectorType::GenericVector); 5667 } 5668 } 5669 5670 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5671 if (TheCall->getArg(i)->isTypeDependent() || 5672 TheCall->getArg(i)->isValueDependent()) 5673 continue; 5674 5675 llvm::APSInt Result(32); 5676 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5677 return ExprError(Diag(TheCall->getBeginLoc(), 5678 diag::err_shufflevector_nonconstant_argument) 5679 << TheCall->getArg(i)->getSourceRange()); 5680 5681 // Allow -1 which will be translated to undef in the IR. 5682 if (Result.isSigned() && Result.isAllOnesValue()) 5683 continue; 5684 5685 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5686 return ExprError(Diag(TheCall->getBeginLoc(), 5687 diag::err_shufflevector_argument_too_large) 5688 << TheCall->getArg(i)->getSourceRange()); 5689 } 5690 5691 SmallVector<Expr*, 32> exprs; 5692 5693 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5694 exprs.push_back(TheCall->getArg(i)); 5695 TheCall->setArg(i, nullptr); 5696 } 5697 5698 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5699 TheCall->getCallee()->getBeginLoc(), 5700 TheCall->getRParenLoc()); 5701 } 5702 5703 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5704 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5705 SourceLocation BuiltinLoc, 5706 SourceLocation RParenLoc) { 5707 ExprValueKind VK = VK_RValue; 5708 ExprObjectKind OK = OK_Ordinary; 5709 QualType DstTy = TInfo->getType(); 5710 QualType SrcTy = E->getType(); 5711 5712 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5713 return ExprError(Diag(BuiltinLoc, 5714 diag::err_convertvector_non_vector) 5715 << E->getSourceRange()); 5716 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5717 return ExprError(Diag(BuiltinLoc, 5718 diag::err_convertvector_non_vector_type)); 5719 5720 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5721 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5722 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5723 if (SrcElts != DstElts) 5724 return ExprError(Diag(BuiltinLoc, 5725 diag::err_convertvector_incompatible_vector) 5726 << E->getSourceRange()); 5727 } 5728 5729 return new (Context) 5730 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5731 } 5732 5733 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5734 // This is declared to take (const void*, ...) and can take two 5735 // optional constant int args. 5736 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5737 unsigned NumArgs = TheCall->getNumArgs(); 5738 5739 if (NumArgs > 3) 5740 return Diag(TheCall->getEndLoc(), 5741 diag::err_typecheck_call_too_many_args_at_most) 5742 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5743 5744 // Argument 0 is checked for us and the remaining arguments must be 5745 // constant integers. 5746 for (unsigned i = 1; i != NumArgs; ++i) 5747 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5748 return true; 5749 5750 return false; 5751 } 5752 5753 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5754 // __assume does not evaluate its arguments, and should warn if its argument 5755 // has side effects. 5756 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5757 Expr *Arg = TheCall->getArg(0); 5758 if (Arg->isInstantiationDependent()) return false; 5759 5760 if (Arg->HasSideEffects(Context)) 5761 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5762 << Arg->getSourceRange() 5763 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5764 5765 return false; 5766 } 5767 5768 /// Handle __builtin_alloca_with_align. This is declared 5769 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5770 /// than 8. 5771 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5772 // The alignment must be a constant integer. 5773 Expr *Arg = TheCall->getArg(1); 5774 5775 // We can't check the value of a dependent argument. 5776 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5777 if (const auto *UE = 5778 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5779 if (UE->getKind() == UETT_AlignOf || 5780 UE->getKind() == UETT_PreferredAlignOf) 5781 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5782 << Arg->getSourceRange(); 5783 5784 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5785 5786 if (!Result.isPowerOf2()) 5787 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5788 << Arg->getSourceRange(); 5789 5790 if (Result < Context.getCharWidth()) 5791 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5792 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5793 5794 if (Result > std::numeric_limits<int32_t>::max()) 5795 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5796 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5797 } 5798 5799 return false; 5800 } 5801 5802 /// Handle __builtin_assume_aligned. This is declared 5803 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5804 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5805 unsigned NumArgs = TheCall->getNumArgs(); 5806 5807 if (NumArgs > 3) 5808 return Diag(TheCall->getEndLoc(), 5809 diag::err_typecheck_call_too_many_args_at_most) 5810 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5811 5812 // The alignment must be a constant integer. 5813 Expr *Arg = TheCall->getArg(1); 5814 5815 // We can't check the value of a dependent argument. 5816 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5817 llvm::APSInt Result; 5818 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5819 return true; 5820 5821 if (!Result.isPowerOf2()) 5822 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5823 << Arg->getSourceRange(); 5824 5825 if (Result > Sema::MaximumAlignment) 5826 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5827 << Arg->getSourceRange() << Sema::MaximumAlignment; 5828 } 5829 5830 if (NumArgs > 2) { 5831 ExprResult Arg(TheCall->getArg(2)); 5832 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5833 Context.getSizeType(), false); 5834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5835 if (Arg.isInvalid()) return true; 5836 TheCall->setArg(2, Arg.get()); 5837 } 5838 5839 return false; 5840 } 5841 5842 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5843 unsigned BuiltinID = 5844 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5845 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5846 5847 unsigned NumArgs = TheCall->getNumArgs(); 5848 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5849 if (NumArgs < NumRequiredArgs) { 5850 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5851 << 0 /* function call */ << NumRequiredArgs << NumArgs 5852 << TheCall->getSourceRange(); 5853 } 5854 if (NumArgs >= NumRequiredArgs + 0x100) { 5855 return Diag(TheCall->getEndLoc(), 5856 diag::err_typecheck_call_too_many_args_at_most) 5857 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5858 << TheCall->getSourceRange(); 5859 } 5860 unsigned i = 0; 5861 5862 // For formatting call, check buffer arg. 5863 if (!IsSizeCall) { 5864 ExprResult Arg(TheCall->getArg(i)); 5865 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5866 Context, Context.VoidPtrTy, false); 5867 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5868 if (Arg.isInvalid()) 5869 return true; 5870 TheCall->setArg(i, Arg.get()); 5871 i++; 5872 } 5873 5874 // Check string literal arg. 5875 unsigned FormatIdx = i; 5876 { 5877 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5878 if (Arg.isInvalid()) 5879 return true; 5880 TheCall->setArg(i, Arg.get()); 5881 i++; 5882 } 5883 5884 // Make sure variadic args are scalar. 5885 unsigned FirstDataArg = i; 5886 while (i < NumArgs) { 5887 ExprResult Arg = DefaultVariadicArgumentPromotion( 5888 TheCall->getArg(i), VariadicFunction, nullptr); 5889 if (Arg.isInvalid()) 5890 return true; 5891 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5892 if (ArgSize.getQuantity() >= 0x100) { 5893 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5894 << i << (int)ArgSize.getQuantity() << 0xff 5895 << TheCall->getSourceRange(); 5896 } 5897 TheCall->setArg(i, Arg.get()); 5898 i++; 5899 } 5900 5901 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5902 // call to avoid duplicate diagnostics. 5903 if (!IsSizeCall) { 5904 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5905 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5906 bool Success = CheckFormatArguments( 5907 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5908 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5909 CheckedVarArgs); 5910 if (!Success) 5911 return true; 5912 } 5913 5914 if (IsSizeCall) { 5915 TheCall->setType(Context.getSizeType()); 5916 } else { 5917 TheCall->setType(Context.VoidPtrTy); 5918 } 5919 return false; 5920 } 5921 5922 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5923 /// TheCall is a constant expression. 5924 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5925 llvm::APSInt &Result) { 5926 Expr *Arg = TheCall->getArg(ArgNum); 5927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5928 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5929 5930 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5931 5932 if (!Arg->isIntegerConstantExpr(Result, Context)) 5933 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5934 << FDecl->getDeclName() << Arg->getSourceRange(); 5935 5936 return false; 5937 } 5938 5939 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5940 /// TheCall is a constant expression in the range [Low, High]. 5941 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5942 int Low, int High, bool RangeIsError) { 5943 if (isConstantEvaluated()) 5944 return false; 5945 llvm::APSInt Result; 5946 5947 // We can't check the value of a dependent argument. 5948 Expr *Arg = TheCall->getArg(ArgNum); 5949 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5950 return false; 5951 5952 // Check constant-ness first. 5953 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5954 return true; 5955 5956 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5957 if (RangeIsError) 5958 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5959 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5960 else 5961 // Defer the warning until we know if the code will be emitted so that 5962 // dead code can ignore this. 5963 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5964 PDiag(diag::warn_argument_invalid_range) 5965 << Result.toString(10) << Low << High 5966 << Arg->getSourceRange()); 5967 } 5968 5969 return false; 5970 } 5971 5972 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5973 /// TheCall is a constant expression is a multiple of Num.. 5974 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5975 unsigned Num) { 5976 llvm::APSInt Result; 5977 5978 // We can't check the value of a dependent argument. 5979 Expr *Arg = TheCall->getArg(ArgNum); 5980 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5981 return false; 5982 5983 // Check constant-ness first. 5984 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5985 return true; 5986 5987 if (Result.getSExtValue() % Num != 0) 5988 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5989 << Num << Arg->getSourceRange(); 5990 5991 return false; 5992 } 5993 5994 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 5995 /// constant expression representing a power of 2. 5996 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5997 llvm::APSInt Result; 5998 5999 // We can't check the value of a dependent argument. 6000 Expr *Arg = TheCall->getArg(ArgNum); 6001 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6002 return false; 6003 6004 // Check constant-ness first. 6005 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6006 return true; 6007 6008 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6009 // and only if x is a power of 2. 6010 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6011 return false; 6012 6013 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6014 << Arg->getSourceRange(); 6015 } 6016 6017 static bool IsShiftedByte(llvm::APSInt Value) { 6018 if (Value.isNegative()) 6019 return false; 6020 6021 // Check if it's a shifted byte, by shifting it down 6022 while (true) { 6023 // If the value fits in the bottom byte, the check passes. 6024 if (Value < 0x100) 6025 return true; 6026 6027 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6028 // fails. 6029 if ((Value & 0xFF) != 0) 6030 return false; 6031 6032 // If the bottom 8 bits are all 0, but something above that is nonzero, 6033 // then shifting the value right by 8 bits won't affect whether it's a 6034 // shifted byte or not. So do that, and go round again. 6035 Value >>= 8; 6036 } 6037 } 6038 6039 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6040 /// a constant expression representing an arbitrary byte value shifted left by 6041 /// a multiple of 8 bits. 6042 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6043 unsigned ArgBits) { 6044 llvm::APSInt Result; 6045 6046 // We can't check the value of a dependent argument. 6047 Expr *Arg = TheCall->getArg(ArgNum); 6048 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6049 return false; 6050 6051 // Check constant-ness first. 6052 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6053 return true; 6054 6055 // Truncate to the given size. 6056 Result = Result.getLoBits(ArgBits); 6057 Result.setIsUnsigned(true); 6058 6059 if (IsShiftedByte(Result)) 6060 return false; 6061 6062 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6063 << Arg->getSourceRange(); 6064 } 6065 6066 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6067 /// TheCall is a constant expression representing either a shifted byte value, 6068 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6069 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6070 /// Arm MVE intrinsics. 6071 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6072 int ArgNum, 6073 unsigned ArgBits) { 6074 llvm::APSInt Result; 6075 6076 // We can't check the value of a dependent argument. 6077 Expr *Arg = TheCall->getArg(ArgNum); 6078 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6079 return false; 6080 6081 // Check constant-ness first. 6082 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6083 return true; 6084 6085 // Truncate to the given size. 6086 Result = Result.getLoBits(ArgBits); 6087 Result.setIsUnsigned(true); 6088 6089 // Check to see if it's in either of the required forms. 6090 if (IsShiftedByte(Result) || 6091 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6092 return false; 6093 6094 return Diag(TheCall->getBeginLoc(), 6095 diag::err_argument_not_shifted_byte_or_xxff) 6096 << Arg->getSourceRange(); 6097 } 6098 6099 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6100 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6101 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6102 if (checkArgCount(*this, TheCall, 2)) 6103 return true; 6104 Expr *Arg0 = TheCall->getArg(0); 6105 Expr *Arg1 = TheCall->getArg(1); 6106 6107 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6108 if (FirstArg.isInvalid()) 6109 return true; 6110 QualType FirstArgType = FirstArg.get()->getType(); 6111 if (!FirstArgType->isAnyPointerType()) 6112 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6113 << "first" << FirstArgType << Arg0->getSourceRange(); 6114 TheCall->setArg(0, FirstArg.get()); 6115 6116 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6117 if (SecArg.isInvalid()) 6118 return true; 6119 QualType SecArgType = SecArg.get()->getType(); 6120 if (!SecArgType->isIntegerType()) 6121 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6122 << "second" << SecArgType << Arg1->getSourceRange(); 6123 6124 // Derive the return type from the pointer argument. 6125 TheCall->setType(FirstArgType); 6126 return false; 6127 } 6128 6129 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6130 if (checkArgCount(*this, TheCall, 2)) 6131 return true; 6132 6133 Expr *Arg0 = TheCall->getArg(0); 6134 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6135 if (FirstArg.isInvalid()) 6136 return true; 6137 QualType FirstArgType = FirstArg.get()->getType(); 6138 if (!FirstArgType->isAnyPointerType()) 6139 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6140 << "first" << FirstArgType << Arg0->getSourceRange(); 6141 TheCall->setArg(0, FirstArg.get()); 6142 6143 // Derive the return type from the pointer argument. 6144 TheCall->setType(FirstArgType); 6145 6146 // Second arg must be an constant in range [0,15] 6147 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6148 } 6149 6150 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6151 if (checkArgCount(*this, TheCall, 2)) 6152 return true; 6153 Expr *Arg0 = TheCall->getArg(0); 6154 Expr *Arg1 = TheCall->getArg(1); 6155 6156 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6157 if (FirstArg.isInvalid()) 6158 return true; 6159 QualType FirstArgType = FirstArg.get()->getType(); 6160 if (!FirstArgType->isAnyPointerType()) 6161 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6162 << "first" << FirstArgType << Arg0->getSourceRange(); 6163 6164 QualType SecArgType = Arg1->getType(); 6165 if (!SecArgType->isIntegerType()) 6166 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6167 << "second" << SecArgType << Arg1->getSourceRange(); 6168 TheCall->setType(Context.IntTy); 6169 return false; 6170 } 6171 6172 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6173 BuiltinID == AArch64::BI__builtin_arm_stg) { 6174 if (checkArgCount(*this, TheCall, 1)) 6175 return true; 6176 Expr *Arg0 = TheCall->getArg(0); 6177 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6178 if (FirstArg.isInvalid()) 6179 return true; 6180 6181 QualType FirstArgType = FirstArg.get()->getType(); 6182 if (!FirstArgType->isAnyPointerType()) 6183 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6184 << "first" << FirstArgType << Arg0->getSourceRange(); 6185 TheCall->setArg(0, FirstArg.get()); 6186 6187 // Derive the return type from the pointer argument. 6188 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6189 TheCall->setType(FirstArgType); 6190 return false; 6191 } 6192 6193 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6194 Expr *ArgA = TheCall->getArg(0); 6195 Expr *ArgB = TheCall->getArg(1); 6196 6197 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6198 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6199 6200 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6201 return true; 6202 6203 QualType ArgTypeA = ArgExprA.get()->getType(); 6204 QualType ArgTypeB = ArgExprB.get()->getType(); 6205 6206 auto isNull = [&] (Expr *E) -> bool { 6207 return E->isNullPointerConstant( 6208 Context, Expr::NPC_ValueDependentIsNotNull); }; 6209 6210 // argument should be either a pointer or null 6211 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6212 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6213 << "first" << ArgTypeA << ArgA->getSourceRange(); 6214 6215 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6216 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6217 << "second" << ArgTypeB << ArgB->getSourceRange(); 6218 6219 // Ensure Pointee types are compatible 6220 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6221 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6222 QualType pointeeA = ArgTypeA->getPointeeType(); 6223 QualType pointeeB = ArgTypeB->getPointeeType(); 6224 if (!Context.typesAreCompatible( 6225 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6226 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6227 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6228 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6229 << ArgB->getSourceRange(); 6230 } 6231 } 6232 6233 // at least one argument should be pointer type 6234 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6235 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6236 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6237 6238 if (isNull(ArgA)) // adopt type of the other pointer 6239 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6240 6241 if (isNull(ArgB)) 6242 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6243 6244 TheCall->setArg(0, ArgExprA.get()); 6245 TheCall->setArg(1, ArgExprB.get()); 6246 TheCall->setType(Context.LongLongTy); 6247 return false; 6248 } 6249 assert(false && "Unhandled ARM MTE intrinsic"); 6250 return true; 6251 } 6252 6253 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6254 /// TheCall is an ARM/AArch64 special register string literal. 6255 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6256 int ArgNum, unsigned ExpectedFieldNum, 6257 bool AllowName) { 6258 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6259 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6260 BuiltinID == ARM::BI__builtin_arm_rsr || 6261 BuiltinID == ARM::BI__builtin_arm_rsrp || 6262 BuiltinID == ARM::BI__builtin_arm_wsr || 6263 BuiltinID == ARM::BI__builtin_arm_wsrp; 6264 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6265 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6266 BuiltinID == AArch64::BI__builtin_arm_rsr || 6267 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6268 BuiltinID == AArch64::BI__builtin_arm_wsr || 6269 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6270 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6271 6272 // We can't check the value of a dependent argument. 6273 Expr *Arg = TheCall->getArg(ArgNum); 6274 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6275 return false; 6276 6277 // Check if the argument is a string literal. 6278 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6279 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6280 << Arg->getSourceRange(); 6281 6282 // Check the type of special register given. 6283 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6284 SmallVector<StringRef, 6> Fields; 6285 Reg.split(Fields, ":"); 6286 6287 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6288 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6289 << Arg->getSourceRange(); 6290 6291 // If the string is the name of a register then we cannot check that it is 6292 // valid here but if the string is of one the forms described in ACLE then we 6293 // can check that the supplied fields are integers and within the valid 6294 // ranges. 6295 if (Fields.size() > 1) { 6296 bool FiveFields = Fields.size() == 5; 6297 6298 bool ValidString = true; 6299 if (IsARMBuiltin) { 6300 ValidString &= Fields[0].startswith_lower("cp") || 6301 Fields[0].startswith_lower("p"); 6302 if (ValidString) 6303 Fields[0] = 6304 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6305 6306 ValidString &= Fields[2].startswith_lower("c"); 6307 if (ValidString) 6308 Fields[2] = Fields[2].drop_front(1); 6309 6310 if (FiveFields) { 6311 ValidString &= Fields[3].startswith_lower("c"); 6312 if (ValidString) 6313 Fields[3] = Fields[3].drop_front(1); 6314 } 6315 } 6316 6317 SmallVector<int, 5> Ranges; 6318 if (FiveFields) 6319 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6320 else 6321 Ranges.append({15, 7, 15}); 6322 6323 for (unsigned i=0; i<Fields.size(); ++i) { 6324 int IntField; 6325 ValidString &= !Fields[i].getAsInteger(10, IntField); 6326 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6327 } 6328 6329 if (!ValidString) 6330 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6331 << Arg->getSourceRange(); 6332 } else if (IsAArch64Builtin && Fields.size() == 1) { 6333 // If the register name is one of those that appear in the condition below 6334 // and the special register builtin being used is one of the write builtins, 6335 // then we require that the argument provided for writing to the register 6336 // is an integer constant expression. This is because it will be lowered to 6337 // an MSR (immediate) instruction, so we need to know the immediate at 6338 // compile time. 6339 if (TheCall->getNumArgs() != 2) 6340 return false; 6341 6342 std::string RegLower = Reg.lower(); 6343 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6344 RegLower != "pan" && RegLower != "uao") 6345 return false; 6346 6347 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6348 } 6349 6350 return false; 6351 } 6352 6353 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6354 /// This checks that the target supports __builtin_longjmp and 6355 /// that val is a constant 1. 6356 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6357 if (!Context.getTargetInfo().hasSjLjLowering()) 6358 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6359 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6360 6361 Expr *Arg = TheCall->getArg(1); 6362 llvm::APSInt Result; 6363 6364 // TODO: This is less than ideal. Overload this to take a value. 6365 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6366 return true; 6367 6368 if (Result != 1) 6369 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6370 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6371 6372 return false; 6373 } 6374 6375 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6376 /// This checks that the target supports __builtin_setjmp. 6377 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6378 if (!Context.getTargetInfo().hasSjLjLowering()) 6379 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6380 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6381 return false; 6382 } 6383 6384 namespace { 6385 6386 class UncoveredArgHandler { 6387 enum { Unknown = -1, AllCovered = -2 }; 6388 6389 signed FirstUncoveredArg = Unknown; 6390 SmallVector<const Expr *, 4> DiagnosticExprs; 6391 6392 public: 6393 UncoveredArgHandler() = default; 6394 6395 bool hasUncoveredArg() const { 6396 return (FirstUncoveredArg >= 0); 6397 } 6398 6399 unsigned getUncoveredArg() const { 6400 assert(hasUncoveredArg() && "no uncovered argument"); 6401 return FirstUncoveredArg; 6402 } 6403 6404 void setAllCovered() { 6405 // A string has been found with all arguments covered, so clear out 6406 // the diagnostics. 6407 DiagnosticExprs.clear(); 6408 FirstUncoveredArg = AllCovered; 6409 } 6410 6411 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6412 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6413 6414 // Don't update if a previous string covers all arguments. 6415 if (FirstUncoveredArg == AllCovered) 6416 return; 6417 6418 // UncoveredArgHandler tracks the highest uncovered argument index 6419 // and with it all the strings that match this index. 6420 if (NewFirstUncoveredArg == FirstUncoveredArg) 6421 DiagnosticExprs.push_back(StrExpr); 6422 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6423 DiagnosticExprs.clear(); 6424 DiagnosticExprs.push_back(StrExpr); 6425 FirstUncoveredArg = NewFirstUncoveredArg; 6426 } 6427 } 6428 6429 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6430 }; 6431 6432 enum StringLiteralCheckType { 6433 SLCT_NotALiteral, 6434 SLCT_UncheckedLiteral, 6435 SLCT_CheckedLiteral 6436 }; 6437 6438 } // namespace 6439 6440 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6441 BinaryOperatorKind BinOpKind, 6442 bool AddendIsRight) { 6443 unsigned BitWidth = Offset.getBitWidth(); 6444 unsigned AddendBitWidth = Addend.getBitWidth(); 6445 // There might be negative interim results. 6446 if (Addend.isUnsigned()) { 6447 Addend = Addend.zext(++AddendBitWidth); 6448 Addend.setIsSigned(true); 6449 } 6450 // Adjust the bit width of the APSInts. 6451 if (AddendBitWidth > BitWidth) { 6452 Offset = Offset.sext(AddendBitWidth); 6453 BitWidth = AddendBitWidth; 6454 } else if (BitWidth > AddendBitWidth) { 6455 Addend = Addend.sext(BitWidth); 6456 } 6457 6458 bool Ov = false; 6459 llvm::APSInt ResOffset = Offset; 6460 if (BinOpKind == BO_Add) 6461 ResOffset = Offset.sadd_ov(Addend, Ov); 6462 else { 6463 assert(AddendIsRight && BinOpKind == BO_Sub && 6464 "operator must be add or sub with addend on the right"); 6465 ResOffset = Offset.ssub_ov(Addend, Ov); 6466 } 6467 6468 // We add an offset to a pointer here so we should support an offset as big as 6469 // possible. 6470 if (Ov) { 6471 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6472 "index (intermediate) result too big"); 6473 Offset = Offset.sext(2 * BitWidth); 6474 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6475 return; 6476 } 6477 6478 Offset = ResOffset; 6479 } 6480 6481 namespace { 6482 6483 // This is a wrapper class around StringLiteral to support offsetted string 6484 // literals as format strings. It takes the offset into account when returning 6485 // the string and its length or the source locations to display notes correctly. 6486 class FormatStringLiteral { 6487 const StringLiteral *FExpr; 6488 int64_t Offset; 6489 6490 public: 6491 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6492 : FExpr(fexpr), Offset(Offset) {} 6493 6494 StringRef getString() const { 6495 return FExpr->getString().drop_front(Offset); 6496 } 6497 6498 unsigned getByteLength() const { 6499 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6500 } 6501 6502 unsigned getLength() const { return FExpr->getLength() - Offset; } 6503 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6504 6505 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6506 6507 QualType getType() const { return FExpr->getType(); } 6508 6509 bool isAscii() const { return FExpr->isAscii(); } 6510 bool isWide() const { return FExpr->isWide(); } 6511 bool isUTF8() const { return FExpr->isUTF8(); } 6512 bool isUTF16() const { return FExpr->isUTF16(); } 6513 bool isUTF32() const { return FExpr->isUTF32(); } 6514 bool isPascal() const { return FExpr->isPascal(); } 6515 6516 SourceLocation getLocationOfByte( 6517 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6518 const TargetInfo &Target, unsigned *StartToken = nullptr, 6519 unsigned *StartTokenByteOffset = nullptr) const { 6520 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6521 StartToken, StartTokenByteOffset); 6522 } 6523 6524 SourceLocation getBeginLoc() const LLVM_READONLY { 6525 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6526 } 6527 6528 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6529 }; 6530 6531 } // namespace 6532 6533 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6534 const Expr *OrigFormatExpr, 6535 ArrayRef<const Expr *> Args, 6536 bool HasVAListArg, unsigned format_idx, 6537 unsigned firstDataArg, 6538 Sema::FormatStringType Type, 6539 bool inFunctionCall, 6540 Sema::VariadicCallType CallType, 6541 llvm::SmallBitVector &CheckedVarArgs, 6542 UncoveredArgHandler &UncoveredArg, 6543 bool IgnoreStringsWithoutSpecifiers); 6544 6545 // Determine if an expression is a string literal or constant string. 6546 // If this function returns false on the arguments to a function expecting a 6547 // format string, we will usually need to emit a warning. 6548 // True string literals are then checked by CheckFormatString. 6549 static StringLiteralCheckType 6550 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6551 bool HasVAListArg, unsigned format_idx, 6552 unsigned firstDataArg, Sema::FormatStringType Type, 6553 Sema::VariadicCallType CallType, bool InFunctionCall, 6554 llvm::SmallBitVector &CheckedVarArgs, 6555 UncoveredArgHandler &UncoveredArg, 6556 llvm::APSInt Offset, 6557 bool IgnoreStringsWithoutSpecifiers = false) { 6558 if (S.isConstantEvaluated()) 6559 return SLCT_NotALiteral; 6560 tryAgain: 6561 assert(Offset.isSigned() && "invalid offset"); 6562 6563 if (E->isTypeDependent() || E->isValueDependent()) 6564 return SLCT_NotALiteral; 6565 6566 E = E->IgnoreParenCasts(); 6567 6568 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6569 // Technically -Wformat-nonliteral does not warn about this case. 6570 // The behavior of printf and friends in this case is implementation 6571 // dependent. Ideally if the format string cannot be null then 6572 // it should have a 'nonnull' attribute in the function prototype. 6573 return SLCT_UncheckedLiteral; 6574 6575 switch (E->getStmtClass()) { 6576 case Stmt::BinaryConditionalOperatorClass: 6577 case Stmt::ConditionalOperatorClass: { 6578 // The expression is a literal if both sub-expressions were, and it was 6579 // completely checked only if both sub-expressions were checked. 6580 const AbstractConditionalOperator *C = 6581 cast<AbstractConditionalOperator>(E); 6582 6583 // Determine whether it is necessary to check both sub-expressions, for 6584 // example, because the condition expression is a constant that can be 6585 // evaluated at compile time. 6586 bool CheckLeft = true, CheckRight = true; 6587 6588 bool Cond; 6589 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6590 S.isConstantEvaluated())) { 6591 if (Cond) 6592 CheckRight = false; 6593 else 6594 CheckLeft = false; 6595 } 6596 6597 // We need to maintain the offsets for the right and the left hand side 6598 // separately to check if every possible indexed expression is a valid 6599 // string literal. They might have different offsets for different string 6600 // literals in the end. 6601 StringLiteralCheckType Left; 6602 if (!CheckLeft) 6603 Left = SLCT_UncheckedLiteral; 6604 else { 6605 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6606 HasVAListArg, format_idx, firstDataArg, 6607 Type, CallType, InFunctionCall, 6608 CheckedVarArgs, UncoveredArg, Offset, 6609 IgnoreStringsWithoutSpecifiers); 6610 if (Left == SLCT_NotALiteral || !CheckRight) { 6611 return Left; 6612 } 6613 } 6614 6615 StringLiteralCheckType Right = checkFormatStringExpr( 6616 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6617 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6618 IgnoreStringsWithoutSpecifiers); 6619 6620 return (CheckLeft && Left < Right) ? Left : Right; 6621 } 6622 6623 case Stmt::ImplicitCastExprClass: 6624 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6625 goto tryAgain; 6626 6627 case Stmt::OpaqueValueExprClass: 6628 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6629 E = src; 6630 goto tryAgain; 6631 } 6632 return SLCT_NotALiteral; 6633 6634 case Stmt::PredefinedExprClass: 6635 // While __func__, etc., are technically not string literals, they 6636 // cannot contain format specifiers and thus are not a security 6637 // liability. 6638 return SLCT_UncheckedLiteral; 6639 6640 case Stmt::DeclRefExprClass: { 6641 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6642 6643 // As an exception, do not flag errors for variables binding to 6644 // const string literals. 6645 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6646 bool isConstant = false; 6647 QualType T = DR->getType(); 6648 6649 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6650 isConstant = AT->getElementType().isConstant(S.Context); 6651 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6652 isConstant = T.isConstant(S.Context) && 6653 PT->getPointeeType().isConstant(S.Context); 6654 } else if (T->isObjCObjectPointerType()) { 6655 // In ObjC, there is usually no "const ObjectPointer" type, 6656 // so don't check if the pointee type is constant. 6657 isConstant = T.isConstant(S.Context); 6658 } 6659 6660 if (isConstant) { 6661 if (const Expr *Init = VD->getAnyInitializer()) { 6662 // Look through initializers like const char c[] = { "foo" } 6663 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6664 if (InitList->isStringLiteralInit()) 6665 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6666 } 6667 return checkFormatStringExpr(S, Init, Args, 6668 HasVAListArg, format_idx, 6669 firstDataArg, Type, CallType, 6670 /*InFunctionCall*/ false, CheckedVarArgs, 6671 UncoveredArg, Offset); 6672 } 6673 } 6674 6675 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6676 // special check to see if the format string is a function parameter 6677 // of the function calling the printf function. If the function 6678 // has an attribute indicating it is a printf-like function, then we 6679 // should suppress warnings concerning non-literals being used in a call 6680 // to a vprintf function. For example: 6681 // 6682 // void 6683 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6684 // va_list ap; 6685 // va_start(ap, fmt); 6686 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6687 // ... 6688 // } 6689 if (HasVAListArg) { 6690 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6691 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6692 int PVIndex = PV->getFunctionScopeIndex() + 1; 6693 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6694 // adjust for implicit parameter 6695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6696 if (MD->isInstance()) 6697 ++PVIndex; 6698 // We also check if the formats are compatible. 6699 // We can't pass a 'scanf' string to a 'printf' function. 6700 if (PVIndex == PVFormat->getFormatIdx() && 6701 Type == S.GetFormatStringType(PVFormat)) 6702 return SLCT_UncheckedLiteral; 6703 } 6704 } 6705 } 6706 } 6707 } 6708 6709 return SLCT_NotALiteral; 6710 } 6711 6712 case Stmt::CallExprClass: 6713 case Stmt::CXXMemberCallExprClass: { 6714 const CallExpr *CE = cast<CallExpr>(E); 6715 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6716 bool IsFirst = true; 6717 StringLiteralCheckType CommonResult; 6718 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6719 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6720 StringLiteralCheckType Result = checkFormatStringExpr( 6721 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6722 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6723 IgnoreStringsWithoutSpecifiers); 6724 if (IsFirst) { 6725 CommonResult = Result; 6726 IsFirst = false; 6727 } 6728 } 6729 if (!IsFirst) 6730 return CommonResult; 6731 6732 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6733 unsigned BuiltinID = FD->getBuiltinID(); 6734 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6735 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6736 const Expr *Arg = CE->getArg(0); 6737 return checkFormatStringExpr(S, Arg, Args, 6738 HasVAListArg, format_idx, 6739 firstDataArg, Type, CallType, 6740 InFunctionCall, CheckedVarArgs, 6741 UncoveredArg, Offset, 6742 IgnoreStringsWithoutSpecifiers); 6743 } 6744 } 6745 } 6746 6747 return SLCT_NotALiteral; 6748 } 6749 case Stmt::ObjCMessageExprClass: { 6750 const auto *ME = cast<ObjCMessageExpr>(E); 6751 if (const auto *MD = ME->getMethodDecl()) { 6752 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6753 // As a special case heuristic, if we're using the method -[NSBundle 6754 // localizedStringForKey:value:table:], ignore any key strings that lack 6755 // format specifiers. The idea is that if the key doesn't have any 6756 // format specifiers then its probably just a key to map to the 6757 // localized strings. If it does have format specifiers though, then its 6758 // likely that the text of the key is the format string in the 6759 // programmer's language, and should be checked. 6760 const ObjCInterfaceDecl *IFace; 6761 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6762 IFace->getIdentifier()->isStr("NSBundle") && 6763 MD->getSelector().isKeywordSelector( 6764 {"localizedStringForKey", "value", "table"})) { 6765 IgnoreStringsWithoutSpecifiers = true; 6766 } 6767 6768 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6769 return checkFormatStringExpr( 6770 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6771 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6772 IgnoreStringsWithoutSpecifiers); 6773 } 6774 } 6775 6776 return SLCT_NotALiteral; 6777 } 6778 case Stmt::ObjCStringLiteralClass: 6779 case Stmt::StringLiteralClass: { 6780 const StringLiteral *StrE = nullptr; 6781 6782 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6783 StrE = ObjCFExpr->getString(); 6784 else 6785 StrE = cast<StringLiteral>(E); 6786 6787 if (StrE) { 6788 if (Offset.isNegative() || Offset > StrE->getLength()) { 6789 // TODO: It would be better to have an explicit warning for out of 6790 // bounds literals. 6791 return SLCT_NotALiteral; 6792 } 6793 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6794 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6795 firstDataArg, Type, InFunctionCall, CallType, 6796 CheckedVarArgs, UncoveredArg, 6797 IgnoreStringsWithoutSpecifiers); 6798 return SLCT_CheckedLiteral; 6799 } 6800 6801 return SLCT_NotALiteral; 6802 } 6803 case Stmt::BinaryOperatorClass: { 6804 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6805 6806 // A string literal + an int offset is still a string literal. 6807 if (BinOp->isAdditiveOp()) { 6808 Expr::EvalResult LResult, RResult; 6809 6810 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6811 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6812 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6813 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6814 6815 if (LIsInt != RIsInt) { 6816 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6817 6818 if (LIsInt) { 6819 if (BinOpKind == BO_Add) { 6820 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6821 E = BinOp->getRHS(); 6822 goto tryAgain; 6823 } 6824 } else { 6825 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6826 E = BinOp->getLHS(); 6827 goto tryAgain; 6828 } 6829 } 6830 } 6831 6832 return SLCT_NotALiteral; 6833 } 6834 case Stmt::UnaryOperatorClass: { 6835 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6836 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6837 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6838 Expr::EvalResult IndexResult; 6839 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6840 Expr::SE_NoSideEffects, 6841 S.isConstantEvaluated())) { 6842 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6843 /*RHS is int*/ true); 6844 E = ASE->getBase(); 6845 goto tryAgain; 6846 } 6847 } 6848 6849 return SLCT_NotALiteral; 6850 } 6851 6852 default: 6853 return SLCT_NotALiteral; 6854 } 6855 } 6856 6857 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6858 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6859 .Case("scanf", FST_Scanf) 6860 .Cases("printf", "printf0", FST_Printf) 6861 .Cases("NSString", "CFString", FST_NSString) 6862 .Case("strftime", FST_Strftime) 6863 .Case("strfmon", FST_Strfmon) 6864 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6865 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6866 .Case("os_trace", FST_OSLog) 6867 .Case("os_log", FST_OSLog) 6868 .Default(FST_Unknown); 6869 } 6870 6871 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6872 /// functions) for correct use of format strings. 6873 /// Returns true if a format string has been fully checked. 6874 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6875 ArrayRef<const Expr *> Args, 6876 bool IsCXXMember, 6877 VariadicCallType CallType, 6878 SourceLocation Loc, SourceRange Range, 6879 llvm::SmallBitVector &CheckedVarArgs) { 6880 FormatStringInfo FSI; 6881 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6882 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6883 FSI.FirstDataArg, GetFormatStringType(Format), 6884 CallType, Loc, Range, CheckedVarArgs); 6885 return false; 6886 } 6887 6888 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6889 bool HasVAListArg, unsigned format_idx, 6890 unsigned firstDataArg, FormatStringType Type, 6891 VariadicCallType CallType, 6892 SourceLocation Loc, SourceRange Range, 6893 llvm::SmallBitVector &CheckedVarArgs) { 6894 // CHECK: printf/scanf-like function is called with no format string. 6895 if (format_idx >= Args.size()) { 6896 Diag(Loc, diag::warn_missing_format_string) << Range; 6897 return false; 6898 } 6899 6900 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6901 6902 // CHECK: format string is not a string literal. 6903 // 6904 // Dynamically generated format strings are difficult to 6905 // automatically vet at compile time. Requiring that format strings 6906 // are string literals: (1) permits the checking of format strings by 6907 // the compiler and thereby (2) can practically remove the source of 6908 // many format string exploits. 6909 6910 // Format string can be either ObjC string (e.g. @"%d") or 6911 // C string (e.g. "%d") 6912 // ObjC string uses the same format specifiers as C string, so we can use 6913 // the same format string checking logic for both ObjC and C strings. 6914 UncoveredArgHandler UncoveredArg; 6915 StringLiteralCheckType CT = 6916 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6917 format_idx, firstDataArg, Type, CallType, 6918 /*IsFunctionCall*/ true, CheckedVarArgs, 6919 UncoveredArg, 6920 /*no string offset*/ llvm::APSInt(64, false) = 0); 6921 6922 // Generate a diagnostic where an uncovered argument is detected. 6923 if (UncoveredArg.hasUncoveredArg()) { 6924 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6925 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6926 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6927 } 6928 6929 if (CT != SLCT_NotALiteral) 6930 // Literal format string found, check done! 6931 return CT == SLCT_CheckedLiteral; 6932 6933 // Strftime is particular as it always uses a single 'time' argument, 6934 // so it is safe to pass a non-literal string. 6935 if (Type == FST_Strftime) 6936 return false; 6937 6938 // Do not emit diag when the string param is a macro expansion and the 6939 // format is either NSString or CFString. This is a hack to prevent 6940 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6941 // which are usually used in place of NS and CF string literals. 6942 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6943 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6944 return false; 6945 6946 // If there are no arguments specified, warn with -Wformat-security, otherwise 6947 // warn only with -Wformat-nonliteral. 6948 if (Args.size() == firstDataArg) { 6949 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6950 << OrigFormatExpr->getSourceRange(); 6951 switch (Type) { 6952 default: 6953 break; 6954 case FST_Kprintf: 6955 case FST_FreeBSDKPrintf: 6956 case FST_Printf: 6957 Diag(FormatLoc, diag::note_format_security_fixit) 6958 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6959 break; 6960 case FST_NSString: 6961 Diag(FormatLoc, diag::note_format_security_fixit) 6962 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6963 break; 6964 } 6965 } else { 6966 Diag(FormatLoc, diag::warn_format_nonliteral) 6967 << OrigFormatExpr->getSourceRange(); 6968 } 6969 return false; 6970 } 6971 6972 namespace { 6973 6974 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6975 protected: 6976 Sema &S; 6977 const FormatStringLiteral *FExpr; 6978 const Expr *OrigFormatExpr; 6979 const Sema::FormatStringType FSType; 6980 const unsigned FirstDataArg; 6981 const unsigned NumDataArgs; 6982 const char *Beg; // Start of format string. 6983 const bool HasVAListArg; 6984 ArrayRef<const Expr *> Args; 6985 unsigned FormatIdx; 6986 llvm::SmallBitVector CoveredArgs; 6987 bool usesPositionalArgs = false; 6988 bool atFirstArg = true; 6989 bool inFunctionCall; 6990 Sema::VariadicCallType CallType; 6991 llvm::SmallBitVector &CheckedVarArgs; 6992 UncoveredArgHandler &UncoveredArg; 6993 6994 public: 6995 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6996 const Expr *origFormatExpr, 6997 const Sema::FormatStringType type, unsigned firstDataArg, 6998 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6999 ArrayRef<const Expr *> Args, unsigned formatIdx, 7000 bool inFunctionCall, Sema::VariadicCallType callType, 7001 llvm::SmallBitVector &CheckedVarArgs, 7002 UncoveredArgHandler &UncoveredArg) 7003 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7004 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7005 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7006 inFunctionCall(inFunctionCall), CallType(callType), 7007 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7008 CoveredArgs.resize(numDataArgs); 7009 CoveredArgs.reset(); 7010 } 7011 7012 void DoneProcessing(); 7013 7014 void HandleIncompleteSpecifier(const char *startSpecifier, 7015 unsigned specifierLen) override; 7016 7017 void HandleInvalidLengthModifier( 7018 const analyze_format_string::FormatSpecifier &FS, 7019 const analyze_format_string::ConversionSpecifier &CS, 7020 const char *startSpecifier, unsigned specifierLen, 7021 unsigned DiagID); 7022 7023 void HandleNonStandardLengthModifier( 7024 const analyze_format_string::FormatSpecifier &FS, 7025 const char *startSpecifier, unsigned specifierLen); 7026 7027 void HandleNonStandardConversionSpecifier( 7028 const analyze_format_string::ConversionSpecifier &CS, 7029 const char *startSpecifier, unsigned specifierLen); 7030 7031 void HandlePosition(const char *startPos, unsigned posLen) override; 7032 7033 void HandleInvalidPosition(const char *startSpecifier, 7034 unsigned specifierLen, 7035 analyze_format_string::PositionContext p) override; 7036 7037 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7038 7039 void HandleNullChar(const char *nullCharacter) override; 7040 7041 template <typename Range> 7042 static void 7043 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7044 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7045 bool IsStringLocation, Range StringRange, 7046 ArrayRef<FixItHint> Fixit = None); 7047 7048 protected: 7049 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7050 const char *startSpec, 7051 unsigned specifierLen, 7052 const char *csStart, unsigned csLen); 7053 7054 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7055 const char *startSpec, 7056 unsigned specifierLen); 7057 7058 SourceRange getFormatStringRange(); 7059 CharSourceRange getSpecifierRange(const char *startSpecifier, 7060 unsigned specifierLen); 7061 SourceLocation getLocationOfByte(const char *x); 7062 7063 const Expr *getDataArg(unsigned i) const; 7064 7065 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7066 const analyze_format_string::ConversionSpecifier &CS, 7067 const char *startSpecifier, unsigned specifierLen, 7068 unsigned argIndex); 7069 7070 template <typename Range> 7071 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7072 bool IsStringLocation, Range StringRange, 7073 ArrayRef<FixItHint> Fixit = None); 7074 }; 7075 7076 } // namespace 7077 7078 SourceRange CheckFormatHandler::getFormatStringRange() { 7079 return OrigFormatExpr->getSourceRange(); 7080 } 7081 7082 CharSourceRange CheckFormatHandler:: 7083 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7084 SourceLocation Start = getLocationOfByte(startSpecifier); 7085 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7086 7087 // Advance the end SourceLocation by one due to half-open ranges. 7088 End = End.getLocWithOffset(1); 7089 7090 return CharSourceRange::getCharRange(Start, End); 7091 } 7092 7093 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7094 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7095 S.getLangOpts(), S.Context.getTargetInfo()); 7096 } 7097 7098 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7099 unsigned specifierLen){ 7100 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7101 getLocationOfByte(startSpecifier), 7102 /*IsStringLocation*/true, 7103 getSpecifierRange(startSpecifier, specifierLen)); 7104 } 7105 7106 void CheckFormatHandler::HandleInvalidLengthModifier( 7107 const analyze_format_string::FormatSpecifier &FS, 7108 const analyze_format_string::ConversionSpecifier &CS, 7109 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7110 using namespace analyze_format_string; 7111 7112 const LengthModifier &LM = FS.getLengthModifier(); 7113 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7114 7115 // See if we know how to fix this length modifier. 7116 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7117 if (FixedLM) { 7118 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7119 getLocationOfByte(LM.getStart()), 7120 /*IsStringLocation*/true, 7121 getSpecifierRange(startSpecifier, specifierLen)); 7122 7123 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7124 << FixedLM->toString() 7125 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7126 7127 } else { 7128 FixItHint Hint; 7129 if (DiagID == diag::warn_format_nonsensical_length) 7130 Hint = FixItHint::CreateRemoval(LMRange); 7131 7132 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7133 getLocationOfByte(LM.getStart()), 7134 /*IsStringLocation*/true, 7135 getSpecifierRange(startSpecifier, specifierLen), 7136 Hint); 7137 } 7138 } 7139 7140 void CheckFormatHandler::HandleNonStandardLengthModifier( 7141 const analyze_format_string::FormatSpecifier &FS, 7142 const char *startSpecifier, unsigned specifierLen) { 7143 using namespace analyze_format_string; 7144 7145 const LengthModifier &LM = FS.getLengthModifier(); 7146 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7147 7148 // See if we know how to fix this length modifier. 7149 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7150 if (FixedLM) { 7151 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7152 << LM.toString() << 0, 7153 getLocationOfByte(LM.getStart()), 7154 /*IsStringLocation*/true, 7155 getSpecifierRange(startSpecifier, specifierLen)); 7156 7157 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7158 << FixedLM->toString() 7159 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7160 7161 } else { 7162 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7163 << LM.toString() << 0, 7164 getLocationOfByte(LM.getStart()), 7165 /*IsStringLocation*/true, 7166 getSpecifierRange(startSpecifier, specifierLen)); 7167 } 7168 } 7169 7170 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7171 const analyze_format_string::ConversionSpecifier &CS, 7172 const char *startSpecifier, unsigned specifierLen) { 7173 using namespace analyze_format_string; 7174 7175 // See if we know how to fix this conversion specifier. 7176 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7177 if (FixedCS) { 7178 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7179 << CS.toString() << /*conversion specifier*/1, 7180 getLocationOfByte(CS.getStart()), 7181 /*IsStringLocation*/true, 7182 getSpecifierRange(startSpecifier, specifierLen)); 7183 7184 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7185 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7186 << FixedCS->toString() 7187 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7188 } else { 7189 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7190 << CS.toString() << /*conversion specifier*/1, 7191 getLocationOfByte(CS.getStart()), 7192 /*IsStringLocation*/true, 7193 getSpecifierRange(startSpecifier, specifierLen)); 7194 } 7195 } 7196 7197 void CheckFormatHandler::HandlePosition(const char *startPos, 7198 unsigned posLen) { 7199 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7200 getLocationOfByte(startPos), 7201 /*IsStringLocation*/true, 7202 getSpecifierRange(startPos, posLen)); 7203 } 7204 7205 void 7206 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7207 analyze_format_string::PositionContext p) { 7208 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7209 << (unsigned) p, 7210 getLocationOfByte(startPos), /*IsStringLocation*/true, 7211 getSpecifierRange(startPos, posLen)); 7212 } 7213 7214 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7215 unsigned posLen) { 7216 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7217 getLocationOfByte(startPos), 7218 /*IsStringLocation*/true, 7219 getSpecifierRange(startPos, posLen)); 7220 } 7221 7222 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7223 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7224 // The presence of a null character is likely an error. 7225 EmitFormatDiagnostic( 7226 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7227 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7228 getFormatStringRange()); 7229 } 7230 } 7231 7232 // Note that this may return NULL if there was an error parsing or building 7233 // one of the argument expressions. 7234 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7235 return Args[FirstDataArg + i]; 7236 } 7237 7238 void CheckFormatHandler::DoneProcessing() { 7239 // Does the number of data arguments exceed the number of 7240 // format conversions in the format string? 7241 if (!HasVAListArg) { 7242 // Find any arguments that weren't covered. 7243 CoveredArgs.flip(); 7244 signed notCoveredArg = CoveredArgs.find_first(); 7245 if (notCoveredArg >= 0) { 7246 assert((unsigned)notCoveredArg < NumDataArgs); 7247 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7248 } else { 7249 UncoveredArg.setAllCovered(); 7250 } 7251 } 7252 } 7253 7254 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7255 const Expr *ArgExpr) { 7256 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7257 "Invalid state"); 7258 7259 if (!ArgExpr) 7260 return; 7261 7262 SourceLocation Loc = ArgExpr->getBeginLoc(); 7263 7264 if (S.getSourceManager().isInSystemMacro(Loc)) 7265 return; 7266 7267 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7268 for (auto E : DiagnosticExprs) 7269 PDiag << E->getSourceRange(); 7270 7271 CheckFormatHandler::EmitFormatDiagnostic( 7272 S, IsFunctionCall, DiagnosticExprs[0], 7273 PDiag, Loc, /*IsStringLocation*/false, 7274 DiagnosticExprs[0]->getSourceRange()); 7275 } 7276 7277 bool 7278 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7279 SourceLocation Loc, 7280 const char *startSpec, 7281 unsigned specifierLen, 7282 const char *csStart, 7283 unsigned csLen) { 7284 bool keepGoing = true; 7285 if (argIndex < NumDataArgs) { 7286 // Consider the argument coverered, even though the specifier doesn't 7287 // make sense. 7288 CoveredArgs.set(argIndex); 7289 } 7290 else { 7291 // If argIndex exceeds the number of data arguments we 7292 // don't issue a warning because that is just a cascade of warnings (and 7293 // they may have intended '%%' anyway). We don't want to continue processing 7294 // the format string after this point, however, as we will like just get 7295 // gibberish when trying to match arguments. 7296 keepGoing = false; 7297 } 7298 7299 StringRef Specifier(csStart, csLen); 7300 7301 // If the specifier in non-printable, it could be the first byte of a UTF-8 7302 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7303 // hex value. 7304 std::string CodePointStr; 7305 if (!llvm::sys::locale::isPrint(*csStart)) { 7306 llvm::UTF32 CodePoint; 7307 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7308 const llvm::UTF8 *E = 7309 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7310 llvm::ConversionResult Result = 7311 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7312 7313 if (Result != llvm::conversionOK) { 7314 unsigned char FirstChar = *csStart; 7315 CodePoint = (llvm::UTF32)FirstChar; 7316 } 7317 7318 llvm::raw_string_ostream OS(CodePointStr); 7319 if (CodePoint < 256) 7320 OS << "\\x" << llvm::format("%02x", CodePoint); 7321 else if (CodePoint <= 0xFFFF) 7322 OS << "\\u" << llvm::format("%04x", CodePoint); 7323 else 7324 OS << "\\U" << llvm::format("%08x", CodePoint); 7325 OS.flush(); 7326 Specifier = CodePointStr; 7327 } 7328 7329 EmitFormatDiagnostic( 7330 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7331 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7332 7333 return keepGoing; 7334 } 7335 7336 void 7337 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7338 const char *startSpec, 7339 unsigned specifierLen) { 7340 EmitFormatDiagnostic( 7341 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7342 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7343 } 7344 7345 bool 7346 CheckFormatHandler::CheckNumArgs( 7347 const analyze_format_string::FormatSpecifier &FS, 7348 const analyze_format_string::ConversionSpecifier &CS, 7349 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7350 7351 if (argIndex >= NumDataArgs) { 7352 PartialDiagnostic PDiag = FS.usesPositionalArg() 7353 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7354 << (argIndex+1) << NumDataArgs) 7355 : S.PDiag(diag::warn_printf_insufficient_data_args); 7356 EmitFormatDiagnostic( 7357 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7358 getSpecifierRange(startSpecifier, specifierLen)); 7359 7360 // Since more arguments than conversion tokens are given, by extension 7361 // all arguments are covered, so mark this as so. 7362 UncoveredArg.setAllCovered(); 7363 return false; 7364 } 7365 return true; 7366 } 7367 7368 template<typename Range> 7369 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7370 SourceLocation Loc, 7371 bool IsStringLocation, 7372 Range StringRange, 7373 ArrayRef<FixItHint> FixIt) { 7374 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7375 Loc, IsStringLocation, StringRange, FixIt); 7376 } 7377 7378 /// If the format string is not within the function call, emit a note 7379 /// so that the function call and string are in diagnostic messages. 7380 /// 7381 /// \param InFunctionCall if true, the format string is within the function 7382 /// call and only one diagnostic message will be produced. Otherwise, an 7383 /// extra note will be emitted pointing to location of the format string. 7384 /// 7385 /// \param ArgumentExpr the expression that is passed as the format string 7386 /// argument in the function call. Used for getting locations when two 7387 /// diagnostics are emitted. 7388 /// 7389 /// \param PDiag the callee should already have provided any strings for the 7390 /// diagnostic message. This function only adds locations and fixits 7391 /// to diagnostics. 7392 /// 7393 /// \param Loc primary location for diagnostic. If two diagnostics are 7394 /// required, one will be at Loc and a new SourceLocation will be created for 7395 /// the other one. 7396 /// 7397 /// \param IsStringLocation if true, Loc points to the format string should be 7398 /// used for the note. Otherwise, Loc points to the argument list and will 7399 /// be used with PDiag. 7400 /// 7401 /// \param StringRange some or all of the string to highlight. This is 7402 /// templated so it can accept either a CharSourceRange or a SourceRange. 7403 /// 7404 /// \param FixIt optional fix it hint for the format string. 7405 template <typename Range> 7406 void CheckFormatHandler::EmitFormatDiagnostic( 7407 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7408 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7409 Range StringRange, ArrayRef<FixItHint> FixIt) { 7410 if (InFunctionCall) { 7411 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7412 D << StringRange; 7413 D << FixIt; 7414 } else { 7415 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7416 << ArgumentExpr->getSourceRange(); 7417 7418 const Sema::SemaDiagnosticBuilder &Note = 7419 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7420 diag::note_format_string_defined); 7421 7422 Note << StringRange; 7423 Note << FixIt; 7424 } 7425 } 7426 7427 //===--- CHECK: Printf format string checking ------------------------------===// 7428 7429 namespace { 7430 7431 class CheckPrintfHandler : public CheckFormatHandler { 7432 public: 7433 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7434 const Expr *origFormatExpr, 7435 const Sema::FormatStringType type, unsigned firstDataArg, 7436 unsigned numDataArgs, bool isObjC, const char *beg, 7437 bool hasVAListArg, ArrayRef<const Expr *> Args, 7438 unsigned formatIdx, bool inFunctionCall, 7439 Sema::VariadicCallType CallType, 7440 llvm::SmallBitVector &CheckedVarArgs, 7441 UncoveredArgHandler &UncoveredArg) 7442 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7443 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7444 inFunctionCall, CallType, CheckedVarArgs, 7445 UncoveredArg) {} 7446 7447 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7448 7449 /// Returns true if '%@' specifiers are allowed in the format string. 7450 bool allowsObjCArg() const { 7451 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7452 FSType == Sema::FST_OSTrace; 7453 } 7454 7455 bool HandleInvalidPrintfConversionSpecifier( 7456 const analyze_printf::PrintfSpecifier &FS, 7457 const char *startSpecifier, 7458 unsigned specifierLen) override; 7459 7460 void handleInvalidMaskType(StringRef MaskType) override; 7461 7462 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7463 const char *startSpecifier, 7464 unsigned specifierLen) override; 7465 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7466 const char *StartSpecifier, 7467 unsigned SpecifierLen, 7468 const Expr *E); 7469 7470 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7471 const char *startSpecifier, unsigned specifierLen); 7472 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7473 const analyze_printf::OptionalAmount &Amt, 7474 unsigned type, 7475 const char *startSpecifier, unsigned specifierLen); 7476 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7477 const analyze_printf::OptionalFlag &flag, 7478 const char *startSpecifier, unsigned specifierLen); 7479 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7480 const analyze_printf::OptionalFlag &ignoredFlag, 7481 const analyze_printf::OptionalFlag &flag, 7482 const char *startSpecifier, unsigned specifierLen); 7483 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7484 const Expr *E); 7485 7486 void HandleEmptyObjCModifierFlag(const char *startFlag, 7487 unsigned flagLen) override; 7488 7489 void HandleInvalidObjCModifierFlag(const char *startFlag, 7490 unsigned flagLen) override; 7491 7492 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7493 const char *flagsEnd, 7494 const char *conversionPosition) 7495 override; 7496 }; 7497 7498 } // namespace 7499 7500 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7501 const analyze_printf::PrintfSpecifier &FS, 7502 const char *startSpecifier, 7503 unsigned specifierLen) { 7504 const analyze_printf::PrintfConversionSpecifier &CS = 7505 FS.getConversionSpecifier(); 7506 7507 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7508 getLocationOfByte(CS.getStart()), 7509 startSpecifier, specifierLen, 7510 CS.getStart(), CS.getLength()); 7511 } 7512 7513 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7514 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7515 } 7516 7517 bool CheckPrintfHandler::HandleAmount( 7518 const analyze_format_string::OptionalAmount &Amt, 7519 unsigned k, const char *startSpecifier, 7520 unsigned specifierLen) { 7521 if (Amt.hasDataArgument()) { 7522 if (!HasVAListArg) { 7523 unsigned argIndex = Amt.getArgIndex(); 7524 if (argIndex >= NumDataArgs) { 7525 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7526 << k, 7527 getLocationOfByte(Amt.getStart()), 7528 /*IsStringLocation*/true, 7529 getSpecifierRange(startSpecifier, specifierLen)); 7530 // Don't do any more checking. We will just emit 7531 // spurious errors. 7532 return false; 7533 } 7534 7535 // Type check the data argument. It should be an 'int'. 7536 // Although not in conformance with C99, we also allow the argument to be 7537 // an 'unsigned int' as that is a reasonably safe case. GCC also 7538 // doesn't emit a warning for that case. 7539 CoveredArgs.set(argIndex); 7540 const Expr *Arg = getDataArg(argIndex); 7541 if (!Arg) 7542 return false; 7543 7544 QualType T = Arg->getType(); 7545 7546 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7547 assert(AT.isValid()); 7548 7549 if (!AT.matchesType(S.Context, T)) { 7550 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7551 << k << AT.getRepresentativeTypeName(S.Context) 7552 << T << Arg->getSourceRange(), 7553 getLocationOfByte(Amt.getStart()), 7554 /*IsStringLocation*/true, 7555 getSpecifierRange(startSpecifier, specifierLen)); 7556 // Don't do any more checking. We will just emit 7557 // spurious errors. 7558 return false; 7559 } 7560 } 7561 } 7562 return true; 7563 } 7564 7565 void CheckPrintfHandler::HandleInvalidAmount( 7566 const analyze_printf::PrintfSpecifier &FS, 7567 const analyze_printf::OptionalAmount &Amt, 7568 unsigned type, 7569 const char *startSpecifier, 7570 unsigned specifierLen) { 7571 const analyze_printf::PrintfConversionSpecifier &CS = 7572 FS.getConversionSpecifier(); 7573 7574 FixItHint fixit = 7575 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7576 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7577 Amt.getConstantLength())) 7578 : FixItHint(); 7579 7580 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7581 << type << CS.toString(), 7582 getLocationOfByte(Amt.getStart()), 7583 /*IsStringLocation*/true, 7584 getSpecifierRange(startSpecifier, specifierLen), 7585 fixit); 7586 } 7587 7588 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7589 const analyze_printf::OptionalFlag &flag, 7590 const char *startSpecifier, 7591 unsigned specifierLen) { 7592 // Warn about pointless flag with a fixit removal. 7593 const analyze_printf::PrintfConversionSpecifier &CS = 7594 FS.getConversionSpecifier(); 7595 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7596 << flag.toString() << CS.toString(), 7597 getLocationOfByte(flag.getPosition()), 7598 /*IsStringLocation*/true, 7599 getSpecifierRange(startSpecifier, specifierLen), 7600 FixItHint::CreateRemoval( 7601 getSpecifierRange(flag.getPosition(), 1))); 7602 } 7603 7604 void CheckPrintfHandler::HandleIgnoredFlag( 7605 const analyze_printf::PrintfSpecifier &FS, 7606 const analyze_printf::OptionalFlag &ignoredFlag, 7607 const analyze_printf::OptionalFlag &flag, 7608 const char *startSpecifier, 7609 unsigned specifierLen) { 7610 // Warn about ignored flag with a fixit removal. 7611 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7612 << ignoredFlag.toString() << flag.toString(), 7613 getLocationOfByte(ignoredFlag.getPosition()), 7614 /*IsStringLocation*/true, 7615 getSpecifierRange(startSpecifier, specifierLen), 7616 FixItHint::CreateRemoval( 7617 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7618 } 7619 7620 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7621 unsigned flagLen) { 7622 // Warn about an empty flag. 7623 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7624 getLocationOfByte(startFlag), 7625 /*IsStringLocation*/true, 7626 getSpecifierRange(startFlag, flagLen)); 7627 } 7628 7629 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7630 unsigned flagLen) { 7631 // Warn about an invalid flag. 7632 auto Range = getSpecifierRange(startFlag, flagLen); 7633 StringRef flag(startFlag, flagLen); 7634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7635 getLocationOfByte(startFlag), 7636 /*IsStringLocation*/true, 7637 Range, FixItHint::CreateRemoval(Range)); 7638 } 7639 7640 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7641 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7642 // Warn about using '[...]' without a '@' conversion. 7643 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7644 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7645 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7646 getLocationOfByte(conversionPosition), 7647 /*IsStringLocation*/true, 7648 Range, FixItHint::CreateRemoval(Range)); 7649 } 7650 7651 // Determines if the specified is a C++ class or struct containing 7652 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7653 // "c_str()"). 7654 template<typename MemberKind> 7655 static llvm::SmallPtrSet<MemberKind*, 1> 7656 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7657 const RecordType *RT = Ty->getAs<RecordType>(); 7658 llvm::SmallPtrSet<MemberKind*, 1> Results; 7659 7660 if (!RT) 7661 return Results; 7662 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7663 if (!RD || !RD->getDefinition()) 7664 return Results; 7665 7666 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7667 Sema::LookupMemberName); 7668 R.suppressDiagnostics(); 7669 7670 // We just need to include all members of the right kind turned up by the 7671 // filter, at this point. 7672 if (S.LookupQualifiedName(R, RT->getDecl())) 7673 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7674 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7675 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7676 Results.insert(FK); 7677 } 7678 return Results; 7679 } 7680 7681 /// Check if we could call '.c_str()' on an object. 7682 /// 7683 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7684 /// allow the call, or if it would be ambiguous). 7685 bool Sema::hasCStrMethod(const Expr *E) { 7686 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7687 7688 MethodSet Results = 7689 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7690 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7691 MI != ME; ++MI) 7692 if ((*MI)->getMinRequiredArguments() == 0) 7693 return true; 7694 return false; 7695 } 7696 7697 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7698 // better diagnostic if so. AT is assumed to be valid. 7699 // Returns true when a c_str() conversion method is found. 7700 bool CheckPrintfHandler::checkForCStrMembers( 7701 const analyze_printf::ArgType &AT, const Expr *E) { 7702 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7703 7704 MethodSet Results = 7705 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7706 7707 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7708 MI != ME; ++MI) { 7709 const CXXMethodDecl *Method = *MI; 7710 if (Method->getMinRequiredArguments() == 0 && 7711 AT.matchesType(S.Context, Method->getReturnType())) { 7712 // FIXME: Suggest parens if the expression needs them. 7713 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7714 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7715 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7716 return true; 7717 } 7718 } 7719 7720 return false; 7721 } 7722 7723 bool 7724 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7725 &FS, 7726 const char *startSpecifier, 7727 unsigned specifierLen) { 7728 using namespace analyze_format_string; 7729 using namespace analyze_printf; 7730 7731 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7732 7733 if (FS.consumesDataArgument()) { 7734 if (atFirstArg) { 7735 atFirstArg = false; 7736 usesPositionalArgs = FS.usesPositionalArg(); 7737 } 7738 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7739 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7740 startSpecifier, specifierLen); 7741 return false; 7742 } 7743 } 7744 7745 // First check if the field width, precision, and conversion specifier 7746 // have matching data arguments. 7747 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7748 startSpecifier, specifierLen)) { 7749 return false; 7750 } 7751 7752 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7753 startSpecifier, specifierLen)) { 7754 return false; 7755 } 7756 7757 if (!CS.consumesDataArgument()) { 7758 // FIXME: Technically specifying a precision or field width here 7759 // makes no sense. Worth issuing a warning at some point. 7760 return true; 7761 } 7762 7763 // Consume the argument. 7764 unsigned argIndex = FS.getArgIndex(); 7765 if (argIndex < NumDataArgs) { 7766 // The check to see if the argIndex is valid will come later. 7767 // We set the bit here because we may exit early from this 7768 // function if we encounter some other error. 7769 CoveredArgs.set(argIndex); 7770 } 7771 7772 // FreeBSD kernel extensions. 7773 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7774 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7775 // We need at least two arguments. 7776 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7777 return false; 7778 7779 // Claim the second argument. 7780 CoveredArgs.set(argIndex + 1); 7781 7782 // Type check the first argument (int for %b, pointer for %D) 7783 const Expr *Ex = getDataArg(argIndex); 7784 const analyze_printf::ArgType &AT = 7785 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7786 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7787 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7788 EmitFormatDiagnostic( 7789 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7790 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7791 << false << Ex->getSourceRange(), 7792 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7793 getSpecifierRange(startSpecifier, specifierLen)); 7794 7795 // Type check the second argument (char * for both %b and %D) 7796 Ex = getDataArg(argIndex + 1); 7797 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7798 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7799 EmitFormatDiagnostic( 7800 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7801 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7802 << false << Ex->getSourceRange(), 7803 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7804 getSpecifierRange(startSpecifier, specifierLen)); 7805 7806 return true; 7807 } 7808 7809 // Check for using an Objective-C specific conversion specifier 7810 // in a non-ObjC literal. 7811 if (!allowsObjCArg() && CS.isObjCArg()) { 7812 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7813 specifierLen); 7814 } 7815 7816 // %P can only be used with os_log. 7817 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7818 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7819 specifierLen); 7820 } 7821 7822 // %n is not allowed with os_log. 7823 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7824 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7825 getLocationOfByte(CS.getStart()), 7826 /*IsStringLocation*/ false, 7827 getSpecifierRange(startSpecifier, specifierLen)); 7828 7829 return true; 7830 } 7831 7832 // Only scalars are allowed for os_trace. 7833 if (FSType == Sema::FST_OSTrace && 7834 (CS.getKind() == ConversionSpecifier::PArg || 7835 CS.getKind() == ConversionSpecifier::sArg || 7836 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7837 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7838 specifierLen); 7839 } 7840 7841 // Check for use of public/private annotation outside of os_log(). 7842 if (FSType != Sema::FST_OSLog) { 7843 if (FS.isPublic().isSet()) { 7844 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7845 << "public", 7846 getLocationOfByte(FS.isPublic().getPosition()), 7847 /*IsStringLocation*/ false, 7848 getSpecifierRange(startSpecifier, specifierLen)); 7849 } 7850 if (FS.isPrivate().isSet()) { 7851 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7852 << "private", 7853 getLocationOfByte(FS.isPrivate().getPosition()), 7854 /*IsStringLocation*/ false, 7855 getSpecifierRange(startSpecifier, specifierLen)); 7856 } 7857 } 7858 7859 // Check for invalid use of field width 7860 if (!FS.hasValidFieldWidth()) { 7861 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7862 startSpecifier, specifierLen); 7863 } 7864 7865 // Check for invalid use of precision 7866 if (!FS.hasValidPrecision()) { 7867 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7868 startSpecifier, specifierLen); 7869 } 7870 7871 // Precision is mandatory for %P specifier. 7872 if (CS.getKind() == ConversionSpecifier::PArg && 7873 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7874 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7875 getLocationOfByte(startSpecifier), 7876 /*IsStringLocation*/ false, 7877 getSpecifierRange(startSpecifier, specifierLen)); 7878 } 7879 7880 // Check each flag does not conflict with any other component. 7881 if (!FS.hasValidThousandsGroupingPrefix()) 7882 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7883 if (!FS.hasValidLeadingZeros()) 7884 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7885 if (!FS.hasValidPlusPrefix()) 7886 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7887 if (!FS.hasValidSpacePrefix()) 7888 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7889 if (!FS.hasValidAlternativeForm()) 7890 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7891 if (!FS.hasValidLeftJustified()) 7892 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7893 7894 // Check that flags are not ignored by another flag 7895 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7896 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7897 startSpecifier, specifierLen); 7898 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7899 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7900 startSpecifier, specifierLen); 7901 7902 // Check the length modifier is valid with the given conversion specifier. 7903 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7904 S.getLangOpts())) 7905 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7906 diag::warn_format_nonsensical_length); 7907 else if (!FS.hasStandardLengthModifier()) 7908 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7909 else if (!FS.hasStandardLengthConversionCombination()) 7910 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7911 diag::warn_format_non_standard_conversion_spec); 7912 7913 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7914 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7915 7916 // The remaining checks depend on the data arguments. 7917 if (HasVAListArg) 7918 return true; 7919 7920 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7921 return false; 7922 7923 const Expr *Arg = getDataArg(argIndex); 7924 if (!Arg) 7925 return true; 7926 7927 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7928 } 7929 7930 static bool requiresParensToAddCast(const Expr *E) { 7931 // FIXME: We should have a general way to reason about operator 7932 // precedence and whether parens are actually needed here. 7933 // Take care of a few common cases where they aren't. 7934 const Expr *Inside = E->IgnoreImpCasts(); 7935 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7936 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7937 7938 switch (Inside->getStmtClass()) { 7939 case Stmt::ArraySubscriptExprClass: 7940 case Stmt::CallExprClass: 7941 case Stmt::CharacterLiteralClass: 7942 case Stmt::CXXBoolLiteralExprClass: 7943 case Stmt::DeclRefExprClass: 7944 case Stmt::FloatingLiteralClass: 7945 case Stmt::IntegerLiteralClass: 7946 case Stmt::MemberExprClass: 7947 case Stmt::ObjCArrayLiteralClass: 7948 case Stmt::ObjCBoolLiteralExprClass: 7949 case Stmt::ObjCBoxedExprClass: 7950 case Stmt::ObjCDictionaryLiteralClass: 7951 case Stmt::ObjCEncodeExprClass: 7952 case Stmt::ObjCIvarRefExprClass: 7953 case Stmt::ObjCMessageExprClass: 7954 case Stmt::ObjCPropertyRefExprClass: 7955 case Stmt::ObjCStringLiteralClass: 7956 case Stmt::ObjCSubscriptRefExprClass: 7957 case Stmt::ParenExprClass: 7958 case Stmt::StringLiteralClass: 7959 case Stmt::UnaryOperatorClass: 7960 return false; 7961 default: 7962 return true; 7963 } 7964 } 7965 7966 static std::pair<QualType, StringRef> 7967 shouldNotPrintDirectly(const ASTContext &Context, 7968 QualType IntendedTy, 7969 const Expr *E) { 7970 // Use a 'while' to peel off layers of typedefs. 7971 QualType TyTy = IntendedTy; 7972 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7973 StringRef Name = UserTy->getDecl()->getName(); 7974 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7975 .Case("CFIndex", Context.getNSIntegerType()) 7976 .Case("NSInteger", Context.getNSIntegerType()) 7977 .Case("NSUInteger", Context.getNSUIntegerType()) 7978 .Case("SInt32", Context.IntTy) 7979 .Case("UInt32", Context.UnsignedIntTy) 7980 .Default(QualType()); 7981 7982 if (!CastTy.isNull()) 7983 return std::make_pair(CastTy, Name); 7984 7985 TyTy = UserTy->desugar(); 7986 } 7987 7988 // Strip parens if necessary. 7989 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7990 return shouldNotPrintDirectly(Context, 7991 PE->getSubExpr()->getType(), 7992 PE->getSubExpr()); 7993 7994 // If this is a conditional expression, then its result type is constructed 7995 // via usual arithmetic conversions and thus there might be no necessary 7996 // typedef sugar there. Recurse to operands to check for NSInteger & 7997 // Co. usage condition. 7998 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7999 QualType TrueTy, FalseTy; 8000 StringRef TrueName, FalseName; 8001 8002 std::tie(TrueTy, TrueName) = 8003 shouldNotPrintDirectly(Context, 8004 CO->getTrueExpr()->getType(), 8005 CO->getTrueExpr()); 8006 std::tie(FalseTy, FalseName) = 8007 shouldNotPrintDirectly(Context, 8008 CO->getFalseExpr()->getType(), 8009 CO->getFalseExpr()); 8010 8011 if (TrueTy == FalseTy) 8012 return std::make_pair(TrueTy, TrueName); 8013 else if (TrueTy.isNull()) 8014 return std::make_pair(FalseTy, FalseName); 8015 else if (FalseTy.isNull()) 8016 return std::make_pair(TrueTy, TrueName); 8017 } 8018 8019 return std::make_pair(QualType(), StringRef()); 8020 } 8021 8022 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8023 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8024 /// type do not count. 8025 static bool 8026 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8027 QualType From = ICE->getSubExpr()->getType(); 8028 QualType To = ICE->getType(); 8029 // It's an integer promotion if the destination type is the promoted 8030 // source type. 8031 if (ICE->getCastKind() == CK_IntegralCast && 8032 From->isPromotableIntegerType() && 8033 S.Context.getPromotedIntegerType(From) == To) 8034 return true; 8035 // Look through vector types, since we do default argument promotion for 8036 // those in OpenCL. 8037 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8038 From = VecTy->getElementType(); 8039 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8040 To = VecTy->getElementType(); 8041 // It's a floating promotion if the source type is a lower rank. 8042 return ICE->getCastKind() == CK_FloatingCast && 8043 S.Context.getFloatingTypeOrder(From, To) < 0; 8044 } 8045 8046 bool 8047 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8048 const char *StartSpecifier, 8049 unsigned SpecifierLen, 8050 const Expr *E) { 8051 using namespace analyze_format_string; 8052 using namespace analyze_printf; 8053 8054 // Now type check the data expression that matches the 8055 // format specifier. 8056 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8057 if (!AT.isValid()) 8058 return true; 8059 8060 QualType ExprTy = E->getType(); 8061 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8062 ExprTy = TET->getUnderlyingExpr()->getType(); 8063 } 8064 8065 // Diagnose attempts to print a boolean value as a character. Unlike other 8066 // -Wformat diagnostics, this is fine from a type perspective, but it still 8067 // doesn't make sense. 8068 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8069 E->isKnownToHaveBooleanValue()) { 8070 const CharSourceRange &CSR = 8071 getSpecifierRange(StartSpecifier, SpecifierLen); 8072 SmallString<4> FSString; 8073 llvm::raw_svector_ostream os(FSString); 8074 FS.toString(os); 8075 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8076 << FSString, 8077 E->getExprLoc(), false, CSR); 8078 return true; 8079 } 8080 8081 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8082 if (Match == analyze_printf::ArgType::Match) 8083 return true; 8084 8085 // Look through argument promotions for our error message's reported type. 8086 // This includes the integral and floating promotions, but excludes array 8087 // and function pointer decay (seeing that an argument intended to be a 8088 // string has type 'char [6]' is probably more confusing than 'char *') and 8089 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8090 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8091 if (isArithmeticArgumentPromotion(S, ICE)) { 8092 E = ICE->getSubExpr(); 8093 ExprTy = E->getType(); 8094 8095 // Check if we didn't match because of an implicit cast from a 'char' 8096 // or 'short' to an 'int'. This is done because printf is a varargs 8097 // function. 8098 if (ICE->getType() == S.Context.IntTy || 8099 ICE->getType() == S.Context.UnsignedIntTy) { 8100 // All further checking is done on the subexpression 8101 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8102 AT.matchesType(S.Context, ExprTy); 8103 if (ImplicitMatch == analyze_printf::ArgType::Match) 8104 return true; 8105 if (ImplicitMatch == ArgType::NoMatchPedantic || 8106 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8107 Match = ImplicitMatch; 8108 } 8109 } 8110 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8111 // Special case for 'a', which has type 'int' in C. 8112 // Note, however, that we do /not/ want to treat multibyte constants like 8113 // 'MooV' as characters! This form is deprecated but still exists. 8114 if (ExprTy == S.Context.IntTy) 8115 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8116 ExprTy = S.Context.CharTy; 8117 } 8118 8119 // Look through enums to their underlying type. 8120 bool IsEnum = false; 8121 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8122 ExprTy = EnumTy->getDecl()->getIntegerType(); 8123 IsEnum = true; 8124 } 8125 8126 // %C in an Objective-C context prints a unichar, not a wchar_t. 8127 // If the argument is an integer of some kind, believe the %C and suggest 8128 // a cast instead of changing the conversion specifier. 8129 QualType IntendedTy = ExprTy; 8130 if (isObjCContext() && 8131 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8132 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8133 !ExprTy->isCharType()) { 8134 // 'unichar' is defined as a typedef of unsigned short, but we should 8135 // prefer using the typedef if it is visible. 8136 IntendedTy = S.Context.UnsignedShortTy; 8137 8138 // While we are here, check if the value is an IntegerLiteral that happens 8139 // to be within the valid range. 8140 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8141 const llvm::APInt &V = IL->getValue(); 8142 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8143 return true; 8144 } 8145 8146 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8147 Sema::LookupOrdinaryName); 8148 if (S.LookupName(Result, S.getCurScope())) { 8149 NamedDecl *ND = Result.getFoundDecl(); 8150 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8151 if (TD->getUnderlyingType() == IntendedTy) 8152 IntendedTy = S.Context.getTypedefType(TD); 8153 } 8154 } 8155 } 8156 8157 // Special-case some of Darwin's platform-independence types by suggesting 8158 // casts to primitive types that are known to be large enough. 8159 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8160 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8161 QualType CastTy; 8162 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8163 if (!CastTy.isNull()) { 8164 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8165 // (long in ASTContext). Only complain to pedants. 8166 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8167 (AT.isSizeT() || AT.isPtrdiffT()) && 8168 AT.matchesType(S.Context, CastTy)) 8169 Match = ArgType::NoMatchPedantic; 8170 IntendedTy = CastTy; 8171 ShouldNotPrintDirectly = true; 8172 } 8173 } 8174 8175 // We may be able to offer a FixItHint if it is a supported type. 8176 PrintfSpecifier fixedFS = FS; 8177 bool Success = 8178 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8179 8180 if (Success) { 8181 // Get the fix string from the fixed format specifier 8182 SmallString<16> buf; 8183 llvm::raw_svector_ostream os(buf); 8184 fixedFS.toString(os); 8185 8186 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8187 8188 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8189 unsigned Diag; 8190 switch (Match) { 8191 case ArgType::Match: llvm_unreachable("expected non-matching"); 8192 case ArgType::NoMatchPedantic: 8193 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8194 break; 8195 case ArgType::NoMatchTypeConfusion: 8196 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8197 break; 8198 case ArgType::NoMatch: 8199 Diag = diag::warn_format_conversion_argument_type_mismatch; 8200 break; 8201 } 8202 8203 // In this case, the specifier is wrong and should be changed to match 8204 // the argument. 8205 EmitFormatDiagnostic(S.PDiag(Diag) 8206 << AT.getRepresentativeTypeName(S.Context) 8207 << IntendedTy << IsEnum << E->getSourceRange(), 8208 E->getBeginLoc(), 8209 /*IsStringLocation*/ false, SpecRange, 8210 FixItHint::CreateReplacement(SpecRange, os.str())); 8211 } else { 8212 // The canonical type for formatting this value is different from the 8213 // actual type of the expression. (This occurs, for example, with Darwin's 8214 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8215 // should be printed as 'long' for 64-bit compatibility.) 8216 // Rather than emitting a normal format/argument mismatch, we want to 8217 // add a cast to the recommended type (and correct the format string 8218 // if necessary). 8219 SmallString<16> CastBuf; 8220 llvm::raw_svector_ostream CastFix(CastBuf); 8221 CastFix << "("; 8222 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8223 CastFix << ")"; 8224 8225 SmallVector<FixItHint,4> Hints; 8226 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8227 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8228 8229 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8230 // If there's already a cast present, just replace it. 8231 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8232 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8233 8234 } else if (!requiresParensToAddCast(E)) { 8235 // If the expression has high enough precedence, 8236 // just write the C-style cast. 8237 Hints.push_back( 8238 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8239 } else { 8240 // Otherwise, add parens around the expression as well as the cast. 8241 CastFix << "("; 8242 Hints.push_back( 8243 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8244 8245 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8246 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8247 } 8248 8249 if (ShouldNotPrintDirectly) { 8250 // The expression has a type that should not be printed directly. 8251 // We extract the name from the typedef because we don't want to show 8252 // the underlying type in the diagnostic. 8253 StringRef Name; 8254 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8255 Name = TypedefTy->getDecl()->getName(); 8256 else 8257 Name = CastTyName; 8258 unsigned Diag = Match == ArgType::NoMatchPedantic 8259 ? diag::warn_format_argument_needs_cast_pedantic 8260 : diag::warn_format_argument_needs_cast; 8261 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8262 << E->getSourceRange(), 8263 E->getBeginLoc(), /*IsStringLocation=*/false, 8264 SpecRange, Hints); 8265 } else { 8266 // In this case, the expression could be printed using a different 8267 // specifier, but we've decided that the specifier is probably correct 8268 // and we should cast instead. Just use the normal warning message. 8269 EmitFormatDiagnostic( 8270 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8271 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8272 << E->getSourceRange(), 8273 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8274 } 8275 } 8276 } else { 8277 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8278 SpecifierLen); 8279 // Since the warning for passing non-POD types to variadic functions 8280 // was deferred until now, we emit a warning for non-POD 8281 // arguments here. 8282 switch (S.isValidVarArgType(ExprTy)) { 8283 case Sema::VAK_Valid: 8284 case Sema::VAK_ValidInCXX11: { 8285 unsigned Diag; 8286 switch (Match) { 8287 case ArgType::Match: llvm_unreachable("expected non-matching"); 8288 case ArgType::NoMatchPedantic: 8289 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8290 break; 8291 case ArgType::NoMatchTypeConfusion: 8292 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8293 break; 8294 case ArgType::NoMatch: 8295 Diag = diag::warn_format_conversion_argument_type_mismatch; 8296 break; 8297 } 8298 8299 EmitFormatDiagnostic( 8300 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8301 << IsEnum << CSR << E->getSourceRange(), 8302 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8303 break; 8304 } 8305 case Sema::VAK_Undefined: 8306 case Sema::VAK_MSVCUndefined: 8307 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8308 << S.getLangOpts().CPlusPlus11 << ExprTy 8309 << CallType 8310 << AT.getRepresentativeTypeName(S.Context) << CSR 8311 << E->getSourceRange(), 8312 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8313 checkForCStrMembers(AT, E); 8314 break; 8315 8316 case Sema::VAK_Invalid: 8317 if (ExprTy->isObjCObjectType()) 8318 EmitFormatDiagnostic( 8319 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8320 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8321 << AT.getRepresentativeTypeName(S.Context) << CSR 8322 << E->getSourceRange(), 8323 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8324 else 8325 // FIXME: If this is an initializer list, suggest removing the braces 8326 // or inserting a cast to the target type. 8327 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8328 << isa<InitListExpr>(E) << ExprTy << CallType 8329 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8330 break; 8331 } 8332 8333 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8334 "format string specifier index out of range"); 8335 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8336 } 8337 8338 return true; 8339 } 8340 8341 //===--- CHECK: Scanf format string checking ------------------------------===// 8342 8343 namespace { 8344 8345 class CheckScanfHandler : public CheckFormatHandler { 8346 public: 8347 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8348 const Expr *origFormatExpr, Sema::FormatStringType type, 8349 unsigned firstDataArg, unsigned numDataArgs, 8350 const char *beg, bool hasVAListArg, 8351 ArrayRef<const Expr *> Args, unsigned formatIdx, 8352 bool inFunctionCall, Sema::VariadicCallType CallType, 8353 llvm::SmallBitVector &CheckedVarArgs, 8354 UncoveredArgHandler &UncoveredArg) 8355 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8356 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8357 inFunctionCall, CallType, CheckedVarArgs, 8358 UncoveredArg) {} 8359 8360 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8361 const char *startSpecifier, 8362 unsigned specifierLen) override; 8363 8364 bool HandleInvalidScanfConversionSpecifier( 8365 const analyze_scanf::ScanfSpecifier &FS, 8366 const char *startSpecifier, 8367 unsigned specifierLen) override; 8368 8369 void HandleIncompleteScanList(const char *start, const char *end) override; 8370 }; 8371 8372 } // namespace 8373 8374 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8375 const char *end) { 8376 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8377 getLocationOfByte(end), /*IsStringLocation*/true, 8378 getSpecifierRange(start, end - start)); 8379 } 8380 8381 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8382 const analyze_scanf::ScanfSpecifier &FS, 8383 const char *startSpecifier, 8384 unsigned specifierLen) { 8385 const analyze_scanf::ScanfConversionSpecifier &CS = 8386 FS.getConversionSpecifier(); 8387 8388 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8389 getLocationOfByte(CS.getStart()), 8390 startSpecifier, specifierLen, 8391 CS.getStart(), CS.getLength()); 8392 } 8393 8394 bool CheckScanfHandler::HandleScanfSpecifier( 8395 const analyze_scanf::ScanfSpecifier &FS, 8396 const char *startSpecifier, 8397 unsigned specifierLen) { 8398 using namespace analyze_scanf; 8399 using namespace analyze_format_string; 8400 8401 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8402 8403 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8404 // be used to decide if we are using positional arguments consistently. 8405 if (FS.consumesDataArgument()) { 8406 if (atFirstArg) { 8407 atFirstArg = false; 8408 usesPositionalArgs = FS.usesPositionalArg(); 8409 } 8410 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8411 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8412 startSpecifier, specifierLen); 8413 return false; 8414 } 8415 } 8416 8417 // Check if the field with is non-zero. 8418 const OptionalAmount &Amt = FS.getFieldWidth(); 8419 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8420 if (Amt.getConstantAmount() == 0) { 8421 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8422 Amt.getConstantLength()); 8423 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8424 getLocationOfByte(Amt.getStart()), 8425 /*IsStringLocation*/true, R, 8426 FixItHint::CreateRemoval(R)); 8427 } 8428 } 8429 8430 if (!FS.consumesDataArgument()) { 8431 // FIXME: Technically specifying a precision or field width here 8432 // makes no sense. Worth issuing a warning at some point. 8433 return true; 8434 } 8435 8436 // Consume the argument. 8437 unsigned argIndex = FS.getArgIndex(); 8438 if (argIndex < NumDataArgs) { 8439 // The check to see if the argIndex is valid will come later. 8440 // We set the bit here because we may exit early from this 8441 // function if we encounter some other error. 8442 CoveredArgs.set(argIndex); 8443 } 8444 8445 // Check the length modifier is valid with the given conversion specifier. 8446 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8447 S.getLangOpts())) 8448 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8449 diag::warn_format_nonsensical_length); 8450 else if (!FS.hasStandardLengthModifier()) 8451 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8452 else if (!FS.hasStandardLengthConversionCombination()) 8453 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8454 diag::warn_format_non_standard_conversion_spec); 8455 8456 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8457 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8458 8459 // The remaining checks depend on the data arguments. 8460 if (HasVAListArg) 8461 return true; 8462 8463 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8464 return false; 8465 8466 // Check that the argument type matches the format specifier. 8467 const Expr *Ex = getDataArg(argIndex); 8468 if (!Ex) 8469 return true; 8470 8471 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8472 8473 if (!AT.isValid()) { 8474 return true; 8475 } 8476 8477 analyze_format_string::ArgType::MatchKind Match = 8478 AT.matchesType(S.Context, Ex->getType()); 8479 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8480 if (Match == analyze_format_string::ArgType::Match) 8481 return true; 8482 8483 ScanfSpecifier fixedFS = FS; 8484 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8485 S.getLangOpts(), S.Context); 8486 8487 unsigned Diag = 8488 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8489 : diag::warn_format_conversion_argument_type_mismatch; 8490 8491 if (Success) { 8492 // Get the fix string from the fixed format specifier. 8493 SmallString<128> buf; 8494 llvm::raw_svector_ostream os(buf); 8495 fixedFS.toString(os); 8496 8497 EmitFormatDiagnostic( 8498 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8499 << Ex->getType() << false << Ex->getSourceRange(), 8500 Ex->getBeginLoc(), 8501 /*IsStringLocation*/ false, 8502 getSpecifierRange(startSpecifier, specifierLen), 8503 FixItHint::CreateReplacement( 8504 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8505 } else { 8506 EmitFormatDiagnostic(S.PDiag(Diag) 8507 << AT.getRepresentativeTypeName(S.Context) 8508 << Ex->getType() << false << Ex->getSourceRange(), 8509 Ex->getBeginLoc(), 8510 /*IsStringLocation*/ false, 8511 getSpecifierRange(startSpecifier, specifierLen)); 8512 } 8513 8514 return true; 8515 } 8516 8517 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8518 const Expr *OrigFormatExpr, 8519 ArrayRef<const Expr *> Args, 8520 bool HasVAListArg, unsigned format_idx, 8521 unsigned firstDataArg, 8522 Sema::FormatStringType Type, 8523 bool inFunctionCall, 8524 Sema::VariadicCallType CallType, 8525 llvm::SmallBitVector &CheckedVarArgs, 8526 UncoveredArgHandler &UncoveredArg, 8527 bool IgnoreStringsWithoutSpecifiers) { 8528 // CHECK: is the format string a wide literal? 8529 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8530 CheckFormatHandler::EmitFormatDiagnostic( 8531 S, inFunctionCall, Args[format_idx], 8532 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8533 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8534 return; 8535 } 8536 8537 // Str - The format string. NOTE: this is NOT null-terminated! 8538 StringRef StrRef = FExpr->getString(); 8539 const char *Str = StrRef.data(); 8540 // Account for cases where the string literal is truncated in a declaration. 8541 const ConstantArrayType *T = 8542 S.Context.getAsConstantArrayType(FExpr->getType()); 8543 assert(T && "String literal not of constant array type!"); 8544 size_t TypeSize = T->getSize().getZExtValue(); 8545 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8546 const unsigned numDataArgs = Args.size() - firstDataArg; 8547 8548 if (IgnoreStringsWithoutSpecifiers && 8549 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8550 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8551 return; 8552 8553 // Emit a warning if the string literal is truncated and does not contain an 8554 // embedded null character. 8555 if (TypeSize <= StrRef.size() && 8556 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8557 CheckFormatHandler::EmitFormatDiagnostic( 8558 S, inFunctionCall, Args[format_idx], 8559 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8560 FExpr->getBeginLoc(), 8561 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8562 return; 8563 } 8564 8565 // CHECK: empty format string? 8566 if (StrLen == 0 && numDataArgs > 0) { 8567 CheckFormatHandler::EmitFormatDiagnostic( 8568 S, inFunctionCall, Args[format_idx], 8569 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8570 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8571 return; 8572 } 8573 8574 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8575 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8576 Type == Sema::FST_OSTrace) { 8577 CheckPrintfHandler H( 8578 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8579 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8580 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8581 CheckedVarArgs, UncoveredArg); 8582 8583 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8584 S.getLangOpts(), 8585 S.Context.getTargetInfo(), 8586 Type == Sema::FST_FreeBSDKPrintf)) 8587 H.DoneProcessing(); 8588 } else if (Type == Sema::FST_Scanf) { 8589 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8590 numDataArgs, Str, HasVAListArg, Args, format_idx, 8591 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8592 8593 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8594 S.getLangOpts(), 8595 S.Context.getTargetInfo())) 8596 H.DoneProcessing(); 8597 } // TODO: handle other formats 8598 } 8599 8600 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8601 // Str - The format string. NOTE: this is NOT null-terminated! 8602 StringRef StrRef = FExpr->getString(); 8603 const char *Str = StrRef.data(); 8604 // Account for cases where the string literal is truncated in a declaration. 8605 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8606 assert(T && "String literal not of constant array type!"); 8607 size_t TypeSize = T->getSize().getZExtValue(); 8608 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8609 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8610 getLangOpts(), 8611 Context.getTargetInfo()); 8612 } 8613 8614 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8615 8616 // Returns the related absolute value function that is larger, of 0 if one 8617 // does not exist. 8618 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8619 switch (AbsFunction) { 8620 default: 8621 return 0; 8622 8623 case Builtin::BI__builtin_abs: 8624 return Builtin::BI__builtin_labs; 8625 case Builtin::BI__builtin_labs: 8626 return Builtin::BI__builtin_llabs; 8627 case Builtin::BI__builtin_llabs: 8628 return 0; 8629 8630 case Builtin::BI__builtin_fabsf: 8631 return Builtin::BI__builtin_fabs; 8632 case Builtin::BI__builtin_fabs: 8633 return Builtin::BI__builtin_fabsl; 8634 case Builtin::BI__builtin_fabsl: 8635 return 0; 8636 8637 case Builtin::BI__builtin_cabsf: 8638 return Builtin::BI__builtin_cabs; 8639 case Builtin::BI__builtin_cabs: 8640 return Builtin::BI__builtin_cabsl; 8641 case Builtin::BI__builtin_cabsl: 8642 return 0; 8643 8644 case Builtin::BIabs: 8645 return Builtin::BIlabs; 8646 case Builtin::BIlabs: 8647 return Builtin::BIllabs; 8648 case Builtin::BIllabs: 8649 return 0; 8650 8651 case Builtin::BIfabsf: 8652 return Builtin::BIfabs; 8653 case Builtin::BIfabs: 8654 return Builtin::BIfabsl; 8655 case Builtin::BIfabsl: 8656 return 0; 8657 8658 case Builtin::BIcabsf: 8659 return Builtin::BIcabs; 8660 case Builtin::BIcabs: 8661 return Builtin::BIcabsl; 8662 case Builtin::BIcabsl: 8663 return 0; 8664 } 8665 } 8666 8667 // Returns the argument type of the absolute value function. 8668 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8669 unsigned AbsType) { 8670 if (AbsType == 0) 8671 return QualType(); 8672 8673 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8674 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8675 if (Error != ASTContext::GE_None) 8676 return QualType(); 8677 8678 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8679 if (!FT) 8680 return QualType(); 8681 8682 if (FT->getNumParams() != 1) 8683 return QualType(); 8684 8685 return FT->getParamType(0); 8686 } 8687 8688 // Returns the best absolute value function, or zero, based on type and 8689 // current absolute value function. 8690 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8691 unsigned AbsFunctionKind) { 8692 unsigned BestKind = 0; 8693 uint64_t ArgSize = Context.getTypeSize(ArgType); 8694 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8695 Kind = getLargerAbsoluteValueFunction(Kind)) { 8696 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8697 if (Context.getTypeSize(ParamType) >= ArgSize) { 8698 if (BestKind == 0) 8699 BestKind = Kind; 8700 else if (Context.hasSameType(ParamType, ArgType)) { 8701 BestKind = Kind; 8702 break; 8703 } 8704 } 8705 } 8706 return BestKind; 8707 } 8708 8709 enum AbsoluteValueKind { 8710 AVK_Integer, 8711 AVK_Floating, 8712 AVK_Complex 8713 }; 8714 8715 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8716 if (T->isIntegralOrEnumerationType()) 8717 return AVK_Integer; 8718 if (T->isRealFloatingType()) 8719 return AVK_Floating; 8720 if (T->isAnyComplexType()) 8721 return AVK_Complex; 8722 8723 llvm_unreachable("Type not integer, floating, or complex"); 8724 } 8725 8726 // Changes the absolute value function to a different type. Preserves whether 8727 // the function is a builtin. 8728 static unsigned changeAbsFunction(unsigned AbsKind, 8729 AbsoluteValueKind ValueKind) { 8730 switch (ValueKind) { 8731 case AVK_Integer: 8732 switch (AbsKind) { 8733 default: 8734 return 0; 8735 case Builtin::BI__builtin_fabsf: 8736 case Builtin::BI__builtin_fabs: 8737 case Builtin::BI__builtin_fabsl: 8738 case Builtin::BI__builtin_cabsf: 8739 case Builtin::BI__builtin_cabs: 8740 case Builtin::BI__builtin_cabsl: 8741 return Builtin::BI__builtin_abs; 8742 case Builtin::BIfabsf: 8743 case Builtin::BIfabs: 8744 case Builtin::BIfabsl: 8745 case Builtin::BIcabsf: 8746 case Builtin::BIcabs: 8747 case Builtin::BIcabsl: 8748 return Builtin::BIabs; 8749 } 8750 case AVK_Floating: 8751 switch (AbsKind) { 8752 default: 8753 return 0; 8754 case Builtin::BI__builtin_abs: 8755 case Builtin::BI__builtin_labs: 8756 case Builtin::BI__builtin_llabs: 8757 case Builtin::BI__builtin_cabsf: 8758 case Builtin::BI__builtin_cabs: 8759 case Builtin::BI__builtin_cabsl: 8760 return Builtin::BI__builtin_fabsf; 8761 case Builtin::BIabs: 8762 case Builtin::BIlabs: 8763 case Builtin::BIllabs: 8764 case Builtin::BIcabsf: 8765 case Builtin::BIcabs: 8766 case Builtin::BIcabsl: 8767 return Builtin::BIfabsf; 8768 } 8769 case AVK_Complex: 8770 switch (AbsKind) { 8771 default: 8772 return 0; 8773 case Builtin::BI__builtin_abs: 8774 case Builtin::BI__builtin_labs: 8775 case Builtin::BI__builtin_llabs: 8776 case Builtin::BI__builtin_fabsf: 8777 case Builtin::BI__builtin_fabs: 8778 case Builtin::BI__builtin_fabsl: 8779 return Builtin::BI__builtin_cabsf; 8780 case Builtin::BIabs: 8781 case Builtin::BIlabs: 8782 case Builtin::BIllabs: 8783 case Builtin::BIfabsf: 8784 case Builtin::BIfabs: 8785 case Builtin::BIfabsl: 8786 return Builtin::BIcabsf; 8787 } 8788 } 8789 llvm_unreachable("Unable to convert function"); 8790 } 8791 8792 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8793 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8794 if (!FnInfo) 8795 return 0; 8796 8797 switch (FDecl->getBuiltinID()) { 8798 default: 8799 return 0; 8800 case Builtin::BI__builtin_abs: 8801 case Builtin::BI__builtin_fabs: 8802 case Builtin::BI__builtin_fabsf: 8803 case Builtin::BI__builtin_fabsl: 8804 case Builtin::BI__builtin_labs: 8805 case Builtin::BI__builtin_llabs: 8806 case Builtin::BI__builtin_cabs: 8807 case Builtin::BI__builtin_cabsf: 8808 case Builtin::BI__builtin_cabsl: 8809 case Builtin::BIabs: 8810 case Builtin::BIlabs: 8811 case Builtin::BIllabs: 8812 case Builtin::BIfabs: 8813 case Builtin::BIfabsf: 8814 case Builtin::BIfabsl: 8815 case Builtin::BIcabs: 8816 case Builtin::BIcabsf: 8817 case Builtin::BIcabsl: 8818 return FDecl->getBuiltinID(); 8819 } 8820 llvm_unreachable("Unknown Builtin type"); 8821 } 8822 8823 // If the replacement is valid, emit a note with replacement function. 8824 // Additionally, suggest including the proper header if not already included. 8825 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8826 unsigned AbsKind, QualType ArgType) { 8827 bool EmitHeaderHint = true; 8828 const char *HeaderName = nullptr; 8829 const char *FunctionName = nullptr; 8830 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8831 FunctionName = "std::abs"; 8832 if (ArgType->isIntegralOrEnumerationType()) { 8833 HeaderName = "cstdlib"; 8834 } else if (ArgType->isRealFloatingType()) { 8835 HeaderName = "cmath"; 8836 } else { 8837 llvm_unreachable("Invalid Type"); 8838 } 8839 8840 // Lookup all std::abs 8841 if (NamespaceDecl *Std = S.getStdNamespace()) { 8842 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8843 R.suppressDiagnostics(); 8844 S.LookupQualifiedName(R, Std); 8845 8846 for (const auto *I : R) { 8847 const FunctionDecl *FDecl = nullptr; 8848 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8849 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8850 } else { 8851 FDecl = dyn_cast<FunctionDecl>(I); 8852 } 8853 if (!FDecl) 8854 continue; 8855 8856 // Found std::abs(), check that they are the right ones. 8857 if (FDecl->getNumParams() != 1) 8858 continue; 8859 8860 // Check that the parameter type can handle the argument. 8861 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8862 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8863 S.Context.getTypeSize(ArgType) <= 8864 S.Context.getTypeSize(ParamType)) { 8865 // Found a function, don't need the header hint. 8866 EmitHeaderHint = false; 8867 break; 8868 } 8869 } 8870 } 8871 } else { 8872 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8873 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8874 8875 if (HeaderName) { 8876 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8877 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8878 R.suppressDiagnostics(); 8879 S.LookupName(R, S.getCurScope()); 8880 8881 if (R.isSingleResult()) { 8882 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8883 if (FD && FD->getBuiltinID() == AbsKind) { 8884 EmitHeaderHint = false; 8885 } else { 8886 return; 8887 } 8888 } else if (!R.empty()) { 8889 return; 8890 } 8891 } 8892 } 8893 8894 S.Diag(Loc, diag::note_replace_abs_function) 8895 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8896 8897 if (!HeaderName) 8898 return; 8899 8900 if (!EmitHeaderHint) 8901 return; 8902 8903 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8904 << FunctionName; 8905 } 8906 8907 template <std::size_t StrLen> 8908 static bool IsStdFunction(const FunctionDecl *FDecl, 8909 const char (&Str)[StrLen]) { 8910 if (!FDecl) 8911 return false; 8912 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8913 return false; 8914 if (!FDecl->isInStdNamespace()) 8915 return false; 8916 8917 return true; 8918 } 8919 8920 // Warn when using the wrong abs() function. 8921 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8922 const FunctionDecl *FDecl) { 8923 if (Call->getNumArgs() != 1) 8924 return; 8925 8926 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8927 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8928 if (AbsKind == 0 && !IsStdAbs) 8929 return; 8930 8931 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8932 QualType ParamType = Call->getArg(0)->getType(); 8933 8934 // Unsigned types cannot be negative. Suggest removing the absolute value 8935 // function call. 8936 if (ArgType->isUnsignedIntegerType()) { 8937 const char *FunctionName = 8938 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8939 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8940 Diag(Call->getExprLoc(), diag::note_remove_abs) 8941 << FunctionName 8942 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8943 return; 8944 } 8945 8946 // Taking the absolute value of a pointer is very suspicious, they probably 8947 // wanted to index into an array, dereference a pointer, call a function, etc. 8948 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8949 unsigned DiagType = 0; 8950 if (ArgType->isFunctionType()) 8951 DiagType = 1; 8952 else if (ArgType->isArrayType()) 8953 DiagType = 2; 8954 8955 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8956 return; 8957 } 8958 8959 // std::abs has overloads which prevent most of the absolute value problems 8960 // from occurring. 8961 if (IsStdAbs) 8962 return; 8963 8964 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8965 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8966 8967 // The argument and parameter are the same kind. Check if they are the right 8968 // size. 8969 if (ArgValueKind == ParamValueKind) { 8970 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8971 return; 8972 8973 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8974 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8975 << FDecl << ArgType << ParamType; 8976 8977 if (NewAbsKind == 0) 8978 return; 8979 8980 emitReplacement(*this, Call->getExprLoc(), 8981 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8982 return; 8983 } 8984 8985 // ArgValueKind != ParamValueKind 8986 // The wrong type of absolute value function was used. Attempt to find the 8987 // proper one. 8988 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8989 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8990 if (NewAbsKind == 0) 8991 return; 8992 8993 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8994 << FDecl << ParamValueKind << ArgValueKind; 8995 8996 emitReplacement(*this, Call->getExprLoc(), 8997 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8998 } 8999 9000 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9001 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9002 const FunctionDecl *FDecl) { 9003 if (!Call || !FDecl) return; 9004 9005 // Ignore template specializations and macros. 9006 if (inTemplateInstantiation()) return; 9007 if (Call->getExprLoc().isMacroID()) return; 9008 9009 // Only care about the one template argument, two function parameter std::max 9010 if (Call->getNumArgs() != 2) return; 9011 if (!IsStdFunction(FDecl, "max")) return; 9012 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9013 if (!ArgList) return; 9014 if (ArgList->size() != 1) return; 9015 9016 // Check that template type argument is unsigned integer. 9017 const auto& TA = ArgList->get(0); 9018 if (TA.getKind() != TemplateArgument::Type) return; 9019 QualType ArgType = TA.getAsType(); 9020 if (!ArgType->isUnsignedIntegerType()) return; 9021 9022 // See if either argument is a literal zero. 9023 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9024 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9025 if (!MTE) return false; 9026 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9027 if (!Num) return false; 9028 if (Num->getValue() != 0) return false; 9029 return true; 9030 }; 9031 9032 const Expr *FirstArg = Call->getArg(0); 9033 const Expr *SecondArg = Call->getArg(1); 9034 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9035 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9036 9037 // Only warn when exactly one argument is zero. 9038 if (IsFirstArgZero == IsSecondArgZero) return; 9039 9040 SourceRange FirstRange = FirstArg->getSourceRange(); 9041 SourceRange SecondRange = SecondArg->getSourceRange(); 9042 9043 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9044 9045 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9046 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9047 9048 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9049 SourceRange RemovalRange; 9050 if (IsFirstArgZero) { 9051 RemovalRange = SourceRange(FirstRange.getBegin(), 9052 SecondRange.getBegin().getLocWithOffset(-1)); 9053 } else { 9054 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9055 SecondRange.getEnd()); 9056 } 9057 9058 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9059 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9060 << FixItHint::CreateRemoval(RemovalRange); 9061 } 9062 9063 //===--- CHECK: Standard memory functions ---------------------------------===// 9064 9065 /// Takes the expression passed to the size_t parameter of functions 9066 /// such as memcmp, strncat, etc and warns if it's a comparison. 9067 /// 9068 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9069 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9070 IdentifierInfo *FnName, 9071 SourceLocation FnLoc, 9072 SourceLocation RParenLoc) { 9073 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9074 if (!Size) 9075 return false; 9076 9077 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9078 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9079 return false; 9080 9081 SourceRange SizeRange = Size->getSourceRange(); 9082 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9083 << SizeRange << FnName; 9084 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9085 << FnName 9086 << FixItHint::CreateInsertion( 9087 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9088 << FixItHint::CreateRemoval(RParenLoc); 9089 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9090 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9091 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9092 ")"); 9093 9094 return true; 9095 } 9096 9097 /// Determine whether the given type is or contains a dynamic class type 9098 /// (e.g., whether it has a vtable). 9099 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9100 bool &IsContained) { 9101 // Look through array types while ignoring qualifiers. 9102 const Type *Ty = T->getBaseElementTypeUnsafe(); 9103 IsContained = false; 9104 9105 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9106 RD = RD ? RD->getDefinition() : nullptr; 9107 if (!RD || RD->isInvalidDecl()) 9108 return nullptr; 9109 9110 if (RD->isDynamicClass()) 9111 return RD; 9112 9113 // Check all the fields. If any bases were dynamic, the class is dynamic. 9114 // It's impossible for a class to transitively contain itself by value, so 9115 // infinite recursion is impossible. 9116 for (auto *FD : RD->fields()) { 9117 bool SubContained; 9118 if (const CXXRecordDecl *ContainedRD = 9119 getContainedDynamicClass(FD->getType(), SubContained)) { 9120 IsContained = true; 9121 return ContainedRD; 9122 } 9123 } 9124 9125 return nullptr; 9126 } 9127 9128 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9129 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9130 if (Unary->getKind() == UETT_SizeOf) 9131 return Unary; 9132 return nullptr; 9133 } 9134 9135 /// If E is a sizeof expression, returns its argument expression, 9136 /// otherwise returns NULL. 9137 static const Expr *getSizeOfExprArg(const Expr *E) { 9138 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9139 if (!SizeOf->isArgumentType()) 9140 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9141 return nullptr; 9142 } 9143 9144 /// If E is a sizeof expression, returns its argument type. 9145 static QualType getSizeOfArgType(const Expr *E) { 9146 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9147 return SizeOf->getTypeOfArgument(); 9148 return QualType(); 9149 } 9150 9151 namespace { 9152 9153 struct SearchNonTrivialToInitializeField 9154 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9155 using Super = 9156 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9157 9158 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9159 9160 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9161 SourceLocation SL) { 9162 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9163 asDerived().visitArray(PDIK, AT, SL); 9164 return; 9165 } 9166 9167 Super::visitWithKind(PDIK, FT, SL); 9168 } 9169 9170 void visitARCStrong(QualType FT, SourceLocation SL) { 9171 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9172 } 9173 void visitARCWeak(QualType FT, SourceLocation SL) { 9174 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9175 } 9176 void visitStruct(QualType FT, SourceLocation SL) { 9177 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9178 visit(FD->getType(), FD->getLocation()); 9179 } 9180 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9181 const ArrayType *AT, SourceLocation SL) { 9182 visit(getContext().getBaseElementType(AT), SL); 9183 } 9184 void visitTrivial(QualType FT, SourceLocation SL) {} 9185 9186 static void diag(QualType RT, const Expr *E, Sema &S) { 9187 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9188 } 9189 9190 ASTContext &getContext() { return S.getASTContext(); } 9191 9192 const Expr *E; 9193 Sema &S; 9194 }; 9195 9196 struct SearchNonTrivialToCopyField 9197 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9198 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9199 9200 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9201 9202 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9203 SourceLocation SL) { 9204 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9205 asDerived().visitArray(PCK, AT, SL); 9206 return; 9207 } 9208 9209 Super::visitWithKind(PCK, FT, SL); 9210 } 9211 9212 void visitARCStrong(QualType FT, SourceLocation SL) { 9213 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9214 } 9215 void visitARCWeak(QualType FT, SourceLocation SL) { 9216 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9217 } 9218 void visitStruct(QualType FT, SourceLocation SL) { 9219 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9220 visit(FD->getType(), FD->getLocation()); 9221 } 9222 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9223 SourceLocation SL) { 9224 visit(getContext().getBaseElementType(AT), SL); 9225 } 9226 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9227 SourceLocation SL) {} 9228 void visitTrivial(QualType FT, SourceLocation SL) {} 9229 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9230 9231 static void diag(QualType RT, const Expr *E, Sema &S) { 9232 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9233 } 9234 9235 ASTContext &getContext() { return S.getASTContext(); } 9236 9237 const Expr *E; 9238 Sema &S; 9239 }; 9240 9241 } 9242 9243 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9244 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9245 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9246 9247 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9248 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9249 return false; 9250 9251 return doesExprLikelyComputeSize(BO->getLHS()) || 9252 doesExprLikelyComputeSize(BO->getRHS()); 9253 } 9254 9255 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9256 } 9257 9258 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9259 /// 9260 /// \code 9261 /// #define MACRO 0 9262 /// foo(MACRO); 9263 /// foo(0); 9264 /// \endcode 9265 /// 9266 /// This should return true for the first call to foo, but not for the second 9267 /// (regardless of whether foo is a macro or function). 9268 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9269 SourceLocation CallLoc, 9270 SourceLocation ArgLoc) { 9271 if (!CallLoc.isMacroID()) 9272 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9273 9274 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9275 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9276 } 9277 9278 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9279 /// last two arguments transposed. 9280 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9281 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9282 return; 9283 9284 const Expr *SizeArg = 9285 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9286 9287 auto isLiteralZero = [](const Expr *E) { 9288 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9289 }; 9290 9291 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9292 SourceLocation CallLoc = Call->getRParenLoc(); 9293 SourceManager &SM = S.getSourceManager(); 9294 if (isLiteralZero(SizeArg) && 9295 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9296 9297 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9298 9299 // Some platforms #define bzero to __builtin_memset. See if this is the 9300 // case, and if so, emit a better diagnostic. 9301 if (BId == Builtin::BIbzero || 9302 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9303 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9304 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9305 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9306 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9307 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9308 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9309 } 9310 return; 9311 } 9312 9313 // If the second argument to a memset is a sizeof expression and the third 9314 // isn't, this is also likely an error. This should catch 9315 // 'memset(buf, sizeof(buf), 0xff)'. 9316 if (BId == Builtin::BImemset && 9317 doesExprLikelyComputeSize(Call->getArg(1)) && 9318 !doesExprLikelyComputeSize(Call->getArg(2))) { 9319 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9320 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9321 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9322 return; 9323 } 9324 } 9325 9326 /// Check for dangerous or invalid arguments to memset(). 9327 /// 9328 /// This issues warnings on known problematic, dangerous or unspecified 9329 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9330 /// function calls. 9331 /// 9332 /// \param Call The call expression to diagnose. 9333 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9334 unsigned BId, 9335 IdentifierInfo *FnName) { 9336 assert(BId != 0); 9337 9338 // It is possible to have a non-standard definition of memset. Validate 9339 // we have enough arguments, and if not, abort further checking. 9340 unsigned ExpectedNumArgs = 9341 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9342 if (Call->getNumArgs() < ExpectedNumArgs) 9343 return; 9344 9345 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9346 BId == Builtin::BIstrndup ? 1 : 2); 9347 unsigned LenArg = 9348 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9349 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9350 9351 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9352 Call->getBeginLoc(), Call->getRParenLoc())) 9353 return; 9354 9355 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9356 CheckMemaccessSize(*this, BId, Call); 9357 9358 // We have special checking when the length is a sizeof expression. 9359 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9360 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9361 llvm::FoldingSetNodeID SizeOfArgID; 9362 9363 // Although widely used, 'bzero' is not a standard function. Be more strict 9364 // with the argument types before allowing diagnostics and only allow the 9365 // form bzero(ptr, sizeof(...)). 9366 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9367 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9368 return; 9369 9370 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9371 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9372 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9373 9374 QualType DestTy = Dest->getType(); 9375 QualType PointeeTy; 9376 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9377 PointeeTy = DestPtrTy->getPointeeType(); 9378 9379 // Never warn about void type pointers. This can be used to suppress 9380 // false positives. 9381 if (PointeeTy->isVoidType()) 9382 continue; 9383 9384 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9385 // actually comparing the expressions for equality. Because computing the 9386 // expression IDs can be expensive, we only do this if the diagnostic is 9387 // enabled. 9388 if (SizeOfArg && 9389 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9390 SizeOfArg->getExprLoc())) { 9391 // We only compute IDs for expressions if the warning is enabled, and 9392 // cache the sizeof arg's ID. 9393 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9394 SizeOfArg->Profile(SizeOfArgID, Context, true); 9395 llvm::FoldingSetNodeID DestID; 9396 Dest->Profile(DestID, Context, true); 9397 if (DestID == SizeOfArgID) { 9398 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9399 // over sizeof(src) as well. 9400 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9401 StringRef ReadableName = FnName->getName(); 9402 9403 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9404 if (UnaryOp->getOpcode() == UO_AddrOf) 9405 ActionIdx = 1; // If its an address-of operator, just remove it. 9406 if (!PointeeTy->isIncompleteType() && 9407 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9408 ActionIdx = 2; // If the pointee's size is sizeof(char), 9409 // suggest an explicit length. 9410 9411 // If the function is defined as a builtin macro, do not show macro 9412 // expansion. 9413 SourceLocation SL = SizeOfArg->getExprLoc(); 9414 SourceRange DSR = Dest->getSourceRange(); 9415 SourceRange SSR = SizeOfArg->getSourceRange(); 9416 SourceManager &SM = getSourceManager(); 9417 9418 if (SM.isMacroArgExpansion(SL)) { 9419 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9420 SL = SM.getSpellingLoc(SL); 9421 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9422 SM.getSpellingLoc(DSR.getEnd())); 9423 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9424 SM.getSpellingLoc(SSR.getEnd())); 9425 } 9426 9427 DiagRuntimeBehavior(SL, SizeOfArg, 9428 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9429 << ReadableName 9430 << PointeeTy 9431 << DestTy 9432 << DSR 9433 << SSR); 9434 DiagRuntimeBehavior(SL, SizeOfArg, 9435 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9436 << ActionIdx 9437 << SSR); 9438 9439 break; 9440 } 9441 } 9442 9443 // Also check for cases where the sizeof argument is the exact same 9444 // type as the memory argument, and where it points to a user-defined 9445 // record type. 9446 if (SizeOfArgTy != QualType()) { 9447 if (PointeeTy->isRecordType() && 9448 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9449 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9450 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9451 << FnName << SizeOfArgTy << ArgIdx 9452 << PointeeTy << Dest->getSourceRange() 9453 << LenExpr->getSourceRange()); 9454 break; 9455 } 9456 } 9457 } else if (DestTy->isArrayType()) { 9458 PointeeTy = DestTy; 9459 } 9460 9461 if (PointeeTy == QualType()) 9462 continue; 9463 9464 // Always complain about dynamic classes. 9465 bool IsContained; 9466 if (const CXXRecordDecl *ContainedRD = 9467 getContainedDynamicClass(PointeeTy, IsContained)) { 9468 9469 unsigned OperationType = 0; 9470 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9471 // "overwritten" if we're warning about the destination for any call 9472 // but memcmp; otherwise a verb appropriate to the call. 9473 if (ArgIdx != 0 || IsCmp) { 9474 if (BId == Builtin::BImemcpy) 9475 OperationType = 1; 9476 else if(BId == Builtin::BImemmove) 9477 OperationType = 2; 9478 else if (IsCmp) 9479 OperationType = 3; 9480 } 9481 9482 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9483 PDiag(diag::warn_dyn_class_memaccess) 9484 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9485 << IsContained << ContainedRD << OperationType 9486 << Call->getCallee()->getSourceRange()); 9487 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9488 BId != Builtin::BImemset) 9489 DiagRuntimeBehavior( 9490 Dest->getExprLoc(), Dest, 9491 PDiag(diag::warn_arc_object_memaccess) 9492 << ArgIdx << FnName << PointeeTy 9493 << Call->getCallee()->getSourceRange()); 9494 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9495 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9496 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9497 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9498 PDiag(diag::warn_cstruct_memaccess) 9499 << ArgIdx << FnName << PointeeTy << 0); 9500 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9501 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9502 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9503 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9504 PDiag(diag::warn_cstruct_memaccess) 9505 << ArgIdx << FnName << PointeeTy << 1); 9506 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9507 } else { 9508 continue; 9509 } 9510 } else 9511 continue; 9512 9513 DiagRuntimeBehavior( 9514 Dest->getExprLoc(), Dest, 9515 PDiag(diag::note_bad_memaccess_silence) 9516 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9517 break; 9518 } 9519 } 9520 9521 // A little helper routine: ignore addition and subtraction of integer literals. 9522 // This intentionally does not ignore all integer constant expressions because 9523 // we don't want to remove sizeof(). 9524 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9525 Ex = Ex->IgnoreParenCasts(); 9526 9527 while (true) { 9528 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9529 if (!BO || !BO->isAdditiveOp()) 9530 break; 9531 9532 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9533 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9534 9535 if (isa<IntegerLiteral>(RHS)) 9536 Ex = LHS; 9537 else if (isa<IntegerLiteral>(LHS)) 9538 Ex = RHS; 9539 else 9540 break; 9541 } 9542 9543 return Ex; 9544 } 9545 9546 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9547 ASTContext &Context) { 9548 // Only handle constant-sized or VLAs, but not flexible members. 9549 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9550 // Only issue the FIXIT for arrays of size > 1. 9551 if (CAT->getSize().getSExtValue() <= 1) 9552 return false; 9553 } else if (!Ty->isVariableArrayType()) { 9554 return false; 9555 } 9556 return true; 9557 } 9558 9559 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9560 // be the size of the source, instead of the destination. 9561 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9562 IdentifierInfo *FnName) { 9563 9564 // Don't crash if the user has the wrong number of arguments 9565 unsigned NumArgs = Call->getNumArgs(); 9566 if ((NumArgs != 3) && (NumArgs != 4)) 9567 return; 9568 9569 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9570 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9571 const Expr *CompareWithSrc = nullptr; 9572 9573 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9574 Call->getBeginLoc(), Call->getRParenLoc())) 9575 return; 9576 9577 // Look for 'strlcpy(dst, x, sizeof(x))' 9578 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9579 CompareWithSrc = Ex; 9580 else { 9581 // Look for 'strlcpy(dst, x, strlen(x))' 9582 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9583 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9584 SizeCall->getNumArgs() == 1) 9585 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9586 } 9587 } 9588 9589 if (!CompareWithSrc) 9590 return; 9591 9592 // Determine if the argument to sizeof/strlen is equal to the source 9593 // argument. In principle there's all kinds of things you could do 9594 // here, for instance creating an == expression and evaluating it with 9595 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9596 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9597 if (!SrcArgDRE) 9598 return; 9599 9600 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9601 if (!CompareWithSrcDRE || 9602 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9603 return; 9604 9605 const Expr *OriginalSizeArg = Call->getArg(2); 9606 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9607 << OriginalSizeArg->getSourceRange() << FnName; 9608 9609 // Output a FIXIT hint if the destination is an array (rather than a 9610 // pointer to an array). This could be enhanced to handle some 9611 // pointers if we know the actual size, like if DstArg is 'array+2' 9612 // we could say 'sizeof(array)-2'. 9613 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9614 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9615 return; 9616 9617 SmallString<128> sizeString; 9618 llvm::raw_svector_ostream OS(sizeString); 9619 OS << "sizeof("; 9620 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9621 OS << ")"; 9622 9623 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9624 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9625 OS.str()); 9626 } 9627 9628 /// Check if two expressions refer to the same declaration. 9629 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9630 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9631 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9632 return D1->getDecl() == D2->getDecl(); 9633 return false; 9634 } 9635 9636 static const Expr *getStrlenExprArg(const Expr *E) { 9637 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9638 const FunctionDecl *FD = CE->getDirectCallee(); 9639 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9640 return nullptr; 9641 return CE->getArg(0)->IgnoreParenCasts(); 9642 } 9643 return nullptr; 9644 } 9645 9646 // Warn on anti-patterns as the 'size' argument to strncat. 9647 // The correct size argument should look like following: 9648 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9649 void Sema::CheckStrncatArguments(const CallExpr *CE, 9650 IdentifierInfo *FnName) { 9651 // Don't crash if the user has the wrong number of arguments. 9652 if (CE->getNumArgs() < 3) 9653 return; 9654 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9655 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9656 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9657 9658 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9659 CE->getRParenLoc())) 9660 return; 9661 9662 // Identify common expressions, which are wrongly used as the size argument 9663 // to strncat and may lead to buffer overflows. 9664 unsigned PatternType = 0; 9665 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9666 // - sizeof(dst) 9667 if (referToTheSameDecl(SizeOfArg, DstArg)) 9668 PatternType = 1; 9669 // - sizeof(src) 9670 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9671 PatternType = 2; 9672 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9673 if (BE->getOpcode() == BO_Sub) { 9674 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9675 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9676 // - sizeof(dst) - strlen(dst) 9677 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9678 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9679 PatternType = 1; 9680 // - sizeof(src) - (anything) 9681 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9682 PatternType = 2; 9683 } 9684 } 9685 9686 if (PatternType == 0) 9687 return; 9688 9689 // Generate the diagnostic. 9690 SourceLocation SL = LenArg->getBeginLoc(); 9691 SourceRange SR = LenArg->getSourceRange(); 9692 SourceManager &SM = getSourceManager(); 9693 9694 // If the function is defined as a builtin macro, do not show macro expansion. 9695 if (SM.isMacroArgExpansion(SL)) { 9696 SL = SM.getSpellingLoc(SL); 9697 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9698 SM.getSpellingLoc(SR.getEnd())); 9699 } 9700 9701 // Check if the destination is an array (rather than a pointer to an array). 9702 QualType DstTy = DstArg->getType(); 9703 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9704 Context); 9705 if (!isKnownSizeArray) { 9706 if (PatternType == 1) 9707 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9708 else 9709 Diag(SL, diag::warn_strncat_src_size) << SR; 9710 return; 9711 } 9712 9713 if (PatternType == 1) 9714 Diag(SL, diag::warn_strncat_large_size) << SR; 9715 else 9716 Diag(SL, diag::warn_strncat_src_size) << SR; 9717 9718 SmallString<128> sizeString; 9719 llvm::raw_svector_ostream OS(sizeString); 9720 OS << "sizeof("; 9721 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9722 OS << ") - "; 9723 OS << "strlen("; 9724 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9725 OS << ") - 1"; 9726 9727 Diag(SL, diag::note_strncat_wrong_size) 9728 << FixItHint::CreateReplacement(SR, OS.str()); 9729 } 9730 9731 void 9732 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9733 SourceLocation ReturnLoc, 9734 bool isObjCMethod, 9735 const AttrVec *Attrs, 9736 const FunctionDecl *FD) { 9737 // Check if the return value is null but should not be. 9738 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9739 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9740 CheckNonNullExpr(*this, RetValExp)) 9741 Diag(ReturnLoc, diag::warn_null_ret) 9742 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9743 9744 // C++11 [basic.stc.dynamic.allocation]p4: 9745 // If an allocation function declared with a non-throwing 9746 // exception-specification fails to allocate storage, it shall return 9747 // a null pointer. Any other allocation function that fails to allocate 9748 // storage shall indicate failure only by throwing an exception [...] 9749 if (FD) { 9750 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9751 if (Op == OO_New || Op == OO_Array_New) { 9752 const FunctionProtoType *Proto 9753 = FD->getType()->castAs<FunctionProtoType>(); 9754 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9755 CheckNonNullExpr(*this, RetValExp)) 9756 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9757 << FD << getLangOpts().CPlusPlus11; 9758 } 9759 } 9760 } 9761 9762 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9763 9764 /// Check for comparisons of floating point operands using != and ==. 9765 /// Issue a warning if these are no self-comparisons, as they are not likely 9766 /// to do what the programmer intended. 9767 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9768 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9769 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9770 9771 // Special case: check for x == x (which is OK). 9772 // Do not emit warnings for such cases. 9773 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9774 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9775 if (DRL->getDecl() == DRR->getDecl()) 9776 return; 9777 9778 // Special case: check for comparisons against literals that can be exactly 9779 // represented by APFloat. In such cases, do not emit a warning. This 9780 // is a heuristic: often comparison against such literals are used to 9781 // detect if a value in a variable has not changed. This clearly can 9782 // lead to false negatives. 9783 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9784 if (FLL->isExact()) 9785 return; 9786 } else 9787 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9788 if (FLR->isExact()) 9789 return; 9790 9791 // Check for comparisons with builtin types. 9792 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9793 if (CL->getBuiltinCallee()) 9794 return; 9795 9796 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9797 if (CR->getBuiltinCallee()) 9798 return; 9799 9800 // Emit the diagnostic. 9801 Diag(Loc, diag::warn_floatingpoint_eq) 9802 << LHS->getSourceRange() << RHS->getSourceRange(); 9803 } 9804 9805 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9806 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9807 9808 namespace { 9809 9810 /// Structure recording the 'active' range of an integer-valued 9811 /// expression. 9812 struct IntRange { 9813 /// The number of bits active in the int. 9814 unsigned Width; 9815 9816 /// True if the int is known not to have negative values. 9817 bool NonNegative; 9818 9819 IntRange(unsigned Width, bool NonNegative) 9820 : Width(Width), NonNegative(NonNegative) {} 9821 9822 /// Returns the range of the bool type. 9823 static IntRange forBoolType() { 9824 return IntRange(1, true); 9825 } 9826 9827 /// Returns the range of an opaque value of the given integral type. 9828 static IntRange forValueOfType(ASTContext &C, QualType T) { 9829 return forValueOfCanonicalType(C, 9830 T->getCanonicalTypeInternal().getTypePtr()); 9831 } 9832 9833 /// Returns the range of an opaque value of a canonical integral type. 9834 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9835 assert(T->isCanonicalUnqualified()); 9836 9837 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9838 T = VT->getElementType().getTypePtr(); 9839 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9840 T = CT->getElementType().getTypePtr(); 9841 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9842 T = AT->getValueType().getTypePtr(); 9843 9844 if (!C.getLangOpts().CPlusPlus) { 9845 // For enum types in C code, use the underlying datatype. 9846 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9847 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9848 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9849 // For enum types in C++, use the known bit width of the enumerators. 9850 EnumDecl *Enum = ET->getDecl(); 9851 // In C++11, enums can have a fixed underlying type. Use this type to 9852 // compute the range. 9853 if (Enum->isFixed()) { 9854 return IntRange(C.getIntWidth(QualType(T, 0)), 9855 !ET->isSignedIntegerOrEnumerationType()); 9856 } 9857 9858 unsigned NumPositive = Enum->getNumPositiveBits(); 9859 unsigned NumNegative = Enum->getNumNegativeBits(); 9860 9861 if (NumNegative == 0) 9862 return IntRange(NumPositive, true/*NonNegative*/); 9863 else 9864 return IntRange(std::max(NumPositive + 1, NumNegative), 9865 false/*NonNegative*/); 9866 } 9867 9868 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9869 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9870 9871 const BuiltinType *BT = cast<BuiltinType>(T); 9872 assert(BT->isInteger()); 9873 9874 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9875 } 9876 9877 /// Returns the "target" range of a canonical integral type, i.e. 9878 /// the range of values expressible in the type. 9879 /// 9880 /// This matches forValueOfCanonicalType except that enums have the 9881 /// full range of their type, not the range of their enumerators. 9882 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9883 assert(T->isCanonicalUnqualified()); 9884 9885 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9886 T = VT->getElementType().getTypePtr(); 9887 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9888 T = CT->getElementType().getTypePtr(); 9889 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9890 T = AT->getValueType().getTypePtr(); 9891 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9892 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9893 9894 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9895 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9896 9897 const BuiltinType *BT = cast<BuiltinType>(T); 9898 assert(BT->isInteger()); 9899 9900 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9901 } 9902 9903 /// Returns the supremum of two ranges: i.e. their conservative merge. 9904 static IntRange join(IntRange L, IntRange R) { 9905 return IntRange(std::max(L.Width, R.Width), 9906 L.NonNegative && R.NonNegative); 9907 } 9908 9909 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9910 static IntRange meet(IntRange L, IntRange R) { 9911 return IntRange(std::min(L.Width, R.Width), 9912 L.NonNegative || R.NonNegative); 9913 } 9914 }; 9915 9916 } // namespace 9917 9918 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9919 unsigned MaxWidth) { 9920 if (value.isSigned() && value.isNegative()) 9921 return IntRange(value.getMinSignedBits(), false); 9922 9923 if (value.getBitWidth() > MaxWidth) 9924 value = value.trunc(MaxWidth); 9925 9926 // isNonNegative() just checks the sign bit without considering 9927 // signedness. 9928 return IntRange(value.getActiveBits(), true); 9929 } 9930 9931 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9932 unsigned MaxWidth) { 9933 if (result.isInt()) 9934 return GetValueRange(C, result.getInt(), MaxWidth); 9935 9936 if (result.isVector()) { 9937 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9938 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9939 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9940 R = IntRange::join(R, El); 9941 } 9942 return R; 9943 } 9944 9945 if (result.isComplexInt()) { 9946 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9947 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9948 return IntRange::join(R, I); 9949 } 9950 9951 // This can happen with lossless casts to intptr_t of "based" lvalues. 9952 // Assume it might use arbitrary bits. 9953 // FIXME: The only reason we need to pass the type in here is to get 9954 // the sign right on this one case. It would be nice if APValue 9955 // preserved this. 9956 assert(result.isLValue() || result.isAddrLabelDiff()); 9957 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9958 } 9959 9960 static QualType GetExprType(const Expr *E) { 9961 QualType Ty = E->getType(); 9962 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9963 Ty = AtomicRHS->getValueType(); 9964 return Ty; 9965 } 9966 9967 /// Pseudo-evaluate the given integer expression, estimating the 9968 /// range of values it might take. 9969 /// 9970 /// \param MaxWidth - the width to which the value will be truncated 9971 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9972 bool InConstantContext) { 9973 E = E->IgnoreParens(); 9974 9975 // Try a full evaluation first. 9976 Expr::EvalResult result; 9977 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9978 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9979 9980 // I think we only want to look through implicit casts here; if the 9981 // user has an explicit widening cast, we should treat the value as 9982 // being of the new, wider type. 9983 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9984 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9985 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9986 9987 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9988 9989 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9990 CE->getCastKind() == CK_BooleanToSignedIntegral; 9991 9992 // Assume that non-integer casts can span the full range of the type. 9993 if (!isIntegerCast) 9994 return OutputTypeRange; 9995 9996 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9997 std::min(MaxWidth, OutputTypeRange.Width), 9998 InConstantContext); 9999 10000 // Bail out if the subexpr's range is as wide as the cast type. 10001 if (SubRange.Width >= OutputTypeRange.Width) 10002 return OutputTypeRange; 10003 10004 // Otherwise, we take the smaller width, and we're non-negative if 10005 // either the output type or the subexpr is. 10006 return IntRange(SubRange.Width, 10007 SubRange.NonNegative || OutputTypeRange.NonNegative); 10008 } 10009 10010 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10011 // If we can fold the condition, just take that operand. 10012 bool CondResult; 10013 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10014 return GetExprRange(C, 10015 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10016 MaxWidth, InConstantContext); 10017 10018 // Otherwise, conservatively merge. 10019 IntRange L = 10020 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10021 IntRange R = 10022 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10023 return IntRange::join(L, R); 10024 } 10025 10026 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10027 switch (BO->getOpcode()) { 10028 case BO_Cmp: 10029 llvm_unreachable("builtin <=> should have class type"); 10030 10031 // Boolean-valued operations are single-bit and positive. 10032 case BO_LAnd: 10033 case BO_LOr: 10034 case BO_LT: 10035 case BO_GT: 10036 case BO_LE: 10037 case BO_GE: 10038 case BO_EQ: 10039 case BO_NE: 10040 return IntRange::forBoolType(); 10041 10042 // The type of the assignments is the type of the LHS, so the RHS 10043 // is not necessarily the same type. 10044 case BO_MulAssign: 10045 case BO_DivAssign: 10046 case BO_RemAssign: 10047 case BO_AddAssign: 10048 case BO_SubAssign: 10049 case BO_XorAssign: 10050 case BO_OrAssign: 10051 // TODO: bitfields? 10052 return IntRange::forValueOfType(C, GetExprType(E)); 10053 10054 // Simple assignments just pass through the RHS, which will have 10055 // been coerced to the LHS type. 10056 case BO_Assign: 10057 // TODO: bitfields? 10058 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10059 10060 // Operations with opaque sources are black-listed. 10061 case BO_PtrMemD: 10062 case BO_PtrMemI: 10063 return IntRange::forValueOfType(C, GetExprType(E)); 10064 10065 // Bitwise-and uses the *infinum* of the two source ranges. 10066 case BO_And: 10067 case BO_AndAssign: 10068 return IntRange::meet( 10069 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10070 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10071 10072 // Left shift gets black-listed based on a judgement call. 10073 case BO_Shl: 10074 // ...except that we want to treat '1 << (blah)' as logically 10075 // positive. It's an important idiom. 10076 if (IntegerLiteral *I 10077 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10078 if (I->getValue() == 1) { 10079 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10080 return IntRange(R.Width, /*NonNegative*/ true); 10081 } 10082 } 10083 LLVM_FALLTHROUGH; 10084 10085 case BO_ShlAssign: 10086 return IntRange::forValueOfType(C, GetExprType(E)); 10087 10088 // Right shift by a constant can narrow its left argument. 10089 case BO_Shr: 10090 case BO_ShrAssign: { 10091 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10092 10093 // If the shift amount is a positive constant, drop the width by 10094 // that much. 10095 llvm::APSInt shift; 10096 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10097 shift.isNonNegative()) { 10098 unsigned zext = shift.getZExtValue(); 10099 if (zext >= L.Width) 10100 L.Width = (L.NonNegative ? 0 : 1); 10101 else 10102 L.Width -= zext; 10103 } 10104 10105 return L; 10106 } 10107 10108 // Comma acts as its right operand. 10109 case BO_Comma: 10110 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10111 10112 // Black-list pointer subtractions. 10113 case BO_Sub: 10114 if (BO->getLHS()->getType()->isPointerType()) 10115 return IntRange::forValueOfType(C, GetExprType(E)); 10116 break; 10117 10118 // The width of a division result is mostly determined by the size 10119 // of the LHS. 10120 case BO_Div: { 10121 // Don't 'pre-truncate' the operands. 10122 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10123 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10124 10125 // If the divisor is constant, use that. 10126 llvm::APSInt divisor; 10127 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10128 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10129 if (log2 >= L.Width) 10130 L.Width = (L.NonNegative ? 0 : 1); 10131 else 10132 L.Width = std::min(L.Width - log2, MaxWidth); 10133 return L; 10134 } 10135 10136 // Otherwise, just use the LHS's width. 10137 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10138 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10139 } 10140 10141 // The result of a remainder can't be larger than the result of 10142 // either side. 10143 case BO_Rem: { 10144 // Don't 'pre-truncate' the operands. 10145 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10146 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10147 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10148 10149 IntRange meet = IntRange::meet(L, R); 10150 meet.Width = std::min(meet.Width, MaxWidth); 10151 return meet; 10152 } 10153 10154 // The default behavior is okay for these. 10155 case BO_Mul: 10156 case BO_Add: 10157 case BO_Xor: 10158 case BO_Or: 10159 break; 10160 } 10161 10162 // The default case is to treat the operation as if it were closed 10163 // on the narrowest type that encompasses both operands. 10164 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10165 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10166 return IntRange::join(L, R); 10167 } 10168 10169 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10170 switch (UO->getOpcode()) { 10171 // Boolean-valued operations are white-listed. 10172 case UO_LNot: 10173 return IntRange::forBoolType(); 10174 10175 // Operations with opaque sources are black-listed. 10176 case UO_Deref: 10177 case UO_AddrOf: // should be impossible 10178 return IntRange::forValueOfType(C, GetExprType(E)); 10179 10180 default: 10181 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10182 } 10183 } 10184 10185 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10186 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10187 10188 if (const auto *BitField = E->getSourceBitField()) 10189 return IntRange(BitField->getBitWidthValue(C), 10190 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10191 10192 return IntRange::forValueOfType(C, GetExprType(E)); 10193 } 10194 10195 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10196 bool InConstantContext) { 10197 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10198 } 10199 10200 /// Checks whether the given value, which currently has the given 10201 /// source semantics, has the same value when coerced through the 10202 /// target semantics. 10203 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10204 const llvm::fltSemantics &Src, 10205 const llvm::fltSemantics &Tgt) { 10206 llvm::APFloat truncated = value; 10207 10208 bool ignored; 10209 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10210 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10211 10212 return truncated.bitwiseIsEqual(value); 10213 } 10214 10215 /// Checks whether the given value, which currently has the given 10216 /// source semantics, has the same value when coerced through the 10217 /// target semantics. 10218 /// 10219 /// The value might be a vector of floats (or a complex number). 10220 static bool IsSameFloatAfterCast(const APValue &value, 10221 const llvm::fltSemantics &Src, 10222 const llvm::fltSemantics &Tgt) { 10223 if (value.isFloat()) 10224 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10225 10226 if (value.isVector()) { 10227 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10228 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10229 return false; 10230 return true; 10231 } 10232 10233 assert(value.isComplexFloat()); 10234 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10235 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10236 } 10237 10238 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10239 bool IsListInit = false); 10240 10241 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10242 // Suppress cases where we are comparing against an enum constant. 10243 if (const DeclRefExpr *DR = 10244 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10245 if (isa<EnumConstantDecl>(DR->getDecl())) 10246 return true; 10247 10248 // Suppress cases where the value is expanded from a macro, unless that macro 10249 // is how a language represents a boolean literal. This is the case in both C 10250 // and Objective-C. 10251 SourceLocation BeginLoc = E->getBeginLoc(); 10252 if (BeginLoc.isMacroID()) { 10253 StringRef MacroName = Lexer::getImmediateMacroName( 10254 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10255 return MacroName != "YES" && MacroName != "NO" && 10256 MacroName != "true" && MacroName != "false"; 10257 } 10258 10259 return false; 10260 } 10261 10262 static bool isKnownToHaveUnsignedValue(Expr *E) { 10263 return E->getType()->isIntegerType() && 10264 (!E->getType()->isSignedIntegerType() || 10265 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10266 } 10267 10268 namespace { 10269 /// The promoted range of values of a type. In general this has the 10270 /// following structure: 10271 /// 10272 /// |-----------| . . . |-----------| 10273 /// ^ ^ ^ ^ 10274 /// Min HoleMin HoleMax Max 10275 /// 10276 /// ... where there is only a hole if a signed type is promoted to unsigned 10277 /// (in which case Min and Max are the smallest and largest representable 10278 /// values). 10279 struct PromotedRange { 10280 // Min, or HoleMax if there is a hole. 10281 llvm::APSInt PromotedMin; 10282 // Max, or HoleMin if there is a hole. 10283 llvm::APSInt PromotedMax; 10284 10285 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10286 if (R.Width == 0) 10287 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10288 else if (R.Width >= BitWidth && !Unsigned) { 10289 // Promotion made the type *narrower*. This happens when promoting 10290 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10291 // Treat all values of 'signed int' as being in range for now. 10292 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10293 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10294 } else { 10295 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10296 .extOrTrunc(BitWidth); 10297 PromotedMin.setIsUnsigned(Unsigned); 10298 10299 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10300 .extOrTrunc(BitWidth); 10301 PromotedMax.setIsUnsigned(Unsigned); 10302 } 10303 } 10304 10305 // Determine whether this range is contiguous (has no hole). 10306 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10307 10308 // Where a constant value is within the range. 10309 enum ComparisonResult { 10310 LT = 0x1, 10311 LE = 0x2, 10312 GT = 0x4, 10313 GE = 0x8, 10314 EQ = 0x10, 10315 NE = 0x20, 10316 InRangeFlag = 0x40, 10317 10318 Less = LE | LT | NE, 10319 Min = LE | InRangeFlag, 10320 InRange = InRangeFlag, 10321 Max = GE | InRangeFlag, 10322 Greater = GE | GT | NE, 10323 10324 OnlyValue = LE | GE | EQ | InRangeFlag, 10325 InHole = NE 10326 }; 10327 10328 ComparisonResult compare(const llvm::APSInt &Value) const { 10329 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10330 Value.isUnsigned() == PromotedMin.isUnsigned()); 10331 if (!isContiguous()) { 10332 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10333 if (Value.isMinValue()) return Min; 10334 if (Value.isMaxValue()) return Max; 10335 if (Value >= PromotedMin) return InRange; 10336 if (Value <= PromotedMax) return InRange; 10337 return InHole; 10338 } 10339 10340 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10341 case -1: return Less; 10342 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10343 case 1: 10344 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10345 case -1: return InRange; 10346 case 0: return Max; 10347 case 1: return Greater; 10348 } 10349 } 10350 10351 llvm_unreachable("impossible compare result"); 10352 } 10353 10354 static llvm::Optional<StringRef> 10355 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10356 if (Op == BO_Cmp) { 10357 ComparisonResult LTFlag = LT, GTFlag = GT; 10358 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10359 10360 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10361 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10362 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10363 return llvm::None; 10364 } 10365 10366 ComparisonResult TrueFlag, FalseFlag; 10367 if (Op == BO_EQ) { 10368 TrueFlag = EQ; 10369 FalseFlag = NE; 10370 } else if (Op == BO_NE) { 10371 TrueFlag = NE; 10372 FalseFlag = EQ; 10373 } else { 10374 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10375 TrueFlag = LT; 10376 FalseFlag = GE; 10377 } else { 10378 TrueFlag = GT; 10379 FalseFlag = LE; 10380 } 10381 if (Op == BO_GE || Op == BO_LE) 10382 std::swap(TrueFlag, FalseFlag); 10383 } 10384 if (R & TrueFlag) 10385 return StringRef("true"); 10386 if (R & FalseFlag) 10387 return StringRef("false"); 10388 return llvm::None; 10389 } 10390 }; 10391 } 10392 10393 static bool HasEnumType(Expr *E) { 10394 // Strip off implicit integral promotions. 10395 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10396 if (ICE->getCastKind() != CK_IntegralCast && 10397 ICE->getCastKind() != CK_NoOp) 10398 break; 10399 E = ICE->getSubExpr(); 10400 } 10401 10402 return E->getType()->isEnumeralType(); 10403 } 10404 10405 static int classifyConstantValue(Expr *Constant) { 10406 // The values of this enumeration are used in the diagnostics 10407 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10408 enum ConstantValueKind { 10409 Miscellaneous = 0, 10410 LiteralTrue, 10411 LiteralFalse 10412 }; 10413 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10414 return BL->getValue() ? ConstantValueKind::LiteralTrue 10415 : ConstantValueKind::LiteralFalse; 10416 return ConstantValueKind::Miscellaneous; 10417 } 10418 10419 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10420 Expr *Constant, Expr *Other, 10421 const llvm::APSInt &Value, 10422 bool RhsConstant) { 10423 if (S.inTemplateInstantiation()) 10424 return false; 10425 10426 Expr *OriginalOther = Other; 10427 10428 Constant = Constant->IgnoreParenImpCasts(); 10429 Other = Other->IgnoreParenImpCasts(); 10430 10431 // Suppress warnings on tautological comparisons between values of the same 10432 // enumeration type. There are only two ways we could warn on this: 10433 // - If the constant is outside the range of representable values of 10434 // the enumeration. In such a case, we should warn about the cast 10435 // to enumeration type, not about the comparison. 10436 // - If the constant is the maximum / minimum in-range value. For an 10437 // enumeratin type, such comparisons can be meaningful and useful. 10438 if (Constant->getType()->isEnumeralType() && 10439 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10440 return false; 10441 10442 // TODO: Investigate using GetExprRange() to get tighter bounds 10443 // on the bit ranges. 10444 QualType OtherT = Other->getType(); 10445 if (const auto *AT = OtherT->getAs<AtomicType>()) 10446 OtherT = AT->getValueType(); 10447 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10448 10449 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10450 // (Namely, macOS). 10451 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10452 S.NSAPIObj->isObjCBOOLType(OtherT) && 10453 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10454 10455 // Whether we're treating Other as being a bool because of the form of 10456 // expression despite it having another type (typically 'int' in C). 10457 bool OtherIsBooleanDespiteType = 10458 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10459 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10460 OtherRange = IntRange::forBoolType(); 10461 10462 // Determine the promoted range of the other type and see if a comparison of 10463 // the constant against that range is tautological. 10464 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10465 Value.isUnsigned()); 10466 auto Cmp = OtherPromotedRange.compare(Value); 10467 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10468 if (!Result) 10469 return false; 10470 10471 // Suppress the diagnostic for an in-range comparison if the constant comes 10472 // from a macro or enumerator. We don't want to diagnose 10473 // 10474 // some_long_value <= INT_MAX 10475 // 10476 // when sizeof(int) == sizeof(long). 10477 bool InRange = Cmp & PromotedRange::InRangeFlag; 10478 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10479 return false; 10480 10481 // If this is a comparison to an enum constant, include that 10482 // constant in the diagnostic. 10483 const EnumConstantDecl *ED = nullptr; 10484 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10485 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10486 10487 // Should be enough for uint128 (39 decimal digits) 10488 SmallString<64> PrettySourceValue; 10489 llvm::raw_svector_ostream OS(PrettySourceValue); 10490 if (ED) { 10491 OS << '\'' << *ED << "' (" << Value << ")"; 10492 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10493 Constant->IgnoreParenImpCasts())) { 10494 OS << (BL->getValue() ? "YES" : "NO"); 10495 } else { 10496 OS << Value; 10497 } 10498 10499 if (IsObjCSignedCharBool) { 10500 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10501 S.PDiag(diag::warn_tautological_compare_objc_bool) 10502 << OS.str() << *Result); 10503 return true; 10504 } 10505 10506 // FIXME: We use a somewhat different formatting for the in-range cases and 10507 // cases involving boolean values for historical reasons. We should pick a 10508 // consistent way of presenting these diagnostics. 10509 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10510 10511 S.DiagRuntimeBehavior( 10512 E->getOperatorLoc(), E, 10513 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10514 : diag::warn_tautological_bool_compare) 10515 << OS.str() << classifyConstantValue(Constant) << OtherT 10516 << OtherIsBooleanDespiteType << *Result 10517 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10518 } else { 10519 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10520 ? (HasEnumType(OriginalOther) 10521 ? diag::warn_unsigned_enum_always_true_comparison 10522 : diag::warn_unsigned_always_true_comparison) 10523 : diag::warn_tautological_constant_compare; 10524 10525 S.Diag(E->getOperatorLoc(), Diag) 10526 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10527 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10528 } 10529 10530 return true; 10531 } 10532 10533 /// Analyze the operands of the given comparison. Implements the 10534 /// fallback case from AnalyzeComparison. 10535 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10536 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10537 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10538 } 10539 10540 /// Implements -Wsign-compare. 10541 /// 10542 /// \param E the binary operator to check for warnings 10543 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10544 // The type the comparison is being performed in. 10545 QualType T = E->getLHS()->getType(); 10546 10547 // Only analyze comparison operators where both sides have been converted to 10548 // the same type. 10549 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10550 return AnalyzeImpConvsInComparison(S, E); 10551 10552 // Don't analyze value-dependent comparisons directly. 10553 if (E->isValueDependent()) 10554 return AnalyzeImpConvsInComparison(S, E); 10555 10556 Expr *LHS = E->getLHS(); 10557 Expr *RHS = E->getRHS(); 10558 10559 if (T->isIntegralType(S.Context)) { 10560 llvm::APSInt RHSValue; 10561 llvm::APSInt LHSValue; 10562 10563 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10564 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10565 10566 // We don't care about expressions whose result is a constant. 10567 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10568 return AnalyzeImpConvsInComparison(S, E); 10569 10570 // We only care about expressions where just one side is literal 10571 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10572 // Is the constant on the RHS or LHS? 10573 const bool RhsConstant = IsRHSIntegralLiteral; 10574 Expr *Const = RhsConstant ? RHS : LHS; 10575 Expr *Other = RhsConstant ? LHS : RHS; 10576 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10577 10578 // Check whether an integer constant comparison results in a value 10579 // of 'true' or 'false'. 10580 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10581 return AnalyzeImpConvsInComparison(S, E); 10582 } 10583 } 10584 10585 if (!T->hasUnsignedIntegerRepresentation()) { 10586 // We don't do anything special if this isn't an unsigned integral 10587 // comparison: we're only interested in integral comparisons, and 10588 // signed comparisons only happen in cases we don't care to warn about. 10589 return AnalyzeImpConvsInComparison(S, E); 10590 } 10591 10592 LHS = LHS->IgnoreParenImpCasts(); 10593 RHS = RHS->IgnoreParenImpCasts(); 10594 10595 if (!S.getLangOpts().CPlusPlus) { 10596 // Avoid warning about comparison of integers with different signs when 10597 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10598 // the type of `E`. 10599 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10600 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10601 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10602 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10603 } 10604 10605 // Check to see if one of the (unmodified) operands is of different 10606 // signedness. 10607 Expr *signedOperand, *unsignedOperand; 10608 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10609 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10610 "unsigned comparison between two signed integer expressions?"); 10611 signedOperand = LHS; 10612 unsignedOperand = RHS; 10613 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10614 signedOperand = RHS; 10615 unsignedOperand = LHS; 10616 } else { 10617 return AnalyzeImpConvsInComparison(S, E); 10618 } 10619 10620 // Otherwise, calculate the effective range of the signed operand. 10621 IntRange signedRange = 10622 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10623 10624 // Go ahead and analyze implicit conversions in the operands. Note 10625 // that we skip the implicit conversions on both sides. 10626 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10627 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10628 10629 // If the signed range is non-negative, -Wsign-compare won't fire. 10630 if (signedRange.NonNegative) 10631 return; 10632 10633 // For (in)equality comparisons, if the unsigned operand is a 10634 // constant which cannot collide with a overflowed signed operand, 10635 // then reinterpreting the signed operand as unsigned will not 10636 // change the result of the comparison. 10637 if (E->isEqualityOp()) { 10638 unsigned comparisonWidth = S.Context.getIntWidth(T); 10639 IntRange unsignedRange = 10640 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10641 10642 // We should never be unable to prove that the unsigned operand is 10643 // non-negative. 10644 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10645 10646 if (unsignedRange.Width < comparisonWidth) 10647 return; 10648 } 10649 10650 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10651 S.PDiag(diag::warn_mixed_sign_comparison) 10652 << LHS->getType() << RHS->getType() 10653 << LHS->getSourceRange() << RHS->getSourceRange()); 10654 } 10655 10656 /// Analyzes an attempt to assign the given value to a bitfield. 10657 /// 10658 /// Returns true if there was something fishy about the attempt. 10659 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10660 SourceLocation InitLoc) { 10661 assert(Bitfield->isBitField()); 10662 if (Bitfield->isInvalidDecl()) 10663 return false; 10664 10665 // White-list bool bitfields. 10666 QualType BitfieldType = Bitfield->getType(); 10667 if (BitfieldType->isBooleanType()) 10668 return false; 10669 10670 if (BitfieldType->isEnumeralType()) { 10671 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10672 // If the underlying enum type was not explicitly specified as an unsigned 10673 // type and the enum contain only positive values, MSVC++ will cause an 10674 // inconsistency by storing this as a signed type. 10675 if (S.getLangOpts().CPlusPlus11 && 10676 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10677 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10678 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10679 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10680 << BitfieldEnumDecl->getNameAsString(); 10681 } 10682 } 10683 10684 if (Bitfield->getType()->isBooleanType()) 10685 return false; 10686 10687 // Ignore value- or type-dependent expressions. 10688 if (Bitfield->getBitWidth()->isValueDependent() || 10689 Bitfield->getBitWidth()->isTypeDependent() || 10690 Init->isValueDependent() || 10691 Init->isTypeDependent()) 10692 return false; 10693 10694 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10695 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10696 10697 Expr::EvalResult Result; 10698 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10699 Expr::SE_AllowSideEffects)) { 10700 // The RHS is not constant. If the RHS has an enum type, make sure the 10701 // bitfield is wide enough to hold all the values of the enum without 10702 // truncation. 10703 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10704 EnumDecl *ED = EnumTy->getDecl(); 10705 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10706 10707 // Enum types are implicitly signed on Windows, so check if there are any 10708 // negative enumerators to see if the enum was intended to be signed or 10709 // not. 10710 bool SignedEnum = ED->getNumNegativeBits() > 0; 10711 10712 // Check for surprising sign changes when assigning enum values to a 10713 // bitfield of different signedness. If the bitfield is signed and we 10714 // have exactly the right number of bits to store this unsigned enum, 10715 // suggest changing the enum to an unsigned type. This typically happens 10716 // on Windows where unfixed enums always use an underlying type of 'int'. 10717 unsigned DiagID = 0; 10718 if (SignedEnum && !SignedBitfield) { 10719 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10720 } else if (SignedBitfield && !SignedEnum && 10721 ED->getNumPositiveBits() == FieldWidth) { 10722 DiagID = diag::warn_signed_bitfield_enum_conversion; 10723 } 10724 10725 if (DiagID) { 10726 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10727 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10728 SourceRange TypeRange = 10729 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10730 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10731 << SignedEnum << TypeRange; 10732 } 10733 10734 // Compute the required bitwidth. If the enum has negative values, we need 10735 // one more bit than the normal number of positive bits to represent the 10736 // sign bit. 10737 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10738 ED->getNumNegativeBits()) 10739 : ED->getNumPositiveBits(); 10740 10741 // Check the bitwidth. 10742 if (BitsNeeded > FieldWidth) { 10743 Expr *WidthExpr = Bitfield->getBitWidth(); 10744 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10745 << Bitfield << ED; 10746 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10747 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10748 } 10749 } 10750 10751 return false; 10752 } 10753 10754 llvm::APSInt Value = Result.Val.getInt(); 10755 10756 unsigned OriginalWidth = Value.getBitWidth(); 10757 10758 if (!Value.isSigned() || Value.isNegative()) 10759 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10760 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10761 OriginalWidth = Value.getMinSignedBits(); 10762 10763 if (OriginalWidth <= FieldWidth) 10764 return false; 10765 10766 // Compute the value which the bitfield will contain. 10767 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10768 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10769 10770 // Check whether the stored value is equal to the original value. 10771 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10772 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10773 return false; 10774 10775 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10776 // therefore don't strictly fit into a signed bitfield of width 1. 10777 if (FieldWidth == 1 && Value == 1) 10778 return false; 10779 10780 std::string PrettyValue = Value.toString(10); 10781 std::string PrettyTrunc = TruncatedValue.toString(10); 10782 10783 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10784 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10785 << Init->getSourceRange(); 10786 10787 return true; 10788 } 10789 10790 /// Analyze the given simple or compound assignment for warning-worthy 10791 /// operations. 10792 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10793 // Just recurse on the LHS. 10794 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10795 10796 // We want to recurse on the RHS as normal unless we're assigning to 10797 // a bitfield. 10798 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10799 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10800 E->getOperatorLoc())) { 10801 // Recurse, ignoring any implicit conversions on the RHS. 10802 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10803 E->getOperatorLoc()); 10804 } 10805 } 10806 10807 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10808 10809 // Diagnose implicitly sequentially-consistent atomic assignment. 10810 if (E->getLHS()->getType()->isAtomicType()) 10811 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10812 } 10813 10814 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10815 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10816 SourceLocation CContext, unsigned diag, 10817 bool pruneControlFlow = false) { 10818 if (pruneControlFlow) { 10819 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10820 S.PDiag(diag) 10821 << SourceType << T << E->getSourceRange() 10822 << SourceRange(CContext)); 10823 return; 10824 } 10825 S.Diag(E->getExprLoc(), diag) 10826 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10827 } 10828 10829 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10830 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10831 SourceLocation CContext, 10832 unsigned diag, bool pruneControlFlow = false) { 10833 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10834 } 10835 10836 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10837 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10838 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10839 } 10840 10841 static void adornObjCBoolConversionDiagWithTernaryFixit( 10842 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10843 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10844 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10845 Ignored = OVE->getSourceExpr(); 10846 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10847 isa<BinaryOperator>(Ignored) || 10848 isa<CXXOperatorCallExpr>(Ignored); 10849 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10850 if (NeedsParens) 10851 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10852 << FixItHint::CreateInsertion(EndLoc, ")"); 10853 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10854 } 10855 10856 /// Diagnose an implicit cast from a floating point value to an integer value. 10857 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10858 SourceLocation CContext) { 10859 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10860 const bool PruneWarnings = S.inTemplateInstantiation(); 10861 10862 Expr *InnerE = E->IgnoreParenImpCasts(); 10863 // We also want to warn on, e.g., "int i = -1.234" 10864 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10865 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10866 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10867 10868 const bool IsLiteral = 10869 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10870 10871 llvm::APFloat Value(0.0); 10872 bool IsConstant = 10873 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10874 if (!IsConstant) { 10875 if (isObjCSignedCharBool(S, T)) { 10876 return adornObjCBoolConversionDiagWithTernaryFixit( 10877 S, E, 10878 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10879 << E->getType()); 10880 } 10881 10882 return DiagnoseImpCast(S, E, T, CContext, 10883 diag::warn_impcast_float_integer, PruneWarnings); 10884 } 10885 10886 bool isExact = false; 10887 10888 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10889 T->hasUnsignedIntegerRepresentation()); 10890 llvm::APFloat::opStatus Result = Value.convertToInteger( 10891 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10892 10893 // FIXME: Force the precision of the source value down so we don't print 10894 // digits which are usually useless (we don't really care here if we 10895 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10896 // would automatically print the shortest representation, but it's a bit 10897 // tricky to implement. 10898 SmallString<16> PrettySourceValue; 10899 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10900 precision = (precision * 59 + 195) / 196; 10901 Value.toString(PrettySourceValue, precision); 10902 10903 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10904 return adornObjCBoolConversionDiagWithTernaryFixit( 10905 S, E, 10906 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10907 << PrettySourceValue); 10908 } 10909 10910 if (Result == llvm::APFloat::opOK && isExact) { 10911 if (IsLiteral) return; 10912 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10913 PruneWarnings); 10914 } 10915 10916 // Conversion of a floating-point value to a non-bool integer where the 10917 // integral part cannot be represented by the integer type is undefined. 10918 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10919 return DiagnoseImpCast( 10920 S, E, T, CContext, 10921 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10922 : diag::warn_impcast_float_to_integer_out_of_range, 10923 PruneWarnings); 10924 10925 unsigned DiagID = 0; 10926 if (IsLiteral) { 10927 // Warn on floating point literal to integer. 10928 DiagID = diag::warn_impcast_literal_float_to_integer; 10929 } else if (IntegerValue == 0) { 10930 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10931 return DiagnoseImpCast(S, E, T, CContext, 10932 diag::warn_impcast_float_integer, PruneWarnings); 10933 } 10934 // Warn on non-zero to zero conversion. 10935 DiagID = diag::warn_impcast_float_to_integer_zero; 10936 } else { 10937 if (IntegerValue.isUnsigned()) { 10938 if (!IntegerValue.isMaxValue()) { 10939 return DiagnoseImpCast(S, E, T, CContext, 10940 diag::warn_impcast_float_integer, PruneWarnings); 10941 } 10942 } else { // IntegerValue.isSigned() 10943 if (!IntegerValue.isMaxSignedValue() && 10944 !IntegerValue.isMinSignedValue()) { 10945 return DiagnoseImpCast(S, E, T, CContext, 10946 diag::warn_impcast_float_integer, PruneWarnings); 10947 } 10948 } 10949 // Warn on evaluatable floating point expression to integer conversion. 10950 DiagID = diag::warn_impcast_float_to_integer; 10951 } 10952 10953 SmallString<16> PrettyTargetValue; 10954 if (IsBool) 10955 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10956 else 10957 IntegerValue.toString(PrettyTargetValue); 10958 10959 if (PruneWarnings) { 10960 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10961 S.PDiag(DiagID) 10962 << E->getType() << T.getUnqualifiedType() 10963 << PrettySourceValue << PrettyTargetValue 10964 << E->getSourceRange() << SourceRange(CContext)); 10965 } else { 10966 S.Diag(E->getExprLoc(), DiagID) 10967 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10968 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10969 } 10970 } 10971 10972 /// Analyze the given compound assignment for the possible losing of 10973 /// floating-point precision. 10974 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10975 assert(isa<CompoundAssignOperator>(E) && 10976 "Must be compound assignment operation"); 10977 // Recurse on the LHS and RHS in here 10978 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10979 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10980 10981 if (E->getLHS()->getType()->isAtomicType()) 10982 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10983 10984 // Now check the outermost expression 10985 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10986 const auto *RBT = cast<CompoundAssignOperator>(E) 10987 ->getComputationResultType() 10988 ->getAs<BuiltinType>(); 10989 10990 // The below checks assume source is floating point. 10991 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10992 10993 // If source is floating point but target is an integer. 10994 if (ResultBT->isInteger()) 10995 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10996 E->getExprLoc(), diag::warn_impcast_float_integer); 10997 10998 if (!ResultBT->isFloatingPoint()) 10999 return; 11000 11001 // If both source and target are floating points, warn about losing precision. 11002 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11003 QualType(ResultBT, 0), QualType(RBT, 0)); 11004 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11005 // warn about dropping FP rank. 11006 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11007 diag::warn_impcast_float_result_precision); 11008 } 11009 11010 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11011 IntRange Range) { 11012 if (!Range.Width) return "0"; 11013 11014 llvm::APSInt ValueInRange = Value; 11015 ValueInRange.setIsSigned(!Range.NonNegative); 11016 ValueInRange = ValueInRange.trunc(Range.Width); 11017 return ValueInRange.toString(10); 11018 } 11019 11020 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11021 if (!isa<ImplicitCastExpr>(Ex)) 11022 return false; 11023 11024 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11025 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11026 const Type *Source = 11027 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11028 if (Target->isDependentType()) 11029 return false; 11030 11031 const BuiltinType *FloatCandidateBT = 11032 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11033 const Type *BoolCandidateType = ToBool ? Target : Source; 11034 11035 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11036 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11037 } 11038 11039 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11040 SourceLocation CC) { 11041 unsigned NumArgs = TheCall->getNumArgs(); 11042 for (unsigned i = 0; i < NumArgs; ++i) { 11043 Expr *CurrA = TheCall->getArg(i); 11044 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11045 continue; 11046 11047 bool IsSwapped = ((i > 0) && 11048 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11049 IsSwapped |= ((i < (NumArgs - 1)) && 11050 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11051 if (IsSwapped) { 11052 // Warn on this floating-point to bool conversion. 11053 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11054 CurrA->getType(), CC, 11055 diag::warn_impcast_floating_point_to_bool); 11056 } 11057 } 11058 } 11059 11060 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11061 SourceLocation CC) { 11062 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11063 E->getExprLoc())) 11064 return; 11065 11066 // Don't warn on functions which have return type nullptr_t. 11067 if (isa<CallExpr>(E)) 11068 return; 11069 11070 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11071 const Expr::NullPointerConstantKind NullKind = 11072 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11073 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11074 return; 11075 11076 // Return if target type is a safe conversion. 11077 if (T->isAnyPointerType() || T->isBlockPointerType() || 11078 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11079 return; 11080 11081 SourceLocation Loc = E->getSourceRange().getBegin(); 11082 11083 // Venture through the macro stacks to get to the source of macro arguments. 11084 // The new location is a better location than the complete location that was 11085 // passed in. 11086 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11087 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11088 11089 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11090 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11091 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11092 Loc, S.SourceMgr, S.getLangOpts()); 11093 if (MacroName == "NULL") 11094 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11095 } 11096 11097 // Only warn if the null and context location are in the same macro expansion. 11098 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11099 return; 11100 11101 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11102 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11103 << FixItHint::CreateReplacement(Loc, 11104 S.getFixItZeroLiteralForType(T, Loc)); 11105 } 11106 11107 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11108 ObjCArrayLiteral *ArrayLiteral); 11109 11110 static void 11111 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11112 ObjCDictionaryLiteral *DictionaryLiteral); 11113 11114 /// Check a single element within a collection literal against the 11115 /// target element type. 11116 static void checkObjCCollectionLiteralElement(Sema &S, 11117 QualType TargetElementType, 11118 Expr *Element, 11119 unsigned ElementKind) { 11120 // Skip a bitcast to 'id' or qualified 'id'. 11121 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11122 if (ICE->getCastKind() == CK_BitCast && 11123 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11124 Element = ICE->getSubExpr(); 11125 } 11126 11127 QualType ElementType = Element->getType(); 11128 ExprResult ElementResult(Element); 11129 if (ElementType->getAs<ObjCObjectPointerType>() && 11130 S.CheckSingleAssignmentConstraints(TargetElementType, 11131 ElementResult, 11132 false, false) 11133 != Sema::Compatible) { 11134 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11135 << ElementType << ElementKind << TargetElementType 11136 << Element->getSourceRange(); 11137 } 11138 11139 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11140 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11141 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11142 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11143 } 11144 11145 /// Check an Objective-C array literal being converted to the given 11146 /// target type. 11147 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11148 ObjCArrayLiteral *ArrayLiteral) { 11149 if (!S.NSArrayDecl) 11150 return; 11151 11152 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11153 if (!TargetObjCPtr) 11154 return; 11155 11156 if (TargetObjCPtr->isUnspecialized() || 11157 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11158 != S.NSArrayDecl->getCanonicalDecl()) 11159 return; 11160 11161 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11162 if (TypeArgs.size() != 1) 11163 return; 11164 11165 QualType TargetElementType = TypeArgs[0]; 11166 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11167 checkObjCCollectionLiteralElement(S, TargetElementType, 11168 ArrayLiteral->getElement(I), 11169 0); 11170 } 11171 } 11172 11173 /// Check an Objective-C dictionary literal being converted to the given 11174 /// target type. 11175 static void 11176 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11177 ObjCDictionaryLiteral *DictionaryLiteral) { 11178 if (!S.NSDictionaryDecl) 11179 return; 11180 11181 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11182 if (!TargetObjCPtr) 11183 return; 11184 11185 if (TargetObjCPtr->isUnspecialized() || 11186 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11187 != S.NSDictionaryDecl->getCanonicalDecl()) 11188 return; 11189 11190 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11191 if (TypeArgs.size() != 2) 11192 return; 11193 11194 QualType TargetKeyType = TypeArgs[0]; 11195 QualType TargetObjectType = TypeArgs[1]; 11196 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11197 auto Element = DictionaryLiteral->getKeyValueElement(I); 11198 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11199 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11200 } 11201 } 11202 11203 // Helper function to filter out cases for constant width constant conversion. 11204 // Don't warn on char array initialization or for non-decimal values. 11205 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11206 SourceLocation CC) { 11207 // If initializing from a constant, and the constant starts with '0', 11208 // then it is a binary, octal, or hexadecimal. Allow these constants 11209 // to fill all the bits, even if there is a sign change. 11210 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11211 const char FirstLiteralCharacter = 11212 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11213 if (FirstLiteralCharacter == '0') 11214 return false; 11215 } 11216 11217 // If the CC location points to a '{', and the type is char, then assume 11218 // assume it is an array initialization. 11219 if (CC.isValid() && T->isCharType()) { 11220 const char FirstContextCharacter = 11221 S.getSourceManager().getCharacterData(CC)[0]; 11222 if (FirstContextCharacter == '{') 11223 return false; 11224 } 11225 11226 return true; 11227 } 11228 11229 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11230 const auto *IL = dyn_cast<IntegerLiteral>(E); 11231 if (!IL) { 11232 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11233 if (UO->getOpcode() == UO_Minus) 11234 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11235 } 11236 } 11237 11238 return IL; 11239 } 11240 11241 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11242 E = E->IgnoreParenImpCasts(); 11243 SourceLocation ExprLoc = E->getExprLoc(); 11244 11245 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11246 BinaryOperator::Opcode Opc = BO->getOpcode(); 11247 Expr::EvalResult Result; 11248 // Do not diagnose unsigned shifts. 11249 if (Opc == BO_Shl) { 11250 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11251 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11252 if (LHS && LHS->getValue() == 0) 11253 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11254 else if (!E->isValueDependent() && LHS && RHS && 11255 RHS->getValue().isNonNegative() && 11256 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11257 S.Diag(ExprLoc, diag::warn_left_shift_always) 11258 << (Result.Val.getInt() != 0); 11259 else if (E->getType()->isSignedIntegerType()) 11260 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11261 } 11262 } 11263 11264 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11265 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11266 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11267 if (!LHS || !RHS) 11268 return; 11269 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11270 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11271 // Do not diagnose common idioms. 11272 return; 11273 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11274 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11275 } 11276 } 11277 11278 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11279 SourceLocation CC, 11280 bool *ICContext = nullptr, 11281 bool IsListInit = false) { 11282 if (E->isTypeDependent() || E->isValueDependent()) return; 11283 11284 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11285 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11286 if (Source == Target) return; 11287 if (Target->isDependentType()) return; 11288 11289 // If the conversion context location is invalid don't complain. We also 11290 // don't want to emit a warning if the issue occurs from the expansion of 11291 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11292 // delay this check as long as possible. Once we detect we are in that 11293 // scenario, we just return. 11294 if (CC.isInvalid()) 11295 return; 11296 11297 if (Source->isAtomicType()) 11298 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11299 11300 // Diagnose implicit casts to bool. 11301 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11302 if (isa<StringLiteral>(E)) 11303 // Warn on string literal to bool. Checks for string literals in logical 11304 // and expressions, for instance, assert(0 && "error here"), are 11305 // prevented by a check in AnalyzeImplicitConversions(). 11306 return DiagnoseImpCast(S, E, T, CC, 11307 diag::warn_impcast_string_literal_to_bool); 11308 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11309 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11310 // This covers the literal expressions that evaluate to Objective-C 11311 // objects. 11312 return DiagnoseImpCast(S, E, T, CC, 11313 diag::warn_impcast_objective_c_literal_to_bool); 11314 } 11315 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11316 // Warn on pointer to bool conversion that is always true. 11317 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11318 SourceRange(CC)); 11319 } 11320 } 11321 11322 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11323 // is a typedef for signed char (macOS), then that constant value has to be 1 11324 // or 0. 11325 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11326 Expr::EvalResult Result; 11327 if (E->EvaluateAsInt(Result, S.getASTContext(), 11328 Expr::SE_AllowSideEffects)) { 11329 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11330 adornObjCBoolConversionDiagWithTernaryFixit( 11331 S, E, 11332 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11333 << Result.Val.getInt().toString(10)); 11334 } 11335 return; 11336 } 11337 } 11338 11339 // Check implicit casts from Objective-C collection literals to specialized 11340 // collection types, e.g., NSArray<NSString *> *. 11341 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11342 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11343 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11344 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11345 11346 // Strip vector types. 11347 if (isa<VectorType>(Source)) { 11348 if (!isa<VectorType>(Target)) { 11349 if (S.SourceMgr.isInSystemMacro(CC)) 11350 return; 11351 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11352 } 11353 11354 // If the vector cast is cast between two vectors of the same size, it is 11355 // a bitcast, not a conversion. 11356 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11357 return; 11358 11359 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11360 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11361 } 11362 if (auto VecTy = dyn_cast<VectorType>(Target)) 11363 Target = VecTy->getElementType().getTypePtr(); 11364 11365 // Strip complex types. 11366 if (isa<ComplexType>(Source)) { 11367 if (!isa<ComplexType>(Target)) { 11368 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11369 return; 11370 11371 return DiagnoseImpCast(S, E, T, CC, 11372 S.getLangOpts().CPlusPlus 11373 ? diag::err_impcast_complex_scalar 11374 : diag::warn_impcast_complex_scalar); 11375 } 11376 11377 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11378 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11379 } 11380 11381 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11382 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11383 11384 // If the source is floating point... 11385 if (SourceBT && SourceBT->isFloatingPoint()) { 11386 // ...and the target is floating point... 11387 if (TargetBT && TargetBT->isFloatingPoint()) { 11388 // ...then warn if we're dropping FP rank. 11389 11390 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11391 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11392 if (Order > 0) { 11393 // Don't warn about float constants that are precisely 11394 // representable in the target type. 11395 Expr::EvalResult result; 11396 if (E->EvaluateAsRValue(result, S.Context)) { 11397 // Value might be a float, a float vector, or a float complex. 11398 if (IsSameFloatAfterCast(result.Val, 11399 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11400 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11401 return; 11402 } 11403 11404 if (S.SourceMgr.isInSystemMacro(CC)) 11405 return; 11406 11407 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11408 } 11409 // ... or possibly if we're increasing rank, too 11410 else if (Order < 0) { 11411 if (S.SourceMgr.isInSystemMacro(CC)) 11412 return; 11413 11414 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11415 } 11416 return; 11417 } 11418 11419 // If the target is integral, always warn. 11420 if (TargetBT && TargetBT->isInteger()) { 11421 if (S.SourceMgr.isInSystemMacro(CC)) 11422 return; 11423 11424 DiagnoseFloatingImpCast(S, E, T, CC); 11425 } 11426 11427 // Detect the case where a call result is converted from floating-point to 11428 // to bool, and the final argument to the call is converted from bool, to 11429 // discover this typo: 11430 // 11431 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11432 // 11433 // FIXME: This is an incredibly special case; is there some more general 11434 // way to detect this class of misplaced-parentheses bug? 11435 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11436 // Check last argument of function call to see if it is an 11437 // implicit cast from a type matching the type the result 11438 // is being cast to. 11439 CallExpr *CEx = cast<CallExpr>(E); 11440 if (unsigned NumArgs = CEx->getNumArgs()) { 11441 Expr *LastA = CEx->getArg(NumArgs - 1); 11442 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11443 if (isa<ImplicitCastExpr>(LastA) && 11444 InnerE->getType()->isBooleanType()) { 11445 // Warn on this floating-point to bool conversion 11446 DiagnoseImpCast(S, E, T, CC, 11447 diag::warn_impcast_floating_point_to_bool); 11448 } 11449 } 11450 } 11451 return; 11452 } 11453 11454 // Valid casts involving fixed point types should be accounted for here. 11455 if (Source->isFixedPointType()) { 11456 if (Target->isUnsaturatedFixedPointType()) { 11457 Expr::EvalResult Result; 11458 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11459 S.isConstantEvaluated())) { 11460 APFixedPoint Value = Result.Val.getFixedPoint(); 11461 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11462 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11463 if (Value > MaxVal || Value < MinVal) { 11464 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11465 S.PDiag(diag::warn_impcast_fixed_point_range) 11466 << Value.toString() << T 11467 << E->getSourceRange() 11468 << clang::SourceRange(CC)); 11469 return; 11470 } 11471 } 11472 } else if (Target->isIntegerType()) { 11473 Expr::EvalResult Result; 11474 if (!S.isConstantEvaluated() && 11475 E->EvaluateAsFixedPoint(Result, S.Context, 11476 Expr::SE_AllowSideEffects)) { 11477 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11478 11479 bool Overflowed; 11480 llvm::APSInt IntResult = FXResult.convertToInt( 11481 S.Context.getIntWidth(T), 11482 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11483 11484 if (Overflowed) { 11485 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11486 S.PDiag(diag::warn_impcast_fixed_point_range) 11487 << FXResult.toString() << T 11488 << E->getSourceRange() 11489 << clang::SourceRange(CC)); 11490 return; 11491 } 11492 } 11493 } 11494 } else if (Target->isUnsaturatedFixedPointType()) { 11495 if (Source->isIntegerType()) { 11496 Expr::EvalResult Result; 11497 if (!S.isConstantEvaluated() && 11498 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11499 llvm::APSInt Value = Result.Val.getInt(); 11500 11501 bool Overflowed; 11502 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11503 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11504 11505 if (Overflowed) { 11506 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11507 S.PDiag(diag::warn_impcast_fixed_point_range) 11508 << Value.toString(/*Radix=*/10) << T 11509 << E->getSourceRange() 11510 << clang::SourceRange(CC)); 11511 return; 11512 } 11513 } 11514 } 11515 } 11516 11517 // If we are casting an integer type to a floating point type without 11518 // initialization-list syntax, we might lose accuracy if the floating 11519 // point type has a narrower significand than the integer type. 11520 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11521 TargetBT->isFloatingType() && !IsListInit) { 11522 // Determine the number of precision bits in the source integer type. 11523 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11524 unsigned int SourcePrecision = SourceRange.Width; 11525 11526 // Determine the number of precision bits in the 11527 // target floating point type. 11528 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11529 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11530 11531 if (SourcePrecision > 0 && TargetPrecision > 0 && 11532 SourcePrecision > TargetPrecision) { 11533 11534 llvm::APSInt SourceInt; 11535 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11536 // If the source integer is a constant, convert it to the target 11537 // floating point type. Issue a warning if the value changes 11538 // during the whole conversion. 11539 llvm::APFloat TargetFloatValue( 11540 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11541 llvm::APFloat::opStatus ConversionStatus = 11542 TargetFloatValue.convertFromAPInt( 11543 SourceInt, SourceBT->isSignedInteger(), 11544 llvm::APFloat::rmNearestTiesToEven); 11545 11546 if (ConversionStatus != llvm::APFloat::opOK) { 11547 std::string PrettySourceValue = SourceInt.toString(10); 11548 SmallString<32> PrettyTargetValue; 11549 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11550 11551 S.DiagRuntimeBehavior( 11552 E->getExprLoc(), E, 11553 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11554 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11555 << E->getSourceRange() << clang::SourceRange(CC)); 11556 } 11557 } else { 11558 // Otherwise, the implicit conversion may lose precision. 11559 DiagnoseImpCast(S, E, T, CC, 11560 diag::warn_impcast_integer_float_precision); 11561 } 11562 } 11563 } 11564 11565 DiagnoseNullConversion(S, E, T, CC); 11566 11567 S.DiscardMisalignedMemberAddress(Target, E); 11568 11569 if (Target->isBooleanType()) 11570 DiagnoseIntInBoolContext(S, E); 11571 11572 if (!Source->isIntegerType() || !Target->isIntegerType()) 11573 return; 11574 11575 // TODO: remove this early return once the false positives for constant->bool 11576 // in templates, macros, etc, are reduced or removed. 11577 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11578 return; 11579 11580 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11581 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11582 return adornObjCBoolConversionDiagWithTernaryFixit( 11583 S, E, 11584 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11585 << E->getType()); 11586 } 11587 11588 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11589 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11590 11591 if (SourceRange.Width > TargetRange.Width) { 11592 // If the source is a constant, use a default-on diagnostic. 11593 // TODO: this should happen for bitfield stores, too. 11594 Expr::EvalResult Result; 11595 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11596 S.isConstantEvaluated())) { 11597 llvm::APSInt Value(32); 11598 Value = Result.Val.getInt(); 11599 11600 if (S.SourceMgr.isInSystemMacro(CC)) 11601 return; 11602 11603 std::string PrettySourceValue = Value.toString(10); 11604 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11605 11606 S.DiagRuntimeBehavior( 11607 E->getExprLoc(), E, 11608 S.PDiag(diag::warn_impcast_integer_precision_constant) 11609 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11610 << E->getSourceRange() << clang::SourceRange(CC)); 11611 return; 11612 } 11613 11614 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11615 if (S.SourceMgr.isInSystemMacro(CC)) 11616 return; 11617 11618 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11619 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11620 /* pruneControlFlow */ true); 11621 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11622 } 11623 11624 if (TargetRange.Width > SourceRange.Width) { 11625 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11626 if (UO->getOpcode() == UO_Minus) 11627 if (Source->isUnsignedIntegerType()) { 11628 if (Target->isUnsignedIntegerType()) 11629 return DiagnoseImpCast(S, E, T, CC, 11630 diag::warn_impcast_high_order_zero_bits); 11631 if (Target->isSignedIntegerType()) 11632 return DiagnoseImpCast(S, E, T, CC, 11633 diag::warn_impcast_nonnegative_result); 11634 } 11635 } 11636 11637 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11638 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11639 // Warn when doing a signed to signed conversion, warn if the positive 11640 // source value is exactly the width of the target type, which will 11641 // cause a negative value to be stored. 11642 11643 Expr::EvalResult Result; 11644 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11645 !S.SourceMgr.isInSystemMacro(CC)) { 11646 llvm::APSInt Value = Result.Val.getInt(); 11647 if (isSameWidthConstantConversion(S, E, T, CC)) { 11648 std::string PrettySourceValue = Value.toString(10); 11649 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11650 11651 S.DiagRuntimeBehavior( 11652 E->getExprLoc(), E, 11653 S.PDiag(diag::warn_impcast_integer_precision_constant) 11654 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11655 << E->getSourceRange() << clang::SourceRange(CC)); 11656 return; 11657 } 11658 } 11659 11660 // Fall through for non-constants to give a sign conversion warning. 11661 } 11662 11663 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11664 (!TargetRange.NonNegative && SourceRange.NonNegative && 11665 SourceRange.Width == TargetRange.Width)) { 11666 if (S.SourceMgr.isInSystemMacro(CC)) 11667 return; 11668 11669 unsigned DiagID = diag::warn_impcast_integer_sign; 11670 11671 // Traditionally, gcc has warned about this under -Wsign-compare. 11672 // We also want to warn about it in -Wconversion. 11673 // So if -Wconversion is off, use a completely identical diagnostic 11674 // in the sign-compare group. 11675 // The conditional-checking code will 11676 if (ICContext) { 11677 DiagID = diag::warn_impcast_integer_sign_conditional; 11678 *ICContext = true; 11679 } 11680 11681 return DiagnoseImpCast(S, E, T, CC, DiagID); 11682 } 11683 11684 // Diagnose conversions between different enumeration types. 11685 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11686 // type, to give us better diagnostics. 11687 QualType SourceType = E->getType(); 11688 if (!S.getLangOpts().CPlusPlus) { 11689 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11690 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11691 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11692 SourceType = S.Context.getTypeDeclType(Enum); 11693 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11694 } 11695 } 11696 11697 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11698 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11699 if (SourceEnum->getDecl()->hasNameForLinkage() && 11700 TargetEnum->getDecl()->hasNameForLinkage() && 11701 SourceEnum != TargetEnum) { 11702 if (S.SourceMgr.isInSystemMacro(CC)) 11703 return; 11704 11705 return DiagnoseImpCast(S, E, SourceType, T, CC, 11706 diag::warn_impcast_different_enum_types); 11707 } 11708 } 11709 11710 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11711 SourceLocation CC, QualType T); 11712 11713 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11714 SourceLocation CC, bool &ICContext) { 11715 E = E->IgnoreParenImpCasts(); 11716 11717 if (isa<ConditionalOperator>(E)) 11718 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11719 11720 AnalyzeImplicitConversions(S, E, CC); 11721 if (E->getType() != T) 11722 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11723 } 11724 11725 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11726 SourceLocation CC, QualType T) { 11727 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11728 11729 bool Suspicious = false; 11730 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11731 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11732 11733 if (T->isBooleanType()) 11734 DiagnoseIntInBoolContext(S, E); 11735 11736 // If -Wconversion would have warned about either of the candidates 11737 // for a signedness conversion to the context type... 11738 if (!Suspicious) return; 11739 11740 // ...but it's currently ignored... 11741 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11742 return; 11743 11744 // ...then check whether it would have warned about either of the 11745 // candidates for a signedness conversion to the condition type. 11746 if (E->getType() == T) return; 11747 11748 Suspicious = false; 11749 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11750 E->getType(), CC, &Suspicious); 11751 if (!Suspicious) 11752 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11753 E->getType(), CC, &Suspicious); 11754 } 11755 11756 /// Check conversion of given expression to boolean. 11757 /// Input argument E is a logical expression. 11758 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11759 if (S.getLangOpts().Bool) 11760 return; 11761 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11762 return; 11763 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11764 } 11765 11766 namespace { 11767 struct AnalyzeImplicitConversionsWorkItem { 11768 Expr *E; 11769 SourceLocation CC; 11770 bool IsListInit; 11771 }; 11772 } 11773 11774 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11775 /// that should be visited are added to WorkList. 11776 static void AnalyzeImplicitConversions( 11777 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11778 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11779 Expr *OrigE = Item.E; 11780 SourceLocation CC = Item.CC; 11781 11782 QualType T = OrigE->getType(); 11783 Expr *E = OrigE->IgnoreParenImpCasts(); 11784 11785 // Propagate whether we are in a C++ list initialization expression. 11786 // If so, we do not issue warnings for implicit int-float conversion 11787 // precision loss, because C++11 narrowing already handles it. 11788 bool IsListInit = Item.IsListInit || 11789 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11790 11791 if (E->isTypeDependent() || E->isValueDependent()) 11792 return; 11793 11794 Expr *SourceExpr = E; 11795 // Examine, but don't traverse into the source expression of an 11796 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11797 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11798 // evaluate it in the context of checking the specific conversion to T though. 11799 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11800 if (auto *Src = OVE->getSourceExpr()) 11801 SourceExpr = Src; 11802 11803 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11804 if (UO->getOpcode() == UO_Not && 11805 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11806 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11807 << OrigE->getSourceRange() << T->isBooleanType() 11808 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11809 11810 // For conditional operators, we analyze the arguments as if they 11811 // were being fed directly into the output. 11812 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11813 CheckConditionalOperator(S, CO, CC, T); 11814 return; 11815 } 11816 11817 // Check implicit argument conversions for function calls. 11818 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11819 CheckImplicitArgumentConversions(S, Call, CC); 11820 11821 // Go ahead and check any implicit conversions we might have skipped. 11822 // The non-canonical typecheck is just an optimization; 11823 // CheckImplicitConversion will filter out dead implicit conversions. 11824 if (SourceExpr->getType() != T) 11825 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11826 11827 // Now continue drilling into this expression. 11828 11829 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11830 // The bound subexpressions in a PseudoObjectExpr are not reachable 11831 // as transitive children. 11832 // FIXME: Use a more uniform representation for this. 11833 for (auto *SE : POE->semantics()) 11834 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11835 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11836 } 11837 11838 // Skip past explicit casts. 11839 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11840 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11841 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11842 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11843 WorkList.push_back({E, CC, IsListInit}); 11844 return; 11845 } 11846 11847 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11848 // Do a somewhat different check with comparison operators. 11849 if (BO->isComparisonOp()) 11850 return AnalyzeComparison(S, BO); 11851 11852 // And with simple assignments. 11853 if (BO->getOpcode() == BO_Assign) 11854 return AnalyzeAssignment(S, BO); 11855 // And with compound assignments. 11856 if (BO->isAssignmentOp()) 11857 return AnalyzeCompoundAssignment(S, BO); 11858 } 11859 11860 // These break the otherwise-useful invariant below. Fortunately, 11861 // we don't really need to recurse into them, because any internal 11862 // expressions should have been analyzed already when they were 11863 // built into statements. 11864 if (isa<StmtExpr>(E)) return; 11865 11866 // Don't descend into unevaluated contexts. 11867 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11868 11869 // Now just recurse over the expression's children. 11870 CC = E->getExprLoc(); 11871 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11872 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11873 for (Stmt *SubStmt : E->children()) { 11874 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11875 if (!ChildExpr) 11876 continue; 11877 11878 if (IsLogicalAndOperator && 11879 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11880 // Ignore checking string literals that are in logical and operators. 11881 // This is a common pattern for asserts. 11882 continue; 11883 WorkList.push_back({ChildExpr, CC, IsListInit}); 11884 } 11885 11886 if (BO && BO->isLogicalOp()) { 11887 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11888 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11889 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11890 11891 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11892 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11893 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11894 } 11895 11896 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11897 if (U->getOpcode() == UO_LNot) { 11898 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11899 } else if (U->getOpcode() != UO_AddrOf) { 11900 if (U->getSubExpr()->getType()->isAtomicType()) 11901 S.Diag(U->getSubExpr()->getBeginLoc(), 11902 diag::warn_atomic_implicit_seq_cst); 11903 } 11904 } 11905 } 11906 11907 /// AnalyzeImplicitConversions - Find and report any interesting 11908 /// implicit conversions in the given expression. There are a couple 11909 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11910 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11911 bool IsListInit/*= false*/) { 11912 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 11913 WorkList.push_back({OrigE, CC, IsListInit}); 11914 while (!WorkList.empty()) 11915 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 11916 } 11917 11918 /// Diagnose integer type and any valid implicit conversion to it. 11919 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11920 // Taking into account implicit conversions, 11921 // allow any integer. 11922 if (!E->getType()->isIntegerType()) { 11923 S.Diag(E->getBeginLoc(), 11924 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11925 return true; 11926 } 11927 // Potentially emit standard warnings for implicit conversions if enabled 11928 // using -Wconversion. 11929 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11930 return false; 11931 } 11932 11933 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11934 // Returns true when emitting a warning about taking the address of a reference. 11935 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11936 const PartialDiagnostic &PD) { 11937 E = E->IgnoreParenImpCasts(); 11938 11939 const FunctionDecl *FD = nullptr; 11940 11941 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11942 if (!DRE->getDecl()->getType()->isReferenceType()) 11943 return false; 11944 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11945 if (!M->getMemberDecl()->getType()->isReferenceType()) 11946 return false; 11947 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11948 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11949 return false; 11950 FD = Call->getDirectCallee(); 11951 } else { 11952 return false; 11953 } 11954 11955 SemaRef.Diag(E->getExprLoc(), PD); 11956 11957 // If possible, point to location of function. 11958 if (FD) { 11959 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11960 } 11961 11962 return true; 11963 } 11964 11965 // Returns true if the SourceLocation is expanded from any macro body. 11966 // Returns false if the SourceLocation is invalid, is from not in a macro 11967 // expansion, or is from expanded from a top-level macro argument. 11968 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11969 if (Loc.isInvalid()) 11970 return false; 11971 11972 while (Loc.isMacroID()) { 11973 if (SM.isMacroBodyExpansion(Loc)) 11974 return true; 11975 Loc = SM.getImmediateMacroCallerLoc(Loc); 11976 } 11977 11978 return false; 11979 } 11980 11981 /// Diagnose pointers that are always non-null. 11982 /// \param E the expression containing the pointer 11983 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11984 /// compared to a null pointer 11985 /// \param IsEqual True when the comparison is equal to a null pointer 11986 /// \param Range Extra SourceRange to highlight in the diagnostic 11987 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11988 Expr::NullPointerConstantKind NullKind, 11989 bool IsEqual, SourceRange Range) { 11990 if (!E) 11991 return; 11992 11993 // Don't warn inside macros. 11994 if (E->getExprLoc().isMacroID()) { 11995 const SourceManager &SM = getSourceManager(); 11996 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11997 IsInAnyMacroBody(SM, Range.getBegin())) 11998 return; 11999 } 12000 E = E->IgnoreImpCasts(); 12001 12002 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12003 12004 if (isa<CXXThisExpr>(E)) { 12005 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12006 : diag::warn_this_bool_conversion; 12007 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12008 return; 12009 } 12010 12011 bool IsAddressOf = false; 12012 12013 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12014 if (UO->getOpcode() != UO_AddrOf) 12015 return; 12016 IsAddressOf = true; 12017 E = UO->getSubExpr(); 12018 } 12019 12020 if (IsAddressOf) { 12021 unsigned DiagID = IsCompare 12022 ? diag::warn_address_of_reference_null_compare 12023 : diag::warn_address_of_reference_bool_conversion; 12024 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12025 << IsEqual; 12026 if (CheckForReference(*this, E, PD)) { 12027 return; 12028 } 12029 } 12030 12031 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12032 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12033 std::string Str; 12034 llvm::raw_string_ostream S(Str); 12035 E->printPretty(S, nullptr, getPrintingPolicy()); 12036 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12037 : diag::warn_cast_nonnull_to_bool; 12038 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12039 << E->getSourceRange() << Range << IsEqual; 12040 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12041 }; 12042 12043 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12044 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12045 if (auto *Callee = Call->getDirectCallee()) { 12046 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12047 ComplainAboutNonnullParamOrCall(A); 12048 return; 12049 } 12050 } 12051 } 12052 12053 // Expect to find a single Decl. Skip anything more complicated. 12054 ValueDecl *D = nullptr; 12055 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12056 D = R->getDecl(); 12057 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12058 D = M->getMemberDecl(); 12059 } 12060 12061 // Weak Decls can be null. 12062 if (!D || D->isWeak()) 12063 return; 12064 12065 // Check for parameter decl with nonnull attribute 12066 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12067 if (getCurFunction() && 12068 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12069 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12070 ComplainAboutNonnullParamOrCall(A); 12071 return; 12072 } 12073 12074 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12075 // Skip function template not specialized yet. 12076 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12077 return; 12078 auto ParamIter = llvm::find(FD->parameters(), PV); 12079 assert(ParamIter != FD->param_end()); 12080 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12081 12082 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12083 if (!NonNull->args_size()) { 12084 ComplainAboutNonnullParamOrCall(NonNull); 12085 return; 12086 } 12087 12088 for (const ParamIdx &ArgNo : NonNull->args()) { 12089 if (ArgNo.getASTIndex() == ParamNo) { 12090 ComplainAboutNonnullParamOrCall(NonNull); 12091 return; 12092 } 12093 } 12094 } 12095 } 12096 } 12097 } 12098 12099 QualType T = D->getType(); 12100 const bool IsArray = T->isArrayType(); 12101 const bool IsFunction = T->isFunctionType(); 12102 12103 // Address of function is used to silence the function warning. 12104 if (IsAddressOf && IsFunction) { 12105 return; 12106 } 12107 12108 // Found nothing. 12109 if (!IsAddressOf && !IsFunction && !IsArray) 12110 return; 12111 12112 // Pretty print the expression for the diagnostic. 12113 std::string Str; 12114 llvm::raw_string_ostream S(Str); 12115 E->printPretty(S, nullptr, getPrintingPolicy()); 12116 12117 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12118 : diag::warn_impcast_pointer_to_bool; 12119 enum { 12120 AddressOf, 12121 FunctionPointer, 12122 ArrayPointer 12123 } DiagType; 12124 if (IsAddressOf) 12125 DiagType = AddressOf; 12126 else if (IsFunction) 12127 DiagType = FunctionPointer; 12128 else if (IsArray) 12129 DiagType = ArrayPointer; 12130 else 12131 llvm_unreachable("Could not determine diagnostic."); 12132 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12133 << Range << IsEqual; 12134 12135 if (!IsFunction) 12136 return; 12137 12138 // Suggest '&' to silence the function warning. 12139 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12140 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12141 12142 // Check to see if '()' fixit should be emitted. 12143 QualType ReturnType; 12144 UnresolvedSet<4> NonTemplateOverloads; 12145 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12146 if (ReturnType.isNull()) 12147 return; 12148 12149 if (IsCompare) { 12150 // There are two cases here. If there is null constant, the only suggest 12151 // for a pointer return type. If the null is 0, then suggest if the return 12152 // type is a pointer or an integer type. 12153 if (!ReturnType->isPointerType()) { 12154 if (NullKind == Expr::NPCK_ZeroExpression || 12155 NullKind == Expr::NPCK_ZeroLiteral) { 12156 if (!ReturnType->isIntegerType()) 12157 return; 12158 } else { 12159 return; 12160 } 12161 } 12162 } else { // !IsCompare 12163 // For function to bool, only suggest if the function pointer has bool 12164 // return type. 12165 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12166 return; 12167 } 12168 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12169 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12170 } 12171 12172 /// Diagnoses "dangerous" implicit conversions within the given 12173 /// expression (which is a full expression). Implements -Wconversion 12174 /// and -Wsign-compare. 12175 /// 12176 /// \param CC the "context" location of the implicit conversion, i.e. 12177 /// the most location of the syntactic entity requiring the implicit 12178 /// conversion 12179 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12180 // Don't diagnose in unevaluated contexts. 12181 if (isUnevaluatedContext()) 12182 return; 12183 12184 // Don't diagnose for value- or type-dependent expressions. 12185 if (E->isTypeDependent() || E->isValueDependent()) 12186 return; 12187 12188 // Check for array bounds violations in cases where the check isn't triggered 12189 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12190 // ArraySubscriptExpr is on the RHS of a variable initialization. 12191 CheckArrayAccess(E); 12192 12193 // This is not the right CC for (e.g.) a variable initialization. 12194 AnalyzeImplicitConversions(*this, E, CC); 12195 } 12196 12197 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12198 /// Input argument E is a logical expression. 12199 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12200 ::CheckBoolLikeConversion(*this, E, CC); 12201 } 12202 12203 /// Diagnose when expression is an integer constant expression and its evaluation 12204 /// results in integer overflow 12205 void Sema::CheckForIntOverflow (Expr *E) { 12206 // Use a work list to deal with nested struct initializers. 12207 SmallVector<Expr *, 2> Exprs(1, E); 12208 12209 do { 12210 Expr *OriginalE = Exprs.pop_back_val(); 12211 Expr *E = OriginalE->IgnoreParenCasts(); 12212 12213 if (isa<BinaryOperator>(E)) { 12214 E->EvaluateForOverflow(Context); 12215 continue; 12216 } 12217 12218 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12219 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12220 else if (isa<ObjCBoxedExpr>(OriginalE)) 12221 E->EvaluateForOverflow(Context); 12222 else if (auto Call = dyn_cast<CallExpr>(E)) 12223 Exprs.append(Call->arg_begin(), Call->arg_end()); 12224 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12225 Exprs.append(Message->arg_begin(), Message->arg_end()); 12226 } while (!Exprs.empty()); 12227 } 12228 12229 namespace { 12230 12231 /// Visitor for expressions which looks for unsequenced operations on the 12232 /// same object. 12233 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12234 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12235 12236 /// A tree of sequenced regions within an expression. Two regions are 12237 /// unsequenced if one is an ancestor or a descendent of the other. When we 12238 /// finish processing an expression with sequencing, such as a comma 12239 /// expression, we fold its tree nodes into its parent, since they are 12240 /// unsequenced with respect to nodes we will visit later. 12241 class SequenceTree { 12242 struct Value { 12243 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12244 unsigned Parent : 31; 12245 unsigned Merged : 1; 12246 }; 12247 SmallVector<Value, 8> Values; 12248 12249 public: 12250 /// A region within an expression which may be sequenced with respect 12251 /// to some other region. 12252 class Seq { 12253 friend class SequenceTree; 12254 12255 unsigned Index; 12256 12257 explicit Seq(unsigned N) : Index(N) {} 12258 12259 public: 12260 Seq() : Index(0) {} 12261 }; 12262 12263 SequenceTree() { Values.push_back(Value(0)); } 12264 Seq root() const { return Seq(0); } 12265 12266 /// Create a new sequence of operations, which is an unsequenced 12267 /// subset of \p Parent. This sequence of operations is sequenced with 12268 /// respect to other children of \p Parent. 12269 Seq allocate(Seq Parent) { 12270 Values.push_back(Value(Parent.Index)); 12271 return Seq(Values.size() - 1); 12272 } 12273 12274 /// Merge a sequence of operations into its parent. 12275 void merge(Seq S) { 12276 Values[S.Index].Merged = true; 12277 } 12278 12279 /// Determine whether two operations are unsequenced. This operation 12280 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12281 /// should have been merged into its parent as appropriate. 12282 bool isUnsequenced(Seq Cur, Seq Old) { 12283 unsigned C = representative(Cur.Index); 12284 unsigned Target = representative(Old.Index); 12285 while (C >= Target) { 12286 if (C == Target) 12287 return true; 12288 C = Values[C].Parent; 12289 } 12290 return false; 12291 } 12292 12293 private: 12294 /// Pick a representative for a sequence. 12295 unsigned representative(unsigned K) { 12296 if (Values[K].Merged) 12297 // Perform path compression as we go. 12298 return Values[K].Parent = representative(Values[K].Parent); 12299 return K; 12300 } 12301 }; 12302 12303 /// An object for which we can track unsequenced uses. 12304 using Object = const NamedDecl *; 12305 12306 /// Different flavors of object usage which we track. We only track the 12307 /// least-sequenced usage of each kind. 12308 enum UsageKind { 12309 /// A read of an object. Multiple unsequenced reads are OK. 12310 UK_Use, 12311 12312 /// A modification of an object which is sequenced before the value 12313 /// computation of the expression, such as ++n in C++. 12314 UK_ModAsValue, 12315 12316 /// A modification of an object which is not sequenced before the value 12317 /// computation of the expression, such as n++. 12318 UK_ModAsSideEffect, 12319 12320 UK_Count = UK_ModAsSideEffect + 1 12321 }; 12322 12323 /// Bundle together a sequencing region and the expression corresponding 12324 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12325 struct Usage { 12326 const Expr *UsageExpr; 12327 SequenceTree::Seq Seq; 12328 12329 Usage() : UsageExpr(nullptr), Seq() {} 12330 }; 12331 12332 struct UsageInfo { 12333 Usage Uses[UK_Count]; 12334 12335 /// Have we issued a diagnostic for this object already? 12336 bool Diagnosed; 12337 12338 UsageInfo() : Uses(), Diagnosed(false) {} 12339 }; 12340 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12341 12342 Sema &SemaRef; 12343 12344 /// Sequenced regions within the expression. 12345 SequenceTree Tree; 12346 12347 /// Declaration modifications and references which we have seen. 12348 UsageInfoMap UsageMap; 12349 12350 /// The region we are currently within. 12351 SequenceTree::Seq Region; 12352 12353 /// Filled in with declarations which were modified as a side-effect 12354 /// (that is, post-increment operations). 12355 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12356 12357 /// Expressions to check later. We defer checking these to reduce 12358 /// stack usage. 12359 SmallVectorImpl<const Expr *> &WorkList; 12360 12361 /// RAII object wrapping the visitation of a sequenced subexpression of an 12362 /// expression. At the end of this process, the side-effects of the evaluation 12363 /// become sequenced with respect to the value computation of the result, so 12364 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12365 /// UK_ModAsValue. 12366 struct SequencedSubexpression { 12367 SequencedSubexpression(SequenceChecker &Self) 12368 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12369 Self.ModAsSideEffect = &ModAsSideEffect; 12370 } 12371 12372 ~SequencedSubexpression() { 12373 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12374 // Add a new usage with usage kind UK_ModAsValue, and then restore 12375 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12376 // the previous one was empty). 12377 UsageInfo &UI = Self.UsageMap[M.first]; 12378 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12379 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12380 SideEffectUsage = M.second; 12381 } 12382 Self.ModAsSideEffect = OldModAsSideEffect; 12383 } 12384 12385 SequenceChecker &Self; 12386 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12387 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12388 }; 12389 12390 /// RAII object wrapping the visitation of a subexpression which we might 12391 /// choose to evaluate as a constant. If any subexpression is evaluated and 12392 /// found to be non-constant, this allows us to suppress the evaluation of 12393 /// the outer expression. 12394 class EvaluationTracker { 12395 public: 12396 EvaluationTracker(SequenceChecker &Self) 12397 : Self(Self), Prev(Self.EvalTracker) { 12398 Self.EvalTracker = this; 12399 } 12400 12401 ~EvaluationTracker() { 12402 Self.EvalTracker = Prev; 12403 if (Prev) 12404 Prev->EvalOK &= EvalOK; 12405 } 12406 12407 bool evaluate(const Expr *E, bool &Result) { 12408 if (!EvalOK || E->isValueDependent()) 12409 return false; 12410 EvalOK = E->EvaluateAsBooleanCondition( 12411 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12412 return EvalOK; 12413 } 12414 12415 private: 12416 SequenceChecker &Self; 12417 EvaluationTracker *Prev; 12418 bool EvalOK = true; 12419 } *EvalTracker = nullptr; 12420 12421 /// Find the object which is produced by the specified expression, 12422 /// if any. 12423 Object getObject(const Expr *E, bool Mod) const { 12424 E = E->IgnoreParenCasts(); 12425 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12426 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12427 return getObject(UO->getSubExpr(), Mod); 12428 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12429 if (BO->getOpcode() == BO_Comma) 12430 return getObject(BO->getRHS(), Mod); 12431 if (Mod && BO->isAssignmentOp()) 12432 return getObject(BO->getLHS(), Mod); 12433 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12434 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12435 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12436 return ME->getMemberDecl(); 12437 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12438 // FIXME: If this is a reference, map through to its value. 12439 return DRE->getDecl(); 12440 return nullptr; 12441 } 12442 12443 /// Note that an object \p O was modified or used by an expression 12444 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12445 /// the object \p O as obtained via the \p UsageMap. 12446 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12447 // Get the old usage for the given object and usage kind. 12448 Usage &U = UI.Uses[UK]; 12449 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12450 // If we have a modification as side effect and are in a sequenced 12451 // subexpression, save the old Usage so that we can restore it later 12452 // in SequencedSubexpression::~SequencedSubexpression. 12453 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12454 ModAsSideEffect->push_back(std::make_pair(O, U)); 12455 // Then record the new usage with the current sequencing region. 12456 U.UsageExpr = UsageExpr; 12457 U.Seq = Region; 12458 } 12459 } 12460 12461 /// Check whether a modification or use of an object \p O in an expression 12462 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12463 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12464 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12465 /// usage and false we are checking for a mod-use unsequenced usage. 12466 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12467 UsageKind OtherKind, bool IsModMod) { 12468 if (UI.Diagnosed) 12469 return; 12470 12471 const Usage &U = UI.Uses[OtherKind]; 12472 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12473 return; 12474 12475 const Expr *Mod = U.UsageExpr; 12476 const Expr *ModOrUse = UsageExpr; 12477 if (OtherKind == UK_Use) 12478 std::swap(Mod, ModOrUse); 12479 12480 SemaRef.DiagRuntimeBehavior( 12481 Mod->getExprLoc(), {Mod, ModOrUse}, 12482 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12483 : diag::warn_unsequenced_mod_use) 12484 << O << SourceRange(ModOrUse->getExprLoc())); 12485 UI.Diagnosed = true; 12486 } 12487 12488 // A note on note{Pre, Post}{Use, Mod}: 12489 // 12490 // (It helps to follow the algorithm with an expression such as 12491 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12492 // operations before C++17 and both are well-defined in C++17). 12493 // 12494 // When visiting a node which uses/modify an object we first call notePreUse 12495 // or notePreMod before visiting its sub-expression(s). At this point the 12496 // children of the current node have not yet been visited and so the eventual 12497 // uses/modifications resulting from the children of the current node have not 12498 // been recorded yet. 12499 // 12500 // We then visit the children of the current node. After that notePostUse or 12501 // notePostMod is called. These will 1) detect an unsequenced modification 12502 // as side effect (as in "k++ + k") and 2) add a new usage with the 12503 // appropriate usage kind. 12504 // 12505 // We also have to be careful that some operation sequences modification as 12506 // side effect as well (for example: || or ,). To account for this we wrap 12507 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12508 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12509 // which record usages which are modifications as side effect, and then 12510 // downgrade them (or more accurately restore the previous usage which was a 12511 // modification as side effect) when exiting the scope of the sequenced 12512 // subexpression. 12513 12514 void notePreUse(Object O, const Expr *UseExpr) { 12515 UsageInfo &UI = UsageMap[O]; 12516 // Uses conflict with other modifications. 12517 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12518 } 12519 12520 void notePostUse(Object O, const Expr *UseExpr) { 12521 UsageInfo &UI = UsageMap[O]; 12522 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12523 /*IsModMod=*/false); 12524 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12525 } 12526 12527 void notePreMod(Object O, const Expr *ModExpr) { 12528 UsageInfo &UI = UsageMap[O]; 12529 // Modifications conflict with other modifications and with uses. 12530 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12531 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12532 } 12533 12534 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12535 UsageInfo &UI = UsageMap[O]; 12536 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12537 /*IsModMod=*/true); 12538 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12539 } 12540 12541 public: 12542 SequenceChecker(Sema &S, const Expr *E, 12543 SmallVectorImpl<const Expr *> &WorkList) 12544 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12545 Visit(E); 12546 // Silence a -Wunused-private-field since WorkList is now unused. 12547 // TODO: Evaluate if it can be used, and if not remove it. 12548 (void)this->WorkList; 12549 } 12550 12551 void VisitStmt(const Stmt *S) { 12552 // Skip all statements which aren't expressions for now. 12553 } 12554 12555 void VisitExpr(const Expr *E) { 12556 // By default, just recurse to evaluated subexpressions. 12557 Base::VisitStmt(E); 12558 } 12559 12560 void VisitCastExpr(const CastExpr *E) { 12561 Object O = Object(); 12562 if (E->getCastKind() == CK_LValueToRValue) 12563 O = getObject(E->getSubExpr(), false); 12564 12565 if (O) 12566 notePreUse(O, E); 12567 VisitExpr(E); 12568 if (O) 12569 notePostUse(O, E); 12570 } 12571 12572 void VisitSequencedExpressions(const Expr *SequencedBefore, 12573 const Expr *SequencedAfter) { 12574 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12575 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12576 SequenceTree::Seq OldRegion = Region; 12577 12578 { 12579 SequencedSubexpression SeqBefore(*this); 12580 Region = BeforeRegion; 12581 Visit(SequencedBefore); 12582 } 12583 12584 Region = AfterRegion; 12585 Visit(SequencedAfter); 12586 12587 Region = OldRegion; 12588 12589 Tree.merge(BeforeRegion); 12590 Tree.merge(AfterRegion); 12591 } 12592 12593 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12594 // C++17 [expr.sub]p1: 12595 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12596 // expression E1 is sequenced before the expression E2. 12597 if (SemaRef.getLangOpts().CPlusPlus17) 12598 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12599 else { 12600 Visit(ASE->getLHS()); 12601 Visit(ASE->getRHS()); 12602 } 12603 } 12604 12605 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12606 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12607 void VisitBinPtrMem(const BinaryOperator *BO) { 12608 // C++17 [expr.mptr.oper]p4: 12609 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12610 // the expression E1 is sequenced before the expression E2. 12611 if (SemaRef.getLangOpts().CPlusPlus17) 12612 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12613 else { 12614 Visit(BO->getLHS()); 12615 Visit(BO->getRHS()); 12616 } 12617 } 12618 12619 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12620 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12621 void VisitBinShlShr(const BinaryOperator *BO) { 12622 // C++17 [expr.shift]p4: 12623 // The expression E1 is sequenced before the expression E2. 12624 if (SemaRef.getLangOpts().CPlusPlus17) 12625 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12626 else { 12627 Visit(BO->getLHS()); 12628 Visit(BO->getRHS()); 12629 } 12630 } 12631 12632 void VisitBinComma(const BinaryOperator *BO) { 12633 // C++11 [expr.comma]p1: 12634 // Every value computation and side effect associated with the left 12635 // expression is sequenced before every value computation and side 12636 // effect associated with the right expression. 12637 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12638 } 12639 12640 void VisitBinAssign(const BinaryOperator *BO) { 12641 SequenceTree::Seq RHSRegion; 12642 SequenceTree::Seq LHSRegion; 12643 if (SemaRef.getLangOpts().CPlusPlus17) { 12644 RHSRegion = Tree.allocate(Region); 12645 LHSRegion = Tree.allocate(Region); 12646 } else { 12647 RHSRegion = Region; 12648 LHSRegion = Region; 12649 } 12650 SequenceTree::Seq OldRegion = Region; 12651 12652 // C++11 [expr.ass]p1: 12653 // [...] the assignment is sequenced after the value computation 12654 // of the right and left operands, [...] 12655 // 12656 // so check it before inspecting the operands and update the 12657 // map afterwards. 12658 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12659 if (O) 12660 notePreMod(O, BO); 12661 12662 if (SemaRef.getLangOpts().CPlusPlus17) { 12663 // C++17 [expr.ass]p1: 12664 // [...] The right operand is sequenced before the left operand. [...] 12665 { 12666 SequencedSubexpression SeqBefore(*this); 12667 Region = RHSRegion; 12668 Visit(BO->getRHS()); 12669 } 12670 12671 Region = LHSRegion; 12672 Visit(BO->getLHS()); 12673 12674 if (O && isa<CompoundAssignOperator>(BO)) 12675 notePostUse(O, BO); 12676 12677 } else { 12678 // C++11 does not specify any sequencing between the LHS and RHS. 12679 Region = LHSRegion; 12680 Visit(BO->getLHS()); 12681 12682 if (O && isa<CompoundAssignOperator>(BO)) 12683 notePostUse(O, BO); 12684 12685 Region = RHSRegion; 12686 Visit(BO->getRHS()); 12687 } 12688 12689 // C++11 [expr.ass]p1: 12690 // the assignment is sequenced [...] before the value computation of the 12691 // assignment expression. 12692 // C11 6.5.16/3 has no such rule. 12693 Region = OldRegion; 12694 if (O) 12695 notePostMod(O, BO, 12696 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12697 : UK_ModAsSideEffect); 12698 if (SemaRef.getLangOpts().CPlusPlus17) { 12699 Tree.merge(RHSRegion); 12700 Tree.merge(LHSRegion); 12701 } 12702 } 12703 12704 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12705 VisitBinAssign(CAO); 12706 } 12707 12708 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12709 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12710 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12711 Object O = getObject(UO->getSubExpr(), true); 12712 if (!O) 12713 return VisitExpr(UO); 12714 12715 notePreMod(O, UO); 12716 Visit(UO->getSubExpr()); 12717 // C++11 [expr.pre.incr]p1: 12718 // the expression ++x is equivalent to x+=1 12719 notePostMod(O, UO, 12720 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12721 : UK_ModAsSideEffect); 12722 } 12723 12724 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12725 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12726 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12727 Object O = getObject(UO->getSubExpr(), true); 12728 if (!O) 12729 return VisitExpr(UO); 12730 12731 notePreMod(O, UO); 12732 Visit(UO->getSubExpr()); 12733 notePostMod(O, UO, UK_ModAsSideEffect); 12734 } 12735 12736 void VisitBinLOr(const BinaryOperator *BO) { 12737 // C++11 [expr.log.or]p2: 12738 // If the second expression is evaluated, every value computation and 12739 // side effect associated with the first expression is sequenced before 12740 // every value computation and side effect associated with the 12741 // second expression. 12742 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12743 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12744 SequenceTree::Seq OldRegion = Region; 12745 12746 EvaluationTracker Eval(*this); 12747 { 12748 SequencedSubexpression Sequenced(*this); 12749 Region = LHSRegion; 12750 Visit(BO->getLHS()); 12751 } 12752 12753 // C++11 [expr.log.or]p1: 12754 // [...] the second operand is not evaluated if the first operand 12755 // evaluates to true. 12756 bool EvalResult = false; 12757 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12758 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12759 if (ShouldVisitRHS) { 12760 Region = RHSRegion; 12761 Visit(BO->getRHS()); 12762 } 12763 12764 Region = OldRegion; 12765 Tree.merge(LHSRegion); 12766 Tree.merge(RHSRegion); 12767 } 12768 12769 void VisitBinLAnd(const BinaryOperator *BO) { 12770 // C++11 [expr.log.and]p2: 12771 // If the second expression is evaluated, every value computation and 12772 // side effect associated with the first expression is sequenced before 12773 // every value computation and side effect associated with the 12774 // second expression. 12775 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12776 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12777 SequenceTree::Seq OldRegion = Region; 12778 12779 EvaluationTracker Eval(*this); 12780 { 12781 SequencedSubexpression Sequenced(*this); 12782 Region = LHSRegion; 12783 Visit(BO->getLHS()); 12784 } 12785 12786 // C++11 [expr.log.and]p1: 12787 // [...] the second operand is not evaluated if the first operand is false. 12788 bool EvalResult = false; 12789 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12790 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12791 if (ShouldVisitRHS) { 12792 Region = RHSRegion; 12793 Visit(BO->getRHS()); 12794 } 12795 12796 Region = OldRegion; 12797 Tree.merge(LHSRegion); 12798 Tree.merge(RHSRegion); 12799 } 12800 12801 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12802 // C++11 [expr.cond]p1: 12803 // [...] Every value computation and side effect associated with the first 12804 // expression is sequenced before every value computation and side effect 12805 // associated with the second or third expression. 12806 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12807 12808 // No sequencing is specified between the true and false expression. 12809 // However since exactly one of both is going to be evaluated we can 12810 // consider them to be sequenced. This is needed to avoid warning on 12811 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12812 // both the true and false expressions because we can't evaluate x. 12813 // This will still allow us to detect an expression like (pre C++17) 12814 // "(x ? y += 1 : y += 2) = y". 12815 // 12816 // We don't wrap the visitation of the true and false expression with 12817 // SequencedSubexpression because we don't want to downgrade modifications 12818 // as side effect in the true and false expressions after the visition 12819 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12820 // not warn between the two "y++", but we should warn between the "y++" 12821 // and the "y". 12822 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12823 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12824 SequenceTree::Seq OldRegion = Region; 12825 12826 EvaluationTracker Eval(*this); 12827 { 12828 SequencedSubexpression Sequenced(*this); 12829 Region = ConditionRegion; 12830 Visit(CO->getCond()); 12831 } 12832 12833 // C++11 [expr.cond]p1: 12834 // [...] The first expression is contextually converted to bool (Clause 4). 12835 // It is evaluated and if it is true, the result of the conditional 12836 // expression is the value of the second expression, otherwise that of the 12837 // third expression. Only one of the second and third expressions is 12838 // evaluated. [...] 12839 bool EvalResult = false; 12840 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12841 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12842 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12843 if (ShouldVisitTrueExpr) { 12844 Region = TrueRegion; 12845 Visit(CO->getTrueExpr()); 12846 } 12847 if (ShouldVisitFalseExpr) { 12848 Region = FalseRegion; 12849 Visit(CO->getFalseExpr()); 12850 } 12851 12852 Region = OldRegion; 12853 Tree.merge(ConditionRegion); 12854 Tree.merge(TrueRegion); 12855 Tree.merge(FalseRegion); 12856 } 12857 12858 void VisitCallExpr(const CallExpr *CE) { 12859 // C++11 [intro.execution]p15: 12860 // When calling a function [...], every value computation and side effect 12861 // associated with any argument expression, or with the postfix expression 12862 // designating the called function, is sequenced before execution of every 12863 // expression or statement in the body of the function [and thus before 12864 // the value computation of its result]. 12865 SequencedSubexpression Sequenced(*this); 12866 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12867 [&] { Base::VisitCallExpr(CE); }); 12868 12869 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12870 } 12871 12872 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12873 // This is a call, so all subexpressions are sequenced before the result. 12874 SequencedSubexpression Sequenced(*this); 12875 12876 if (!CCE->isListInitialization()) 12877 return VisitExpr(CCE); 12878 12879 // In C++11, list initializations are sequenced. 12880 SmallVector<SequenceTree::Seq, 32> Elts; 12881 SequenceTree::Seq Parent = Region; 12882 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12883 E = CCE->arg_end(); 12884 I != E; ++I) { 12885 Region = Tree.allocate(Parent); 12886 Elts.push_back(Region); 12887 Visit(*I); 12888 } 12889 12890 // Forget that the initializers are sequenced. 12891 Region = Parent; 12892 for (unsigned I = 0; I < Elts.size(); ++I) 12893 Tree.merge(Elts[I]); 12894 } 12895 12896 void VisitInitListExpr(const InitListExpr *ILE) { 12897 if (!SemaRef.getLangOpts().CPlusPlus11) 12898 return VisitExpr(ILE); 12899 12900 // In C++11, list initializations are sequenced. 12901 SmallVector<SequenceTree::Seq, 32> Elts; 12902 SequenceTree::Seq Parent = Region; 12903 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12904 const Expr *E = ILE->getInit(I); 12905 if (!E) 12906 continue; 12907 Region = Tree.allocate(Parent); 12908 Elts.push_back(Region); 12909 Visit(E); 12910 } 12911 12912 // Forget that the initializers are sequenced. 12913 Region = Parent; 12914 for (unsigned I = 0; I < Elts.size(); ++I) 12915 Tree.merge(Elts[I]); 12916 } 12917 }; 12918 12919 } // namespace 12920 12921 void Sema::CheckUnsequencedOperations(const Expr *E) { 12922 SmallVector<const Expr *, 8> WorkList; 12923 WorkList.push_back(E); 12924 while (!WorkList.empty()) { 12925 const Expr *Item = WorkList.pop_back_val(); 12926 SequenceChecker(*this, Item, WorkList); 12927 } 12928 } 12929 12930 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12931 bool IsConstexpr) { 12932 llvm::SaveAndRestore<bool> ConstantContext( 12933 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12934 CheckImplicitConversions(E, CheckLoc); 12935 if (!E->isInstantiationDependent()) 12936 CheckUnsequencedOperations(E); 12937 if (!IsConstexpr && !E->isValueDependent()) 12938 CheckForIntOverflow(E); 12939 DiagnoseMisalignedMembers(); 12940 } 12941 12942 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12943 FieldDecl *BitField, 12944 Expr *Init) { 12945 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12946 } 12947 12948 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12949 SourceLocation Loc) { 12950 if (!PType->isVariablyModifiedType()) 12951 return; 12952 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12953 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12954 return; 12955 } 12956 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12957 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12958 return; 12959 } 12960 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12961 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12962 return; 12963 } 12964 12965 const ArrayType *AT = S.Context.getAsArrayType(PType); 12966 if (!AT) 12967 return; 12968 12969 if (AT->getSizeModifier() != ArrayType::Star) { 12970 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12971 return; 12972 } 12973 12974 S.Diag(Loc, diag::err_array_star_in_function_definition); 12975 } 12976 12977 /// CheckParmsForFunctionDef - Check that the parameters of the given 12978 /// function are appropriate for the definition of a function. This 12979 /// takes care of any checks that cannot be performed on the 12980 /// declaration itself, e.g., that the types of each of the function 12981 /// parameters are complete. 12982 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12983 bool CheckParameterNames) { 12984 bool HasInvalidParm = false; 12985 for (ParmVarDecl *Param : Parameters) { 12986 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12987 // function declarator that is part of a function definition of 12988 // that function shall not have incomplete type. 12989 // 12990 // This is also C++ [dcl.fct]p6. 12991 if (!Param->isInvalidDecl() && 12992 RequireCompleteType(Param->getLocation(), Param->getType(), 12993 diag::err_typecheck_decl_incomplete_type)) { 12994 Param->setInvalidDecl(); 12995 HasInvalidParm = true; 12996 } 12997 12998 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12999 // declaration of each parameter shall include an identifier. 13000 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13001 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13002 // Diagnose this as an extension in C17 and earlier. 13003 if (!getLangOpts().C2x) 13004 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13005 } 13006 13007 // C99 6.7.5.3p12: 13008 // If the function declarator is not part of a definition of that 13009 // function, parameters may have incomplete type and may use the [*] 13010 // notation in their sequences of declarator specifiers to specify 13011 // variable length array types. 13012 QualType PType = Param->getOriginalType(); 13013 // FIXME: This diagnostic should point the '[*]' if source-location 13014 // information is added for it. 13015 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13016 13017 // If the parameter is a c++ class type and it has to be destructed in the 13018 // callee function, declare the destructor so that it can be called by the 13019 // callee function. Do not perform any direct access check on the dtor here. 13020 if (!Param->isInvalidDecl()) { 13021 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13022 if (!ClassDecl->isInvalidDecl() && 13023 !ClassDecl->hasIrrelevantDestructor() && 13024 !ClassDecl->isDependentContext() && 13025 ClassDecl->isParamDestroyedInCallee()) { 13026 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13027 MarkFunctionReferenced(Param->getLocation(), Destructor); 13028 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13029 } 13030 } 13031 } 13032 13033 // Parameters with the pass_object_size attribute only need to be marked 13034 // constant at function definitions. Because we lack information about 13035 // whether we're on a declaration or definition when we're instantiating the 13036 // attribute, we need to check for constness here. 13037 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13038 if (!Param->getType().isConstQualified()) 13039 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13040 << Attr->getSpelling() << 1; 13041 13042 // Check for parameter names shadowing fields from the class. 13043 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13044 // The owning context for the parameter should be the function, but we 13045 // want to see if this function's declaration context is a record. 13046 DeclContext *DC = Param->getDeclContext(); 13047 if (DC && DC->isFunctionOrMethod()) { 13048 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13049 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13050 RD, /*DeclIsField*/ false); 13051 } 13052 } 13053 } 13054 13055 return HasInvalidParm; 13056 } 13057 13058 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 13059 /// or MemberExpr. 13060 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 13061 ASTContext &Context) { 13062 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 13063 return Context.getDeclAlign(DRE->getDecl()); 13064 13065 if (const auto *ME = dyn_cast<MemberExpr>(E)) 13066 return Context.getDeclAlign(ME->getMemberDecl()); 13067 13068 return TypeAlign; 13069 } 13070 13071 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13072 /// pointer cast increases the alignment requirements. 13073 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13074 // This is actually a lot of work to potentially be doing on every 13075 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13076 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13077 return; 13078 13079 // Ignore dependent types. 13080 if (T->isDependentType() || Op->getType()->isDependentType()) 13081 return; 13082 13083 // Require that the destination be a pointer type. 13084 const PointerType *DestPtr = T->getAs<PointerType>(); 13085 if (!DestPtr) return; 13086 13087 // If the destination has alignment 1, we're done. 13088 QualType DestPointee = DestPtr->getPointeeType(); 13089 if (DestPointee->isIncompleteType()) return; 13090 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13091 if (DestAlign.isOne()) return; 13092 13093 // Require that the source be a pointer type. 13094 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13095 if (!SrcPtr) return; 13096 QualType SrcPointee = SrcPtr->getPointeeType(); 13097 13098 // Whitelist casts from cv void*. We already implicitly 13099 // whitelisted casts to cv void*, since they have alignment 1. 13100 // Also whitelist casts involving incomplete types, which implicitly 13101 // includes 'void'. 13102 if (SrcPointee->isIncompleteType()) return; 13103 13104 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 13105 13106 if (auto *CE = dyn_cast<CastExpr>(Op)) { 13107 if (CE->getCastKind() == CK_ArrayToPointerDecay) 13108 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 13109 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 13110 if (UO->getOpcode() == UO_AddrOf) 13111 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 13112 } 13113 13114 if (SrcAlign >= DestAlign) return; 13115 13116 Diag(TRange.getBegin(), diag::warn_cast_align) 13117 << Op->getType() << T 13118 << static_cast<unsigned>(SrcAlign.getQuantity()) 13119 << static_cast<unsigned>(DestAlign.getQuantity()) 13120 << TRange << Op->getSourceRange(); 13121 } 13122 13123 /// Check whether this array fits the idiom of a size-one tail padded 13124 /// array member of a struct. 13125 /// 13126 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13127 /// commonly used to emulate flexible arrays in C89 code. 13128 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13129 const NamedDecl *ND) { 13130 if (Size != 1 || !ND) return false; 13131 13132 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13133 if (!FD) return false; 13134 13135 // Don't consider sizes resulting from macro expansions or template argument 13136 // substitution to form C89 tail-padded arrays. 13137 13138 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13139 while (TInfo) { 13140 TypeLoc TL = TInfo->getTypeLoc(); 13141 // Look through typedefs. 13142 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13143 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13144 TInfo = TDL->getTypeSourceInfo(); 13145 continue; 13146 } 13147 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13148 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13149 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13150 return false; 13151 } 13152 break; 13153 } 13154 13155 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13156 if (!RD) return false; 13157 if (RD->isUnion()) return false; 13158 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13159 if (!CRD->isStandardLayout()) return false; 13160 } 13161 13162 // See if this is the last field decl in the record. 13163 const Decl *D = FD; 13164 while ((D = D->getNextDeclInContext())) 13165 if (isa<FieldDecl>(D)) 13166 return false; 13167 return true; 13168 } 13169 13170 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13171 const ArraySubscriptExpr *ASE, 13172 bool AllowOnePastEnd, bool IndexNegated) { 13173 // Already diagnosed by the constant evaluator. 13174 if (isConstantEvaluated()) 13175 return; 13176 13177 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13178 if (IndexExpr->isValueDependent()) 13179 return; 13180 13181 const Type *EffectiveType = 13182 BaseExpr->getType()->getPointeeOrArrayElementType(); 13183 BaseExpr = BaseExpr->IgnoreParenCasts(); 13184 const ConstantArrayType *ArrayTy = 13185 Context.getAsConstantArrayType(BaseExpr->getType()); 13186 13187 if (!ArrayTy) 13188 return; 13189 13190 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13191 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13192 return; 13193 13194 Expr::EvalResult Result; 13195 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13196 return; 13197 13198 llvm::APSInt index = Result.Val.getInt(); 13199 if (IndexNegated) 13200 index = -index; 13201 13202 const NamedDecl *ND = nullptr; 13203 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13204 ND = DRE->getDecl(); 13205 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13206 ND = ME->getMemberDecl(); 13207 13208 if (index.isUnsigned() || !index.isNegative()) { 13209 // It is possible that the type of the base expression after 13210 // IgnoreParenCasts is incomplete, even though the type of the base 13211 // expression before IgnoreParenCasts is complete (see PR39746 for an 13212 // example). In this case we have no information about whether the array 13213 // access exceeds the array bounds. However we can still diagnose an array 13214 // access which precedes the array bounds. 13215 if (BaseType->isIncompleteType()) 13216 return; 13217 13218 llvm::APInt size = ArrayTy->getSize(); 13219 if (!size.isStrictlyPositive()) 13220 return; 13221 13222 if (BaseType != EffectiveType) { 13223 // Make sure we're comparing apples to apples when comparing index to size 13224 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13225 uint64_t array_typesize = Context.getTypeSize(BaseType); 13226 // Handle ptrarith_typesize being zero, such as when casting to void* 13227 if (!ptrarith_typesize) ptrarith_typesize = 1; 13228 if (ptrarith_typesize != array_typesize) { 13229 // There's a cast to a different size type involved 13230 uint64_t ratio = array_typesize / ptrarith_typesize; 13231 // TODO: Be smarter about handling cases where array_typesize is not a 13232 // multiple of ptrarith_typesize 13233 if (ptrarith_typesize * ratio == array_typesize) 13234 size *= llvm::APInt(size.getBitWidth(), ratio); 13235 } 13236 } 13237 13238 if (size.getBitWidth() > index.getBitWidth()) 13239 index = index.zext(size.getBitWidth()); 13240 else if (size.getBitWidth() < index.getBitWidth()) 13241 size = size.zext(index.getBitWidth()); 13242 13243 // For array subscripting the index must be less than size, but for pointer 13244 // arithmetic also allow the index (offset) to be equal to size since 13245 // computing the next address after the end of the array is legal and 13246 // commonly done e.g. in C++ iterators and range-based for loops. 13247 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13248 return; 13249 13250 // Also don't warn for arrays of size 1 which are members of some 13251 // structure. These are often used to approximate flexible arrays in C89 13252 // code. 13253 if (IsTailPaddedMemberArray(*this, size, ND)) 13254 return; 13255 13256 // Suppress the warning if the subscript expression (as identified by the 13257 // ']' location) and the index expression are both from macro expansions 13258 // within a system header. 13259 if (ASE) { 13260 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13261 ASE->getRBracketLoc()); 13262 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13263 SourceLocation IndexLoc = 13264 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13265 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13266 return; 13267 } 13268 } 13269 13270 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13271 if (ASE) 13272 DiagID = diag::warn_array_index_exceeds_bounds; 13273 13274 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13275 PDiag(DiagID) << index.toString(10, true) 13276 << size.toString(10, true) 13277 << (unsigned)size.getLimitedValue(~0U) 13278 << IndexExpr->getSourceRange()); 13279 } else { 13280 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13281 if (!ASE) { 13282 DiagID = diag::warn_ptr_arith_precedes_bounds; 13283 if (index.isNegative()) index = -index; 13284 } 13285 13286 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13287 PDiag(DiagID) << index.toString(10, true) 13288 << IndexExpr->getSourceRange()); 13289 } 13290 13291 if (!ND) { 13292 // Try harder to find a NamedDecl to point at in the note. 13293 while (const ArraySubscriptExpr *ASE = 13294 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13295 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13296 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13297 ND = DRE->getDecl(); 13298 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13299 ND = ME->getMemberDecl(); 13300 } 13301 13302 if (ND) 13303 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13304 PDiag(diag::note_array_declared_here) 13305 << ND->getDeclName()); 13306 } 13307 13308 void Sema::CheckArrayAccess(const Expr *expr) { 13309 int AllowOnePastEnd = 0; 13310 while (expr) { 13311 expr = expr->IgnoreParenImpCasts(); 13312 switch (expr->getStmtClass()) { 13313 case Stmt::ArraySubscriptExprClass: { 13314 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13315 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13316 AllowOnePastEnd > 0); 13317 expr = ASE->getBase(); 13318 break; 13319 } 13320 case Stmt::MemberExprClass: { 13321 expr = cast<MemberExpr>(expr)->getBase(); 13322 break; 13323 } 13324 case Stmt::OMPArraySectionExprClass: { 13325 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13326 if (ASE->getLowerBound()) 13327 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13328 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13329 return; 13330 } 13331 case Stmt::UnaryOperatorClass: { 13332 // Only unwrap the * and & unary operators 13333 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13334 expr = UO->getSubExpr(); 13335 switch (UO->getOpcode()) { 13336 case UO_AddrOf: 13337 AllowOnePastEnd++; 13338 break; 13339 case UO_Deref: 13340 AllowOnePastEnd--; 13341 break; 13342 default: 13343 return; 13344 } 13345 break; 13346 } 13347 case Stmt::ConditionalOperatorClass: { 13348 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13349 if (const Expr *lhs = cond->getLHS()) 13350 CheckArrayAccess(lhs); 13351 if (const Expr *rhs = cond->getRHS()) 13352 CheckArrayAccess(rhs); 13353 return; 13354 } 13355 case Stmt::CXXOperatorCallExprClass: { 13356 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13357 for (const auto *Arg : OCE->arguments()) 13358 CheckArrayAccess(Arg); 13359 return; 13360 } 13361 default: 13362 return; 13363 } 13364 } 13365 } 13366 13367 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13368 13369 namespace { 13370 13371 struct RetainCycleOwner { 13372 VarDecl *Variable = nullptr; 13373 SourceRange Range; 13374 SourceLocation Loc; 13375 bool Indirect = false; 13376 13377 RetainCycleOwner() = default; 13378 13379 void setLocsFrom(Expr *e) { 13380 Loc = e->getExprLoc(); 13381 Range = e->getSourceRange(); 13382 } 13383 }; 13384 13385 } // namespace 13386 13387 /// Consider whether capturing the given variable can possibly lead to 13388 /// a retain cycle. 13389 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13390 // In ARC, it's captured strongly iff the variable has __strong 13391 // lifetime. In MRR, it's captured strongly if the variable is 13392 // __block and has an appropriate type. 13393 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13394 return false; 13395 13396 owner.Variable = var; 13397 if (ref) 13398 owner.setLocsFrom(ref); 13399 return true; 13400 } 13401 13402 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13403 while (true) { 13404 e = e->IgnoreParens(); 13405 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13406 switch (cast->getCastKind()) { 13407 case CK_BitCast: 13408 case CK_LValueBitCast: 13409 case CK_LValueToRValue: 13410 case CK_ARCReclaimReturnedObject: 13411 e = cast->getSubExpr(); 13412 continue; 13413 13414 default: 13415 return false; 13416 } 13417 } 13418 13419 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13420 ObjCIvarDecl *ivar = ref->getDecl(); 13421 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13422 return false; 13423 13424 // Try to find a retain cycle in the base. 13425 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13426 return false; 13427 13428 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13429 owner.Indirect = true; 13430 return true; 13431 } 13432 13433 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13434 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13435 if (!var) return false; 13436 return considerVariable(var, ref, owner); 13437 } 13438 13439 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13440 if (member->isArrow()) return false; 13441 13442 // Don't count this as an indirect ownership. 13443 e = member->getBase(); 13444 continue; 13445 } 13446 13447 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13448 // Only pay attention to pseudo-objects on property references. 13449 ObjCPropertyRefExpr *pre 13450 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13451 ->IgnoreParens()); 13452 if (!pre) return false; 13453 if (pre->isImplicitProperty()) return false; 13454 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13455 if (!property->isRetaining() && 13456 !(property->getPropertyIvarDecl() && 13457 property->getPropertyIvarDecl()->getType() 13458 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13459 return false; 13460 13461 owner.Indirect = true; 13462 if (pre->isSuperReceiver()) { 13463 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13464 if (!owner.Variable) 13465 return false; 13466 owner.Loc = pre->getLocation(); 13467 owner.Range = pre->getSourceRange(); 13468 return true; 13469 } 13470 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13471 ->getSourceExpr()); 13472 continue; 13473 } 13474 13475 // Array ivars? 13476 13477 return false; 13478 } 13479 } 13480 13481 namespace { 13482 13483 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13484 ASTContext &Context; 13485 VarDecl *Variable; 13486 Expr *Capturer = nullptr; 13487 bool VarWillBeReased = false; 13488 13489 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13490 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13491 Context(Context), Variable(variable) {} 13492 13493 void VisitDeclRefExpr(DeclRefExpr *ref) { 13494 if (ref->getDecl() == Variable && !Capturer) 13495 Capturer = ref; 13496 } 13497 13498 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13499 if (Capturer) return; 13500 Visit(ref->getBase()); 13501 if (Capturer && ref->isFreeIvar()) 13502 Capturer = ref; 13503 } 13504 13505 void VisitBlockExpr(BlockExpr *block) { 13506 // Look inside nested blocks 13507 if (block->getBlockDecl()->capturesVariable(Variable)) 13508 Visit(block->getBlockDecl()->getBody()); 13509 } 13510 13511 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13512 if (Capturer) return; 13513 if (OVE->getSourceExpr()) 13514 Visit(OVE->getSourceExpr()); 13515 } 13516 13517 void VisitBinaryOperator(BinaryOperator *BinOp) { 13518 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13519 return; 13520 Expr *LHS = BinOp->getLHS(); 13521 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13522 if (DRE->getDecl() != Variable) 13523 return; 13524 if (Expr *RHS = BinOp->getRHS()) { 13525 RHS = RHS->IgnoreParenCasts(); 13526 llvm::APSInt Value; 13527 VarWillBeReased = 13528 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13529 } 13530 } 13531 } 13532 }; 13533 13534 } // namespace 13535 13536 /// Check whether the given argument is a block which captures a 13537 /// variable. 13538 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13539 assert(owner.Variable && owner.Loc.isValid()); 13540 13541 e = e->IgnoreParenCasts(); 13542 13543 // Look through [^{...} copy] and Block_copy(^{...}). 13544 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13545 Selector Cmd = ME->getSelector(); 13546 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13547 e = ME->getInstanceReceiver(); 13548 if (!e) 13549 return nullptr; 13550 e = e->IgnoreParenCasts(); 13551 } 13552 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13553 if (CE->getNumArgs() == 1) { 13554 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13555 if (Fn) { 13556 const IdentifierInfo *FnI = Fn->getIdentifier(); 13557 if (FnI && FnI->isStr("_Block_copy")) { 13558 e = CE->getArg(0)->IgnoreParenCasts(); 13559 } 13560 } 13561 } 13562 } 13563 13564 BlockExpr *block = dyn_cast<BlockExpr>(e); 13565 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13566 return nullptr; 13567 13568 FindCaptureVisitor visitor(S.Context, owner.Variable); 13569 visitor.Visit(block->getBlockDecl()->getBody()); 13570 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13571 } 13572 13573 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13574 RetainCycleOwner &owner) { 13575 assert(capturer); 13576 assert(owner.Variable && owner.Loc.isValid()); 13577 13578 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13579 << owner.Variable << capturer->getSourceRange(); 13580 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13581 << owner.Indirect << owner.Range; 13582 } 13583 13584 /// Check for a keyword selector that starts with the word 'add' or 13585 /// 'set'. 13586 static bool isSetterLikeSelector(Selector sel) { 13587 if (sel.isUnarySelector()) return false; 13588 13589 StringRef str = sel.getNameForSlot(0); 13590 while (!str.empty() && str.front() == '_') str = str.substr(1); 13591 if (str.startswith("set")) 13592 str = str.substr(3); 13593 else if (str.startswith("add")) { 13594 // Specially whitelist 'addOperationWithBlock:'. 13595 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13596 return false; 13597 str = str.substr(3); 13598 } 13599 else 13600 return false; 13601 13602 if (str.empty()) return true; 13603 return !isLowercase(str.front()); 13604 } 13605 13606 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13607 ObjCMessageExpr *Message) { 13608 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13609 Message->getReceiverInterface(), 13610 NSAPI::ClassId_NSMutableArray); 13611 if (!IsMutableArray) { 13612 return None; 13613 } 13614 13615 Selector Sel = Message->getSelector(); 13616 13617 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13618 S.NSAPIObj->getNSArrayMethodKind(Sel); 13619 if (!MKOpt) { 13620 return None; 13621 } 13622 13623 NSAPI::NSArrayMethodKind MK = *MKOpt; 13624 13625 switch (MK) { 13626 case NSAPI::NSMutableArr_addObject: 13627 case NSAPI::NSMutableArr_insertObjectAtIndex: 13628 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13629 return 0; 13630 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13631 return 1; 13632 13633 default: 13634 return None; 13635 } 13636 13637 return None; 13638 } 13639 13640 static 13641 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13642 ObjCMessageExpr *Message) { 13643 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13644 Message->getReceiverInterface(), 13645 NSAPI::ClassId_NSMutableDictionary); 13646 if (!IsMutableDictionary) { 13647 return None; 13648 } 13649 13650 Selector Sel = Message->getSelector(); 13651 13652 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13653 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13654 if (!MKOpt) { 13655 return None; 13656 } 13657 13658 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13659 13660 switch (MK) { 13661 case NSAPI::NSMutableDict_setObjectForKey: 13662 case NSAPI::NSMutableDict_setValueForKey: 13663 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13664 return 0; 13665 13666 default: 13667 return None; 13668 } 13669 13670 return None; 13671 } 13672 13673 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13674 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13675 Message->getReceiverInterface(), 13676 NSAPI::ClassId_NSMutableSet); 13677 13678 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13679 Message->getReceiverInterface(), 13680 NSAPI::ClassId_NSMutableOrderedSet); 13681 if (!IsMutableSet && !IsMutableOrderedSet) { 13682 return None; 13683 } 13684 13685 Selector Sel = Message->getSelector(); 13686 13687 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13688 if (!MKOpt) { 13689 return None; 13690 } 13691 13692 NSAPI::NSSetMethodKind MK = *MKOpt; 13693 13694 switch (MK) { 13695 case NSAPI::NSMutableSet_addObject: 13696 case NSAPI::NSOrderedSet_setObjectAtIndex: 13697 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13698 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13699 return 0; 13700 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13701 return 1; 13702 } 13703 13704 return None; 13705 } 13706 13707 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13708 if (!Message->isInstanceMessage()) { 13709 return; 13710 } 13711 13712 Optional<int> ArgOpt; 13713 13714 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13715 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13716 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13717 return; 13718 } 13719 13720 int ArgIndex = *ArgOpt; 13721 13722 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13723 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13724 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13725 } 13726 13727 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13728 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13729 if (ArgRE->isObjCSelfExpr()) { 13730 Diag(Message->getSourceRange().getBegin(), 13731 diag::warn_objc_circular_container) 13732 << ArgRE->getDecl() << StringRef("'super'"); 13733 } 13734 } 13735 } else { 13736 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13737 13738 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13739 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13740 } 13741 13742 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13743 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13744 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13745 ValueDecl *Decl = ReceiverRE->getDecl(); 13746 Diag(Message->getSourceRange().getBegin(), 13747 diag::warn_objc_circular_container) 13748 << Decl << Decl; 13749 if (!ArgRE->isObjCSelfExpr()) { 13750 Diag(Decl->getLocation(), 13751 diag::note_objc_circular_container_declared_here) 13752 << Decl; 13753 } 13754 } 13755 } 13756 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13757 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13758 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13759 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13760 Diag(Message->getSourceRange().getBegin(), 13761 diag::warn_objc_circular_container) 13762 << Decl << Decl; 13763 Diag(Decl->getLocation(), 13764 diag::note_objc_circular_container_declared_here) 13765 << Decl; 13766 } 13767 } 13768 } 13769 } 13770 } 13771 13772 /// Check a message send to see if it's likely to cause a retain cycle. 13773 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13774 // Only check instance methods whose selector looks like a setter. 13775 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13776 return; 13777 13778 // Try to find a variable that the receiver is strongly owned by. 13779 RetainCycleOwner owner; 13780 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13781 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13782 return; 13783 } else { 13784 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13785 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13786 owner.Loc = msg->getSuperLoc(); 13787 owner.Range = msg->getSuperLoc(); 13788 } 13789 13790 // Check whether the receiver is captured by any of the arguments. 13791 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13792 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13793 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13794 // noescape blocks should not be retained by the method. 13795 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13796 continue; 13797 return diagnoseRetainCycle(*this, capturer, owner); 13798 } 13799 } 13800 } 13801 13802 /// Check a property assign to see if it's likely to cause a retain cycle. 13803 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13804 RetainCycleOwner owner; 13805 if (!findRetainCycleOwner(*this, receiver, owner)) 13806 return; 13807 13808 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13809 diagnoseRetainCycle(*this, capturer, owner); 13810 } 13811 13812 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13813 RetainCycleOwner Owner; 13814 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13815 return; 13816 13817 // Because we don't have an expression for the variable, we have to set the 13818 // location explicitly here. 13819 Owner.Loc = Var->getLocation(); 13820 Owner.Range = Var->getSourceRange(); 13821 13822 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13823 diagnoseRetainCycle(*this, Capturer, Owner); 13824 } 13825 13826 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13827 Expr *RHS, bool isProperty) { 13828 // Check if RHS is an Objective-C object literal, which also can get 13829 // immediately zapped in a weak reference. Note that we explicitly 13830 // allow ObjCStringLiterals, since those are designed to never really die. 13831 RHS = RHS->IgnoreParenImpCasts(); 13832 13833 // This enum needs to match with the 'select' in 13834 // warn_objc_arc_literal_assign (off-by-1). 13835 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13836 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13837 return false; 13838 13839 S.Diag(Loc, diag::warn_arc_literal_assign) 13840 << (unsigned) Kind 13841 << (isProperty ? 0 : 1) 13842 << RHS->getSourceRange(); 13843 13844 return true; 13845 } 13846 13847 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13848 Qualifiers::ObjCLifetime LT, 13849 Expr *RHS, bool isProperty) { 13850 // Strip off any implicit cast added to get to the one ARC-specific. 13851 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13852 if (cast->getCastKind() == CK_ARCConsumeObject) { 13853 S.Diag(Loc, diag::warn_arc_retained_assign) 13854 << (LT == Qualifiers::OCL_ExplicitNone) 13855 << (isProperty ? 0 : 1) 13856 << RHS->getSourceRange(); 13857 return true; 13858 } 13859 RHS = cast->getSubExpr(); 13860 } 13861 13862 if (LT == Qualifiers::OCL_Weak && 13863 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13864 return true; 13865 13866 return false; 13867 } 13868 13869 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13870 QualType LHS, Expr *RHS) { 13871 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13872 13873 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13874 return false; 13875 13876 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13877 return true; 13878 13879 return false; 13880 } 13881 13882 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13883 Expr *LHS, Expr *RHS) { 13884 QualType LHSType; 13885 // PropertyRef on LHS type need be directly obtained from 13886 // its declaration as it has a PseudoType. 13887 ObjCPropertyRefExpr *PRE 13888 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13889 if (PRE && !PRE->isImplicitProperty()) { 13890 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13891 if (PD) 13892 LHSType = PD->getType(); 13893 } 13894 13895 if (LHSType.isNull()) 13896 LHSType = LHS->getType(); 13897 13898 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13899 13900 if (LT == Qualifiers::OCL_Weak) { 13901 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13902 getCurFunction()->markSafeWeakUse(LHS); 13903 } 13904 13905 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13906 return; 13907 13908 // FIXME. Check for other life times. 13909 if (LT != Qualifiers::OCL_None) 13910 return; 13911 13912 if (PRE) { 13913 if (PRE->isImplicitProperty()) 13914 return; 13915 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13916 if (!PD) 13917 return; 13918 13919 unsigned Attributes = PD->getPropertyAttributes(); 13920 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13921 // when 'assign' attribute was not explicitly specified 13922 // by user, ignore it and rely on property type itself 13923 // for lifetime info. 13924 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13925 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13926 LHSType->isObjCRetainableType()) 13927 return; 13928 13929 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13930 if (cast->getCastKind() == CK_ARCConsumeObject) { 13931 Diag(Loc, diag::warn_arc_retained_property_assign) 13932 << RHS->getSourceRange(); 13933 return; 13934 } 13935 RHS = cast->getSubExpr(); 13936 } 13937 } 13938 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13939 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13940 return; 13941 } 13942 } 13943 } 13944 13945 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13946 13947 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13948 SourceLocation StmtLoc, 13949 const NullStmt *Body) { 13950 // Do not warn if the body is a macro that expands to nothing, e.g: 13951 // 13952 // #define CALL(x) 13953 // if (condition) 13954 // CALL(0); 13955 if (Body->hasLeadingEmptyMacro()) 13956 return false; 13957 13958 // Get line numbers of statement and body. 13959 bool StmtLineInvalid; 13960 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13961 &StmtLineInvalid); 13962 if (StmtLineInvalid) 13963 return false; 13964 13965 bool BodyLineInvalid; 13966 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13967 &BodyLineInvalid); 13968 if (BodyLineInvalid) 13969 return false; 13970 13971 // Warn if null statement and body are on the same line. 13972 if (StmtLine != BodyLine) 13973 return false; 13974 13975 return true; 13976 } 13977 13978 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13979 const Stmt *Body, 13980 unsigned DiagID) { 13981 // Since this is a syntactic check, don't emit diagnostic for template 13982 // instantiations, this just adds noise. 13983 if (CurrentInstantiationScope) 13984 return; 13985 13986 // The body should be a null statement. 13987 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13988 if (!NBody) 13989 return; 13990 13991 // Do the usual checks. 13992 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13993 return; 13994 13995 Diag(NBody->getSemiLoc(), DiagID); 13996 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13997 } 13998 13999 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14000 const Stmt *PossibleBody) { 14001 assert(!CurrentInstantiationScope); // Ensured by caller 14002 14003 SourceLocation StmtLoc; 14004 const Stmt *Body; 14005 unsigned DiagID; 14006 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14007 StmtLoc = FS->getRParenLoc(); 14008 Body = FS->getBody(); 14009 DiagID = diag::warn_empty_for_body; 14010 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14011 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14012 Body = WS->getBody(); 14013 DiagID = diag::warn_empty_while_body; 14014 } else 14015 return; // Neither `for' nor `while'. 14016 14017 // The body should be a null statement. 14018 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14019 if (!NBody) 14020 return; 14021 14022 // Skip expensive checks if diagnostic is disabled. 14023 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14024 return; 14025 14026 // Do the usual checks. 14027 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14028 return; 14029 14030 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14031 // noise level low, emit diagnostics only if for/while is followed by a 14032 // CompoundStmt, e.g.: 14033 // for (int i = 0; i < n; i++); 14034 // { 14035 // a(i); 14036 // } 14037 // or if for/while is followed by a statement with more indentation 14038 // than for/while itself: 14039 // for (int i = 0; i < n; i++); 14040 // a(i); 14041 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14042 if (!ProbableTypo) { 14043 bool BodyColInvalid; 14044 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14045 PossibleBody->getBeginLoc(), &BodyColInvalid); 14046 if (BodyColInvalid) 14047 return; 14048 14049 bool StmtColInvalid; 14050 unsigned StmtCol = 14051 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14052 if (StmtColInvalid) 14053 return; 14054 14055 if (BodyCol > StmtCol) 14056 ProbableTypo = true; 14057 } 14058 14059 if (ProbableTypo) { 14060 Diag(NBody->getSemiLoc(), DiagID); 14061 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14062 } 14063 } 14064 14065 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14066 14067 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14068 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14069 SourceLocation OpLoc) { 14070 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14071 return; 14072 14073 if (inTemplateInstantiation()) 14074 return; 14075 14076 // Strip parens and casts away. 14077 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14078 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14079 14080 // Check for a call expression 14081 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14082 if (!CE || CE->getNumArgs() != 1) 14083 return; 14084 14085 // Check for a call to std::move 14086 if (!CE->isCallToStdMove()) 14087 return; 14088 14089 // Get argument from std::move 14090 RHSExpr = CE->getArg(0); 14091 14092 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14093 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14094 14095 // Two DeclRefExpr's, check that the decls are the same. 14096 if (LHSDeclRef && RHSDeclRef) { 14097 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14098 return; 14099 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14100 RHSDeclRef->getDecl()->getCanonicalDecl()) 14101 return; 14102 14103 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14104 << LHSExpr->getSourceRange() 14105 << RHSExpr->getSourceRange(); 14106 return; 14107 } 14108 14109 // Member variables require a different approach to check for self moves. 14110 // MemberExpr's are the same if every nested MemberExpr refers to the same 14111 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14112 // the base Expr's are CXXThisExpr's. 14113 const Expr *LHSBase = LHSExpr; 14114 const Expr *RHSBase = RHSExpr; 14115 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14116 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14117 if (!LHSME || !RHSME) 14118 return; 14119 14120 while (LHSME && RHSME) { 14121 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14122 RHSME->getMemberDecl()->getCanonicalDecl()) 14123 return; 14124 14125 LHSBase = LHSME->getBase(); 14126 RHSBase = RHSME->getBase(); 14127 LHSME = dyn_cast<MemberExpr>(LHSBase); 14128 RHSME = dyn_cast<MemberExpr>(RHSBase); 14129 } 14130 14131 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14132 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14133 if (LHSDeclRef && RHSDeclRef) { 14134 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14135 return; 14136 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14137 RHSDeclRef->getDecl()->getCanonicalDecl()) 14138 return; 14139 14140 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14141 << LHSExpr->getSourceRange() 14142 << RHSExpr->getSourceRange(); 14143 return; 14144 } 14145 14146 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14147 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14148 << LHSExpr->getSourceRange() 14149 << RHSExpr->getSourceRange(); 14150 } 14151 14152 //===--- Layout compatibility ----------------------------------------------// 14153 14154 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14155 14156 /// Check if two enumeration types are layout-compatible. 14157 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14158 // C++11 [dcl.enum] p8: 14159 // Two enumeration types are layout-compatible if they have the same 14160 // underlying type. 14161 return ED1->isComplete() && ED2->isComplete() && 14162 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14163 } 14164 14165 /// Check if two fields are layout-compatible. 14166 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14167 FieldDecl *Field2) { 14168 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14169 return false; 14170 14171 if (Field1->isBitField() != Field2->isBitField()) 14172 return false; 14173 14174 if (Field1->isBitField()) { 14175 // Make sure that the bit-fields are the same length. 14176 unsigned Bits1 = Field1->getBitWidthValue(C); 14177 unsigned Bits2 = Field2->getBitWidthValue(C); 14178 14179 if (Bits1 != Bits2) 14180 return false; 14181 } 14182 14183 return true; 14184 } 14185 14186 /// Check if two standard-layout structs are layout-compatible. 14187 /// (C++11 [class.mem] p17) 14188 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14189 RecordDecl *RD2) { 14190 // If both records are C++ classes, check that base classes match. 14191 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14192 // If one of records is a CXXRecordDecl we are in C++ mode, 14193 // thus the other one is a CXXRecordDecl, too. 14194 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14195 // Check number of base classes. 14196 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14197 return false; 14198 14199 // Check the base classes. 14200 for (CXXRecordDecl::base_class_const_iterator 14201 Base1 = D1CXX->bases_begin(), 14202 BaseEnd1 = D1CXX->bases_end(), 14203 Base2 = D2CXX->bases_begin(); 14204 Base1 != BaseEnd1; 14205 ++Base1, ++Base2) { 14206 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14207 return false; 14208 } 14209 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14210 // If only RD2 is a C++ class, it should have zero base classes. 14211 if (D2CXX->getNumBases() > 0) 14212 return false; 14213 } 14214 14215 // Check the fields. 14216 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14217 Field2End = RD2->field_end(), 14218 Field1 = RD1->field_begin(), 14219 Field1End = RD1->field_end(); 14220 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14221 if (!isLayoutCompatible(C, *Field1, *Field2)) 14222 return false; 14223 } 14224 if (Field1 != Field1End || Field2 != Field2End) 14225 return false; 14226 14227 return true; 14228 } 14229 14230 /// Check if two standard-layout unions are layout-compatible. 14231 /// (C++11 [class.mem] p18) 14232 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14233 RecordDecl *RD2) { 14234 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14235 for (auto *Field2 : RD2->fields()) 14236 UnmatchedFields.insert(Field2); 14237 14238 for (auto *Field1 : RD1->fields()) { 14239 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14240 I = UnmatchedFields.begin(), 14241 E = UnmatchedFields.end(); 14242 14243 for ( ; I != E; ++I) { 14244 if (isLayoutCompatible(C, Field1, *I)) { 14245 bool Result = UnmatchedFields.erase(*I); 14246 (void) Result; 14247 assert(Result); 14248 break; 14249 } 14250 } 14251 if (I == E) 14252 return false; 14253 } 14254 14255 return UnmatchedFields.empty(); 14256 } 14257 14258 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14259 RecordDecl *RD2) { 14260 if (RD1->isUnion() != RD2->isUnion()) 14261 return false; 14262 14263 if (RD1->isUnion()) 14264 return isLayoutCompatibleUnion(C, RD1, RD2); 14265 else 14266 return isLayoutCompatibleStruct(C, RD1, RD2); 14267 } 14268 14269 /// Check if two types are layout-compatible in C++11 sense. 14270 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14271 if (T1.isNull() || T2.isNull()) 14272 return false; 14273 14274 // C++11 [basic.types] p11: 14275 // If two types T1 and T2 are the same type, then T1 and T2 are 14276 // layout-compatible types. 14277 if (C.hasSameType(T1, T2)) 14278 return true; 14279 14280 T1 = T1.getCanonicalType().getUnqualifiedType(); 14281 T2 = T2.getCanonicalType().getUnqualifiedType(); 14282 14283 const Type::TypeClass TC1 = T1->getTypeClass(); 14284 const Type::TypeClass TC2 = T2->getTypeClass(); 14285 14286 if (TC1 != TC2) 14287 return false; 14288 14289 if (TC1 == Type::Enum) { 14290 return isLayoutCompatible(C, 14291 cast<EnumType>(T1)->getDecl(), 14292 cast<EnumType>(T2)->getDecl()); 14293 } else if (TC1 == Type::Record) { 14294 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14295 return false; 14296 14297 return isLayoutCompatible(C, 14298 cast<RecordType>(T1)->getDecl(), 14299 cast<RecordType>(T2)->getDecl()); 14300 } 14301 14302 return false; 14303 } 14304 14305 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14306 14307 /// Given a type tag expression find the type tag itself. 14308 /// 14309 /// \param TypeExpr Type tag expression, as it appears in user's code. 14310 /// 14311 /// \param VD Declaration of an identifier that appears in a type tag. 14312 /// 14313 /// \param MagicValue Type tag magic value. 14314 /// 14315 /// \param isConstantEvaluated wether the evalaution should be performed in 14316 14317 /// constant context. 14318 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14319 const ValueDecl **VD, uint64_t *MagicValue, 14320 bool isConstantEvaluated) { 14321 while(true) { 14322 if (!TypeExpr) 14323 return false; 14324 14325 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14326 14327 switch (TypeExpr->getStmtClass()) { 14328 case Stmt::UnaryOperatorClass: { 14329 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14330 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14331 TypeExpr = UO->getSubExpr(); 14332 continue; 14333 } 14334 return false; 14335 } 14336 14337 case Stmt::DeclRefExprClass: { 14338 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14339 *VD = DRE->getDecl(); 14340 return true; 14341 } 14342 14343 case Stmt::IntegerLiteralClass: { 14344 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14345 llvm::APInt MagicValueAPInt = IL->getValue(); 14346 if (MagicValueAPInt.getActiveBits() <= 64) { 14347 *MagicValue = MagicValueAPInt.getZExtValue(); 14348 return true; 14349 } else 14350 return false; 14351 } 14352 14353 case Stmt::BinaryConditionalOperatorClass: 14354 case Stmt::ConditionalOperatorClass: { 14355 const AbstractConditionalOperator *ACO = 14356 cast<AbstractConditionalOperator>(TypeExpr); 14357 bool Result; 14358 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14359 isConstantEvaluated)) { 14360 if (Result) 14361 TypeExpr = ACO->getTrueExpr(); 14362 else 14363 TypeExpr = ACO->getFalseExpr(); 14364 continue; 14365 } 14366 return false; 14367 } 14368 14369 case Stmt::BinaryOperatorClass: { 14370 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14371 if (BO->getOpcode() == BO_Comma) { 14372 TypeExpr = BO->getRHS(); 14373 continue; 14374 } 14375 return false; 14376 } 14377 14378 default: 14379 return false; 14380 } 14381 } 14382 } 14383 14384 /// Retrieve the C type corresponding to type tag TypeExpr. 14385 /// 14386 /// \param TypeExpr Expression that specifies a type tag. 14387 /// 14388 /// \param MagicValues Registered magic values. 14389 /// 14390 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14391 /// kind. 14392 /// 14393 /// \param TypeInfo Information about the corresponding C type. 14394 /// 14395 /// \param isConstantEvaluated wether the evalaution should be performed in 14396 /// constant context. 14397 /// 14398 /// \returns true if the corresponding C type was found. 14399 static bool GetMatchingCType( 14400 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14401 const ASTContext &Ctx, 14402 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14403 *MagicValues, 14404 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14405 bool isConstantEvaluated) { 14406 FoundWrongKind = false; 14407 14408 // Variable declaration that has type_tag_for_datatype attribute. 14409 const ValueDecl *VD = nullptr; 14410 14411 uint64_t MagicValue; 14412 14413 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14414 return false; 14415 14416 if (VD) { 14417 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14418 if (I->getArgumentKind() != ArgumentKind) { 14419 FoundWrongKind = true; 14420 return false; 14421 } 14422 TypeInfo.Type = I->getMatchingCType(); 14423 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14424 TypeInfo.MustBeNull = I->getMustBeNull(); 14425 return true; 14426 } 14427 return false; 14428 } 14429 14430 if (!MagicValues) 14431 return false; 14432 14433 llvm::DenseMap<Sema::TypeTagMagicValue, 14434 Sema::TypeTagData>::const_iterator I = 14435 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14436 if (I == MagicValues->end()) 14437 return false; 14438 14439 TypeInfo = I->second; 14440 return true; 14441 } 14442 14443 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14444 uint64_t MagicValue, QualType Type, 14445 bool LayoutCompatible, 14446 bool MustBeNull) { 14447 if (!TypeTagForDatatypeMagicValues) 14448 TypeTagForDatatypeMagicValues.reset( 14449 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14450 14451 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14452 (*TypeTagForDatatypeMagicValues)[Magic] = 14453 TypeTagData(Type, LayoutCompatible, MustBeNull); 14454 } 14455 14456 static bool IsSameCharType(QualType T1, QualType T2) { 14457 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14458 if (!BT1) 14459 return false; 14460 14461 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14462 if (!BT2) 14463 return false; 14464 14465 BuiltinType::Kind T1Kind = BT1->getKind(); 14466 BuiltinType::Kind T2Kind = BT2->getKind(); 14467 14468 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14469 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14470 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14471 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14472 } 14473 14474 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14475 const ArrayRef<const Expr *> ExprArgs, 14476 SourceLocation CallSiteLoc) { 14477 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14478 bool IsPointerAttr = Attr->getIsPointer(); 14479 14480 // Retrieve the argument representing the 'type_tag'. 14481 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14482 if (TypeTagIdxAST >= ExprArgs.size()) { 14483 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14484 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14485 return; 14486 } 14487 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14488 bool FoundWrongKind; 14489 TypeTagData TypeInfo; 14490 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14491 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14492 TypeInfo, isConstantEvaluated())) { 14493 if (FoundWrongKind) 14494 Diag(TypeTagExpr->getExprLoc(), 14495 diag::warn_type_tag_for_datatype_wrong_kind) 14496 << TypeTagExpr->getSourceRange(); 14497 return; 14498 } 14499 14500 // Retrieve the argument representing the 'arg_idx'. 14501 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14502 if (ArgumentIdxAST >= ExprArgs.size()) { 14503 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14504 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14505 return; 14506 } 14507 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14508 if (IsPointerAttr) { 14509 // Skip implicit cast of pointer to `void *' (as a function argument). 14510 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14511 if (ICE->getType()->isVoidPointerType() && 14512 ICE->getCastKind() == CK_BitCast) 14513 ArgumentExpr = ICE->getSubExpr(); 14514 } 14515 QualType ArgumentType = ArgumentExpr->getType(); 14516 14517 // Passing a `void*' pointer shouldn't trigger a warning. 14518 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14519 return; 14520 14521 if (TypeInfo.MustBeNull) { 14522 // Type tag with matching void type requires a null pointer. 14523 if (!ArgumentExpr->isNullPointerConstant(Context, 14524 Expr::NPC_ValueDependentIsNotNull)) { 14525 Diag(ArgumentExpr->getExprLoc(), 14526 diag::warn_type_safety_null_pointer_required) 14527 << ArgumentKind->getName() 14528 << ArgumentExpr->getSourceRange() 14529 << TypeTagExpr->getSourceRange(); 14530 } 14531 return; 14532 } 14533 14534 QualType RequiredType = TypeInfo.Type; 14535 if (IsPointerAttr) 14536 RequiredType = Context.getPointerType(RequiredType); 14537 14538 bool mismatch = false; 14539 if (!TypeInfo.LayoutCompatible) { 14540 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14541 14542 // C++11 [basic.fundamental] p1: 14543 // Plain char, signed char, and unsigned char are three distinct types. 14544 // 14545 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14546 // char' depending on the current char signedness mode. 14547 if (mismatch) 14548 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14549 RequiredType->getPointeeType())) || 14550 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14551 mismatch = false; 14552 } else 14553 if (IsPointerAttr) 14554 mismatch = !isLayoutCompatible(Context, 14555 ArgumentType->getPointeeType(), 14556 RequiredType->getPointeeType()); 14557 else 14558 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14559 14560 if (mismatch) 14561 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14562 << ArgumentType << ArgumentKind 14563 << TypeInfo.LayoutCompatible << RequiredType 14564 << ArgumentExpr->getSourceRange() 14565 << TypeTagExpr->getSourceRange(); 14566 } 14567 14568 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14569 CharUnits Alignment) { 14570 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14571 } 14572 14573 void Sema::DiagnoseMisalignedMembers() { 14574 for (MisalignedMember &m : MisalignedMembers) { 14575 const NamedDecl *ND = m.RD; 14576 if (ND->getName().empty()) { 14577 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14578 ND = TD; 14579 } 14580 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14581 << m.MD << ND << m.E->getSourceRange(); 14582 } 14583 MisalignedMembers.clear(); 14584 } 14585 14586 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14587 E = E->IgnoreParens(); 14588 if (!T->isPointerType() && !T->isIntegerType()) 14589 return; 14590 if (isa<UnaryOperator>(E) && 14591 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14592 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14593 if (isa<MemberExpr>(Op)) { 14594 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14595 if (MA != MisalignedMembers.end() && 14596 (T->isIntegerType() || 14597 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14598 Context.getTypeAlignInChars( 14599 T->getPointeeType()) <= MA->Alignment)))) 14600 MisalignedMembers.erase(MA); 14601 } 14602 } 14603 } 14604 14605 void Sema::RefersToMemberWithReducedAlignment( 14606 Expr *E, 14607 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14608 Action) { 14609 const auto *ME = dyn_cast<MemberExpr>(E); 14610 if (!ME) 14611 return; 14612 14613 // No need to check expressions with an __unaligned-qualified type. 14614 if (E->getType().getQualifiers().hasUnaligned()) 14615 return; 14616 14617 // For a chain of MemberExpr like "a.b.c.d" this list 14618 // will keep FieldDecl's like [d, c, b]. 14619 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14620 const MemberExpr *TopME = nullptr; 14621 bool AnyIsPacked = false; 14622 do { 14623 QualType BaseType = ME->getBase()->getType(); 14624 if (BaseType->isDependentType()) 14625 return; 14626 if (ME->isArrow()) 14627 BaseType = BaseType->getPointeeType(); 14628 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14629 if (RD->isInvalidDecl()) 14630 return; 14631 14632 ValueDecl *MD = ME->getMemberDecl(); 14633 auto *FD = dyn_cast<FieldDecl>(MD); 14634 // We do not care about non-data members. 14635 if (!FD || FD->isInvalidDecl()) 14636 return; 14637 14638 AnyIsPacked = 14639 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14640 ReverseMemberChain.push_back(FD); 14641 14642 TopME = ME; 14643 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14644 } while (ME); 14645 assert(TopME && "We did not compute a topmost MemberExpr!"); 14646 14647 // Not the scope of this diagnostic. 14648 if (!AnyIsPacked) 14649 return; 14650 14651 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14652 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14653 // TODO: The innermost base of the member expression may be too complicated. 14654 // For now, just disregard these cases. This is left for future 14655 // improvement. 14656 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14657 return; 14658 14659 // Alignment expected by the whole expression. 14660 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14661 14662 // No need to do anything else with this case. 14663 if (ExpectedAlignment.isOne()) 14664 return; 14665 14666 // Synthesize offset of the whole access. 14667 CharUnits Offset; 14668 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14669 I++) { 14670 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14671 } 14672 14673 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14674 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14675 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14676 14677 // The base expression of the innermost MemberExpr may give 14678 // stronger guarantees than the class containing the member. 14679 if (DRE && !TopME->isArrow()) { 14680 const ValueDecl *VD = DRE->getDecl(); 14681 if (!VD->getType()->isReferenceType()) 14682 CompleteObjectAlignment = 14683 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14684 } 14685 14686 // Check if the synthesized offset fulfills the alignment. 14687 if (Offset % ExpectedAlignment != 0 || 14688 // It may fulfill the offset it but the effective alignment may still be 14689 // lower than the expected expression alignment. 14690 CompleteObjectAlignment < ExpectedAlignment) { 14691 // If this happens, we want to determine a sensible culprit of this. 14692 // Intuitively, watching the chain of member expressions from right to 14693 // left, we start with the required alignment (as required by the field 14694 // type) but some packed attribute in that chain has reduced the alignment. 14695 // It may happen that another packed structure increases it again. But if 14696 // we are here such increase has not been enough. So pointing the first 14697 // FieldDecl that either is packed or else its RecordDecl is, 14698 // seems reasonable. 14699 FieldDecl *FD = nullptr; 14700 CharUnits Alignment; 14701 for (FieldDecl *FDI : ReverseMemberChain) { 14702 if (FDI->hasAttr<PackedAttr>() || 14703 FDI->getParent()->hasAttr<PackedAttr>()) { 14704 FD = FDI; 14705 Alignment = std::min( 14706 Context.getTypeAlignInChars(FD->getType()), 14707 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14708 break; 14709 } 14710 } 14711 assert(FD && "We did not find a packed FieldDecl!"); 14712 Action(E, FD->getParent(), FD, Alignment); 14713 } 14714 } 14715 14716 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14717 using namespace std::placeholders; 14718 14719 RefersToMemberWithReducedAlignment( 14720 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14721 _2, _3, _4)); 14722 } 14723