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/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <functional> 95 #include <limits> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 using namespace sema; 102 103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 104 unsigned ByteNo) const { 105 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 106 Context.getTargetInfo()); 107 } 108 109 /// Checks that a call expression's argument count is the desired number. 110 /// This is useful when doing custom type-checking. Returns true on error. 111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 112 unsigned argCount = call->getNumArgs(); 113 if (argCount == desiredArgCount) return false; 114 115 if (argCount < desiredArgCount) 116 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 117 << 0 /*function call*/ << desiredArgCount << argCount 118 << call->getSourceRange(); 119 120 // Highlight all the excess arguments. 121 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 122 call->getArg(argCount - 1)->getEndLoc()); 123 124 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 125 << 0 /*function call*/ << desiredArgCount << argCount 126 << call->getArg(1)->getSourceRange(); 127 } 128 129 /// Check that the first argument to __builtin_annotation is an integer 130 /// and the second argument is a non-wide string literal. 131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 132 if (checkArgCount(S, TheCall, 2)) 133 return true; 134 135 // First argument should be an integer. 136 Expr *ValArg = TheCall->getArg(0); 137 QualType Ty = ValArg->getType(); 138 if (!Ty->isIntegerType()) { 139 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 140 << ValArg->getSourceRange(); 141 return true; 142 } 143 144 // Second argument should be a constant string. 145 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 146 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 147 if (!Literal || !Literal->isAscii()) { 148 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 149 << StrArg->getSourceRange(); 150 return true; 151 } 152 153 TheCall->setType(Ty); 154 return false; 155 } 156 157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 158 // We need at least one argument. 159 if (TheCall->getNumArgs() < 1) { 160 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 161 << 0 << 1 << TheCall->getNumArgs() 162 << TheCall->getCallee()->getSourceRange(); 163 return true; 164 } 165 166 // All arguments should be wide string literals. 167 for (Expr *Arg : TheCall->arguments()) { 168 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 169 if (!Literal || !Literal->isWide()) { 170 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 171 << Arg->getSourceRange(); 172 return true; 173 } 174 } 175 176 return false; 177 } 178 179 /// Check that the argument to __builtin_addressof is a glvalue, and set the 180 /// result type to the corresponding pointer type. 181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 182 if (checkArgCount(S, TheCall, 1)) 183 return true; 184 185 ExprResult Arg(TheCall->getArg(0)); 186 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 187 if (ResultType.isNull()) 188 return true; 189 190 TheCall->setArg(0, Arg.get()); 191 TheCall->setType(ResultType); 192 return false; 193 } 194 195 /// Check the number of arguments and set the result type to 196 /// the argument type. 197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 198 if (checkArgCount(S, TheCall, 1)) 199 return true; 200 201 TheCall->setType(TheCall->getArg(0)->getType()); 202 return false; 203 } 204 205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 207 /// type (but not a function pointer) and that the alignment is a power-of-two. 208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 209 if (checkArgCount(S, TheCall, 2)) 210 return true; 211 212 clang::Expr *Source = TheCall->getArg(0); 213 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 214 215 auto IsValidIntegerType = [](QualType Ty) { 216 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 217 }; 218 QualType SrcTy = Source->getType(); 219 // We should also be able to use it with arrays (but not functions!). 220 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 221 SrcTy = S.Context.getDecayedType(SrcTy); 222 } 223 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 224 SrcTy->isFunctionPointerType()) { 225 // FIXME: this is not quite the right error message since we don't allow 226 // floating point types, or member pointers. 227 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 228 << SrcTy; 229 return true; 230 } 231 232 clang::Expr *AlignOp = TheCall->getArg(1); 233 if (!IsValidIntegerType(AlignOp->getType())) { 234 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 235 << AlignOp->getType(); 236 return true; 237 } 238 Expr::EvalResult AlignResult; 239 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 240 // We can't check validity of alignment if it is type dependent. 241 if (!AlignOp->isInstantiationDependent() && 242 AlignOp->EvaluateAsInt(AlignResult, S.Context, 243 Expr::SE_AllowSideEffects)) { 244 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 245 llvm::APSInt MaxValue( 246 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 247 if (AlignValue < 1) { 248 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 249 return true; 250 } 251 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 252 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 253 << MaxValue.toString(10); 254 return true; 255 } 256 if (!AlignValue.isPowerOf2()) { 257 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 258 return true; 259 } 260 if (AlignValue == 1) { 261 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 262 << IsBooleanAlignBuiltin; 263 } 264 } 265 266 ExprResult SrcArg = S.PerformCopyInitialization( 267 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 268 SourceLocation(), Source); 269 if (SrcArg.isInvalid()) 270 return true; 271 TheCall->setArg(0, SrcArg.get()); 272 ExprResult AlignArg = 273 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 274 S.Context, AlignOp->getType(), false), 275 SourceLocation(), AlignOp); 276 if (AlignArg.isInvalid()) 277 return true; 278 TheCall->setArg(1, AlignArg.get()); 279 // For align_up/align_down, the return type is the same as the (potentially 280 // decayed) argument type including qualifiers. For is_aligned(), the result 281 // is always bool. 282 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 283 return false; 284 } 285 286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 287 if (checkArgCount(S, TheCall, 3)) 288 return true; 289 290 // First two arguments should be integers. 291 for (unsigned I = 0; I < 2; ++I) { 292 ExprResult Arg = TheCall->getArg(I); 293 QualType Ty = Arg.get()->getType(); 294 if (!Ty->isIntegerType()) { 295 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 296 << Ty << Arg.get()->getSourceRange(); 297 return true; 298 } 299 InitializedEntity Entity = InitializedEntity::InitializeParameter( 300 S.getASTContext(), Ty, /*consume*/ false); 301 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 302 if (Arg.isInvalid()) 303 return true; 304 TheCall->setArg(I, Arg.get()); 305 } 306 307 // Third argument should be a pointer to a non-const integer. 308 // IRGen correctly handles volatile, restrict, and address spaces, and 309 // the other qualifiers aren't possible. 310 { 311 ExprResult Arg = TheCall->getArg(2); 312 QualType Ty = Arg.get()->getType(); 313 const auto *PtrTy = Ty->getAs<PointerType>(); 314 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 315 !PtrTy->getPointeeType().isConstQualified())) { 316 S.Diag(Arg.get()->getBeginLoc(), 317 diag::err_overflow_builtin_must_be_ptr_int) 318 << Ty << Arg.get()->getSourceRange(); 319 return true; 320 } 321 InitializedEntity Entity = InitializedEntity::InitializeParameter( 322 S.getASTContext(), Ty, /*consume*/ false); 323 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 324 if (Arg.isInvalid()) 325 return true; 326 TheCall->setArg(2, Arg.get()); 327 } 328 return false; 329 } 330 331 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 332 if (checkArgCount(S, BuiltinCall, 2)) 333 return true; 334 335 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 336 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 337 Expr *Call = BuiltinCall->getArg(0); 338 Expr *Chain = BuiltinCall->getArg(1); 339 340 if (Call->getStmtClass() != Stmt::CallExprClass) { 341 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 342 << Call->getSourceRange(); 343 return true; 344 } 345 346 auto CE = cast<CallExpr>(Call); 347 if (CE->getCallee()->getType()->isBlockPointerType()) { 348 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 349 << Call->getSourceRange(); 350 return true; 351 } 352 353 const Decl *TargetDecl = CE->getCalleeDecl(); 354 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 355 if (FD->getBuiltinID()) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 362 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 363 << Call->getSourceRange(); 364 return true; 365 } 366 367 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 368 if (ChainResult.isInvalid()) 369 return true; 370 if (!ChainResult.get()->getType()->isPointerType()) { 371 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 372 << Chain->getSourceRange(); 373 return true; 374 } 375 376 QualType ReturnTy = CE->getCallReturnType(S.Context); 377 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 378 QualType BuiltinTy = S.Context.getFunctionType( 379 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 380 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 381 382 Builtin = 383 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 384 385 BuiltinCall->setType(CE->getType()); 386 BuiltinCall->setValueKind(CE->getValueKind()); 387 BuiltinCall->setObjectKind(CE->getObjectKind()); 388 BuiltinCall->setCallee(Builtin); 389 BuiltinCall->setArg(1, ChainResult.get()); 390 391 return false; 392 } 393 394 namespace { 395 396 class EstimateSizeFormatHandler 397 : public analyze_format_string::FormatStringHandler { 398 size_t Size; 399 400 public: 401 EstimateSizeFormatHandler(StringRef Format) 402 : Size(std::min(Format.find(0), Format.size()) + 403 1 /* null byte always written by sprintf */) {} 404 405 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 406 const char *, unsigned SpecifierLen) override { 407 408 const size_t FieldWidth = computeFieldWidth(FS); 409 const size_t Precision = computePrecision(FS); 410 411 // The actual format. 412 switch (FS.getConversionSpecifier().getKind()) { 413 // Just a char. 414 case analyze_format_string::ConversionSpecifier::cArg: 415 case analyze_format_string::ConversionSpecifier::CArg: 416 Size += std::max(FieldWidth, (size_t)1); 417 break; 418 // Just an integer. 419 case analyze_format_string::ConversionSpecifier::dArg: 420 case analyze_format_string::ConversionSpecifier::DArg: 421 case analyze_format_string::ConversionSpecifier::iArg: 422 case analyze_format_string::ConversionSpecifier::oArg: 423 case analyze_format_string::ConversionSpecifier::OArg: 424 case analyze_format_string::ConversionSpecifier::uArg: 425 case analyze_format_string::ConversionSpecifier::UArg: 426 case analyze_format_string::ConversionSpecifier::xArg: 427 case analyze_format_string::ConversionSpecifier::XArg: 428 Size += std::max(FieldWidth, Precision); 429 break; 430 431 // %g style conversion switches between %f or %e style dynamically. 432 // %f always takes less space, so default to it. 433 case analyze_format_string::ConversionSpecifier::gArg: 434 case analyze_format_string::ConversionSpecifier::GArg: 435 436 // Floating point number in the form '[+]ddd.ddd'. 437 case analyze_format_string::ConversionSpecifier::fArg: 438 case analyze_format_string::ConversionSpecifier::FArg: 439 Size += std::max(FieldWidth, 1 /* integer part */ + 440 (Precision ? 1 + Precision 441 : 0) /* period + decimal */); 442 break; 443 444 // Floating point number in the form '[-]d.ddde[+-]dd'. 445 case analyze_format_string::ConversionSpecifier::eArg: 446 case analyze_format_string::ConversionSpecifier::EArg: 447 Size += 448 std::max(FieldWidth, 449 1 /* integer part */ + 450 (Precision ? 1 + Precision : 0) /* period + decimal */ + 451 1 /* e or E letter */ + 2 /* exponent */); 452 break; 453 454 // Floating point number in the form '[-]0xh.hhhhp±dd'. 455 case analyze_format_string::ConversionSpecifier::aArg: 456 case analyze_format_string::ConversionSpecifier::AArg: 457 Size += 458 std::max(FieldWidth, 459 2 /* 0x */ + 1 /* integer part */ + 460 (Precision ? 1 + Precision : 0) /* period + decimal */ + 461 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 462 break; 463 464 // Just a string. 465 case analyze_format_string::ConversionSpecifier::sArg: 466 case analyze_format_string::ConversionSpecifier::SArg: 467 Size += FieldWidth; 468 break; 469 470 // Just a pointer in the form '0xddd'. 471 case analyze_format_string::ConversionSpecifier::pArg: 472 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 473 break; 474 475 // A plain percent. 476 case analyze_format_string::ConversionSpecifier::PercentArg: 477 Size += 1; 478 break; 479 480 default: 481 break; 482 } 483 484 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 485 486 if (FS.hasAlternativeForm()) { 487 switch (FS.getConversionSpecifier().getKind()) { 488 default: 489 break; 490 // Force a leading '0'. 491 case analyze_format_string::ConversionSpecifier::oArg: 492 Size += 1; 493 break; 494 // Force a leading '0x'. 495 case analyze_format_string::ConversionSpecifier::xArg: 496 case analyze_format_string::ConversionSpecifier::XArg: 497 Size += 2; 498 break; 499 // Force a period '.' before decimal, even if precision is 0. 500 case analyze_format_string::ConversionSpecifier::aArg: 501 case analyze_format_string::ConversionSpecifier::AArg: 502 case analyze_format_string::ConversionSpecifier::eArg: 503 case analyze_format_string::ConversionSpecifier::EArg: 504 case analyze_format_string::ConversionSpecifier::fArg: 505 case analyze_format_string::ConversionSpecifier::FArg: 506 case analyze_format_string::ConversionSpecifier::gArg: 507 case analyze_format_string::ConversionSpecifier::GArg: 508 Size += (Precision ? 0 : 1); 509 break; 510 } 511 } 512 assert(SpecifierLen <= Size && "no underflow"); 513 Size -= SpecifierLen; 514 return true; 515 } 516 517 size_t getSizeLowerBound() const { return Size; } 518 519 private: 520 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 521 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 522 size_t FieldWidth = 0; 523 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 524 FieldWidth = FW.getConstantAmount(); 525 return FieldWidth; 526 } 527 528 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 529 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 530 size_t Precision = 0; 531 532 // See man 3 printf for default precision value based on the specifier. 533 switch (FW.getHowSpecified()) { 534 case analyze_format_string::OptionalAmount::NotSpecified: 535 switch (FS.getConversionSpecifier().getKind()) { 536 default: 537 break; 538 case analyze_format_string::ConversionSpecifier::dArg: // %d 539 case analyze_format_string::ConversionSpecifier::DArg: // %D 540 case analyze_format_string::ConversionSpecifier::iArg: // %i 541 Precision = 1; 542 break; 543 case analyze_format_string::ConversionSpecifier::oArg: // %d 544 case analyze_format_string::ConversionSpecifier::OArg: // %D 545 case analyze_format_string::ConversionSpecifier::uArg: // %d 546 case analyze_format_string::ConversionSpecifier::UArg: // %D 547 case analyze_format_string::ConversionSpecifier::xArg: // %d 548 case analyze_format_string::ConversionSpecifier::XArg: // %D 549 Precision = 1; 550 break; 551 case analyze_format_string::ConversionSpecifier::fArg: // %f 552 case analyze_format_string::ConversionSpecifier::FArg: // %F 553 case analyze_format_string::ConversionSpecifier::eArg: // %e 554 case analyze_format_string::ConversionSpecifier::EArg: // %E 555 case analyze_format_string::ConversionSpecifier::gArg: // %g 556 case analyze_format_string::ConversionSpecifier::GArg: // %G 557 Precision = 6; 558 break; 559 case analyze_format_string::ConversionSpecifier::pArg: // %d 560 Precision = 1; 561 break; 562 } 563 break; 564 case analyze_format_string::OptionalAmount::Constant: 565 Precision = FW.getConstantAmount(); 566 break; 567 default: 568 break; 569 } 570 return Precision; 571 } 572 }; 573 574 } // namespace 575 576 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 577 /// __builtin_*_chk function, then use the object size argument specified in the 578 /// source. Otherwise, infer the object size using __builtin_object_size. 579 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 580 CallExpr *TheCall) { 581 // FIXME: There are some more useful checks we could be doing here: 582 // - Evaluate strlen of strcpy arguments, use as object size. 583 584 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 585 isConstantEvaluated()) 586 return; 587 588 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 589 if (!BuiltinID) 590 return; 591 592 const TargetInfo &TI = getASTContext().getTargetInfo(); 593 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 594 595 unsigned DiagID = 0; 596 bool IsChkVariant = false; 597 Optional<llvm::APSInt> UsedSize; 598 unsigned SizeIndex, ObjectIndex; 599 switch (BuiltinID) { 600 default: 601 return; 602 case Builtin::BIsprintf: 603 case Builtin::BI__builtin___sprintf_chk: { 604 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 605 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 606 607 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 608 609 if (!Format->isAscii() && !Format->isUTF8()) 610 return; 611 612 StringRef FormatStrRef = Format->getString(); 613 EstimateSizeFormatHandler H(FormatStrRef); 614 const char *FormatBytes = FormatStrRef.data(); 615 const ConstantArrayType *T = 616 Context.getAsConstantArrayType(Format->getType()); 617 assert(T && "String literal not of constant array type!"); 618 size_t TypeSize = T->getSize().getZExtValue(); 619 620 // In case there's a null byte somewhere. 621 size_t StrLen = 622 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 623 if (!analyze_format_string::ParsePrintfString( 624 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 625 Context.getTargetInfo(), false)) { 626 DiagID = diag::warn_fortify_source_format_overflow; 627 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 628 .extOrTrunc(SizeTypeWidth); 629 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 630 IsChkVariant = true; 631 ObjectIndex = 2; 632 } else { 633 IsChkVariant = false; 634 ObjectIndex = 0; 635 } 636 break; 637 } 638 } 639 return; 640 } 641 case Builtin::BI__builtin___memcpy_chk: 642 case Builtin::BI__builtin___memmove_chk: 643 case Builtin::BI__builtin___memset_chk: 644 case Builtin::BI__builtin___strlcat_chk: 645 case Builtin::BI__builtin___strlcpy_chk: 646 case Builtin::BI__builtin___strncat_chk: 647 case Builtin::BI__builtin___strncpy_chk: 648 case Builtin::BI__builtin___stpncpy_chk: 649 case Builtin::BI__builtin___memccpy_chk: 650 case Builtin::BI__builtin___mempcpy_chk: { 651 DiagID = diag::warn_builtin_chk_overflow; 652 IsChkVariant = true; 653 SizeIndex = TheCall->getNumArgs() - 2; 654 ObjectIndex = TheCall->getNumArgs() - 1; 655 break; 656 } 657 658 case Builtin::BI__builtin___snprintf_chk: 659 case Builtin::BI__builtin___vsnprintf_chk: { 660 DiagID = diag::warn_builtin_chk_overflow; 661 IsChkVariant = true; 662 SizeIndex = 1; 663 ObjectIndex = 3; 664 break; 665 } 666 667 case Builtin::BIstrncat: 668 case Builtin::BI__builtin_strncat: 669 case Builtin::BIstrncpy: 670 case Builtin::BI__builtin_strncpy: 671 case Builtin::BIstpncpy: 672 case Builtin::BI__builtin_stpncpy: { 673 // Whether these functions overflow depends on the runtime strlen of the 674 // string, not just the buffer size, so emitting the "always overflow" 675 // diagnostic isn't quite right. We should still diagnose passing a buffer 676 // size larger than the destination buffer though; this is a runtime abort 677 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 678 DiagID = diag::warn_fortify_source_size_mismatch; 679 SizeIndex = TheCall->getNumArgs() - 1; 680 ObjectIndex = 0; 681 break; 682 } 683 684 case Builtin::BImemcpy: 685 case Builtin::BI__builtin_memcpy: 686 case Builtin::BImemmove: 687 case Builtin::BI__builtin_memmove: 688 case Builtin::BImemset: 689 case Builtin::BI__builtin_memset: 690 case Builtin::BImempcpy: 691 case Builtin::BI__builtin_mempcpy: { 692 DiagID = diag::warn_fortify_source_overflow; 693 SizeIndex = TheCall->getNumArgs() - 1; 694 ObjectIndex = 0; 695 break; 696 } 697 case Builtin::BIsnprintf: 698 case Builtin::BI__builtin_snprintf: 699 case Builtin::BIvsnprintf: 700 case Builtin::BI__builtin_vsnprintf: { 701 DiagID = diag::warn_fortify_source_size_mismatch; 702 SizeIndex = 1; 703 ObjectIndex = 0; 704 break; 705 } 706 } 707 708 llvm::APSInt ObjectSize; 709 // For __builtin___*_chk, the object size is explicitly provided by the caller 710 // (usually using __builtin_object_size). Use that value to check this call. 711 if (IsChkVariant) { 712 Expr::EvalResult Result; 713 Expr *SizeArg = TheCall->getArg(ObjectIndex); 714 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 715 return; 716 ObjectSize = Result.Val.getInt(); 717 718 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 719 } else { 720 // If the parameter has a pass_object_size attribute, then we should use its 721 // (potentially) more strict checking mode. Otherwise, conservatively assume 722 // type 0. 723 int BOSType = 0; 724 if (const auto *POS = 725 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 726 BOSType = POS->getType(); 727 728 Expr *ObjArg = TheCall->getArg(ObjectIndex); 729 uint64_t Result; 730 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 731 return; 732 // Get the object size in the target's size_t width. 733 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 734 } 735 736 // Evaluate the number of bytes of the object that this call will use. 737 if (!UsedSize) { 738 Expr::EvalResult Result; 739 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 740 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 741 return; 742 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 743 } 744 745 if (UsedSize.getValue().ule(ObjectSize)) 746 return; 747 748 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 749 // Skim off the details of whichever builtin was called to produce a better 750 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 751 if (IsChkVariant) { 752 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 753 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 754 } else if (FunctionName.startswith("__builtin_")) { 755 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 756 } 757 758 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 759 PDiag(DiagID) 760 << FunctionName << ObjectSize.toString(/*Radix=*/10) 761 << UsedSize.getValue().toString(/*Radix=*/10)); 762 } 763 764 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 765 Scope::ScopeFlags NeededScopeFlags, 766 unsigned DiagID) { 767 // Scopes aren't available during instantiation. Fortunately, builtin 768 // functions cannot be template args so they cannot be formed through template 769 // instantiation. Therefore checking once during the parse is sufficient. 770 if (SemaRef.inTemplateInstantiation()) 771 return false; 772 773 Scope *S = SemaRef.getCurScope(); 774 while (S && !S->isSEHExceptScope()) 775 S = S->getParent(); 776 if (!S || !(S->getFlags() & NeededScopeFlags)) { 777 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 778 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 779 << DRE->getDecl()->getIdentifier(); 780 return true; 781 } 782 783 return false; 784 } 785 786 static inline bool isBlockPointer(Expr *Arg) { 787 return Arg->getType()->isBlockPointerType(); 788 } 789 790 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 791 /// void*, which is a requirement of device side enqueue. 792 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 793 const BlockPointerType *BPT = 794 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 795 ArrayRef<QualType> Params = 796 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 797 unsigned ArgCounter = 0; 798 bool IllegalParams = false; 799 // Iterate through the block parameters until either one is found that is not 800 // a local void*, or the block is valid. 801 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 802 I != E; ++I, ++ArgCounter) { 803 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 804 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 805 LangAS::opencl_local) { 806 // Get the location of the error. If a block literal has been passed 807 // (BlockExpr) then we can point straight to the offending argument, 808 // else we just point to the variable reference. 809 SourceLocation ErrorLoc; 810 if (isa<BlockExpr>(BlockArg)) { 811 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 812 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 813 } else if (isa<DeclRefExpr>(BlockArg)) { 814 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 815 } 816 S.Diag(ErrorLoc, 817 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 818 IllegalParams = true; 819 } 820 } 821 822 return IllegalParams; 823 } 824 825 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 826 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 827 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 828 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 829 return true; 830 } 831 return false; 832 } 833 834 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 835 if (checkArgCount(S, TheCall, 2)) 836 return true; 837 838 if (checkOpenCLSubgroupExt(S, TheCall)) 839 return true; 840 841 // First argument is an ndrange_t type. 842 Expr *NDRangeArg = TheCall->getArg(0); 843 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 844 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 845 << TheCall->getDirectCallee() << "'ndrange_t'"; 846 return true; 847 } 848 849 Expr *BlockArg = TheCall->getArg(1); 850 if (!isBlockPointer(BlockArg)) { 851 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 852 << TheCall->getDirectCallee() << "block"; 853 return true; 854 } 855 return checkOpenCLBlockArgs(S, BlockArg); 856 } 857 858 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 859 /// get_kernel_work_group_size 860 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 861 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 862 if (checkArgCount(S, TheCall, 1)) 863 return true; 864 865 Expr *BlockArg = TheCall->getArg(0); 866 if (!isBlockPointer(BlockArg)) { 867 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 868 << TheCall->getDirectCallee() << "block"; 869 return true; 870 } 871 return checkOpenCLBlockArgs(S, BlockArg); 872 } 873 874 /// Diagnose integer type and any valid implicit conversion to it. 875 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 876 const QualType &IntType); 877 878 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 879 unsigned Start, unsigned End) { 880 bool IllegalParams = false; 881 for (unsigned I = Start; I <= End; ++I) 882 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 883 S.Context.getSizeType()); 884 return IllegalParams; 885 } 886 887 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 888 /// 'local void*' parameter of passed block. 889 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 890 Expr *BlockArg, 891 unsigned NumNonVarArgs) { 892 const BlockPointerType *BPT = 893 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 894 unsigned NumBlockParams = 895 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 896 unsigned TotalNumArgs = TheCall->getNumArgs(); 897 898 // For each argument passed to the block, a corresponding uint needs to 899 // be passed to describe the size of the local memory. 900 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 901 S.Diag(TheCall->getBeginLoc(), 902 diag::err_opencl_enqueue_kernel_local_size_args); 903 return true; 904 } 905 906 // Check that the sizes of the local memory are specified by integers. 907 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 908 TotalNumArgs - 1); 909 } 910 911 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 912 /// overload formats specified in Table 6.13.17.1. 913 /// int enqueue_kernel(queue_t queue, 914 /// kernel_enqueue_flags_t flags, 915 /// const ndrange_t ndrange, 916 /// void (^block)(void)) 917 /// int enqueue_kernel(queue_t queue, 918 /// kernel_enqueue_flags_t flags, 919 /// const ndrange_t ndrange, 920 /// uint num_events_in_wait_list, 921 /// clk_event_t *event_wait_list, 922 /// clk_event_t *event_ret, 923 /// void (^block)(void)) 924 /// int enqueue_kernel(queue_t queue, 925 /// kernel_enqueue_flags_t flags, 926 /// const ndrange_t ndrange, 927 /// void (^block)(local void*, ...), 928 /// uint size0, ...) 929 /// int enqueue_kernel(queue_t queue, 930 /// kernel_enqueue_flags_t flags, 931 /// const ndrange_t ndrange, 932 /// uint num_events_in_wait_list, 933 /// clk_event_t *event_wait_list, 934 /// clk_event_t *event_ret, 935 /// void (^block)(local void*, ...), 936 /// uint size0, ...) 937 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 938 unsigned NumArgs = TheCall->getNumArgs(); 939 940 if (NumArgs < 4) { 941 S.Diag(TheCall->getBeginLoc(), 942 diag::err_typecheck_call_too_few_args_at_least) 943 << 0 << 4 << NumArgs; 944 return true; 945 } 946 947 Expr *Arg0 = TheCall->getArg(0); 948 Expr *Arg1 = TheCall->getArg(1); 949 Expr *Arg2 = TheCall->getArg(2); 950 Expr *Arg3 = TheCall->getArg(3); 951 952 // First argument always needs to be a queue_t type. 953 if (!Arg0->getType()->isQueueT()) { 954 S.Diag(TheCall->getArg(0)->getBeginLoc(), 955 diag::err_opencl_builtin_expected_type) 956 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 957 return true; 958 } 959 960 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 961 if (!Arg1->getType()->isIntegerType()) { 962 S.Diag(TheCall->getArg(1)->getBeginLoc(), 963 diag::err_opencl_builtin_expected_type) 964 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 965 return true; 966 } 967 968 // Third argument is always an ndrange_t type. 969 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 970 S.Diag(TheCall->getArg(2)->getBeginLoc(), 971 diag::err_opencl_builtin_expected_type) 972 << TheCall->getDirectCallee() << "'ndrange_t'"; 973 return true; 974 } 975 976 // With four arguments, there is only one form that the function could be 977 // called in: no events and no variable arguments. 978 if (NumArgs == 4) { 979 // check that the last argument is the right block type. 980 if (!isBlockPointer(Arg3)) { 981 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 982 << TheCall->getDirectCallee() << "block"; 983 return true; 984 } 985 // we have a block type, check the prototype 986 const BlockPointerType *BPT = 987 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 988 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 989 S.Diag(Arg3->getBeginLoc(), 990 diag::err_opencl_enqueue_kernel_blocks_no_args); 991 return true; 992 } 993 return false; 994 } 995 // we can have block + varargs. 996 if (isBlockPointer(Arg3)) 997 return (checkOpenCLBlockArgs(S, Arg3) || 998 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 999 // last two cases with either exactly 7 args or 7 args and varargs. 1000 if (NumArgs >= 7) { 1001 // check common block argument. 1002 Expr *Arg6 = TheCall->getArg(6); 1003 if (!isBlockPointer(Arg6)) { 1004 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1005 << TheCall->getDirectCallee() << "block"; 1006 return true; 1007 } 1008 if (checkOpenCLBlockArgs(S, Arg6)) 1009 return true; 1010 1011 // Forth argument has to be any integer type. 1012 if (!Arg3->getType()->isIntegerType()) { 1013 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1014 diag::err_opencl_builtin_expected_type) 1015 << TheCall->getDirectCallee() << "integer"; 1016 return true; 1017 } 1018 // check remaining common arguments. 1019 Expr *Arg4 = TheCall->getArg(4); 1020 Expr *Arg5 = TheCall->getArg(5); 1021 1022 // Fifth argument is always passed as a pointer to clk_event_t. 1023 if (!Arg4->isNullPointerConstant(S.Context, 1024 Expr::NPC_ValueDependentIsNotNull) && 1025 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1026 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() 1029 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1030 return true; 1031 } 1032 1033 // Sixth argument is always passed as a pointer to clk_event_t. 1034 if (!Arg5->isNullPointerConstant(S.Context, 1035 Expr::NPC_ValueDependentIsNotNull) && 1036 !(Arg5->getType()->isPointerType() && 1037 Arg5->getType()->getPointeeType()->isClkEventT())) { 1038 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1039 diag::err_opencl_builtin_expected_type) 1040 << TheCall->getDirectCallee() 1041 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1042 return true; 1043 } 1044 1045 if (NumArgs == 7) 1046 return false; 1047 1048 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1049 } 1050 1051 // None of the specific case has been detected, give generic error 1052 S.Diag(TheCall->getBeginLoc(), 1053 diag::err_opencl_enqueue_kernel_incorrect_args); 1054 return true; 1055 } 1056 1057 /// Returns OpenCL access qual. 1058 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1059 return D->getAttr<OpenCLAccessAttr>(); 1060 } 1061 1062 /// Returns true if pipe element type is different from the pointer. 1063 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1064 const Expr *Arg0 = Call->getArg(0); 1065 // First argument type should always be pipe. 1066 if (!Arg0->getType()->isPipeType()) { 1067 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1068 << Call->getDirectCallee() << Arg0->getSourceRange(); 1069 return true; 1070 } 1071 OpenCLAccessAttr *AccessQual = 1072 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1073 // Validates the access qualifier is compatible with the call. 1074 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1075 // read_only and write_only, and assumed to be read_only if no qualifier is 1076 // specified. 1077 switch (Call->getDirectCallee()->getBuiltinID()) { 1078 case Builtin::BIread_pipe: 1079 case Builtin::BIreserve_read_pipe: 1080 case Builtin::BIcommit_read_pipe: 1081 case Builtin::BIwork_group_reserve_read_pipe: 1082 case Builtin::BIsub_group_reserve_read_pipe: 1083 case Builtin::BIwork_group_commit_read_pipe: 1084 case Builtin::BIsub_group_commit_read_pipe: 1085 if (!(!AccessQual || AccessQual->isReadOnly())) { 1086 S.Diag(Arg0->getBeginLoc(), 1087 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1088 << "read_only" << Arg0->getSourceRange(); 1089 return true; 1090 } 1091 break; 1092 case Builtin::BIwrite_pipe: 1093 case Builtin::BIreserve_write_pipe: 1094 case Builtin::BIcommit_write_pipe: 1095 case Builtin::BIwork_group_reserve_write_pipe: 1096 case Builtin::BIsub_group_reserve_write_pipe: 1097 case Builtin::BIwork_group_commit_write_pipe: 1098 case Builtin::BIsub_group_commit_write_pipe: 1099 if (!(AccessQual && AccessQual->isWriteOnly())) { 1100 S.Diag(Arg0->getBeginLoc(), 1101 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1102 << "write_only" << Arg0->getSourceRange(); 1103 return true; 1104 } 1105 break; 1106 default: 1107 break; 1108 } 1109 return false; 1110 } 1111 1112 /// Returns true if pipe element type is different from the pointer. 1113 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1114 const Expr *Arg0 = Call->getArg(0); 1115 const Expr *ArgIdx = Call->getArg(Idx); 1116 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1117 const QualType EltTy = PipeTy->getElementType(); 1118 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1119 // The Idx argument should be a pointer and the type of the pointer and 1120 // the type of pipe element should also be the same. 1121 if (!ArgTy || 1122 !S.Context.hasSameType( 1123 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1124 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1125 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1126 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1127 return true; 1128 } 1129 return false; 1130 } 1131 1132 // Performs semantic analysis for the read/write_pipe call. 1133 // \param S Reference to the semantic analyzer. 1134 // \param Call A pointer to the builtin call. 1135 // \return True if a semantic error has been found, false otherwise. 1136 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1137 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1138 // functions have two forms. 1139 switch (Call->getNumArgs()) { 1140 case 2: 1141 if (checkOpenCLPipeArg(S, Call)) 1142 return true; 1143 // The call with 2 arguments should be 1144 // read/write_pipe(pipe T, T*). 1145 // Check packet type T. 1146 if (checkOpenCLPipePacketType(S, Call, 1)) 1147 return true; 1148 break; 1149 1150 case 4: { 1151 if (checkOpenCLPipeArg(S, Call)) 1152 return true; 1153 // The call with 4 arguments should be 1154 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1155 // Check reserve_id_t. 1156 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1157 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1158 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1159 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1160 return true; 1161 } 1162 1163 // Check the index. 1164 const Expr *Arg2 = Call->getArg(2); 1165 if (!Arg2->getType()->isIntegerType() && 1166 !Arg2->getType()->isUnsignedIntegerType()) { 1167 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1168 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1169 << Arg2->getType() << Arg2->getSourceRange(); 1170 return true; 1171 } 1172 1173 // Check packet type T. 1174 if (checkOpenCLPipePacketType(S, Call, 3)) 1175 return true; 1176 } break; 1177 default: 1178 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1179 << Call->getDirectCallee() << Call->getSourceRange(); 1180 return true; 1181 } 1182 1183 return false; 1184 } 1185 1186 // Performs a semantic analysis on the {work_group_/sub_group_ 1187 // /_}reserve_{read/write}_pipe 1188 // \param S Reference to the semantic analyzer. 1189 // \param Call The call to the builtin function to be analyzed. 1190 // \return True if a semantic error was found, false otherwise. 1191 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1192 if (checkArgCount(S, Call, 2)) 1193 return true; 1194 1195 if (checkOpenCLPipeArg(S, Call)) 1196 return true; 1197 1198 // Check the reserve size. 1199 if (!Call->getArg(1)->getType()->isIntegerType() && 1200 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1201 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1202 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1203 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1204 return true; 1205 } 1206 1207 // Since return type of reserve_read/write_pipe built-in function is 1208 // reserve_id_t, which is not defined in the builtin def file , we used int 1209 // as return type and need to override the return type of these functions. 1210 Call->setType(S.Context.OCLReserveIDTy); 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on {work_group_/sub_group_ 1216 // /_}commit_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check reserve_id_t. 1228 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1229 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1230 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1231 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1232 return true; 1233 } 1234 1235 return false; 1236 } 1237 1238 // Performs a semantic analysis on the call to built-in Pipe 1239 // Query Functions. 1240 // \param S Reference to the semantic analyzer. 1241 // \param Call The call to the builtin function to be analyzed. 1242 // \return True if a semantic error was found, false otherwise. 1243 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1244 if (checkArgCount(S, Call, 1)) 1245 return true; 1246 1247 if (!Call->getArg(0)->getType()->isPipeType()) { 1248 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1249 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1250 return true; 1251 } 1252 1253 return false; 1254 } 1255 1256 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1257 // Performs semantic analysis for the to_global/local/private call. 1258 // \param S Reference to the semantic analyzer. 1259 // \param BuiltinID ID of the builtin function. 1260 // \param Call A pointer to the builtin call. 1261 // \return True if a semantic error has been found, false otherwise. 1262 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1263 CallExpr *Call) { 1264 if (Call->getNumArgs() != 1) { 1265 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1266 << Call->getDirectCallee() << Call->getSourceRange(); 1267 return true; 1268 } 1269 1270 auto RT = Call->getArg(0)->getType(); 1271 if (!RT->isPointerType() || RT->getPointeeType() 1272 .getAddressSpace() == LangAS::opencl_constant) { 1273 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1274 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1275 return true; 1276 } 1277 1278 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1279 S.Diag(Call->getArg(0)->getBeginLoc(), 1280 diag::warn_opencl_generic_address_space_arg) 1281 << Call->getDirectCallee()->getNameInfo().getAsString() 1282 << Call->getArg(0)->getSourceRange(); 1283 } 1284 1285 RT = RT->getPointeeType(); 1286 auto Qual = RT.getQualifiers(); 1287 switch (BuiltinID) { 1288 case Builtin::BIto_global: 1289 Qual.setAddressSpace(LangAS::opencl_global); 1290 break; 1291 case Builtin::BIto_local: 1292 Qual.setAddressSpace(LangAS::opencl_local); 1293 break; 1294 case Builtin::BIto_private: 1295 Qual.setAddressSpace(LangAS::opencl_private); 1296 break; 1297 default: 1298 llvm_unreachable("Invalid builtin function"); 1299 } 1300 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1301 RT.getUnqualifiedType(), Qual))); 1302 1303 return false; 1304 } 1305 1306 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1307 if (checkArgCount(S, TheCall, 1)) 1308 return ExprError(); 1309 1310 // Compute __builtin_launder's parameter type from the argument. 1311 // The parameter type is: 1312 // * The type of the argument if it's not an array or function type, 1313 // Otherwise, 1314 // * The decayed argument type. 1315 QualType ParamTy = [&]() { 1316 QualType ArgTy = TheCall->getArg(0)->getType(); 1317 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1318 return S.Context.getPointerType(Ty->getElementType()); 1319 if (ArgTy->isFunctionType()) { 1320 return S.Context.getPointerType(ArgTy); 1321 } 1322 return ArgTy; 1323 }(); 1324 1325 TheCall->setType(ParamTy); 1326 1327 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1328 if (!ParamTy->isPointerType()) 1329 return 0; 1330 if (ParamTy->isFunctionPointerType()) 1331 return 1; 1332 if (ParamTy->isVoidPointerType()) 1333 return 2; 1334 return llvm::Optional<unsigned>{}; 1335 }(); 1336 if (DiagSelect.hasValue()) { 1337 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1338 << DiagSelect.getValue() << TheCall->getSourceRange(); 1339 return ExprError(); 1340 } 1341 1342 // We either have an incomplete class type, or we have a class template 1343 // whose instantiation has not been forced. Example: 1344 // 1345 // template <class T> struct Foo { T value; }; 1346 // Foo<int> *p = nullptr; 1347 // auto *d = __builtin_launder(p); 1348 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1349 diag::err_incomplete_type)) 1350 return ExprError(); 1351 1352 assert(ParamTy->getPointeeType()->isObjectType() && 1353 "Unhandled non-object pointer case"); 1354 1355 InitializedEntity Entity = 1356 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1357 ExprResult Arg = 1358 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1359 if (Arg.isInvalid()) 1360 return ExprError(); 1361 TheCall->setArg(0, Arg.get()); 1362 1363 return TheCall; 1364 } 1365 1366 // Emit an error and return true if the current architecture is not in the list 1367 // of supported architectures. 1368 static bool 1369 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1370 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1371 llvm::Triple::ArchType CurArch = 1372 S.getASTContext().getTargetInfo().getTriple().getArch(); 1373 if (llvm::is_contained(SupportedArchs, CurArch)) 1374 return false; 1375 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1376 << TheCall->getSourceRange(); 1377 return true; 1378 } 1379 1380 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1381 SourceLocation CallSiteLoc); 1382 1383 bool Sema::CheckTSBuiltinFunctionCall(llvm::Triple::ArchType Arch, 1384 unsigned BuiltinID, CallExpr *TheCall) { 1385 switch (Arch) { 1386 default: 1387 // Some builtins don't require additional checking, so just consider these 1388 // acceptable. 1389 return false; 1390 case llvm::Triple::arm: 1391 case llvm::Triple::armeb: 1392 case llvm::Triple::thumb: 1393 case llvm::Triple::thumbeb: 1394 return CheckARMBuiltinFunctionCall(BuiltinID, TheCall); 1395 case llvm::Triple::aarch64: 1396 case llvm::Triple::aarch64_32: 1397 case llvm::Triple::aarch64_be: 1398 return CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall); 1399 case llvm::Triple::bpfeb: 1400 case llvm::Triple::bpfel: 1401 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1402 case llvm::Triple::hexagon: 1403 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1404 case llvm::Triple::mips: 1405 case llvm::Triple::mipsel: 1406 case llvm::Triple::mips64: 1407 case llvm::Triple::mips64el: 1408 return CheckMipsBuiltinFunctionCall(BuiltinID, TheCall); 1409 case llvm::Triple::systemz: 1410 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1411 case llvm::Triple::x86: 1412 case llvm::Triple::x86_64: 1413 return CheckX86BuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::ppc: 1415 case llvm::Triple::ppc64: 1416 case llvm::Triple::ppc64le: 1417 return CheckPPCBuiltinFunctionCall(BuiltinID, TheCall); 1418 case llvm::Triple::amdgcn: 1419 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1420 } 1421 } 1422 1423 ExprResult 1424 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1425 CallExpr *TheCall) { 1426 ExprResult TheCallResult(TheCall); 1427 1428 // Find out if any arguments are required to be integer constant expressions. 1429 unsigned ICEArguments = 0; 1430 ASTContext::GetBuiltinTypeError Error; 1431 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1432 if (Error != ASTContext::GE_None) 1433 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1434 1435 // If any arguments are required to be ICE's, check and diagnose. 1436 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1437 // Skip arguments not required to be ICE's. 1438 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1439 1440 llvm::APSInt Result; 1441 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1442 return true; 1443 ICEArguments &= ~(1 << ArgNo); 1444 } 1445 1446 switch (BuiltinID) { 1447 case Builtin::BI__builtin___CFStringMakeConstantString: 1448 assert(TheCall->getNumArgs() == 1 && 1449 "Wrong # arguments to builtin CFStringMakeConstantString"); 1450 if (CheckObjCString(TheCall->getArg(0))) 1451 return ExprError(); 1452 break; 1453 case Builtin::BI__builtin_ms_va_start: 1454 case Builtin::BI__builtin_stdarg_start: 1455 case Builtin::BI__builtin_va_start: 1456 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1457 return ExprError(); 1458 break; 1459 case Builtin::BI__va_start: { 1460 switch (Context.getTargetInfo().getTriple().getArch()) { 1461 case llvm::Triple::aarch64: 1462 case llvm::Triple::arm: 1463 case llvm::Triple::thumb: 1464 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1465 return ExprError(); 1466 break; 1467 default: 1468 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1469 return ExprError(); 1470 break; 1471 } 1472 break; 1473 } 1474 1475 // The acquire, release, and no fence variants are ARM and AArch64 only. 1476 case Builtin::BI_interlockedbittestandset_acq: 1477 case Builtin::BI_interlockedbittestandset_rel: 1478 case Builtin::BI_interlockedbittestandset_nf: 1479 case Builtin::BI_interlockedbittestandreset_acq: 1480 case Builtin::BI_interlockedbittestandreset_rel: 1481 case Builtin::BI_interlockedbittestandreset_nf: 1482 if (CheckBuiltinTargetSupport( 1483 *this, BuiltinID, TheCall, 1484 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1485 return ExprError(); 1486 break; 1487 1488 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1489 case Builtin::BI_bittest64: 1490 case Builtin::BI_bittestandcomplement64: 1491 case Builtin::BI_bittestandreset64: 1492 case Builtin::BI_bittestandset64: 1493 case Builtin::BI_interlockedbittestandreset64: 1494 case Builtin::BI_interlockedbittestandset64: 1495 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1496 {llvm::Triple::x86_64, llvm::Triple::arm, 1497 llvm::Triple::thumb, llvm::Triple::aarch64})) 1498 return ExprError(); 1499 break; 1500 1501 case Builtin::BI__builtin_isgreater: 1502 case Builtin::BI__builtin_isgreaterequal: 1503 case Builtin::BI__builtin_isless: 1504 case Builtin::BI__builtin_islessequal: 1505 case Builtin::BI__builtin_islessgreater: 1506 case Builtin::BI__builtin_isunordered: 1507 if (SemaBuiltinUnorderedCompare(TheCall)) 1508 return ExprError(); 1509 break; 1510 case Builtin::BI__builtin_fpclassify: 1511 if (SemaBuiltinFPClassification(TheCall, 6)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_isfinite: 1515 case Builtin::BI__builtin_isinf: 1516 case Builtin::BI__builtin_isinf_sign: 1517 case Builtin::BI__builtin_isnan: 1518 case Builtin::BI__builtin_isnormal: 1519 case Builtin::BI__builtin_signbit: 1520 case Builtin::BI__builtin_signbitf: 1521 case Builtin::BI__builtin_signbitl: 1522 if (SemaBuiltinFPClassification(TheCall, 1)) 1523 return ExprError(); 1524 break; 1525 case Builtin::BI__builtin_shufflevector: 1526 return SemaBuiltinShuffleVector(TheCall); 1527 // TheCall will be freed by the smart pointer here, but that's fine, since 1528 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1529 case Builtin::BI__builtin_prefetch: 1530 if (SemaBuiltinPrefetch(TheCall)) 1531 return ExprError(); 1532 break; 1533 case Builtin::BI__builtin_alloca_with_align: 1534 if (SemaBuiltinAllocaWithAlign(TheCall)) 1535 return ExprError(); 1536 LLVM_FALLTHROUGH; 1537 case Builtin::BI__builtin_alloca: 1538 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1539 << TheCall->getDirectCallee(); 1540 break; 1541 case Builtin::BI__assume: 1542 case Builtin::BI__builtin_assume: 1543 if (SemaBuiltinAssume(TheCall)) 1544 return ExprError(); 1545 break; 1546 case Builtin::BI__builtin_assume_aligned: 1547 if (SemaBuiltinAssumeAligned(TheCall)) 1548 return ExprError(); 1549 break; 1550 case Builtin::BI__builtin_dynamic_object_size: 1551 case Builtin::BI__builtin_object_size: 1552 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_longjmp: 1556 if (SemaBuiltinLongjmp(TheCall)) 1557 return ExprError(); 1558 break; 1559 case Builtin::BI__builtin_setjmp: 1560 if (SemaBuiltinSetjmp(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI_setjmp: 1564 case Builtin::BI_setjmpex: 1565 if (checkArgCount(*this, TheCall, 1)) 1566 return true; 1567 break; 1568 case Builtin::BI__builtin_classify_type: 1569 if (checkArgCount(*this, TheCall, 1)) return true; 1570 TheCall->setType(Context.IntTy); 1571 break; 1572 case Builtin::BI__builtin_constant_p: { 1573 if (checkArgCount(*this, TheCall, 1)) return true; 1574 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1575 if (Arg.isInvalid()) return true; 1576 TheCall->setArg(0, Arg.get()); 1577 TheCall->setType(Context.IntTy); 1578 break; 1579 } 1580 case Builtin::BI__builtin_launder: 1581 return SemaBuiltinLaunder(*this, TheCall); 1582 case Builtin::BI__sync_fetch_and_add: 1583 case Builtin::BI__sync_fetch_and_add_1: 1584 case Builtin::BI__sync_fetch_and_add_2: 1585 case Builtin::BI__sync_fetch_and_add_4: 1586 case Builtin::BI__sync_fetch_and_add_8: 1587 case Builtin::BI__sync_fetch_and_add_16: 1588 case Builtin::BI__sync_fetch_and_sub: 1589 case Builtin::BI__sync_fetch_and_sub_1: 1590 case Builtin::BI__sync_fetch_and_sub_2: 1591 case Builtin::BI__sync_fetch_and_sub_4: 1592 case Builtin::BI__sync_fetch_and_sub_8: 1593 case Builtin::BI__sync_fetch_and_sub_16: 1594 case Builtin::BI__sync_fetch_and_or: 1595 case Builtin::BI__sync_fetch_and_or_1: 1596 case Builtin::BI__sync_fetch_and_or_2: 1597 case Builtin::BI__sync_fetch_and_or_4: 1598 case Builtin::BI__sync_fetch_and_or_8: 1599 case Builtin::BI__sync_fetch_and_or_16: 1600 case Builtin::BI__sync_fetch_and_and: 1601 case Builtin::BI__sync_fetch_and_and_1: 1602 case Builtin::BI__sync_fetch_and_and_2: 1603 case Builtin::BI__sync_fetch_and_and_4: 1604 case Builtin::BI__sync_fetch_and_and_8: 1605 case Builtin::BI__sync_fetch_and_and_16: 1606 case Builtin::BI__sync_fetch_and_xor: 1607 case Builtin::BI__sync_fetch_and_xor_1: 1608 case Builtin::BI__sync_fetch_and_xor_2: 1609 case Builtin::BI__sync_fetch_and_xor_4: 1610 case Builtin::BI__sync_fetch_and_xor_8: 1611 case Builtin::BI__sync_fetch_and_xor_16: 1612 case Builtin::BI__sync_fetch_and_nand: 1613 case Builtin::BI__sync_fetch_and_nand_1: 1614 case Builtin::BI__sync_fetch_and_nand_2: 1615 case Builtin::BI__sync_fetch_and_nand_4: 1616 case Builtin::BI__sync_fetch_and_nand_8: 1617 case Builtin::BI__sync_fetch_and_nand_16: 1618 case Builtin::BI__sync_add_and_fetch: 1619 case Builtin::BI__sync_add_and_fetch_1: 1620 case Builtin::BI__sync_add_and_fetch_2: 1621 case Builtin::BI__sync_add_and_fetch_4: 1622 case Builtin::BI__sync_add_and_fetch_8: 1623 case Builtin::BI__sync_add_and_fetch_16: 1624 case Builtin::BI__sync_sub_and_fetch: 1625 case Builtin::BI__sync_sub_and_fetch_1: 1626 case Builtin::BI__sync_sub_and_fetch_2: 1627 case Builtin::BI__sync_sub_and_fetch_4: 1628 case Builtin::BI__sync_sub_and_fetch_8: 1629 case Builtin::BI__sync_sub_and_fetch_16: 1630 case Builtin::BI__sync_and_and_fetch: 1631 case Builtin::BI__sync_and_and_fetch_1: 1632 case Builtin::BI__sync_and_and_fetch_2: 1633 case Builtin::BI__sync_and_and_fetch_4: 1634 case Builtin::BI__sync_and_and_fetch_8: 1635 case Builtin::BI__sync_and_and_fetch_16: 1636 case Builtin::BI__sync_or_and_fetch: 1637 case Builtin::BI__sync_or_and_fetch_1: 1638 case Builtin::BI__sync_or_and_fetch_2: 1639 case Builtin::BI__sync_or_and_fetch_4: 1640 case Builtin::BI__sync_or_and_fetch_8: 1641 case Builtin::BI__sync_or_and_fetch_16: 1642 case Builtin::BI__sync_xor_and_fetch: 1643 case Builtin::BI__sync_xor_and_fetch_1: 1644 case Builtin::BI__sync_xor_and_fetch_2: 1645 case Builtin::BI__sync_xor_and_fetch_4: 1646 case Builtin::BI__sync_xor_and_fetch_8: 1647 case Builtin::BI__sync_xor_and_fetch_16: 1648 case Builtin::BI__sync_nand_and_fetch: 1649 case Builtin::BI__sync_nand_and_fetch_1: 1650 case Builtin::BI__sync_nand_and_fetch_2: 1651 case Builtin::BI__sync_nand_and_fetch_4: 1652 case Builtin::BI__sync_nand_and_fetch_8: 1653 case Builtin::BI__sync_nand_and_fetch_16: 1654 case Builtin::BI__sync_val_compare_and_swap: 1655 case Builtin::BI__sync_val_compare_and_swap_1: 1656 case Builtin::BI__sync_val_compare_and_swap_2: 1657 case Builtin::BI__sync_val_compare_and_swap_4: 1658 case Builtin::BI__sync_val_compare_and_swap_8: 1659 case Builtin::BI__sync_val_compare_and_swap_16: 1660 case Builtin::BI__sync_bool_compare_and_swap: 1661 case Builtin::BI__sync_bool_compare_and_swap_1: 1662 case Builtin::BI__sync_bool_compare_and_swap_2: 1663 case Builtin::BI__sync_bool_compare_and_swap_4: 1664 case Builtin::BI__sync_bool_compare_and_swap_8: 1665 case Builtin::BI__sync_bool_compare_and_swap_16: 1666 case Builtin::BI__sync_lock_test_and_set: 1667 case Builtin::BI__sync_lock_test_and_set_1: 1668 case Builtin::BI__sync_lock_test_and_set_2: 1669 case Builtin::BI__sync_lock_test_and_set_4: 1670 case Builtin::BI__sync_lock_test_and_set_8: 1671 case Builtin::BI__sync_lock_test_and_set_16: 1672 case Builtin::BI__sync_lock_release: 1673 case Builtin::BI__sync_lock_release_1: 1674 case Builtin::BI__sync_lock_release_2: 1675 case Builtin::BI__sync_lock_release_4: 1676 case Builtin::BI__sync_lock_release_8: 1677 case Builtin::BI__sync_lock_release_16: 1678 case Builtin::BI__sync_swap: 1679 case Builtin::BI__sync_swap_1: 1680 case Builtin::BI__sync_swap_2: 1681 case Builtin::BI__sync_swap_4: 1682 case Builtin::BI__sync_swap_8: 1683 case Builtin::BI__sync_swap_16: 1684 return SemaBuiltinAtomicOverloaded(TheCallResult); 1685 case Builtin::BI__sync_synchronize: 1686 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1687 << TheCall->getCallee()->getSourceRange(); 1688 break; 1689 case Builtin::BI__builtin_nontemporal_load: 1690 case Builtin::BI__builtin_nontemporal_store: 1691 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1692 case Builtin::BI__builtin_memcpy_inline: { 1693 clang::Expr *SizeOp = TheCall->getArg(2); 1694 // We warn about copying to or from `nullptr` pointers when `size` is 1695 // greater than 0. When `size` is value dependent we cannot evaluate its 1696 // value so we bail out. 1697 if (SizeOp->isValueDependent()) 1698 break; 1699 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1700 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1701 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1702 } 1703 break; 1704 } 1705 #define BUILTIN(ID, TYPE, ATTRS) 1706 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1707 case Builtin::BI##ID: \ 1708 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1709 #include "clang/Basic/Builtins.def" 1710 case Builtin::BI__annotation: 1711 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1712 return ExprError(); 1713 break; 1714 case Builtin::BI__builtin_annotation: 1715 if (SemaBuiltinAnnotation(*this, TheCall)) 1716 return ExprError(); 1717 break; 1718 case Builtin::BI__builtin_addressof: 1719 if (SemaBuiltinAddressof(*this, TheCall)) 1720 return ExprError(); 1721 break; 1722 case Builtin::BI__builtin_is_aligned: 1723 case Builtin::BI__builtin_align_up: 1724 case Builtin::BI__builtin_align_down: 1725 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1726 return ExprError(); 1727 break; 1728 case Builtin::BI__builtin_add_overflow: 1729 case Builtin::BI__builtin_sub_overflow: 1730 case Builtin::BI__builtin_mul_overflow: 1731 if (SemaBuiltinOverflow(*this, TheCall)) 1732 return ExprError(); 1733 break; 1734 case Builtin::BI__builtin_operator_new: 1735 case Builtin::BI__builtin_operator_delete: { 1736 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1737 ExprResult Res = 1738 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1739 if (Res.isInvalid()) 1740 CorrectDelayedTyposInExpr(TheCallResult.get()); 1741 return Res; 1742 } 1743 case Builtin::BI__builtin_dump_struct: { 1744 // We first want to ensure we are called with 2 arguments 1745 if (checkArgCount(*this, TheCall, 2)) 1746 return ExprError(); 1747 // Ensure that the first argument is of type 'struct XX *' 1748 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1749 const QualType PtrArgType = PtrArg->getType(); 1750 if (!PtrArgType->isPointerType() || 1751 !PtrArgType->getPointeeType()->isRecordType()) { 1752 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1753 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1754 << "structure pointer"; 1755 return ExprError(); 1756 } 1757 1758 // Ensure that the second argument is of type 'FunctionType' 1759 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1760 const QualType FnPtrArgType = FnPtrArg->getType(); 1761 if (!FnPtrArgType->isPointerType()) { 1762 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1763 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1764 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1765 return ExprError(); 1766 } 1767 1768 const auto *FuncType = 1769 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1770 1771 if (!FuncType) { 1772 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1773 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1774 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1775 return ExprError(); 1776 } 1777 1778 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1779 if (!FT->getNumParams()) { 1780 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1781 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1782 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1783 return ExprError(); 1784 } 1785 QualType PT = FT->getParamType(0); 1786 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1787 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1788 !PT->getPointeeType().isConstQualified()) { 1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1791 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1792 return ExprError(); 1793 } 1794 } 1795 1796 TheCall->setType(Context.IntTy); 1797 break; 1798 } 1799 case Builtin::BI__builtin_preserve_access_index: 1800 if (SemaBuiltinPreserveAI(*this, TheCall)) 1801 return ExprError(); 1802 break; 1803 case Builtin::BI__builtin_call_with_static_chain: 1804 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1805 return ExprError(); 1806 break; 1807 case Builtin::BI__exception_code: 1808 case Builtin::BI_exception_code: 1809 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1810 diag::err_seh___except_block)) 1811 return ExprError(); 1812 break; 1813 case Builtin::BI__exception_info: 1814 case Builtin::BI_exception_info: 1815 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1816 diag::err_seh___except_filter)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BI__GetExceptionInfo: 1820 if (checkArgCount(*this, TheCall, 1)) 1821 return ExprError(); 1822 1823 if (CheckCXXThrowOperand( 1824 TheCall->getBeginLoc(), 1825 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1826 TheCall)) 1827 return ExprError(); 1828 1829 TheCall->setType(Context.VoidPtrTy); 1830 break; 1831 // OpenCL v2.0, s6.13.16 - Pipe functions 1832 case Builtin::BIread_pipe: 1833 case Builtin::BIwrite_pipe: 1834 // Since those two functions are declared with var args, we need a semantic 1835 // check for the argument. 1836 if (SemaBuiltinRWPipe(*this, TheCall)) 1837 return ExprError(); 1838 break; 1839 case Builtin::BIreserve_read_pipe: 1840 case Builtin::BIreserve_write_pipe: 1841 case Builtin::BIwork_group_reserve_read_pipe: 1842 case Builtin::BIwork_group_reserve_write_pipe: 1843 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1844 return ExprError(); 1845 break; 1846 case Builtin::BIsub_group_reserve_read_pipe: 1847 case Builtin::BIsub_group_reserve_write_pipe: 1848 if (checkOpenCLSubgroupExt(*this, TheCall) || 1849 SemaBuiltinReserveRWPipe(*this, TheCall)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BIcommit_read_pipe: 1853 case Builtin::BIcommit_write_pipe: 1854 case Builtin::BIwork_group_commit_read_pipe: 1855 case Builtin::BIwork_group_commit_write_pipe: 1856 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1857 return ExprError(); 1858 break; 1859 case Builtin::BIsub_group_commit_read_pipe: 1860 case Builtin::BIsub_group_commit_write_pipe: 1861 if (checkOpenCLSubgroupExt(*this, TheCall) || 1862 SemaBuiltinCommitRWPipe(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BIget_pipe_num_packets: 1866 case Builtin::BIget_pipe_max_packets: 1867 if (SemaBuiltinPipePackets(*this, TheCall)) 1868 return ExprError(); 1869 break; 1870 case Builtin::BIto_global: 1871 case Builtin::BIto_local: 1872 case Builtin::BIto_private: 1873 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1874 return ExprError(); 1875 break; 1876 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1877 case Builtin::BIenqueue_kernel: 1878 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BIget_kernel_work_group_size: 1882 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1883 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1884 return ExprError(); 1885 break; 1886 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1887 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1888 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1889 return ExprError(); 1890 break; 1891 case Builtin::BI__builtin_os_log_format: 1892 Cleanup.setExprNeedsCleanups(true); 1893 LLVM_FALLTHROUGH; 1894 case Builtin::BI__builtin_os_log_format_buffer_size: 1895 if (SemaBuiltinOSLogFormat(TheCall)) 1896 return ExprError(); 1897 break; 1898 case Builtin::BI__builtin_frame_address: 1899 case Builtin::BI__builtin_return_address: 1900 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1901 return ExprError(); 1902 1903 // -Wframe-address warning if non-zero passed to builtin 1904 // return/frame address. 1905 Expr::EvalResult Result; 1906 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1907 Result.Val.getInt() != 0) 1908 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1909 << ((BuiltinID == Builtin::BI__builtin_return_address) 1910 ? "__builtin_return_address" 1911 : "__builtin_frame_address") 1912 << TheCall->getSourceRange(); 1913 break; 1914 } 1915 1916 // Since the target specific builtins for each arch overlap, only check those 1917 // of the arch we are compiling for. 1918 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1919 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1920 assert(Context.getAuxTargetInfo() && 1921 "Aux Target Builtin, but not an aux target?"); 1922 1923 if (CheckTSBuiltinFunctionCall( 1924 Context.getAuxTargetInfo()->getTriple().getArch(), 1925 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1926 return ExprError(); 1927 } else { 1928 if (CheckTSBuiltinFunctionCall( 1929 Context.getTargetInfo().getTriple().getArch(), BuiltinID, 1930 TheCall)) 1931 return ExprError(); 1932 } 1933 } 1934 1935 return TheCallResult; 1936 } 1937 1938 // Get the valid immediate range for the specified NEON type code. 1939 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1940 NeonTypeFlags Type(t); 1941 int IsQuad = ForceQuad ? true : Type.isQuad(); 1942 switch (Type.getEltType()) { 1943 case NeonTypeFlags::Int8: 1944 case NeonTypeFlags::Poly8: 1945 return shift ? 7 : (8 << IsQuad) - 1; 1946 case NeonTypeFlags::Int16: 1947 case NeonTypeFlags::Poly16: 1948 return shift ? 15 : (4 << IsQuad) - 1; 1949 case NeonTypeFlags::Int32: 1950 return shift ? 31 : (2 << IsQuad) - 1; 1951 case NeonTypeFlags::Int64: 1952 case NeonTypeFlags::Poly64: 1953 return shift ? 63 : (1 << IsQuad) - 1; 1954 case NeonTypeFlags::Poly128: 1955 return shift ? 127 : (1 << IsQuad) - 1; 1956 case NeonTypeFlags::Float16: 1957 assert(!shift && "cannot shift float types!"); 1958 return (4 << IsQuad) - 1; 1959 case NeonTypeFlags::Float32: 1960 assert(!shift && "cannot shift float types!"); 1961 return (2 << IsQuad) - 1; 1962 case NeonTypeFlags::Float64: 1963 assert(!shift && "cannot shift float types!"); 1964 return (1 << IsQuad) - 1; 1965 } 1966 llvm_unreachable("Invalid NeonTypeFlag!"); 1967 } 1968 1969 /// getNeonEltType - Return the QualType corresponding to the elements of 1970 /// the vector type specified by the NeonTypeFlags. This is used to check 1971 /// the pointer arguments for Neon load/store intrinsics. 1972 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1973 bool IsPolyUnsigned, bool IsInt64Long) { 1974 switch (Flags.getEltType()) { 1975 case NeonTypeFlags::Int8: 1976 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1977 case NeonTypeFlags::Int16: 1978 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1979 case NeonTypeFlags::Int32: 1980 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1981 case NeonTypeFlags::Int64: 1982 if (IsInt64Long) 1983 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1984 else 1985 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1986 : Context.LongLongTy; 1987 case NeonTypeFlags::Poly8: 1988 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1989 case NeonTypeFlags::Poly16: 1990 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1991 case NeonTypeFlags::Poly64: 1992 if (IsInt64Long) 1993 return Context.UnsignedLongTy; 1994 else 1995 return Context.UnsignedLongLongTy; 1996 case NeonTypeFlags::Poly128: 1997 break; 1998 case NeonTypeFlags::Float16: 1999 return Context.HalfTy; 2000 case NeonTypeFlags::Float32: 2001 return Context.FloatTy; 2002 case NeonTypeFlags::Float64: 2003 return Context.DoubleTy; 2004 } 2005 llvm_unreachable("Invalid NeonTypeFlag!"); 2006 } 2007 2008 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2009 // Range check SVE intrinsics that take immediate values. 2010 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2011 2012 switch (BuiltinID) { 2013 default: 2014 return false; 2015 #define GET_SVE_IMMEDIATE_CHECK 2016 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2017 #undef GET_SVE_IMMEDIATE_CHECK 2018 } 2019 2020 // Perform all the immediate checks for this builtin call. 2021 bool HasError = false; 2022 for (auto &I : ImmChecks) { 2023 int ArgNum, CheckTy, ElementSizeInBits; 2024 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2025 2026 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2027 2028 // Function that checks whether the operand (ArgNum) is an immediate 2029 // that is one of the predefined values. 2030 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2031 int ErrDiag) -> bool { 2032 // We can't check the value of a dependent argument. 2033 Expr *Arg = TheCall->getArg(ArgNum); 2034 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2035 return false; 2036 2037 // Check constant-ness first. 2038 llvm::APSInt Imm; 2039 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2040 return true; 2041 2042 if (!CheckImm(Imm.getSExtValue())) 2043 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2044 return false; 2045 }; 2046 2047 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2048 case SVETypeFlags::ImmCheck0_31: 2049 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2050 HasError = true; 2051 break; 2052 case SVETypeFlags::ImmCheck0_13: 2053 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2054 HasError = true; 2055 break; 2056 case SVETypeFlags::ImmCheck1_16: 2057 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2058 HasError = true; 2059 break; 2060 case SVETypeFlags::ImmCheck0_7: 2061 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2062 HasError = true; 2063 break; 2064 case SVETypeFlags::ImmCheckExtract: 2065 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2066 (2048 / ElementSizeInBits) - 1)) 2067 HasError = true; 2068 break; 2069 case SVETypeFlags::ImmCheckShiftRight: 2070 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2071 HasError = true; 2072 break; 2073 case SVETypeFlags::ImmCheckShiftRightNarrow: 2074 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2075 ElementSizeInBits / 2)) 2076 HasError = true; 2077 break; 2078 case SVETypeFlags::ImmCheckShiftLeft: 2079 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2080 ElementSizeInBits - 1)) 2081 HasError = true; 2082 break; 2083 case SVETypeFlags::ImmCheckLaneIndex: 2084 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2085 (128 / (1 * ElementSizeInBits)) - 1)) 2086 HasError = true; 2087 break; 2088 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2089 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2090 (128 / (2 * ElementSizeInBits)) - 1)) 2091 HasError = true; 2092 break; 2093 case SVETypeFlags::ImmCheckLaneIndexDot: 2094 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2095 (128 / (4 * ElementSizeInBits)) - 1)) 2096 HasError = true; 2097 break; 2098 case SVETypeFlags::ImmCheckComplexRot90_270: 2099 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2100 diag::err_rotation_argument_to_cadd)) 2101 HasError = true; 2102 break; 2103 case SVETypeFlags::ImmCheckComplexRotAll90: 2104 if (CheckImmediateInSet( 2105 [](int64_t V) { 2106 return V == 0 || V == 90 || V == 180 || V == 270; 2107 }, 2108 diag::err_rotation_argument_to_cmla)) 2109 HasError = true; 2110 break; 2111 } 2112 } 2113 2114 return HasError; 2115 } 2116 2117 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2118 llvm::APSInt Result; 2119 uint64_t mask = 0; 2120 unsigned TV = 0; 2121 int PtrArgNum = -1; 2122 bool HasConstPtr = false; 2123 switch (BuiltinID) { 2124 #define GET_NEON_OVERLOAD_CHECK 2125 #include "clang/Basic/arm_neon.inc" 2126 #include "clang/Basic/arm_fp16.inc" 2127 #undef GET_NEON_OVERLOAD_CHECK 2128 } 2129 2130 // For NEON intrinsics which are overloaded on vector element type, validate 2131 // the immediate which specifies which variant to emit. 2132 unsigned ImmArg = TheCall->getNumArgs()-1; 2133 if (mask) { 2134 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2135 return true; 2136 2137 TV = Result.getLimitedValue(64); 2138 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2139 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2140 << TheCall->getArg(ImmArg)->getSourceRange(); 2141 } 2142 2143 if (PtrArgNum >= 0) { 2144 // Check that pointer arguments have the specified type. 2145 Expr *Arg = TheCall->getArg(PtrArgNum); 2146 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2147 Arg = ICE->getSubExpr(); 2148 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2149 QualType RHSTy = RHS.get()->getType(); 2150 2151 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2152 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2153 Arch == llvm::Triple::aarch64_32 || 2154 Arch == llvm::Triple::aarch64_be; 2155 bool IsInt64Long = 2156 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2157 QualType EltTy = 2158 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2159 if (HasConstPtr) 2160 EltTy = EltTy.withConst(); 2161 QualType LHSTy = Context.getPointerType(EltTy); 2162 AssignConvertType ConvTy; 2163 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2164 if (RHS.isInvalid()) 2165 return true; 2166 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2167 RHS.get(), AA_Assigning)) 2168 return true; 2169 } 2170 2171 // For NEON intrinsics which take an immediate value as part of the 2172 // instruction, range check them here. 2173 unsigned i = 0, l = 0, u = 0; 2174 switch (BuiltinID) { 2175 default: 2176 return false; 2177 #define GET_NEON_IMMEDIATE_CHECK 2178 #include "clang/Basic/arm_neon.inc" 2179 #include "clang/Basic/arm_fp16.inc" 2180 #undef GET_NEON_IMMEDIATE_CHECK 2181 } 2182 2183 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2184 } 2185 2186 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2187 switch (BuiltinID) { 2188 default: 2189 return false; 2190 #include "clang/Basic/arm_mve_builtin_sema.inc" 2191 } 2192 } 2193 2194 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2195 bool Err = false; 2196 switch (BuiltinID) { 2197 default: 2198 return false; 2199 #include "clang/Basic/arm_cde_builtin_sema.inc" 2200 } 2201 2202 if (Err) 2203 return true; 2204 2205 return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true); 2206 } 2207 2208 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) { 2209 if (isConstantEvaluated()) 2210 return false; 2211 2212 // We can't check the value of a dependent argument. 2213 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2214 return false; 2215 2216 llvm::APSInt CoprocNoAP; 2217 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2218 (void)IsICE; 2219 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2220 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2221 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2222 2223 uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask(); 2224 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2225 2226 if (IsCDECoproc != WantCDE) 2227 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2228 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2229 2230 return false; 2231 } 2232 2233 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2234 unsigned MaxWidth) { 2235 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2236 BuiltinID == ARM::BI__builtin_arm_ldaex || 2237 BuiltinID == ARM::BI__builtin_arm_strex || 2238 BuiltinID == ARM::BI__builtin_arm_stlex || 2239 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2240 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2241 BuiltinID == AArch64::BI__builtin_arm_strex || 2242 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2243 "unexpected ARM builtin"); 2244 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2245 BuiltinID == ARM::BI__builtin_arm_ldaex || 2246 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2247 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2248 2249 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2250 2251 // Ensure that we have the proper number of arguments. 2252 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2253 return true; 2254 2255 // Inspect the pointer argument of the atomic builtin. This should always be 2256 // a pointer type, whose element is an integral scalar or pointer type. 2257 // Because it is a pointer type, we don't have to worry about any implicit 2258 // casts here. 2259 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2260 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2261 if (PointerArgRes.isInvalid()) 2262 return true; 2263 PointerArg = PointerArgRes.get(); 2264 2265 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2266 if (!pointerType) { 2267 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2268 << PointerArg->getType() << PointerArg->getSourceRange(); 2269 return true; 2270 } 2271 2272 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2273 // task is to insert the appropriate casts into the AST. First work out just 2274 // what the appropriate type is. 2275 QualType ValType = pointerType->getPointeeType(); 2276 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2277 if (IsLdrex) 2278 AddrType.addConst(); 2279 2280 // Issue a warning if the cast is dodgy. 2281 CastKind CastNeeded = CK_NoOp; 2282 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2283 CastNeeded = CK_BitCast; 2284 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2285 << PointerArg->getType() << Context.getPointerType(AddrType) 2286 << AA_Passing << PointerArg->getSourceRange(); 2287 } 2288 2289 // Finally, do the cast and replace the argument with the corrected version. 2290 AddrType = Context.getPointerType(AddrType); 2291 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2292 if (PointerArgRes.isInvalid()) 2293 return true; 2294 PointerArg = PointerArgRes.get(); 2295 2296 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2297 2298 // In general, we allow ints, floats and pointers to be loaded and stored. 2299 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2300 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2301 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2302 << PointerArg->getType() << PointerArg->getSourceRange(); 2303 return true; 2304 } 2305 2306 // But ARM doesn't have instructions to deal with 128-bit versions. 2307 if (Context.getTypeSize(ValType) > MaxWidth) { 2308 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2309 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2310 << PointerArg->getType() << PointerArg->getSourceRange(); 2311 return true; 2312 } 2313 2314 switch (ValType.getObjCLifetime()) { 2315 case Qualifiers::OCL_None: 2316 case Qualifiers::OCL_ExplicitNone: 2317 // okay 2318 break; 2319 2320 case Qualifiers::OCL_Weak: 2321 case Qualifiers::OCL_Strong: 2322 case Qualifiers::OCL_Autoreleasing: 2323 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2324 << ValType << PointerArg->getSourceRange(); 2325 return true; 2326 } 2327 2328 if (IsLdrex) { 2329 TheCall->setType(ValType); 2330 return false; 2331 } 2332 2333 // Initialize the argument to be stored. 2334 ExprResult ValArg = TheCall->getArg(0); 2335 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2336 Context, ValType, /*consume*/ false); 2337 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2338 if (ValArg.isInvalid()) 2339 return true; 2340 TheCall->setArg(0, ValArg.get()); 2341 2342 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2343 // but the custom checker bypasses all default analysis. 2344 TheCall->setType(Context.IntTy); 2345 return false; 2346 } 2347 2348 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2349 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2350 BuiltinID == ARM::BI__builtin_arm_ldaex || 2351 BuiltinID == ARM::BI__builtin_arm_strex || 2352 BuiltinID == ARM::BI__builtin_arm_stlex) { 2353 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2354 } 2355 2356 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2357 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2358 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2359 } 2360 2361 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2362 BuiltinID == ARM::BI__builtin_arm_wsr64) 2363 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2364 2365 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2366 BuiltinID == ARM::BI__builtin_arm_rsrp || 2367 BuiltinID == ARM::BI__builtin_arm_wsr || 2368 BuiltinID == ARM::BI__builtin_arm_wsrp) 2369 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2370 2371 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2372 return true; 2373 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2374 return true; 2375 if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall)) 2376 return true; 2377 2378 // For intrinsics which take an immediate value as part of the instruction, 2379 // range check them here. 2380 // FIXME: VFP Intrinsics should error if VFP not present. 2381 switch (BuiltinID) { 2382 default: return false; 2383 case ARM::BI__builtin_arm_ssat: 2384 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2385 case ARM::BI__builtin_arm_usat: 2386 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2387 case ARM::BI__builtin_arm_ssat16: 2388 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2389 case ARM::BI__builtin_arm_usat16: 2390 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2391 case ARM::BI__builtin_arm_vcvtr_f: 2392 case ARM::BI__builtin_arm_vcvtr_d: 2393 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2394 case ARM::BI__builtin_arm_dmb: 2395 case ARM::BI__builtin_arm_dsb: 2396 case ARM::BI__builtin_arm_isb: 2397 case ARM::BI__builtin_arm_dbg: 2398 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2399 case ARM::BI__builtin_arm_cdp: 2400 case ARM::BI__builtin_arm_cdp2: 2401 case ARM::BI__builtin_arm_mcr: 2402 case ARM::BI__builtin_arm_mcr2: 2403 case ARM::BI__builtin_arm_mrc: 2404 case ARM::BI__builtin_arm_mrc2: 2405 case ARM::BI__builtin_arm_mcrr: 2406 case ARM::BI__builtin_arm_mcrr2: 2407 case ARM::BI__builtin_arm_mrrc: 2408 case ARM::BI__builtin_arm_mrrc2: 2409 case ARM::BI__builtin_arm_ldc: 2410 case ARM::BI__builtin_arm_ldcl: 2411 case ARM::BI__builtin_arm_ldc2: 2412 case ARM::BI__builtin_arm_ldc2l: 2413 case ARM::BI__builtin_arm_stc: 2414 case ARM::BI__builtin_arm_stcl: 2415 case ARM::BI__builtin_arm_stc2: 2416 case ARM::BI__builtin_arm_stc2l: 2417 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2418 CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false); 2419 } 2420 } 2421 2422 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2423 CallExpr *TheCall) { 2424 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2425 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2426 BuiltinID == AArch64::BI__builtin_arm_strex || 2427 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2428 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2429 } 2430 2431 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2432 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2433 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2434 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2435 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2436 } 2437 2438 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2439 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2441 2442 // Memory Tagging Extensions (MTE) Intrinsics 2443 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2444 BuiltinID == AArch64::BI__builtin_arm_addg || 2445 BuiltinID == AArch64::BI__builtin_arm_gmi || 2446 BuiltinID == AArch64::BI__builtin_arm_ldg || 2447 BuiltinID == AArch64::BI__builtin_arm_stg || 2448 BuiltinID == AArch64::BI__builtin_arm_subp) { 2449 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2450 } 2451 2452 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2453 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2454 BuiltinID == AArch64::BI__builtin_arm_wsr || 2455 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2456 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2457 2458 // Only check the valid encoding range. Any constant in this range would be 2459 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2460 // an exception for incorrect registers. This matches MSVC behavior. 2461 if (BuiltinID == AArch64::BI_ReadStatusReg || 2462 BuiltinID == AArch64::BI_WriteStatusReg) 2463 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2464 2465 if (BuiltinID == AArch64::BI__getReg) 2466 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2467 2468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2469 return true; 2470 2471 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2472 return true; 2473 2474 // For intrinsics which take an immediate value as part of the instruction, 2475 // range check them here. 2476 unsigned i = 0, l = 0, u = 0; 2477 switch (BuiltinID) { 2478 default: return false; 2479 case AArch64::BI__builtin_arm_dmb: 2480 case AArch64::BI__builtin_arm_dsb: 2481 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2482 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2483 } 2484 2485 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2486 } 2487 2488 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2489 CallExpr *TheCall) { 2490 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2491 "unexpected ARM builtin"); 2492 2493 if (checkArgCount(*this, TheCall, 2)) 2494 return true; 2495 2496 // The first argument needs to be a record field access. 2497 // If it is an array element access, we delay decision 2498 // to BPF backend to check whether the access is a 2499 // field access or not. 2500 Expr *Arg = TheCall->getArg(0); 2501 if (Arg->getType()->getAsPlaceholderType() || 2502 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2503 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2504 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2505 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2506 << 1 << Arg->getSourceRange(); 2507 return true; 2508 } 2509 2510 // The second argument needs to be a constant int 2511 llvm::APSInt Value; 2512 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2513 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2514 << 2 << Arg->getSourceRange(); 2515 return true; 2516 } 2517 2518 TheCall->setType(Context.UnsignedIntTy); 2519 return false; 2520 } 2521 2522 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2523 struct ArgInfo { 2524 uint8_t OpNum; 2525 bool IsSigned; 2526 uint8_t BitWidth; 2527 uint8_t Align; 2528 }; 2529 struct BuiltinInfo { 2530 unsigned BuiltinID; 2531 ArgInfo Infos[2]; 2532 }; 2533 2534 static BuiltinInfo Infos[] = { 2535 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2536 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2537 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2538 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2539 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2540 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2541 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2542 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2543 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2544 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2545 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2546 2547 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2548 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2549 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2550 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2551 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2552 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2553 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2554 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2555 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2556 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2557 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2558 2559 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2560 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2561 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2562 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2563 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2564 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2565 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2566 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2567 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2588 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2600 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2601 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2611 {{ 1, false, 6, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2619 {{ 1, false, 5, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2626 { 2, false, 5, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2628 { 2, false, 6, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2630 { 3, false, 5, 0 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2632 { 3, false, 6, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2649 {{ 2, false, 4, 0 }, 2650 { 3, false, 5, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2652 {{ 2, false, 4, 0 }, 2653 { 3, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2655 {{ 2, false, 4, 0 }, 2656 { 3, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2658 {{ 2, false, 4, 0 }, 2659 { 3, false, 5, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2671 { 2, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2673 { 2, false, 6, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2683 {{ 1, false, 4, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2686 {{ 1, false, 4, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2701 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2707 {{ 3, false, 1, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2712 {{ 3, false, 1, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2717 {{ 3, false, 1, 0 }} }, 2718 }; 2719 2720 // Use a dynamically initialized static to sort the table exactly once on 2721 // first run. 2722 static const bool SortOnce = 2723 (llvm::sort(Infos, 2724 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2725 return LHS.BuiltinID < RHS.BuiltinID; 2726 }), 2727 true); 2728 (void)SortOnce; 2729 2730 const BuiltinInfo *F = llvm::partition_point( 2731 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2732 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2733 return false; 2734 2735 bool Error = false; 2736 2737 for (const ArgInfo &A : F->Infos) { 2738 // Ignore empty ArgInfo elements. 2739 if (A.BitWidth == 0) 2740 continue; 2741 2742 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2743 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2744 if (!A.Align) { 2745 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2746 } else { 2747 unsigned M = 1 << A.Align; 2748 Min *= M; 2749 Max *= M; 2750 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2751 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2752 } 2753 } 2754 return Error; 2755 } 2756 2757 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2758 CallExpr *TheCall) { 2759 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2760 } 2761 2762 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2763 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2764 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2765 } 2766 2767 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2768 const TargetInfo &TI = Context.getTargetInfo(); 2769 2770 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2771 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2772 if (!TI.hasFeature("dsp")) 2773 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2774 } 2775 2776 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2777 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2778 if (!TI.hasFeature("dspr2")) 2779 return Diag(TheCall->getBeginLoc(), 2780 diag::err_mips_builtin_requires_dspr2); 2781 } 2782 2783 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2784 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2785 if (!TI.hasFeature("msa")) 2786 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2787 } 2788 2789 return false; 2790 } 2791 2792 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2793 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2794 // ordering for DSP is unspecified. MSA is ordered by the data format used 2795 // by the underlying instruction i.e., df/m, df/n and then by size. 2796 // 2797 // FIXME: The size tests here should instead be tablegen'd along with the 2798 // definitions from include/clang/Basic/BuiltinsMips.def. 2799 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2800 // be too. 2801 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2802 unsigned i = 0, l = 0, u = 0, m = 0; 2803 switch (BuiltinID) { 2804 default: return false; 2805 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2806 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2807 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2808 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2809 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2810 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2811 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2812 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2813 // df/m field. 2814 // These intrinsics take an unsigned 3 bit immediate. 2815 case Mips::BI__builtin_msa_bclri_b: 2816 case Mips::BI__builtin_msa_bnegi_b: 2817 case Mips::BI__builtin_msa_bseti_b: 2818 case Mips::BI__builtin_msa_sat_s_b: 2819 case Mips::BI__builtin_msa_sat_u_b: 2820 case Mips::BI__builtin_msa_slli_b: 2821 case Mips::BI__builtin_msa_srai_b: 2822 case Mips::BI__builtin_msa_srari_b: 2823 case Mips::BI__builtin_msa_srli_b: 2824 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2825 case Mips::BI__builtin_msa_binsli_b: 2826 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2827 // These intrinsics take an unsigned 4 bit immediate. 2828 case Mips::BI__builtin_msa_bclri_h: 2829 case Mips::BI__builtin_msa_bnegi_h: 2830 case Mips::BI__builtin_msa_bseti_h: 2831 case Mips::BI__builtin_msa_sat_s_h: 2832 case Mips::BI__builtin_msa_sat_u_h: 2833 case Mips::BI__builtin_msa_slli_h: 2834 case Mips::BI__builtin_msa_srai_h: 2835 case Mips::BI__builtin_msa_srari_h: 2836 case Mips::BI__builtin_msa_srli_h: 2837 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2838 case Mips::BI__builtin_msa_binsli_h: 2839 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2840 // These intrinsics take an unsigned 5 bit immediate. 2841 // The first block of intrinsics actually have an unsigned 5 bit field, 2842 // not a df/n field. 2843 case Mips::BI__builtin_msa_cfcmsa: 2844 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2845 case Mips::BI__builtin_msa_clei_u_b: 2846 case Mips::BI__builtin_msa_clei_u_h: 2847 case Mips::BI__builtin_msa_clei_u_w: 2848 case Mips::BI__builtin_msa_clei_u_d: 2849 case Mips::BI__builtin_msa_clti_u_b: 2850 case Mips::BI__builtin_msa_clti_u_h: 2851 case Mips::BI__builtin_msa_clti_u_w: 2852 case Mips::BI__builtin_msa_clti_u_d: 2853 case Mips::BI__builtin_msa_maxi_u_b: 2854 case Mips::BI__builtin_msa_maxi_u_h: 2855 case Mips::BI__builtin_msa_maxi_u_w: 2856 case Mips::BI__builtin_msa_maxi_u_d: 2857 case Mips::BI__builtin_msa_mini_u_b: 2858 case Mips::BI__builtin_msa_mini_u_h: 2859 case Mips::BI__builtin_msa_mini_u_w: 2860 case Mips::BI__builtin_msa_mini_u_d: 2861 case Mips::BI__builtin_msa_addvi_b: 2862 case Mips::BI__builtin_msa_addvi_h: 2863 case Mips::BI__builtin_msa_addvi_w: 2864 case Mips::BI__builtin_msa_addvi_d: 2865 case Mips::BI__builtin_msa_bclri_w: 2866 case Mips::BI__builtin_msa_bnegi_w: 2867 case Mips::BI__builtin_msa_bseti_w: 2868 case Mips::BI__builtin_msa_sat_s_w: 2869 case Mips::BI__builtin_msa_sat_u_w: 2870 case Mips::BI__builtin_msa_slli_w: 2871 case Mips::BI__builtin_msa_srai_w: 2872 case Mips::BI__builtin_msa_srari_w: 2873 case Mips::BI__builtin_msa_srli_w: 2874 case Mips::BI__builtin_msa_srlri_w: 2875 case Mips::BI__builtin_msa_subvi_b: 2876 case Mips::BI__builtin_msa_subvi_h: 2877 case Mips::BI__builtin_msa_subvi_w: 2878 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2879 case Mips::BI__builtin_msa_binsli_w: 2880 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2881 // These intrinsics take an unsigned 6 bit immediate. 2882 case Mips::BI__builtin_msa_bclri_d: 2883 case Mips::BI__builtin_msa_bnegi_d: 2884 case Mips::BI__builtin_msa_bseti_d: 2885 case Mips::BI__builtin_msa_sat_s_d: 2886 case Mips::BI__builtin_msa_sat_u_d: 2887 case Mips::BI__builtin_msa_slli_d: 2888 case Mips::BI__builtin_msa_srai_d: 2889 case Mips::BI__builtin_msa_srari_d: 2890 case Mips::BI__builtin_msa_srli_d: 2891 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2892 case Mips::BI__builtin_msa_binsli_d: 2893 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2894 // These intrinsics take a signed 5 bit immediate. 2895 case Mips::BI__builtin_msa_ceqi_b: 2896 case Mips::BI__builtin_msa_ceqi_h: 2897 case Mips::BI__builtin_msa_ceqi_w: 2898 case Mips::BI__builtin_msa_ceqi_d: 2899 case Mips::BI__builtin_msa_clti_s_b: 2900 case Mips::BI__builtin_msa_clti_s_h: 2901 case Mips::BI__builtin_msa_clti_s_w: 2902 case Mips::BI__builtin_msa_clti_s_d: 2903 case Mips::BI__builtin_msa_clei_s_b: 2904 case Mips::BI__builtin_msa_clei_s_h: 2905 case Mips::BI__builtin_msa_clei_s_w: 2906 case Mips::BI__builtin_msa_clei_s_d: 2907 case Mips::BI__builtin_msa_maxi_s_b: 2908 case Mips::BI__builtin_msa_maxi_s_h: 2909 case Mips::BI__builtin_msa_maxi_s_w: 2910 case Mips::BI__builtin_msa_maxi_s_d: 2911 case Mips::BI__builtin_msa_mini_s_b: 2912 case Mips::BI__builtin_msa_mini_s_h: 2913 case Mips::BI__builtin_msa_mini_s_w: 2914 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2915 // These intrinsics take an unsigned 8 bit immediate. 2916 case Mips::BI__builtin_msa_andi_b: 2917 case Mips::BI__builtin_msa_nori_b: 2918 case Mips::BI__builtin_msa_ori_b: 2919 case Mips::BI__builtin_msa_shf_b: 2920 case Mips::BI__builtin_msa_shf_h: 2921 case Mips::BI__builtin_msa_shf_w: 2922 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2923 case Mips::BI__builtin_msa_bseli_b: 2924 case Mips::BI__builtin_msa_bmnzi_b: 2925 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2926 // df/n format 2927 // These intrinsics take an unsigned 4 bit immediate. 2928 case Mips::BI__builtin_msa_copy_s_b: 2929 case Mips::BI__builtin_msa_copy_u_b: 2930 case Mips::BI__builtin_msa_insve_b: 2931 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2932 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2933 // These intrinsics take an unsigned 3 bit immediate. 2934 case Mips::BI__builtin_msa_copy_s_h: 2935 case Mips::BI__builtin_msa_copy_u_h: 2936 case Mips::BI__builtin_msa_insve_h: 2937 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2938 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2939 // These intrinsics take an unsigned 2 bit immediate. 2940 case Mips::BI__builtin_msa_copy_s_w: 2941 case Mips::BI__builtin_msa_copy_u_w: 2942 case Mips::BI__builtin_msa_insve_w: 2943 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2944 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2945 // These intrinsics take an unsigned 1 bit immediate. 2946 case Mips::BI__builtin_msa_copy_s_d: 2947 case Mips::BI__builtin_msa_copy_u_d: 2948 case Mips::BI__builtin_msa_insve_d: 2949 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2950 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2951 // Memory offsets and immediate loads. 2952 // These intrinsics take a signed 10 bit immediate. 2953 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2954 case Mips::BI__builtin_msa_ldi_h: 2955 case Mips::BI__builtin_msa_ldi_w: 2956 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2957 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2958 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2959 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2960 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2961 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2962 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2963 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2964 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2965 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2966 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2967 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2968 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 2969 } 2970 2971 if (!m) 2972 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2973 2974 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2975 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2976 } 2977 2978 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2979 unsigned i = 0, l = 0, u = 0; 2980 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2981 BuiltinID == PPC::BI__builtin_divdeu || 2982 BuiltinID == PPC::BI__builtin_bpermd; 2983 bool IsTarget64Bit = Context.getTargetInfo() 2984 .getTypeWidth(Context 2985 .getTargetInfo() 2986 .getIntPtrType()) == 64; 2987 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2988 BuiltinID == PPC::BI__builtin_divweu || 2989 BuiltinID == PPC::BI__builtin_divde || 2990 BuiltinID == PPC::BI__builtin_divdeu; 2991 2992 if (Is64BitBltin && !IsTarget64Bit) 2993 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2994 << TheCall->getSourceRange(); 2995 2996 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2997 (BuiltinID == PPC::BI__builtin_bpermd && 2998 !Context.getTargetInfo().hasFeature("bpermd"))) 2999 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3000 << TheCall->getSourceRange(); 3001 3002 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3003 if (!Context.getTargetInfo().hasFeature("vsx")) 3004 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3005 << TheCall->getSourceRange(); 3006 return false; 3007 }; 3008 3009 switch (BuiltinID) { 3010 default: return false; 3011 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3012 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3013 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3014 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3015 case PPC::BI__builtin_altivec_dss: 3016 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3017 case PPC::BI__builtin_tbegin: 3018 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3019 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3020 case PPC::BI__builtin_tabortwc: 3021 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3022 case PPC::BI__builtin_tabortwci: 3023 case PPC::BI__builtin_tabortdci: 3024 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3025 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3026 case PPC::BI__builtin_altivec_dst: 3027 case PPC::BI__builtin_altivec_dstt: 3028 case PPC::BI__builtin_altivec_dstst: 3029 case PPC::BI__builtin_altivec_dststt: 3030 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3031 case PPC::BI__builtin_vsx_xxpermdi: 3032 case PPC::BI__builtin_vsx_xxsldwi: 3033 return SemaBuiltinVSX(TheCall); 3034 case PPC::BI__builtin_unpack_vector_int128: 3035 return SemaVSXCheck(TheCall) || 3036 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3037 case PPC::BI__builtin_pack_vector_int128: 3038 return SemaVSXCheck(TheCall); 3039 } 3040 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3041 } 3042 3043 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3044 CallExpr *TheCall) { 3045 switch (BuiltinID) { 3046 case AMDGPU::BI__builtin_amdgcn_fence: { 3047 ExprResult Arg = TheCall->getArg(0); 3048 auto ArgExpr = Arg.get(); 3049 Expr::EvalResult ArgResult; 3050 3051 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3052 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3053 << ArgExpr->getType(); 3054 int ord = ArgResult.Val.getInt().getZExtValue(); 3055 3056 // Check valididty of memory ordering as per C11 / C++11's memody model. 3057 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3058 case llvm::AtomicOrderingCABI::acquire: 3059 case llvm::AtomicOrderingCABI::release: 3060 case llvm::AtomicOrderingCABI::acq_rel: 3061 case llvm::AtomicOrderingCABI::seq_cst: 3062 break; 3063 default: { 3064 return Diag(ArgExpr->getBeginLoc(), 3065 diag::warn_atomic_op_has_invalid_memory_order) 3066 << ArgExpr->getSourceRange(); 3067 } 3068 } 3069 3070 Arg = TheCall->getArg(1); 3071 ArgExpr = Arg.get(); 3072 Expr::EvalResult ArgResult1; 3073 // Check that sync scope is a constant literal 3074 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3075 Context)) 3076 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3077 << ArgExpr->getType(); 3078 } break; 3079 } 3080 return false; 3081 } 3082 3083 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3084 CallExpr *TheCall) { 3085 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3086 Expr *Arg = TheCall->getArg(0); 3087 llvm::APSInt AbortCode(32); 3088 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3089 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3090 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3091 << Arg->getSourceRange(); 3092 } 3093 3094 // For intrinsics which take an immediate value as part of the instruction, 3095 // range check them here. 3096 unsigned i = 0, l = 0, u = 0; 3097 switch (BuiltinID) { 3098 default: return false; 3099 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3100 case SystemZ::BI__builtin_s390_verimb: 3101 case SystemZ::BI__builtin_s390_verimh: 3102 case SystemZ::BI__builtin_s390_verimf: 3103 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3104 case SystemZ::BI__builtin_s390_vfaeb: 3105 case SystemZ::BI__builtin_s390_vfaeh: 3106 case SystemZ::BI__builtin_s390_vfaef: 3107 case SystemZ::BI__builtin_s390_vfaebs: 3108 case SystemZ::BI__builtin_s390_vfaehs: 3109 case SystemZ::BI__builtin_s390_vfaefs: 3110 case SystemZ::BI__builtin_s390_vfaezb: 3111 case SystemZ::BI__builtin_s390_vfaezh: 3112 case SystemZ::BI__builtin_s390_vfaezf: 3113 case SystemZ::BI__builtin_s390_vfaezbs: 3114 case SystemZ::BI__builtin_s390_vfaezhs: 3115 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3116 case SystemZ::BI__builtin_s390_vfisb: 3117 case SystemZ::BI__builtin_s390_vfidb: 3118 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3119 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3120 case SystemZ::BI__builtin_s390_vftcisb: 3121 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3122 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3123 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3124 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3125 case SystemZ::BI__builtin_s390_vstrcb: 3126 case SystemZ::BI__builtin_s390_vstrch: 3127 case SystemZ::BI__builtin_s390_vstrcf: 3128 case SystemZ::BI__builtin_s390_vstrczb: 3129 case SystemZ::BI__builtin_s390_vstrczh: 3130 case SystemZ::BI__builtin_s390_vstrczf: 3131 case SystemZ::BI__builtin_s390_vstrcbs: 3132 case SystemZ::BI__builtin_s390_vstrchs: 3133 case SystemZ::BI__builtin_s390_vstrcfs: 3134 case SystemZ::BI__builtin_s390_vstrczbs: 3135 case SystemZ::BI__builtin_s390_vstrczhs: 3136 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3137 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3138 case SystemZ::BI__builtin_s390_vfminsb: 3139 case SystemZ::BI__builtin_s390_vfmaxsb: 3140 case SystemZ::BI__builtin_s390_vfmindb: 3141 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3142 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3143 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3144 } 3145 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3146 } 3147 3148 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3149 /// This checks that the target supports __builtin_cpu_supports and 3150 /// that the string argument is constant and valid. 3151 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 3152 Expr *Arg = TheCall->getArg(0); 3153 3154 // Check if the argument is a string literal. 3155 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3156 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3157 << Arg->getSourceRange(); 3158 3159 // Check the contents of the string. 3160 StringRef Feature = 3161 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3162 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3163 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3164 << Arg->getSourceRange(); 3165 return false; 3166 } 3167 3168 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3169 /// This checks that the target supports __builtin_cpu_is and 3170 /// that the string argument is constant and valid. 3171 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3172 Expr *Arg = TheCall->getArg(0); 3173 3174 // Check if the argument is a string literal. 3175 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3176 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3177 << Arg->getSourceRange(); 3178 3179 // Check the contents of the string. 3180 StringRef Feature = 3181 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3182 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3183 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3184 << Arg->getSourceRange(); 3185 return false; 3186 } 3187 3188 // Check if the rounding mode is legal. 3189 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3190 // Indicates if this instruction has rounding control or just SAE. 3191 bool HasRC = false; 3192 3193 unsigned ArgNum = 0; 3194 switch (BuiltinID) { 3195 default: 3196 return false; 3197 case X86::BI__builtin_ia32_vcvttsd2si32: 3198 case X86::BI__builtin_ia32_vcvttsd2si64: 3199 case X86::BI__builtin_ia32_vcvttsd2usi32: 3200 case X86::BI__builtin_ia32_vcvttsd2usi64: 3201 case X86::BI__builtin_ia32_vcvttss2si32: 3202 case X86::BI__builtin_ia32_vcvttss2si64: 3203 case X86::BI__builtin_ia32_vcvttss2usi32: 3204 case X86::BI__builtin_ia32_vcvttss2usi64: 3205 ArgNum = 1; 3206 break; 3207 case X86::BI__builtin_ia32_maxpd512: 3208 case X86::BI__builtin_ia32_maxps512: 3209 case X86::BI__builtin_ia32_minpd512: 3210 case X86::BI__builtin_ia32_minps512: 3211 ArgNum = 2; 3212 break; 3213 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3214 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3215 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3216 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3217 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3218 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3219 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3220 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3221 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3222 case X86::BI__builtin_ia32_exp2pd_mask: 3223 case X86::BI__builtin_ia32_exp2ps_mask: 3224 case X86::BI__builtin_ia32_getexppd512_mask: 3225 case X86::BI__builtin_ia32_getexpps512_mask: 3226 case X86::BI__builtin_ia32_rcp28pd_mask: 3227 case X86::BI__builtin_ia32_rcp28ps_mask: 3228 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3229 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3230 case X86::BI__builtin_ia32_vcomisd: 3231 case X86::BI__builtin_ia32_vcomiss: 3232 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3233 ArgNum = 3; 3234 break; 3235 case X86::BI__builtin_ia32_cmppd512_mask: 3236 case X86::BI__builtin_ia32_cmpps512_mask: 3237 case X86::BI__builtin_ia32_cmpsd_mask: 3238 case X86::BI__builtin_ia32_cmpss_mask: 3239 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3240 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3241 case X86::BI__builtin_ia32_getexpss128_round_mask: 3242 case X86::BI__builtin_ia32_getmantpd512_mask: 3243 case X86::BI__builtin_ia32_getmantps512_mask: 3244 case X86::BI__builtin_ia32_maxsd_round_mask: 3245 case X86::BI__builtin_ia32_maxss_round_mask: 3246 case X86::BI__builtin_ia32_minsd_round_mask: 3247 case X86::BI__builtin_ia32_minss_round_mask: 3248 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3249 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3250 case X86::BI__builtin_ia32_reducepd512_mask: 3251 case X86::BI__builtin_ia32_reduceps512_mask: 3252 case X86::BI__builtin_ia32_rndscalepd_mask: 3253 case X86::BI__builtin_ia32_rndscaleps_mask: 3254 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3255 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3256 ArgNum = 4; 3257 break; 3258 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3259 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3260 case X86::BI__builtin_ia32_fixupimmps512_mask: 3261 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3262 case X86::BI__builtin_ia32_fixupimmsd_mask: 3263 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3264 case X86::BI__builtin_ia32_fixupimmss_mask: 3265 case X86::BI__builtin_ia32_fixupimmss_maskz: 3266 case X86::BI__builtin_ia32_getmantsd_round_mask: 3267 case X86::BI__builtin_ia32_getmantss_round_mask: 3268 case X86::BI__builtin_ia32_rangepd512_mask: 3269 case X86::BI__builtin_ia32_rangeps512_mask: 3270 case X86::BI__builtin_ia32_rangesd128_round_mask: 3271 case X86::BI__builtin_ia32_rangess128_round_mask: 3272 case X86::BI__builtin_ia32_reducesd_mask: 3273 case X86::BI__builtin_ia32_reducess_mask: 3274 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3275 case X86::BI__builtin_ia32_rndscaless_round_mask: 3276 ArgNum = 5; 3277 break; 3278 case X86::BI__builtin_ia32_vcvtsd2si64: 3279 case X86::BI__builtin_ia32_vcvtsd2si32: 3280 case X86::BI__builtin_ia32_vcvtsd2usi32: 3281 case X86::BI__builtin_ia32_vcvtsd2usi64: 3282 case X86::BI__builtin_ia32_vcvtss2si32: 3283 case X86::BI__builtin_ia32_vcvtss2si64: 3284 case X86::BI__builtin_ia32_vcvtss2usi32: 3285 case X86::BI__builtin_ia32_vcvtss2usi64: 3286 case X86::BI__builtin_ia32_sqrtpd512: 3287 case X86::BI__builtin_ia32_sqrtps512: 3288 ArgNum = 1; 3289 HasRC = true; 3290 break; 3291 case X86::BI__builtin_ia32_addpd512: 3292 case X86::BI__builtin_ia32_addps512: 3293 case X86::BI__builtin_ia32_divpd512: 3294 case X86::BI__builtin_ia32_divps512: 3295 case X86::BI__builtin_ia32_mulpd512: 3296 case X86::BI__builtin_ia32_mulps512: 3297 case X86::BI__builtin_ia32_subpd512: 3298 case X86::BI__builtin_ia32_subps512: 3299 case X86::BI__builtin_ia32_cvtsi2sd64: 3300 case X86::BI__builtin_ia32_cvtsi2ss32: 3301 case X86::BI__builtin_ia32_cvtsi2ss64: 3302 case X86::BI__builtin_ia32_cvtusi2sd64: 3303 case X86::BI__builtin_ia32_cvtusi2ss32: 3304 case X86::BI__builtin_ia32_cvtusi2ss64: 3305 ArgNum = 2; 3306 HasRC = true; 3307 break; 3308 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3309 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3310 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3311 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3312 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3313 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3314 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3315 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3316 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3317 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3318 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3319 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3320 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3321 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3322 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3323 ArgNum = 3; 3324 HasRC = true; 3325 break; 3326 case X86::BI__builtin_ia32_addss_round_mask: 3327 case X86::BI__builtin_ia32_addsd_round_mask: 3328 case X86::BI__builtin_ia32_divss_round_mask: 3329 case X86::BI__builtin_ia32_divsd_round_mask: 3330 case X86::BI__builtin_ia32_mulss_round_mask: 3331 case X86::BI__builtin_ia32_mulsd_round_mask: 3332 case X86::BI__builtin_ia32_subss_round_mask: 3333 case X86::BI__builtin_ia32_subsd_round_mask: 3334 case X86::BI__builtin_ia32_scalefpd512_mask: 3335 case X86::BI__builtin_ia32_scalefps512_mask: 3336 case X86::BI__builtin_ia32_scalefsd_round_mask: 3337 case X86::BI__builtin_ia32_scalefss_round_mask: 3338 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3339 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3340 case X86::BI__builtin_ia32_sqrtss_round_mask: 3341 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3342 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3343 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3344 case X86::BI__builtin_ia32_vfmaddss3_mask: 3345 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3346 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3347 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3348 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3349 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3350 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3351 case X86::BI__builtin_ia32_vfmaddps512_mask: 3352 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3353 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3354 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3355 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3356 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3357 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3358 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3359 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3360 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3361 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3362 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3363 ArgNum = 4; 3364 HasRC = true; 3365 break; 3366 } 3367 3368 llvm::APSInt Result; 3369 3370 // We can't check the value of a dependent argument. 3371 Expr *Arg = TheCall->getArg(ArgNum); 3372 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3373 return false; 3374 3375 // Check constant-ness first. 3376 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3377 return true; 3378 3379 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3380 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3381 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3382 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3383 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3384 Result == 8/*ROUND_NO_EXC*/ || 3385 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3386 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3387 return false; 3388 3389 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3390 << Arg->getSourceRange(); 3391 } 3392 3393 // Check if the gather/scatter scale is legal. 3394 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3395 CallExpr *TheCall) { 3396 unsigned ArgNum = 0; 3397 switch (BuiltinID) { 3398 default: 3399 return false; 3400 case X86::BI__builtin_ia32_gatherpfdpd: 3401 case X86::BI__builtin_ia32_gatherpfdps: 3402 case X86::BI__builtin_ia32_gatherpfqpd: 3403 case X86::BI__builtin_ia32_gatherpfqps: 3404 case X86::BI__builtin_ia32_scatterpfdpd: 3405 case X86::BI__builtin_ia32_scatterpfdps: 3406 case X86::BI__builtin_ia32_scatterpfqpd: 3407 case X86::BI__builtin_ia32_scatterpfqps: 3408 ArgNum = 3; 3409 break; 3410 case X86::BI__builtin_ia32_gatherd_pd: 3411 case X86::BI__builtin_ia32_gatherd_pd256: 3412 case X86::BI__builtin_ia32_gatherq_pd: 3413 case X86::BI__builtin_ia32_gatherq_pd256: 3414 case X86::BI__builtin_ia32_gatherd_ps: 3415 case X86::BI__builtin_ia32_gatherd_ps256: 3416 case X86::BI__builtin_ia32_gatherq_ps: 3417 case X86::BI__builtin_ia32_gatherq_ps256: 3418 case X86::BI__builtin_ia32_gatherd_q: 3419 case X86::BI__builtin_ia32_gatherd_q256: 3420 case X86::BI__builtin_ia32_gatherq_q: 3421 case X86::BI__builtin_ia32_gatherq_q256: 3422 case X86::BI__builtin_ia32_gatherd_d: 3423 case X86::BI__builtin_ia32_gatherd_d256: 3424 case X86::BI__builtin_ia32_gatherq_d: 3425 case X86::BI__builtin_ia32_gatherq_d256: 3426 case X86::BI__builtin_ia32_gather3div2df: 3427 case X86::BI__builtin_ia32_gather3div2di: 3428 case X86::BI__builtin_ia32_gather3div4df: 3429 case X86::BI__builtin_ia32_gather3div4di: 3430 case X86::BI__builtin_ia32_gather3div4sf: 3431 case X86::BI__builtin_ia32_gather3div4si: 3432 case X86::BI__builtin_ia32_gather3div8sf: 3433 case X86::BI__builtin_ia32_gather3div8si: 3434 case X86::BI__builtin_ia32_gather3siv2df: 3435 case X86::BI__builtin_ia32_gather3siv2di: 3436 case X86::BI__builtin_ia32_gather3siv4df: 3437 case X86::BI__builtin_ia32_gather3siv4di: 3438 case X86::BI__builtin_ia32_gather3siv4sf: 3439 case X86::BI__builtin_ia32_gather3siv4si: 3440 case X86::BI__builtin_ia32_gather3siv8sf: 3441 case X86::BI__builtin_ia32_gather3siv8si: 3442 case X86::BI__builtin_ia32_gathersiv8df: 3443 case X86::BI__builtin_ia32_gathersiv16sf: 3444 case X86::BI__builtin_ia32_gatherdiv8df: 3445 case X86::BI__builtin_ia32_gatherdiv16sf: 3446 case X86::BI__builtin_ia32_gathersiv8di: 3447 case X86::BI__builtin_ia32_gathersiv16si: 3448 case X86::BI__builtin_ia32_gatherdiv8di: 3449 case X86::BI__builtin_ia32_gatherdiv16si: 3450 case X86::BI__builtin_ia32_scatterdiv2df: 3451 case X86::BI__builtin_ia32_scatterdiv2di: 3452 case X86::BI__builtin_ia32_scatterdiv4df: 3453 case X86::BI__builtin_ia32_scatterdiv4di: 3454 case X86::BI__builtin_ia32_scatterdiv4sf: 3455 case X86::BI__builtin_ia32_scatterdiv4si: 3456 case X86::BI__builtin_ia32_scatterdiv8sf: 3457 case X86::BI__builtin_ia32_scatterdiv8si: 3458 case X86::BI__builtin_ia32_scattersiv2df: 3459 case X86::BI__builtin_ia32_scattersiv2di: 3460 case X86::BI__builtin_ia32_scattersiv4df: 3461 case X86::BI__builtin_ia32_scattersiv4di: 3462 case X86::BI__builtin_ia32_scattersiv4sf: 3463 case X86::BI__builtin_ia32_scattersiv4si: 3464 case X86::BI__builtin_ia32_scattersiv8sf: 3465 case X86::BI__builtin_ia32_scattersiv8si: 3466 case X86::BI__builtin_ia32_scattersiv8df: 3467 case X86::BI__builtin_ia32_scattersiv16sf: 3468 case X86::BI__builtin_ia32_scatterdiv8df: 3469 case X86::BI__builtin_ia32_scatterdiv16sf: 3470 case X86::BI__builtin_ia32_scattersiv8di: 3471 case X86::BI__builtin_ia32_scattersiv16si: 3472 case X86::BI__builtin_ia32_scatterdiv8di: 3473 case X86::BI__builtin_ia32_scatterdiv16si: 3474 ArgNum = 4; 3475 break; 3476 } 3477 3478 llvm::APSInt Result; 3479 3480 // We can't check the value of a dependent argument. 3481 Expr *Arg = TheCall->getArg(ArgNum); 3482 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3483 return false; 3484 3485 // Check constant-ness first. 3486 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3487 return true; 3488 3489 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3490 return false; 3491 3492 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3493 << Arg->getSourceRange(); 3494 } 3495 3496 static bool isX86_32Builtin(unsigned BuiltinID) { 3497 // These builtins only work on x86-32 targets. 3498 switch (BuiltinID) { 3499 case X86::BI__builtin_ia32_readeflags_u32: 3500 case X86::BI__builtin_ia32_writeeflags_u32: 3501 return true; 3502 } 3503 3504 return false; 3505 } 3506 3507 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3508 if (BuiltinID == X86::BI__builtin_cpu_supports) 3509 return SemaBuiltinCpuSupports(*this, TheCall); 3510 3511 if (BuiltinID == X86::BI__builtin_cpu_is) 3512 return SemaBuiltinCpuIs(*this, TheCall); 3513 3514 // Check for 32-bit only builtins on a 64-bit target. 3515 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3516 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3517 return Diag(TheCall->getCallee()->getBeginLoc(), 3518 diag::err_32_bit_builtin_64_bit_tgt); 3519 3520 // If the intrinsic has rounding or SAE make sure its valid. 3521 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3522 return true; 3523 3524 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3525 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3526 return true; 3527 3528 // For intrinsics which take an immediate value as part of the instruction, 3529 // range check them here. 3530 int i = 0, l = 0, u = 0; 3531 switch (BuiltinID) { 3532 default: 3533 return false; 3534 case X86::BI__builtin_ia32_vec_ext_v2si: 3535 case X86::BI__builtin_ia32_vec_ext_v2di: 3536 case X86::BI__builtin_ia32_vextractf128_pd256: 3537 case X86::BI__builtin_ia32_vextractf128_ps256: 3538 case X86::BI__builtin_ia32_vextractf128_si256: 3539 case X86::BI__builtin_ia32_extract128i256: 3540 case X86::BI__builtin_ia32_extractf64x4_mask: 3541 case X86::BI__builtin_ia32_extracti64x4_mask: 3542 case X86::BI__builtin_ia32_extractf32x8_mask: 3543 case X86::BI__builtin_ia32_extracti32x8_mask: 3544 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3545 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3546 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3547 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3548 i = 1; l = 0; u = 1; 3549 break; 3550 case X86::BI__builtin_ia32_vec_set_v2di: 3551 case X86::BI__builtin_ia32_vinsertf128_pd256: 3552 case X86::BI__builtin_ia32_vinsertf128_ps256: 3553 case X86::BI__builtin_ia32_vinsertf128_si256: 3554 case X86::BI__builtin_ia32_insert128i256: 3555 case X86::BI__builtin_ia32_insertf32x8: 3556 case X86::BI__builtin_ia32_inserti32x8: 3557 case X86::BI__builtin_ia32_insertf64x4: 3558 case X86::BI__builtin_ia32_inserti64x4: 3559 case X86::BI__builtin_ia32_insertf64x2_256: 3560 case X86::BI__builtin_ia32_inserti64x2_256: 3561 case X86::BI__builtin_ia32_insertf32x4_256: 3562 case X86::BI__builtin_ia32_inserti32x4_256: 3563 i = 2; l = 0; u = 1; 3564 break; 3565 case X86::BI__builtin_ia32_vpermilpd: 3566 case X86::BI__builtin_ia32_vec_ext_v4hi: 3567 case X86::BI__builtin_ia32_vec_ext_v4si: 3568 case X86::BI__builtin_ia32_vec_ext_v4sf: 3569 case X86::BI__builtin_ia32_vec_ext_v4di: 3570 case X86::BI__builtin_ia32_extractf32x4_mask: 3571 case X86::BI__builtin_ia32_extracti32x4_mask: 3572 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3573 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3574 i = 1; l = 0; u = 3; 3575 break; 3576 case X86::BI_mm_prefetch: 3577 case X86::BI__builtin_ia32_vec_ext_v8hi: 3578 case X86::BI__builtin_ia32_vec_ext_v8si: 3579 i = 1; l = 0; u = 7; 3580 break; 3581 case X86::BI__builtin_ia32_sha1rnds4: 3582 case X86::BI__builtin_ia32_blendpd: 3583 case X86::BI__builtin_ia32_shufpd: 3584 case X86::BI__builtin_ia32_vec_set_v4hi: 3585 case X86::BI__builtin_ia32_vec_set_v4si: 3586 case X86::BI__builtin_ia32_vec_set_v4di: 3587 case X86::BI__builtin_ia32_shuf_f32x4_256: 3588 case X86::BI__builtin_ia32_shuf_f64x2_256: 3589 case X86::BI__builtin_ia32_shuf_i32x4_256: 3590 case X86::BI__builtin_ia32_shuf_i64x2_256: 3591 case X86::BI__builtin_ia32_insertf64x2_512: 3592 case X86::BI__builtin_ia32_inserti64x2_512: 3593 case X86::BI__builtin_ia32_insertf32x4: 3594 case X86::BI__builtin_ia32_inserti32x4: 3595 i = 2; l = 0; u = 3; 3596 break; 3597 case X86::BI__builtin_ia32_vpermil2pd: 3598 case X86::BI__builtin_ia32_vpermil2pd256: 3599 case X86::BI__builtin_ia32_vpermil2ps: 3600 case X86::BI__builtin_ia32_vpermil2ps256: 3601 i = 3; l = 0; u = 3; 3602 break; 3603 case X86::BI__builtin_ia32_cmpb128_mask: 3604 case X86::BI__builtin_ia32_cmpw128_mask: 3605 case X86::BI__builtin_ia32_cmpd128_mask: 3606 case X86::BI__builtin_ia32_cmpq128_mask: 3607 case X86::BI__builtin_ia32_cmpb256_mask: 3608 case X86::BI__builtin_ia32_cmpw256_mask: 3609 case X86::BI__builtin_ia32_cmpd256_mask: 3610 case X86::BI__builtin_ia32_cmpq256_mask: 3611 case X86::BI__builtin_ia32_cmpb512_mask: 3612 case X86::BI__builtin_ia32_cmpw512_mask: 3613 case X86::BI__builtin_ia32_cmpd512_mask: 3614 case X86::BI__builtin_ia32_cmpq512_mask: 3615 case X86::BI__builtin_ia32_ucmpb128_mask: 3616 case X86::BI__builtin_ia32_ucmpw128_mask: 3617 case X86::BI__builtin_ia32_ucmpd128_mask: 3618 case X86::BI__builtin_ia32_ucmpq128_mask: 3619 case X86::BI__builtin_ia32_ucmpb256_mask: 3620 case X86::BI__builtin_ia32_ucmpw256_mask: 3621 case X86::BI__builtin_ia32_ucmpd256_mask: 3622 case X86::BI__builtin_ia32_ucmpq256_mask: 3623 case X86::BI__builtin_ia32_ucmpb512_mask: 3624 case X86::BI__builtin_ia32_ucmpw512_mask: 3625 case X86::BI__builtin_ia32_ucmpd512_mask: 3626 case X86::BI__builtin_ia32_ucmpq512_mask: 3627 case X86::BI__builtin_ia32_vpcomub: 3628 case X86::BI__builtin_ia32_vpcomuw: 3629 case X86::BI__builtin_ia32_vpcomud: 3630 case X86::BI__builtin_ia32_vpcomuq: 3631 case X86::BI__builtin_ia32_vpcomb: 3632 case X86::BI__builtin_ia32_vpcomw: 3633 case X86::BI__builtin_ia32_vpcomd: 3634 case X86::BI__builtin_ia32_vpcomq: 3635 case X86::BI__builtin_ia32_vec_set_v8hi: 3636 case X86::BI__builtin_ia32_vec_set_v8si: 3637 i = 2; l = 0; u = 7; 3638 break; 3639 case X86::BI__builtin_ia32_vpermilpd256: 3640 case X86::BI__builtin_ia32_roundps: 3641 case X86::BI__builtin_ia32_roundpd: 3642 case X86::BI__builtin_ia32_roundps256: 3643 case X86::BI__builtin_ia32_roundpd256: 3644 case X86::BI__builtin_ia32_getmantpd128_mask: 3645 case X86::BI__builtin_ia32_getmantpd256_mask: 3646 case X86::BI__builtin_ia32_getmantps128_mask: 3647 case X86::BI__builtin_ia32_getmantps256_mask: 3648 case X86::BI__builtin_ia32_getmantpd512_mask: 3649 case X86::BI__builtin_ia32_getmantps512_mask: 3650 case X86::BI__builtin_ia32_vec_ext_v16qi: 3651 case X86::BI__builtin_ia32_vec_ext_v16hi: 3652 i = 1; l = 0; u = 15; 3653 break; 3654 case X86::BI__builtin_ia32_pblendd128: 3655 case X86::BI__builtin_ia32_blendps: 3656 case X86::BI__builtin_ia32_blendpd256: 3657 case X86::BI__builtin_ia32_shufpd256: 3658 case X86::BI__builtin_ia32_roundss: 3659 case X86::BI__builtin_ia32_roundsd: 3660 case X86::BI__builtin_ia32_rangepd128_mask: 3661 case X86::BI__builtin_ia32_rangepd256_mask: 3662 case X86::BI__builtin_ia32_rangepd512_mask: 3663 case X86::BI__builtin_ia32_rangeps128_mask: 3664 case X86::BI__builtin_ia32_rangeps256_mask: 3665 case X86::BI__builtin_ia32_rangeps512_mask: 3666 case X86::BI__builtin_ia32_getmantsd_round_mask: 3667 case X86::BI__builtin_ia32_getmantss_round_mask: 3668 case X86::BI__builtin_ia32_vec_set_v16qi: 3669 case X86::BI__builtin_ia32_vec_set_v16hi: 3670 i = 2; l = 0; u = 15; 3671 break; 3672 case X86::BI__builtin_ia32_vec_ext_v32qi: 3673 i = 1; l = 0; u = 31; 3674 break; 3675 case X86::BI__builtin_ia32_cmpps: 3676 case X86::BI__builtin_ia32_cmpss: 3677 case X86::BI__builtin_ia32_cmppd: 3678 case X86::BI__builtin_ia32_cmpsd: 3679 case X86::BI__builtin_ia32_cmpps256: 3680 case X86::BI__builtin_ia32_cmppd256: 3681 case X86::BI__builtin_ia32_cmpps128_mask: 3682 case X86::BI__builtin_ia32_cmppd128_mask: 3683 case X86::BI__builtin_ia32_cmpps256_mask: 3684 case X86::BI__builtin_ia32_cmppd256_mask: 3685 case X86::BI__builtin_ia32_cmpps512_mask: 3686 case X86::BI__builtin_ia32_cmppd512_mask: 3687 case X86::BI__builtin_ia32_cmpsd_mask: 3688 case X86::BI__builtin_ia32_cmpss_mask: 3689 case X86::BI__builtin_ia32_vec_set_v32qi: 3690 i = 2; l = 0; u = 31; 3691 break; 3692 case X86::BI__builtin_ia32_permdf256: 3693 case X86::BI__builtin_ia32_permdi256: 3694 case X86::BI__builtin_ia32_permdf512: 3695 case X86::BI__builtin_ia32_permdi512: 3696 case X86::BI__builtin_ia32_vpermilps: 3697 case X86::BI__builtin_ia32_vpermilps256: 3698 case X86::BI__builtin_ia32_vpermilpd512: 3699 case X86::BI__builtin_ia32_vpermilps512: 3700 case X86::BI__builtin_ia32_pshufd: 3701 case X86::BI__builtin_ia32_pshufd256: 3702 case X86::BI__builtin_ia32_pshufd512: 3703 case X86::BI__builtin_ia32_pshufhw: 3704 case X86::BI__builtin_ia32_pshufhw256: 3705 case X86::BI__builtin_ia32_pshufhw512: 3706 case X86::BI__builtin_ia32_pshuflw: 3707 case X86::BI__builtin_ia32_pshuflw256: 3708 case X86::BI__builtin_ia32_pshuflw512: 3709 case X86::BI__builtin_ia32_vcvtps2ph: 3710 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3711 case X86::BI__builtin_ia32_vcvtps2ph256: 3712 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3713 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3714 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3715 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3716 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3717 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3718 case X86::BI__builtin_ia32_rndscaleps_mask: 3719 case X86::BI__builtin_ia32_rndscalepd_mask: 3720 case X86::BI__builtin_ia32_reducepd128_mask: 3721 case X86::BI__builtin_ia32_reducepd256_mask: 3722 case X86::BI__builtin_ia32_reducepd512_mask: 3723 case X86::BI__builtin_ia32_reduceps128_mask: 3724 case X86::BI__builtin_ia32_reduceps256_mask: 3725 case X86::BI__builtin_ia32_reduceps512_mask: 3726 case X86::BI__builtin_ia32_prold512: 3727 case X86::BI__builtin_ia32_prolq512: 3728 case X86::BI__builtin_ia32_prold128: 3729 case X86::BI__builtin_ia32_prold256: 3730 case X86::BI__builtin_ia32_prolq128: 3731 case X86::BI__builtin_ia32_prolq256: 3732 case X86::BI__builtin_ia32_prord512: 3733 case X86::BI__builtin_ia32_prorq512: 3734 case X86::BI__builtin_ia32_prord128: 3735 case X86::BI__builtin_ia32_prord256: 3736 case X86::BI__builtin_ia32_prorq128: 3737 case X86::BI__builtin_ia32_prorq256: 3738 case X86::BI__builtin_ia32_fpclasspd128_mask: 3739 case X86::BI__builtin_ia32_fpclasspd256_mask: 3740 case X86::BI__builtin_ia32_fpclassps128_mask: 3741 case X86::BI__builtin_ia32_fpclassps256_mask: 3742 case X86::BI__builtin_ia32_fpclassps512_mask: 3743 case X86::BI__builtin_ia32_fpclasspd512_mask: 3744 case X86::BI__builtin_ia32_fpclasssd_mask: 3745 case X86::BI__builtin_ia32_fpclassss_mask: 3746 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3747 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3748 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3749 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3750 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3751 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3752 case X86::BI__builtin_ia32_kshiftliqi: 3753 case X86::BI__builtin_ia32_kshiftlihi: 3754 case X86::BI__builtin_ia32_kshiftlisi: 3755 case X86::BI__builtin_ia32_kshiftlidi: 3756 case X86::BI__builtin_ia32_kshiftriqi: 3757 case X86::BI__builtin_ia32_kshiftrihi: 3758 case X86::BI__builtin_ia32_kshiftrisi: 3759 case X86::BI__builtin_ia32_kshiftridi: 3760 i = 1; l = 0; u = 255; 3761 break; 3762 case X86::BI__builtin_ia32_vperm2f128_pd256: 3763 case X86::BI__builtin_ia32_vperm2f128_ps256: 3764 case X86::BI__builtin_ia32_vperm2f128_si256: 3765 case X86::BI__builtin_ia32_permti256: 3766 case X86::BI__builtin_ia32_pblendw128: 3767 case X86::BI__builtin_ia32_pblendw256: 3768 case X86::BI__builtin_ia32_blendps256: 3769 case X86::BI__builtin_ia32_pblendd256: 3770 case X86::BI__builtin_ia32_palignr128: 3771 case X86::BI__builtin_ia32_palignr256: 3772 case X86::BI__builtin_ia32_palignr512: 3773 case X86::BI__builtin_ia32_alignq512: 3774 case X86::BI__builtin_ia32_alignd512: 3775 case X86::BI__builtin_ia32_alignd128: 3776 case X86::BI__builtin_ia32_alignd256: 3777 case X86::BI__builtin_ia32_alignq128: 3778 case X86::BI__builtin_ia32_alignq256: 3779 case X86::BI__builtin_ia32_vcomisd: 3780 case X86::BI__builtin_ia32_vcomiss: 3781 case X86::BI__builtin_ia32_shuf_f32x4: 3782 case X86::BI__builtin_ia32_shuf_f64x2: 3783 case X86::BI__builtin_ia32_shuf_i32x4: 3784 case X86::BI__builtin_ia32_shuf_i64x2: 3785 case X86::BI__builtin_ia32_shufpd512: 3786 case X86::BI__builtin_ia32_shufps: 3787 case X86::BI__builtin_ia32_shufps256: 3788 case X86::BI__builtin_ia32_shufps512: 3789 case X86::BI__builtin_ia32_dbpsadbw128: 3790 case X86::BI__builtin_ia32_dbpsadbw256: 3791 case X86::BI__builtin_ia32_dbpsadbw512: 3792 case X86::BI__builtin_ia32_vpshldd128: 3793 case X86::BI__builtin_ia32_vpshldd256: 3794 case X86::BI__builtin_ia32_vpshldd512: 3795 case X86::BI__builtin_ia32_vpshldq128: 3796 case X86::BI__builtin_ia32_vpshldq256: 3797 case X86::BI__builtin_ia32_vpshldq512: 3798 case X86::BI__builtin_ia32_vpshldw128: 3799 case X86::BI__builtin_ia32_vpshldw256: 3800 case X86::BI__builtin_ia32_vpshldw512: 3801 case X86::BI__builtin_ia32_vpshrdd128: 3802 case X86::BI__builtin_ia32_vpshrdd256: 3803 case X86::BI__builtin_ia32_vpshrdd512: 3804 case X86::BI__builtin_ia32_vpshrdq128: 3805 case X86::BI__builtin_ia32_vpshrdq256: 3806 case X86::BI__builtin_ia32_vpshrdq512: 3807 case X86::BI__builtin_ia32_vpshrdw128: 3808 case X86::BI__builtin_ia32_vpshrdw256: 3809 case X86::BI__builtin_ia32_vpshrdw512: 3810 i = 2; l = 0; u = 255; 3811 break; 3812 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3813 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3814 case X86::BI__builtin_ia32_fixupimmps512_mask: 3815 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3816 case X86::BI__builtin_ia32_fixupimmsd_mask: 3817 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3818 case X86::BI__builtin_ia32_fixupimmss_mask: 3819 case X86::BI__builtin_ia32_fixupimmss_maskz: 3820 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3821 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3822 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3823 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3824 case X86::BI__builtin_ia32_fixupimmps128_mask: 3825 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3826 case X86::BI__builtin_ia32_fixupimmps256_mask: 3827 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3828 case X86::BI__builtin_ia32_pternlogd512_mask: 3829 case X86::BI__builtin_ia32_pternlogd512_maskz: 3830 case X86::BI__builtin_ia32_pternlogq512_mask: 3831 case X86::BI__builtin_ia32_pternlogq512_maskz: 3832 case X86::BI__builtin_ia32_pternlogd128_mask: 3833 case X86::BI__builtin_ia32_pternlogd128_maskz: 3834 case X86::BI__builtin_ia32_pternlogd256_mask: 3835 case X86::BI__builtin_ia32_pternlogd256_maskz: 3836 case X86::BI__builtin_ia32_pternlogq128_mask: 3837 case X86::BI__builtin_ia32_pternlogq128_maskz: 3838 case X86::BI__builtin_ia32_pternlogq256_mask: 3839 case X86::BI__builtin_ia32_pternlogq256_maskz: 3840 i = 3; l = 0; u = 255; 3841 break; 3842 case X86::BI__builtin_ia32_gatherpfdpd: 3843 case X86::BI__builtin_ia32_gatherpfdps: 3844 case X86::BI__builtin_ia32_gatherpfqpd: 3845 case X86::BI__builtin_ia32_gatherpfqps: 3846 case X86::BI__builtin_ia32_scatterpfdpd: 3847 case X86::BI__builtin_ia32_scatterpfdps: 3848 case X86::BI__builtin_ia32_scatterpfqpd: 3849 case X86::BI__builtin_ia32_scatterpfqps: 3850 i = 4; l = 2; u = 3; 3851 break; 3852 case X86::BI__builtin_ia32_reducesd_mask: 3853 case X86::BI__builtin_ia32_reducess_mask: 3854 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3855 case X86::BI__builtin_ia32_rndscaless_round_mask: 3856 i = 4; l = 0; u = 255; 3857 break; 3858 } 3859 3860 // Note that we don't force a hard error on the range check here, allowing 3861 // template-generated or macro-generated dead code to potentially have out-of- 3862 // range values. These need to code generate, but don't need to necessarily 3863 // make any sense. We use a warning that defaults to an error. 3864 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3865 } 3866 3867 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3868 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3869 /// Returns true when the format fits the function and the FormatStringInfo has 3870 /// been populated. 3871 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3872 FormatStringInfo *FSI) { 3873 FSI->HasVAListArg = Format->getFirstArg() == 0; 3874 FSI->FormatIdx = Format->getFormatIdx() - 1; 3875 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3876 3877 // The way the format attribute works in GCC, the implicit this argument 3878 // of member functions is counted. However, it doesn't appear in our own 3879 // lists, so decrement format_idx in that case. 3880 if (IsCXXMember) { 3881 if(FSI->FormatIdx == 0) 3882 return false; 3883 --FSI->FormatIdx; 3884 if (FSI->FirstDataArg != 0) 3885 --FSI->FirstDataArg; 3886 } 3887 return true; 3888 } 3889 3890 /// Checks if a the given expression evaluates to null. 3891 /// 3892 /// Returns true if the value evaluates to null. 3893 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3894 // If the expression has non-null type, it doesn't evaluate to null. 3895 if (auto nullability 3896 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3897 if (*nullability == NullabilityKind::NonNull) 3898 return false; 3899 } 3900 3901 // As a special case, transparent unions initialized with zero are 3902 // considered null for the purposes of the nonnull attribute. 3903 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3904 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3905 if (const CompoundLiteralExpr *CLE = 3906 dyn_cast<CompoundLiteralExpr>(Expr)) 3907 if (const InitListExpr *ILE = 3908 dyn_cast<InitListExpr>(CLE->getInitializer())) 3909 Expr = ILE->getInit(0); 3910 } 3911 3912 bool Result; 3913 return (!Expr->isValueDependent() && 3914 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3915 !Result); 3916 } 3917 3918 static void CheckNonNullArgument(Sema &S, 3919 const Expr *ArgExpr, 3920 SourceLocation CallSiteLoc) { 3921 if (CheckNonNullExpr(S, ArgExpr)) 3922 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3923 S.PDiag(diag::warn_null_arg) 3924 << ArgExpr->getSourceRange()); 3925 } 3926 3927 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3928 FormatStringInfo FSI; 3929 if ((GetFormatStringType(Format) == FST_NSString) && 3930 getFormatStringInfo(Format, false, &FSI)) { 3931 Idx = FSI.FormatIdx; 3932 return true; 3933 } 3934 return false; 3935 } 3936 3937 /// Diagnose use of %s directive in an NSString which is being passed 3938 /// as formatting string to formatting method. 3939 static void 3940 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3941 const NamedDecl *FDecl, 3942 Expr **Args, 3943 unsigned NumArgs) { 3944 unsigned Idx = 0; 3945 bool Format = false; 3946 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3947 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3948 Idx = 2; 3949 Format = true; 3950 } 3951 else 3952 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3953 if (S.GetFormatNSStringIdx(I, Idx)) { 3954 Format = true; 3955 break; 3956 } 3957 } 3958 if (!Format || NumArgs <= Idx) 3959 return; 3960 const Expr *FormatExpr = Args[Idx]; 3961 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3962 FormatExpr = CSCE->getSubExpr(); 3963 const StringLiteral *FormatString; 3964 if (const ObjCStringLiteral *OSL = 3965 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3966 FormatString = OSL->getString(); 3967 else 3968 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3969 if (!FormatString) 3970 return; 3971 if (S.FormatStringHasSArg(FormatString)) { 3972 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3973 << "%s" << 1 << 1; 3974 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3975 << FDecl->getDeclName(); 3976 } 3977 } 3978 3979 /// Determine whether the given type has a non-null nullability annotation. 3980 static bool isNonNullType(ASTContext &ctx, QualType type) { 3981 if (auto nullability = type->getNullability(ctx)) 3982 return *nullability == NullabilityKind::NonNull; 3983 3984 return false; 3985 } 3986 3987 static void CheckNonNullArguments(Sema &S, 3988 const NamedDecl *FDecl, 3989 const FunctionProtoType *Proto, 3990 ArrayRef<const Expr *> Args, 3991 SourceLocation CallSiteLoc) { 3992 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3993 3994 // Already checked by by constant evaluator. 3995 if (S.isConstantEvaluated()) 3996 return; 3997 // Check the attributes attached to the method/function itself. 3998 llvm::SmallBitVector NonNullArgs; 3999 if (FDecl) { 4000 // Handle the nonnull attribute on the function/method declaration itself. 4001 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4002 if (!NonNull->args_size()) { 4003 // Easy case: all pointer arguments are nonnull. 4004 for (const auto *Arg : Args) 4005 if (S.isValidPointerAttrType(Arg->getType())) 4006 CheckNonNullArgument(S, Arg, CallSiteLoc); 4007 return; 4008 } 4009 4010 for (const ParamIdx &Idx : NonNull->args()) { 4011 unsigned IdxAST = Idx.getASTIndex(); 4012 if (IdxAST >= Args.size()) 4013 continue; 4014 if (NonNullArgs.empty()) 4015 NonNullArgs.resize(Args.size()); 4016 NonNullArgs.set(IdxAST); 4017 } 4018 } 4019 } 4020 4021 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4022 // Handle the nonnull attribute on the parameters of the 4023 // function/method. 4024 ArrayRef<ParmVarDecl*> parms; 4025 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4026 parms = FD->parameters(); 4027 else 4028 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4029 4030 unsigned ParamIndex = 0; 4031 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4032 I != E; ++I, ++ParamIndex) { 4033 const ParmVarDecl *PVD = *I; 4034 if (PVD->hasAttr<NonNullAttr>() || 4035 isNonNullType(S.Context, PVD->getType())) { 4036 if (NonNullArgs.empty()) 4037 NonNullArgs.resize(Args.size()); 4038 4039 NonNullArgs.set(ParamIndex); 4040 } 4041 } 4042 } else { 4043 // If we have a non-function, non-method declaration but no 4044 // function prototype, try to dig out the function prototype. 4045 if (!Proto) { 4046 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4047 QualType type = VD->getType().getNonReferenceType(); 4048 if (auto pointerType = type->getAs<PointerType>()) 4049 type = pointerType->getPointeeType(); 4050 else if (auto blockType = type->getAs<BlockPointerType>()) 4051 type = blockType->getPointeeType(); 4052 // FIXME: data member pointers? 4053 4054 // Dig out the function prototype, if there is one. 4055 Proto = type->getAs<FunctionProtoType>(); 4056 } 4057 } 4058 4059 // Fill in non-null argument information from the nullability 4060 // information on the parameter types (if we have them). 4061 if (Proto) { 4062 unsigned Index = 0; 4063 for (auto paramType : Proto->getParamTypes()) { 4064 if (isNonNullType(S.Context, paramType)) { 4065 if (NonNullArgs.empty()) 4066 NonNullArgs.resize(Args.size()); 4067 4068 NonNullArgs.set(Index); 4069 } 4070 4071 ++Index; 4072 } 4073 } 4074 } 4075 4076 // Check for non-null arguments. 4077 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4078 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4079 if (NonNullArgs[ArgIndex]) 4080 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4081 } 4082 } 4083 4084 /// Handles the checks for format strings, non-POD arguments to vararg 4085 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4086 /// attributes. 4087 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4088 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4089 bool IsMemberFunction, SourceLocation Loc, 4090 SourceRange Range, VariadicCallType CallType) { 4091 // FIXME: We should check as much as we can in the template definition. 4092 if (CurContext->isDependentContext()) 4093 return; 4094 4095 // Printf and scanf checking. 4096 llvm::SmallBitVector CheckedVarArgs; 4097 if (FDecl) { 4098 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4099 // Only create vector if there are format attributes. 4100 CheckedVarArgs.resize(Args.size()); 4101 4102 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4103 CheckedVarArgs); 4104 } 4105 } 4106 4107 // Refuse POD arguments that weren't caught by the format string 4108 // checks above. 4109 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4110 if (CallType != VariadicDoesNotApply && 4111 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4112 unsigned NumParams = Proto ? Proto->getNumParams() 4113 : FDecl && isa<FunctionDecl>(FDecl) 4114 ? cast<FunctionDecl>(FDecl)->getNumParams() 4115 : FDecl && isa<ObjCMethodDecl>(FDecl) 4116 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4117 : 0; 4118 4119 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4120 // Args[ArgIdx] can be null in malformed code. 4121 if (const Expr *Arg = Args[ArgIdx]) { 4122 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4123 checkVariadicArgument(Arg, CallType); 4124 } 4125 } 4126 } 4127 4128 if (FDecl || Proto) { 4129 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4130 4131 // Type safety checking. 4132 if (FDecl) { 4133 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4134 CheckArgumentWithTypeTag(I, Args, Loc); 4135 } 4136 } 4137 4138 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4139 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4140 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4141 if (!Arg->isValueDependent()) { 4142 Expr::EvalResult Align; 4143 if (Arg->EvaluateAsInt(Align, Context)) { 4144 const llvm::APSInt &I = Align.Val.getInt(); 4145 if (!I.isPowerOf2()) 4146 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4147 << Arg->getSourceRange(); 4148 4149 if (I > Sema::MaximumAlignment) 4150 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4151 << Arg->getSourceRange() << Sema::MaximumAlignment; 4152 } 4153 } 4154 } 4155 4156 if (FD) 4157 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4158 } 4159 4160 /// CheckConstructorCall - Check a constructor call for correctness and safety 4161 /// properties not enforced by the C type system. 4162 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4163 ArrayRef<const Expr *> Args, 4164 const FunctionProtoType *Proto, 4165 SourceLocation Loc) { 4166 VariadicCallType CallType = 4167 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4168 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4169 Loc, SourceRange(), CallType); 4170 } 4171 4172 /// CheckFunctionCall - Check a direct function call for various correctness 4173 /// and safety properties not strictly enforced by the C type system. 4174 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4175 const FunctionProtoType *Proto) { 4176 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4177 isa<CXXMethodDecl>(FDecl); 4178 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4179 IsMemberOperatorCall; 4180 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4181 TheCall->getCallee()); 4182 Expr** Args = TheCall->getArgs(); 4183 unsigned NumArgs = TheCall->getNumArgs(); 4184 4185 Expr *ImplicitThis = nullptr; 4186 if (IsMemberOperatorCall) { 4187 // If this is a call to a member operator, hide the first argument 4188 // from checkCall. 4189 // FIXME: Our choice of AST representation here is less than ideal. 4190 ImplicitThis = Args[0]; 4191 ++Args; 4192 --NumArgs; 4193 } else if (IsMemberFunction) 4194 ImplicitThis = 4195 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4196 4197 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4198 IsMemberFunction, TheCall->getRParenLoc(), 4199 TheCall->getCallee()->getSourceRange(), CallType); 4200 4201 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4202 // None of the checks below are needed for functions that don't have 4203 // simple names (e.g., C++ conversion functions). 4204 if (!FnInfo) 4205 return false; 4206 4207 CheckAbsoluteValueFunction(TheCall, FDecl); 4208 CheckMaxUnsignedZero(TheCall, FDecl); 4209 4210 if (getLangOpts().ObjC) 4211 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4212 4213 unsigned CMId = FDecl->getMemoryFunctionKind(); 4214 if (CMId == 0) 4215 return false; 4216 4217 // Handle memory setting and copying functions. 4218 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4219 CheckStrlcpycatArguments(TheCall, FnInfo); 4220 else if (CMId == Builtin::BIstrncat) 4221 CheckStrncatArguments(TheCall, FnInfo); 4222 else 4223 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4224 4225 return false; 4226 } 4227 4228 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4229 ArrayRef<const Expr *> Args) { 4230 VariadicCallType CallType = 4231 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4232 4233 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4234 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4235 CallType); 4236 4237 return false; 4238 } 4239 4240 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4241 const FunctionProtoType *Proto) { 4242 QualType Ty; 4243 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4244 Ty = V->getType().getNonReferenceType(); 4245 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4246 Ty = F->getType().getNonReferenceType(); 4247 else 4248 return false; 4249 4250 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4251 !Ty->isFunctionProtoType()) 4252 return false; 4253 4254 VariadicCallType CallType; 4255 if (!Proto || !Proto->isVariadic()) { 4256 CallType = VariadicDoesNotApply; 4257 } else if (Ty->isBlockPointerType()) { 4258 CallType = VariadicBlock; 4259 } else { // Ty->isFunctionPointerType() 4260 CallType = VariadicFunction; 4261 } 4262 4263 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4264 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4265 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4266 TheCall->getCallee()->getSourceRange(), CallType); 4267 4268 return false; 4269 } 4270 4271 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4272 /// such as function pointers returned from functions. 4273 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4274 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4275 TheCall->getCallee()); 4276 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4277 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4278 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4279 TheCall->getCallee()->getSourceRange(), CallType); 4280 4281 return false; 4282 } 4283 4284 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4285 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4286 return false; 4287 4288 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4289 switch (Op) { 4290 case AtomicExpr::AO__c11_atomic_init: 4291 case AtomicExpr::AO__opencl_atomic_init: 4292 llvm_unreachable("There is no ordering argument for an init"); 4293 4294 case AtomicExpr::AO__c11_atomic_load: 4295 case AtomicExpr::AO__opencl_atomic_load: 4296 case AtomicExpr::AO__atomic_load_n: 4297 case AtomicExpr::AO__atomic_load: 4298 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4299 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4300 4301 case AtomicExpr::AO__c11_atomic_store: 4302 case AtomicExpr::AO__opencl_atomic_store: 4303 case AtomicExpr::AO__atomic_store: 4304 case AtomicExpr::AO__atomic_store_n: 4305 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4306 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4307 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4308 4309 default: 4310 return true; 4311 } 4312 } 4313 4314 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4315 AtomicExpr::AtomicOp Op) { 4316 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4317 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4318 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4319 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4320 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4321 Op); 4322 } 4323 4324 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4325 SourceLocation RParenLoc, MultiExprArg Args, 4326 AtomicExpr::AtomicOp Op, 4327 AtomicArgumentOrder ArgOrder) { 4328 // All the non-OpenCL operations take one of the following forms. 4329 // The OpenCL operations take the __c11 forms with one extra argument for 4330 // synchronization scope. 4331 enum { 4332 // C __c11_atomic_init(A *, C) 4333 Init, 4334 4335 // C __c11_atomic_load(A *, int) 4336 Load, 4337 4338 // void __atomic_load(A *, CP, int) 4339 LoadCopy, 4340 4341 // void __atomic_store(A *, CP, int) 4342 Copy, 4343 4344 // C __c11_atomic_add(A *, M, int) 4345 Arithmetic, 4346 4347 // C __atomic_exchange_n(A *, CP, int) 4348 Xchg, 4349 4350 // void __atomic_exchange(A *, C *, CP, int) 4351 GNUXchg, 4352 4353 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4354 C11CmpXchg, 4355 4356 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4357 GNUCmpXchg 4358 } Form = Init; 4359 4360 const unsigned NumForm = GNUCmpXchg + 1; 4361 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4362 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4363 // where: 4364 // C is an appropriate type, 4365 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4366 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4367 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4368 // the int parameters are for orderings. 4369 4370 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4371 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4372 "need to update code for modified forms"); 4373 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4374 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4375 AtomicExpr::AO__atomic_load, 4376 "need to update code for modified C11 atomics"); 4377 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4378 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4379 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4380 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4381 IsOpenCL; 4382 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4383 Op == AtomicExpr::AO__atomic_store_n || 4384 Op == AtomicExpr::AO__atomic_exchange_n || 4385 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4386 bool IsAddSub = false; 4387 4388 switch (Op) { 4389 case AtomicExpr::AO__c11_atomic_init: 4390 case AtomicExpr::AO__opencl_atomic_init: 4391 Form = Init; 4392 break; 4393 4394 case AtomicExpr::AO__c11_atomic_load: 4395 case AtomicExpr::AO__opencl_atomic_load: 4396 case AtomicExpr::AO__atomic_load_n: 4397 Form = Load; 4398 break; 4399 4400 case AtomicExpr::AO__atomic_load: 4401 Form = LoadCopy; 4402 break; 4403 4404 case AtomicExpr::AO__c11_atomic_store: 4405 case AtomicExpr::AO__opencl_atomic_store: 4406 case AtomicExpr::AO__atomic_store: 4407 case AtomicExpr::AO__atomic_store_n: 4408 Form = Copy; 4409 break; 4410 4411 case AtomicExpr::AO__c11_atomic_fetch_add: 4412 case AtomicExpr::AO__c11_atomic_fetch_sub: 4413 case AtomicExpr::AO__opencl_atomic_fetch_add: 4414 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4415 case AtomicExpr::AO__atomic_fetch_add: 4416 case AtomicExpr::AO__atomic_fetch_sub: 4417 case AtomicExpr::AO__atomic_add_fetch: 4418 case AtomicExpr::AO__atomic_sub_fetch: 4419 IsAddSub = true; 4420 LLVM_FALLTHROUGH; 4421 case AtomicExpr::AO__c11_atomic_fetch_and: 4422 case AtomicExpr::AO__c11_atomic_fetch_or: 4423 case AtomicExpr::AO__c11_atomic_fetch_xor: 4424 case AtomicExpr::AO__opencl_atomic_fetch_and: 4425 case AtomicExpr::AO__opencl_atomic_fetch_or: 4426 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4427 case AtomicExpr::AO__atomic_fetch_and: 4428 case AtomicExpr::AO__atomic_fetch_or: 4429 case AtomicExpr::AO__atomic_fetch_xor: 4430 case AtomicExpr::AO__atomic_fetch_nand: 4431 case AtomicExpr::AO__atomic_and_fetch: 4432 case AtomicExpr::AO__atomic_or_fetch: 4433 case AtomicExpr::AO__atomic_xor_fetch: 4434 case AtomicExpr::AO__atomic_nand_fetch: 4435 case AtomicExpr::AO__c11_atomic_fetch_min: 4436 case AtomicExpr::AO__c11_atomic_fetch_max: 4437 case AtomicExpr::AO__opencl_atomic_fetch_min: 4438 case AtomicExpr::AO__opencl_atomic_fetch_max: 4439 case AtomicExpr::AO__atomic_min_fetch: 4440 case AtomicExpr::AO__atomic_max_fetch: 4441 case AtomicExpr::AO__atomic_fetch_min: 4442 case AtomicExpr::AO__atomic_fetch_max: 4443 Form = Arithmetic; 4444 break; 4445 4446 case AtomicExpr::AO__c11_atomic_exchange: 4447 case AtomicExpr::AO__opencl_atomic_exchange: 4448 case AtomicExpr::AO__atomic_exchange_n: 4449 Form = Xchg; 4450 break; 4451 4452 case AtomicExpr::AO__atomic_exchange: 4453 Form = GNUXchg; 4454 break; 4455 4456 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4457 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4458 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4459 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4460 Form = C11CmpXchg; 4461 break; 4462 4463 case AtomicExpr::AO__atomic_compare_exchange: 4464 case AtomicExpr::AO__atomic_compare_exchange_n: 4465 Form = GNUCmpXchg; 4466 break; 4467 } 4468 4469 unsigned AdjustedNumArgs = NumArgs[Form]; 4470 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4471 ++AdjustedNumArgs; 4472 // Check we have the right number of arguments. 4473 if (Args.size() < AdjustedNumArgs) { 4474 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4475 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4476 << ExprRange; 4477 return ExprError(); 4478 } else if (Args.size() > AdjustedNumArgs) { 4479 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4480 diag::err_typecheck_call_too_many_args) 4481 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4482 << ExprRange; 4483 return ExprError(); 4484 } 4485 4486 // Inspect the first argument of the atomic operation. 4487 Expr *Ptr = Args[0]; 4488 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4489 if (ConvertedPtr.isInvalid()) 4490 return ExprError(); 4491 4492 Ptr = ConvertedPtr.get(); 4493 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4494 if (!pointerType) { 4495 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4496 << Ptr->getType() << Ptr->getSourceRange(); 4497 return ExprError(); 4498 } 4499 4500 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4501 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4502 QualType ValType = AtomTy; // 'C' 4503 if (IsC11) { 4504 if (!AtomTy->isAtomicType()) { 4505 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4506 << Ptr->getType() << Ptr->getSourceRange(); 4507 return ExprError(); 4508 } 4509 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4510 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4511 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4512 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4513 << Ptr->getSourceRange(); 4514 return ExprError(); 4515 } 4516 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4517 } else if (Form != Load && Form != LoadCopy) { 4518 if (ValType.isConstQualified()) { 4519 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4520 << Ptr->getType() << Ptr->getSourceRange(); 4521 return ExprError(); 4522 } 4523 } 4524 4525 // For an arithmetic operation, the implied arithmetic must be well-formed. 4526 if (Form == Arithmetic) { 4527 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4528 if (IsAddSub && !ValType->isIntegerType() 4529 && !ValType->isPointerType()) { 4530 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4531 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4532 return ExprError(); 4533 } 4534 if (!IsAddSub && !ValType->isIntegerType()) { 4535 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4536 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4537 return ExprError(); 4538 } 4539 if (IsC11 && ValType->isPointerType() && 4540 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4541 diag::err_incomplete_type)) { 4542 return ExprError(); 4543 } 4544 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4545 // For __atomic_*_n operations, the value type must be a scalar integral or 4546 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4547 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4548 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4549 return ExprError(); 4550 } 4551 4552 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4553 !AtomTy->isScalarType()) { 4554 // For GNU atomics, require a trivially-copyable type. This is not part of 4555 // the GNU atomics specification, but we enforce it for sanity. 4556 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4557 << Ptr->getType() << Ptr->getSourceRange(); 4558 return ExprError(); 4559 } 4560 4561 switch (ValType.getObjCLifetime()) { 4562 case Qualifiers::OCL_None: 4563 case Qualifiers::OCL_ExplicitNone: 4564 // okay 4565 break; 4566 4567 case Qualifiers::OCL_Weak: 4568 case Qualifiers::OCL_Strong: 4569 case Qualifiers::OCL_Autoreleasing: 4570 // FIXME: Can this happen? By this point, ValType should be known 4571 // to be trivially copyable. 4572 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4573 << ValType << Ptr->getSourceRange(); 4574 return ExprError(); 4575 } 4576 4577 // All atomic operations have an overload which takes a pointer to a volatile 4578 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4579 // into the result or the other operands. Similarly atomic_load takes a 4580 // pointer to a const 'A'. 4581 ValType.removeLocalVolatile(); 4582 ValType.removeLocalConst(); 4583 QualType ResultType = ValType; 4584 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4585 Form == Init) 4586 ResultType = Context.VoidTy; 4587 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4588 ResultType = Context.BoolTy; 4589 4590 // The type of a parameter passed 'by value'. In the GNU atomics, such 4591 // arguments are actually passed as pointers. 4592 QualType ByValType = ValType; // 'CP' 4593 bool IsPassedByAddress = false; 4594 if (!IsC11 && !IsN) { 4595 ByValType = Ptr->getType(); 4596 IsPassedByAddress = true; 4597 } 4598 4599 SmallVector<Expr *, 5> APIOrderedArgs; 4600 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4601 APIOrderedArgs.push_back(Args[0]); 4602 switch (Form) { 4603 case Init: 4604 case Load: 4605 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4606 break; 4607 case LoadCopy: 4608 case Copy: 4609 case Arithmetic: 4610 case Xchg: 4611 APIOrderedArgs.push_back(Args[2]); // Val1 4612 APIOrderedArgs.push_back(Args[1]); // Order 4613 break; 4614 case GNUXchg: 4615 APIOrderedArgs.push_back(Args[2]); // Val1 4616 APIOrderedArgs.push_back(Args[3]); // Val2 4617 APIOrderedArgs.push_back(Args[1]); // Order 4618 break; 4619 case C11CmpXchg: 4620 APIOrderedArgs.push_back(Args[2]); // Val1 4621 APIOrderedArgs.push_back(Args[4]); // Val2 4622 APIOrderedArgs.push_back(Args[1]); // Order 4623 APIOrderedArgs.push_back(Args[3]); // OrderFail 4624 break; 4625 case GNUCmpXchg: 4626 APIOrderedArgs.push_back(Args[2]); // Val1 4627 APIOrderedArgs.push_back(Args[4]); // Val2 4628 APIOrderedArgs.push_back(Args[5]); // Weak 4629 APIOrderedArgs.push_back(Args[1]); // Order 4630 APIOrderedArgs.push_back(Args[3]); // OrderFail 4631 break; 4632 } 4633 } else 4634 APIOrderedArgs.append(Args.begin(), Args.end()); 4635 4636 // The first argument's non-CV pointer type is used to deduce the type of 4637 // subsequent arguments, except for: 4638 // - weak flag (always converted to bool) 4639 // - memory order (always converted to int) 4640 // - scope (always converted to int) 4641 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4642 QualType Ty; 4643 if (i < NumVals[Form] + 1) { 4644 switch (i) { 4645 case 0: 4646 // The first argument is always a pointer. It has a fixed type. 4647 // It is always dereferenced, a nullptr is undefined. 4648 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4649 // Nothing else to do: we already know all we want about this pointer. 4650 continue; 4651 case 1: 4652 // The second argument is the non-atomic operand. For arithmetic, this 4653 // is always passed by value, and for a compare_exchange it is always 4654 // passed by address. For the rest, GNU uses by-address and C11 uses 4655 // by-value. 4656 assert(Form != Load); 4657 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4658 Ty = ValType; 4659 else if (Form == Copy || Form == Xchg) { 4660 if (IsPassedByAddress) { 4661 // The value pointer is always dereferenced, a nullptr is undefined. 4662 CheckNonNullArgument(*this, APIOrderedArgs[i], 4663 ExprRange.getBegin()); 4664 } 4665 Ty = ByValType; 4666 } else if (Form == Arithmetic) 4667 Ty = Context.getPointerDiffType(); 4668 else { 4669 Expr *ValArg = APIOrderedArgs[i]; 4670 // The value pointer is always dereferenced, a nullptr is undefined. 4671 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4672 LangAS AS = LangAS::Default; 4673 // Keep address space of non-atomic pointer type. 4674 if (const PointerType *PtrTy = 4675 ValArg->getType()->getAs<PointerType>()) { 4676 AS = PtrTy->getPointeeType().getAddressSpace(); 4677 } 4678 Ty = Context.getPointerType( 4679 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4680 } 4681 break; 4682 case 2: 4683 // The third argument to compare_exchange / GNU exchange is the desired 4684 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4685 if (IsPassedByAddress) 4686 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4687 Ty = ByValType; 4688 break; 4689 case 3: 4690 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4691 Ty = Context.BoolTy; 4692 break; 4693 } 4694 } else { 4695 // The order(s) and scope are always converted to int. 4696 Ty = Context.IntTy; 4697 } 4698 4699 InitializedEntity Entity = 4700 InitializedEntity::InitializeParameter(Context, Ty, false); 4701 ExprResult Arg = APIOrderedArgs[i]; 4702 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4703 if (Arg.isInvalid()) 4704 return true; 4705 APIOrderedArgs[i] = Arg.get(); 4706 } 4707 4708 // Permute the arguments into a 'consistent' order. 4709 SmallVector<Expr*, 5> SubExprs; 4710 SubExprs.push_back(Ptr); 4711 switch (Form) { 4712 case Init: 4713 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4714 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4715 break; 4716 case Load: 4717 SubExprs.push_back(APIOrderedArgs[1]); // Order 4718 break; 4719 case LoadCopy: 4720 case Copy: 4721 case Arithmetic: 4722 case Xchg: 4723 SubExprs.push_back(APIOrderedArgs[2]); // Order 4724 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4725 break; 4726 case GNUXchg: 4727 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4728 SubExprs.push_back(APIOrderedArgs[3]); // Order 4729 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4730 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4731 break; 4732 case C11CmpXchg: 4733 SubExprs.push_back(APIOrderedArgs[3]); // Order 4734 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4735 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4736 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4737 break; 4738 case GNUCmpXchg: 4739 SubExprs.push_back(APIOrderedArgs[4]); // Order 4740 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4741 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4742 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4743 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4744 break; 4745 } 4746 4747 if (SubExprs.size() >= 2 && Form != Init) { 4748 llvm::APSInt Result(32); 4749 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4750 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4751 Diag(SubExprs[1]->getBeginLoc(), 4752 diag::warn_atomic_op_has_invalid_memory_order) 4753 << SubExprs[1]->getSourceRange(); 4754 } 4755 4756 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4757 auto *Scope = Args[Args.size() - 1]; 4758 llvm::APSInt Result(32); 4759 if (Scope->isIntegerConstantExpr(Result, Context) && 4760 !ScopeModel->isValid(Result.getZExtValue())) { 4761 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4762 << Scope->getSourceRange(); 4763 } 4764 SubExprs.push_back(Scope); 4765 } 4766 4767 AtomicExpr *AE = new (Context) 4768 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4769 4770 if ((Op == AtomicExpr::AO__c11_atomic_load || 4771 Op == AtomicExpr::AO__c11_atomic_store || 4772 Op == AtomicExpr::AO__opencl_atomic_load || 4773 Op == AtomicExpr::AO__opencl_atomic_store ) && 4774 Context.AtomicUsesUnsupportedLibcall(AE)) 4775 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4776 << ((Op == AtomicExpr::AO__c11_atomic_load || 4777 Op == AtomicExpr::AO__opencl_atomic_load) 4778 ? 0 4779 : 1); 4780 4781 return AE; 4782 } 4783 4784 /// checkBuiltinArgument - Given a call to a builtin function, perform 4785 /// normal type-checking on the given argument, updating the call in 4786 /// place. This is useful when a builtin function requires custom 4787 /// type-checking for some of its arguments but not necessarily all of 4788 /// them. 4789 /// 4790 /// Returns true on error. 4791 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4792 FunctionDecl *Fn = E->getDirectCallee(); 4793 assert(Fn && "builtin call without direct callee!"); 4794 4795 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4796 InitializedEntity Entity = 4797 InitializedEntity::InitializeParameter(S.Context, Param); 4798 4799 ExprResult Arg = E->getArg(0); 4800 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4801 if (Arg.isInvalid()) 4802 return true; 4803 4804 E->setArg(ArgIndex, Arg.get()); 4805 return false; 4806 } 4807 4808 /// We have a call to a function like __sync_fetch_and_add, which is an 4809 /// overloaded function based on the pointer type of its first argument. 4810 /// The main BuildCallExpr routines have already promoted the types of 4811 /// arguments because all of these calls are prototyped as void(...). 4812 /// 4813 /// This function goes through and does final semantic checking for these 4814 /// builtins, as well as generating any warnings. 4815 ExprResult 4816 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4817 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4818 Expr *Callee = TheCall->getCallee(); 4819 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4820 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4821 4822 // Ensure that we have at least one argument to do type inference from. 4823 if (TheCall->getNumArgs() < 1) { 4824 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4825 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4826 return ExprError(); 4827 } 4828 4829 // Inspect the first argument of the atomic builtin. This should always be 4830 // a pointer type, whose element is an integral scalar or pointer type. 4831 // Because it is a pointer type, we don't have to worry about any implicit 4832 // casts here. 4833 // FIXME: We don't allow floating point scalars as input. 4834 Expr *FirstArg = TheCall->getArg(0); 4835 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4836 if (FirstArgResult.isInvalid()) 4837 return ExprError(); 4838 FirstArg = FirstArgResult.get(); 4839 TheCall->setArg(0, FirstArg); 4840 4841 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4842 if (!pointerType) { 4843 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4844 << FirstArg->getType() << FirstArg->getSourceRange(); 4845 return ExprError(); 4846 } 4847 4848 QualType ValType = pointerType->getPointeeType(); 4849 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4850 !ValType->isBlockPointerType()) { 4851 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4852 << FirstArg->getType() << FirstArg->getSourceRange(); 4853 return ExprError(); 4854 } 4855 4856 if (ValType.isConstQualified()) { 4857 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4858 << FirstArg->getType() << FirstArg->getSourceRange(); 4859 return ExprError(); 4860 } 4861 4862 switch (ValType.getObjCLifetime()) { 4863 case Qualifiers::OCL_None: 4864 case Qualifiers::OCL_ExplicitNone: 4865 // okay 4866 break; 4867 4868 case Qualifiers::OCL_Weak: 4869 case Qualifiers::OCL_Strong: 4870 case Qualifiers::OCL_Autoreleasing: 4871 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4872 << ValType << FirstArg->getSourceRange(); 4873 return ExprError(); 4874 } 4875 4876 // Strip any qualifiers off ValType. 4877 ValType = ValType.getUnqualifiedType(); 4878 4879 // The majority of builtins return a value, but a few have special return 4880 // types, so allow them to override appropriately below. 4881 QualType ResultType = ValType; 4882 4883 // We need to figure out which concrete builtin this maps onto. For example, 4884 // __sync_fetch_and_add with a 2 byte object turns into 4885 // __sync_fetch_and_add_2. 4886 #define BUILTIN_ROW(x) \ 4887 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4888 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4889 4890 static const unsigned BuiltinIndices[][5] = { 4891 BUILTIN_ROW(__sync_fetch_and_add), 4892 BUILTIN_ROW(__sync_fetch_and_sub), 4893 BUILTIN_ROW(__sync_fetch_and_or), 4894 BUILTIN_ROW(__sync_fetch_and_and), 4895 BUILTIN_ROW(__sync_fetch_and_xor), 4896 BUILTIN_ROW(__sync_fetch_and_nand), 4897 4898 BUILTIN_ROW(__sync_add_and_fetch), 4899 BUILTIN_ROW(__sync_sub_and_fetch), 4900 BUILTIN_ROW(__sync_and_and_fetch), 4901 BUILTIN_ROW(__sync_or_and_fetch), 4902 BUILTIN_ROW(__sync_xor_and_fetch), 4903 BUILTIN_ROW(__sync_nand_and_fetch), 4904 4905 BUILTIN_ROW(__sync_val_compare_and_swap), 4906 BUILTIN_ROW(__sync_bool_compare_and_swap), 4907 BUILTIN_ROW(__sync_lock_test_and_set), 4908 BUILTIN_ROW(__sync_lock_release), 4909 BUILTIN_ROW(__sync_swap) 4910 }; 4911 #undef BUILTIN_ROW 4912 4913 // Determine the index of the size. 4914 unsigned SizeIndex; 4915 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4916 case 1: SizeIndex = 0; break; 4917 case 2: SizeIndex = 1; break; 4918 case 4: SizeIndex = 2; break; 4919 case 8: SizeIndex = 3; break; 4920 case 16: SizeIndex = 4; break; 4921 default: 4922 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4923 << FirstArg->getType() << FirstArg->getSourceRange(); 4924 return ExprError(); 4925 } 4926 4927 // Each of these builtins has one pointer argument, followed by some number of 4928 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4929 // that we ignore. Find out which row of BuiltinIndices to read from as well 4930 // as the number of fixed args. 4931 unsigned BuiltinID = FDecl->getBuiltinID(); 4932 unsigned BuiltinIndex, NumFixed = 1; 4933 bool WarnAboutSemanticsChange = false; 4934 switch (BuiltinID) { 4935 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4936 case Builtin::BI__sync_fetch_and_add: 4937 case Builtin::BI__sync_fetch_and_add_1: 4938 case Builtin::BI__sync_fetch_and_add_2: 4939 case Builtin::BI__sync_fetch_and_add_4: 4940 case Builtin::BI__sync_fetch_and_add_8: 4941 case Builtin::BI__sync_fetch_and_add_16: 4942 BuiltinIndex = 0; 4943 break; 4944 4945 case Builtin::BI__sync_fetch_and_sub: 4946 case Builtin::BI__sync_fetch_and_sub_1: 4947 case Builtin::BI__sync_fetch_and_sub_2: 4948 case Builtin::BI__sync_fetch_and_sub_4: 4949 case Builtin::BI__sync_fetch_and_sub_8: 4950 case Builtin::BI__sync_fetch_and_sub_16: 4951 BuiltinIndex = 1; 4952 break; 4953 4954 case Builtin::BI__sync_fetch_and_or: 4955 case Builtin::BI__sync_fetch_and_or_1: 4956 case Builtin::BI__sync_fetch_and_or_2: 4957 case Builtin::BI__sync_fetch_and_or_4: 4958 case Builtin::BI__sync_fetch_and_or_8: 4959 case Builtin::BI__sync_fetch_and_or_16: 4960 BuiltinIndex = 2; 4961 break; 4962 4963 case Builtin::BI__sync_fetch_and_and: 4964 case Builtin::BI__sync_fetch_and_and_1: 4965 case Builtin::BI__sync_fetch_and_and_2: 4966 case Builtin::BI__sync_fetch_and_and_4: 4967 case Builtin::BI__sync_fetch_and_and_8: 4968 case Builtin::BI__sync_fetch_and_and_16: 4969 BuiltinIndex = 3; 4970 break; 4971 4972 case Builtin::BI__sync_fetch_and_xor: 4973 case Builtin::BI__sync_fetch_and_xor_1: 4974 case Builtin::BI__sync_fetch_and_xor_2: 4975 case Builtin::BI__sync_fetch_and_xor_4: 4976 case Builtin::BI__sync_fetch_and_xor_8: 4977 case Builtin::BI__sync_fetch_and_xor_16: 4978 BuiltinIndex = 4; 4979 break; 4980 4981 case Builtin::BI__sync_fetch_and_nand: 4982 case Builtin::BI__sync_fetch_and_nand_1: 4983 case Builtin::BI__sync_fetch_and_nand_2: 4984 case Builtin::BI__sync_fetch_and_nand_4: 4985 case Builtin::BI__sync_fetch_and_nand_8: 4986 case Builtin::BI__sync_fetch_and_nand_16: 4987 BuiltinIndex = 5; 4988 WarnAboutSemanticsChange = true; 4989 break; 4990 4991 case Builtin::BI__sync_add_and_fetch: 4992 case Builtin::BI__sync_add_and_fetch_1: 4993 case Builtin::BI__sync_add_and_fetch_2: 4994 case Builtin::BI__sync_add_and_fetch_4: 4995 case Builtin::BI__sync_add_and_fetch_8: 4996 case Builtin::BI__sync_add_and_fetch_16: 4997 BuiltinIndex = 6; 4998 break; 4999 5000 case Builtin::BI__sync_sub_and_fetch: 5001 case Builtin::BI__sync_sub_and_fetch_1: 5002 case Builtin::BI__sync_sub_and_fetch_2: 5003 case Builtin::BI__sync_sub_and_fetch_4: 5004 case Builtin::BI__sync_sub_and_fetch_8: 5005 case Builtin::BI__sync_sub_and_fetch_16: 5006 BuiltinIndex = 7; 5007 break; 5008 5009 case Builtin::BI__sync_and_and_fetch: 5010 case Builtin::BI__sync_and_and_fetch_1: 5011 case Builtin::BI__sync_and_and_fetch_2: 5012 case Builtin::BI__sync_and_and_fetch_4: 5013 case Builtin::BI__sync_and_and_fetch_8: 5014 case Builtin::BI__sync_and_and_fetch_16: 5015 BuiltinIndex = 8; 5016 break; 5017 5018 case Builtin::BI__sync_or_and_fetch: 5019 case Builtin::BI__sync_or_and_fetch_1: 5020 case Builtin::BI__sync_or_and_fetch_2: 5021 case Builtin::BI__sync_or_and_fetch_4: 5022 case Builtin::BI__sync_or_and_fetch_8: 5023 case Builtin::BI__sync_or_and_fetch_16: 5024 BuiltinIndex = 9; 5025 break; 5026 5027 case Builtin::BI__sync_xor_and_fetch: 5028 case Builtin::BI__sync_xor_and_fetch_1: 5029 case Builtin::BI__sync_xor_and_fetch_2: 5030 case Builtin::BI__sync_xor_and_fetch_4: 5031 case Builtin::BI__sync_xor_and_fetch_8: 5032 case Builtin::BI__sync_xor_and_fetch_16: 5033 BuiltinIndex = 10; 5034 break; 5035 5036 case Builtin::BI__sync_nand_and_fetch: 5037 case Builtin::BI__sync_nand_and_fetch_1: 5038 case Builtin::BI__sync_nand_and_fetch_2: 5039 case Builtin::BI__sync_nand_and_fetch_4: 5040 case Builtin::BI__sync_nand_and_fetch_8: 5041 case Builtin::BI__sync_nand_and_fetch_16: 5042 BuiltinIndex = 11; 5043 WarnAboutSemanticsChange = true; 5044 break; 5045 5046 case Builtin::BI__sync_val_compare_and_swap: 5047 case Builtin::BI__sync_val_compare_and_swap_1: 5048 case Builtin::BI__sync_val_compare_and_swap_2: 5049 case Builtin::BI__sync_val_compare_and_swap_4: 5050 case Builtin::BI__sync_val_compare_and_swap_8: 5051 case Builtin::BI__sync_val_compare_and_swap_16: 5052 BuiltinIndex = 12; 5053 NumFixed = 2; 5054 break; 5055 5056 case Builtin::BI__sync_bool_compare_and_swap: 5057 case Builtin::BI__sync_bool_compare_and_swap_1: 5058 case Builtin::BI__sync_bool_compare_and_swap_2: 5059 case Builtin::BI__sync_bool_compare_and_swap_4: 5060 case Builtin::BI__sync_bool_compare_and_swap_8: 5061 case Builtin::BI__sync_bool_compare_and_swap_16: 5062 BuiltinIndex = 13; 5063 NumFixed = 2; 5064 ResultType = Context.BoolTy; 5065 break; 5066 5067 case Builtin::BI__sync_lock_test_and_set: 5068 case Builtin::BI__sync_lock_test_and_set_1: 5069 case Builtin::BI__sync_lock_test_and_set_2: 5070 case Builtin::BI__sync_lock_test_and_set_4: 5071 case Builtin::BI__sync_lock_test_and_set_8: 5072 case Builtin::BI__sync_lock_test_and_set_16: 5073 BuiltinIndex = 14; 5074 break; 5075 5076 case Builtin::BI__sync_lock_release: 5077 case Builtin::BI__sync_lock_release_1: 5078 case Builtin::BI__sync_lock_release_2: 5079 case Builtin::BI__sync_lock_release_4: 5080 case Builtin::BI__sync_lock_release_8: 5081 case Builtin::BI__sync_lock_release_16: 5082 BuiltinIndex = 15; 5083 NumFixed = 0; 5084 ResultType = Context.VoidTy; 5085 break; 5086 5087 case Builtin::BI__sync_swap: 5088 case Builtin::BI__sync_swap_1: 5089 case Builtin::BI__sync_swap_2: 5090 case Builtin::BI__sync_swap_4: 5091 case Builtin::BI__sync_swap_8: 5092 case Builtin::BI__sync_swap_16: 5093 BuiltinIndex = 16; 5094 break; 5095 } 5096 5097 // Now that we know how many fixed arguments we expect, first check that we 5098 // have at least that many. 5099 if (TheCall->getNumArgs() < 1+NumFixed) { 5100 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5101 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5102 << Callee->getSourceRange(); 5103 return ExprError(); 5104 } 5105 5106 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5107 << Callee->getSourceRange(); 5108 5109 if (WarnAboutSemanticsChange) { 5110 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5111 << Callee->getSourceRange(); 5112 } 5113 5114 // Get the decl for the concrete builtin from this, we can tell what the 5115 // concrete integer type we should convert to is. 5116 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5117 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5118 FunctionDecl *NewBuiltinDecl; 5119 if (NewBuiltinID == BuiltinID) 5120 NewBuiltinDecl = FDecl; 5121 else { 5122 // Perform builtin lookup to avoid redeclaring it. 5123 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5124 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5125 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5126 assert(Res.getFoundDecl()); 5127 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5128 if (!NewBuiltinDecl) 5129 return ExprError(); 5130 } 5131 5132 // The first argument --- the pointer --- has a fixed type; we 5133 // deduce the types of the rest of the arguments accordingly. Walk 5134 // the remaining arguments, converting them to the deduced value type. 5135 for (unsigned i = 0; i != NumFixed; ++i) { 5136 ExprResult Arg = TheCall->getArg(i+1); 5137 5138 // GCC does an implicit conversion to the pointer or integer ValType. This 5139 // can fail in some cases (1i -> int**), check for this error case now. 5140 // Initialize the argument. 5141 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5142 ValType, /*consume*/ false); 5143 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5144 if (Arg.isInvalid()) 5145 return ExprError(); 5146 5147 // Okay, we have something that *can* be converted to the right type. Check 5148 // to see if there is a potentially weird extension going on here. This can 5149 // happen when you do an atomic operation on something like an char* and 5150 // pass in 42. The 42 gets converted to char. This is even more strange 5151 // for things like 45.123 -> char, etc. 5152 // FIXME: Do this check. 5153 TheCall->setArg(i+1, Arg.get()); 5154 } 5155 5156 // Create a new DeclRefExpr to refer to the new decl. 5157 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5158 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5159 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5160 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5161 5162 // Set the callee in the CallExpr. 5163 // FIXME: This loses syntactic information. 5164 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5165 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5166 CK_BuiltinFnToFnPtr); 5167 TheCall->setCallee(PromotedCall.get()); 5168 5169 // Change the result type of the call to match the original value type. This 5170 // is arbitrary, but the codegen for these builtins ins design to handle it 5171 // gracefully. 5172 TheCall->setType(ResultType); 5173 5174 return TheCallResult; 5175 } 5176 5177 /// SemaBuiltinNontemporalOverloaded - We have a call to 5178 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5179 /// overloaded function based on the pointer type of its last argument. 5180 /// 5181 /// This function goes through and does final semantic checking for these 5182 /// builtins. 5183 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5184 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5185 DeclRefExpr *DRE = 5186 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5187 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5188 unsigned BuiltinID = FDecl->getBuiltinID(); 5189 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5190 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5191 "Unexpected nontemporal load/store builtin!"); 5192 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5193 unsigned numArgs = isStore ? 2 : 1; 5194 5195 // Ensure that we have the proper number of arguments. 5196 if (checkArgCount(*this, TheCall, numArgs)) 5197 return ExprError(); 5198 5199 // Inspect the last argument of the nontemporal builtin. This should always 5200 // be a pointer type, from which we imply the type of the memory access. 5201 // Because it is a pointer type, we don't have to worry about any implicit 5202 // casts here. 5203 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5204 ExprResult PointerArgResult = 5205 DefaultFunctionArrayLvalueConversion(PointerArg); 5206 5207 if (PointerArgResult.isInvalid()) 5208 return ExprError(); 5209 PointerArg = PointerArgResult.get(); 5210 TheCall->setArg(numArgs - 1, PointerArg); 5211 5212 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5213 if (!pointerType) { 5214 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5215 << PointerArg->getType() << PointerArg->getSourceRange(); 5216 return ExprError(); 5217 } 5218 5219 QualType ValType = pointerType->getPointeeType(); 5220 5221 // Strip any qualifiers off ValType. 5222 ValType = ValType.getUnqualifiedType(); 5223 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5224 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5225 !ValType->isVectorType()) { 5226 Diag(DRE->getBeginLoc(), 5227 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5228 << PointerArg->getType() << PointerArg->getSourceRange(); 5229 return ExprError(); 5230 } 5231 5232 if (!isStore) { 5233 TheCall->setType(ValType); 5234 return TheCallResult; 5235 } 5236 5237 ExprResult ValArg = TheCall->getArg(0); 5238 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5239 Context, ValType, /*consume*/ false); 5240 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5241 if (ValArg.isInvalid()) 5242 return ExprError(); 5243 5244 TheCall->setArg(0, ValArg.get()); 5245 TheCall->setType(Context.VoidTy); 5246 return TheCallResult; 5247 } 5248 5249 /// CheckObjCString - Checks that the argument to the builtin 5250 /// CFString constructor is correct 5251 /// Note: It might also make sense to do the UTF-16 conversion here (would 5252 /// simplify the backend). 5253 bool Sema::CheckObjCString(Expr *Arg) { 5254 Arg = Arg->IgnoreParenCasts(); 5255 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5256 5257 if (!Literal || !Literal->isAscii()) { 5258 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5259 << Arg->getSourceRange(); 5260 return true; 5261 } 5262 5263 if (Literal->containsNonAsciiOrNull()) { 5264 StringRef String = Literal->getString(); 5265 unsigned NumBytes = String.size(); 5266 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5267 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5268 llvm::UTF16 *ToPtr = &ToBuf[0]; 5269 5270 llvm::ConversionResult Result = 5271 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5272 ToPtr + NumBytes, llvm::strictConversion); 5273 // Check for conversion failure. 5274 if (Result != llvm::conversionOK) 5275 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5276 << Arg->getSourceRange(); 5277 } 5278 return false; 5279 } 5280 5281 /// CheckObjCString - Checks that the format string argument to the os_log() 5282 /// and os_trace() functions is correct, and converts it to const char *. 5283 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5284 Arg = Arg->IgnoreParenCasts(); 5285 auto *Literal = dyn_cast<StringLiteral>(Arg); 5286 if (!Literal) { 5287 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5288 Literal = ObjcLiteral->getString(); 5289 } 5290 } 5291 5292 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5293 return ExprError( 5294 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5295 << Arg->getSourceRange()); 5296 } 5297 5298 ExprResult Result(Literal); 5299 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5300 InitializedEntity Entity = 5301 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5302 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5303 return Result; 5304 } 5305 5306 /// Check that the user is calling the appropriate va_start builtin for the 5307 /// target and calling convention. 5308 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5309 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5310 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5311 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5312 TT.getArch() == llvm::Triple::aarch64_32); 5313 bool IsWindows = TT.isOSWindows(); 5314 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5315 if (IsX64 || IsAArch64) { 5316 CallingConv CC = CC_C; 5317 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5318 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5319 if (IsMSVAStart) { 5320 // Don't allow this in System V ABI functions. 5321 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5322 return S.Diag(Fn->getBeginLoc(), 5323 diag::err_ms_va_start_used_in_sysv_function); 5324 } else { 5325 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5326 // On x64 Windows, don't allow this in System V ABI functions. 5327 // (Yes, that means there's no corresponding way to support variadic 5328 // System V ABI functions on Windows.) 5329 if ((IsWindows && CC == CC_X86_64SysV) || 5330 (!IsWindows && CC == CC_Win64)) 5331 return S.Diag(Fn->getBeginLoc(), 5332 diag::err_va_start_used_in_wrong_abi_function) 5333 << !IsWindows; 5334 } 5335 return false; 5336 } 5337 5338 if (IsMSVAStart) 5339 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5340 return false; 5341 } 5342 5343 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5344 ParmVarDecl **LastParam = nullptr) { 5345 // Determine whether the current function, block, or obj-c method is variadic 5346 // and get its parameter list. 5347 bool IsVariadic = false; 5348 ArrayRef<ParmVarDecl *> Params; 5349 DeclContext *Caller = S.CurContext; 5350 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5351 IsVariadic = Block->isVariadic(); 5352 Params = Block->parameters(); 5353 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5354 IsVariadic = FD->isVariadic(); 5355 Params = FD->parameters(); 5356 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5357 IsVariadic = MD->isVariadic(); 5358 // FIXME: This isn't correct for methods (results in bogus warning). 5359 Params = MD->parameters(); 5360 } else if (isa<CapturedDecl>(Caller)) { 5361 // We don't support va_start in a CapturedDecl. 5362 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5363 return true; 5364 } else { 5365 // This must be some other declcontext that parses exprs. 5366 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5367 return true; 5368 } 5369 5370 if (!IsVariadic) { 5371 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5372 return true; 5373 } 5374 5375 if (LastParam) 5376 *LastParam = Params.empty() ? nullptr : Params.back(); 5377 5378 return false; 5379 } 5380 5381 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5382 /// for validity. Emit an error and return true on failure; return false 5383 /// on success. 5384 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5385 Expr *Fn = TheCall->getCallee(); 5386 5387 if (checkVAStartABI(*this, BuiltinID, Fn)) 5388 return true; 5389 5390 if (TheCall->getNumArgs() > 2) { 5391 Diag(TheCall->getArg(2)->getBeginLoc(), 5392 diag::err_typecheck_call_too_many_args) 5393 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5394 << Fn->getSourceRange() 5395 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5396 (*(TheCall->arg_end() - 1))->getEndLoc()); 5397 return true; 5398 } 5399 5400 if (TheCall->getNumArgs() < 2) { 5401 return Diag(TheCall->getEndLoc(), 5402 diag::err_typecheck_call_too_few_args_at_least) 5403 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5404 } 5405 5406 // Type-check the first argument normally. 5407 if (checkBuiltinArgument(*this, TheCall, 0)) 5408 return true; 5409 5410 // Check that the current function is variadic, and get its last parameter. 5411 ParmVarDecl *LastParam; 5412 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5413 return true; 5414 5415 // Verify that the second argument to the builtin is the last argument of the 5416 // current function or method. 5417 bool SecondArgIsLastNamedArgument = false; 5418 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5419 5420 // These are valid if SecondArgIsLastNamedArgument is false after the next 5421 // block. 5422 QualType Type; 5423 SourceLocation ParamLoc; 5424 bool IsCRegister = false; 5425 5426 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5427 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5428 SecondArgIsLastNamedArgument = PV == LastParam; 5429 5430 Type = PV->getType(); 5431 ParamLoc = PV->getLocation(); 5432 IsCRegister = 5433 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5434 } 5435 } 5436 5437 if (!SecondArgIsLastNamedArgument) 5438 Diag(TheCall->getArg(1)->getBeginLoc(), 5439 diag::warn_second_arg_of_va_start_not_last_named_param); 5440 else if (IsCRegister || Type->isReferenceType() || 5441 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5442 // Promotable integers are UB, but enumerations need a bit of 5443 // extra checking to see what their promotable type actually is. 5444 if (!Type->isPromotableIntegerType()) 5445 return false; 5446 if (!Type->isEnumeralType()) 5447 return true; 5448 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5449 return !(ED && 5450 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5451 }()) { 5452 unsigned Reason = 0; 5453 if (Type->isReferenceType()) Reason = 1; 5454 else if (IsCRegister) Reason = 2; 5455 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5456 Diag(ParamLoc, diag::note_parameter_type) << Type; 5457 } 5458 5459 TheCall->setType(Context.VoidTy); 5460 return false; 5461 } 5462 5463 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5464 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5465 // const char *named_addr); 5466 5467 Expr *Func = Call->getCallee(); 5468 5469 if (Call->getNumArgs() < 3) 5470 return Diag(Call->getEndLoc(), 5471 diag::err_typecheck_call_too_few_args_at_least) 5472 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5473 5474 // Type-check the first argument normally. 5475 if (checkBuiltinArgument(*this, Call, 0)) 5476 return true; 5477 5478 // Check that the current function is variadic. 5479 if (checkVAStartIsInVariadicFunction(*this, Func)) 5480 return true; 5481 5482 // __va_start on Windows does not validate the parameter qualifiers 5483 5484 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5485 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5486 5487 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5488 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5489 5490 const QualType &ConstCharPtrTy = 5491 Context.getPointerType(Context.CharTy.withConst()); 5492 if (!Arg1Ty->isPointerType() || 5493 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5494 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5495 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5496 << 0 /* qualifier difference */ 5497 << 3 /* parameter mismatch */ 5498 << 2 << Arg1->getType() << ConstCharPtrTy; 5499 5500 const QualType SizeTy = Context.getSizeType(); 5501 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5502 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5503 << Arg2->getType() << SizeTy << 1 /* different class */ 5504 << 0 /* qualifier difference */ 5505 << 3 /* parameter mismatch */ 5506 << 3 << Arg2->getType() << SizeTy; 5507 5508 return false; 5509 } 5510 5511 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5512 /// friends. This is declared to take (...), so we have to check everything. 5513 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5514 if (TheCall->getNumArgs() < 2) 5515 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5516 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5517 if (TheCall->getNumArgs() > 2) 5518 return Diag(TheCall->getArg(2)->getBeginLoc(), 5519 diag::err_typecheck_call_too_many_args) 5520 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5521 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5522 (*(TheCall->arg_end() - 1))->getEndLoc()); 5523 5524 ExprResult OrigArg0 = TheCall->getArg(0); 5525 ExprResult OrigArg1 = TheCall->getArg(1); 5526 5527 // Do standard promotions between the two arguments, returning their common 5528 // type. 5529 QualType Res = UsualArithmeticConversions( 5530 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5531 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5532 return true; 5533 5534 // Make sure any conversions are pushed back into the call; this is 5535 // type safe since unordered compare builtins are declared as "_Bool 5536 // foo(...)". 5537 TheCall->setArg(0, OrigArg0.get()); 5538 TheCall->setArg(1, OrigArg1.get()); 5539 5540 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5541 return false; 5542 5543 // If the common type isn't a real floating type, then the arguments were 5544 // invalid for this operation. 5545 if (Res.isNull() || !Res->isRealFloatingType()) 5546 return Diag(OrigArg0.get()->getBeginLoc(), 5547 diag::err_typecheck_call_invalid_ordered_compare) 5548 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5549 << SourceRange(OrigArg0.get()->getBeginLoc(), 5550 OrigArg1.get()->getEndLoc()); 5551 5552 return false; 5553 } 5554 5555 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5556 /// __builtin_isnan and friends. This is declared to take (...), so we have 5557 /// to check everything. We expect the last argument to be a floating point 5558 /// value. 5559 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5560 if (TheCall->getNumArgs() < NumArgs) 5561 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5562 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5563 if (TheCall->getNumArgs() > NumArgs) 5564 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5565 diag::err_typecheck_call_too_many_args) 5566 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5567 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5568 (*(TheCall->arg_end() - 1))->getEndLoc()); 5569 5570 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5571 // on all preceding parameters just being int. Try all of those. 5572 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5573 Expr *Arg = TheCall->getArg(i); 5574 5575 if (Arg->isTypeDependent()) 5576 return false; 5577 5578 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5579 5580 if (Res.isInvalid()) 5581 return true; 5582 TheCall->setArg(i, Res.get()); 5583 } 5584 5585 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5586 5587 if (OrigArg->isTypeDependent()) 5588 return false; 5589 5590 // Usual Unary Conversions will convert half to float, which we want for 5591 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5592 // type how it is, but do normal L->Rvalue conversions. 5593 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5594 OrigArg = UsualUnaryConversions(OrigArg).get(); 5595 else 5596 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5597 TheCall->setArg(NumArgs - 1, OrigArg); 5598 5599 // This operation requires a non-_Complex floating-point number. 5600 if (!OrigArg->getType()->isRealFloatingType()) 5601 return Diag(OrigArg->getBeginLoc(), 5602 diag::err_typecheck_call_invalid_unary_fp) 5603 << OrigArg->getType() << OrigArg->getSourceRange(); 5604 5605 return false; 5606 } 5607 5608 // Customized Sema Checking for VSX builtins that have the following signature: 5609 // vector [...] builtinName(vector [...], vector [...], const int); 5610 // Which takes the same type of vectors (any legal vector type) for the first 5611 // two arguments and takes compile time constant for the third argument. 5612 // Example builtins are : 5613 // vector double vec_xxpermdi(vector double, vector double, int); 5614 // vector short vec_xxsldwi(vector short, vector short, int); 5615 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5616 unsigned ExpectedNumArgs = 3; 5617 if (TheCall->getNumArgs() < ExpectedNumArgs) 5618 return Diag(TheCall->getEndLoc(), 5619 diag::err_typecheck_call_too_few_args_at_least) 5620 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5621 << TheCall->getSourceRange(); 5622 5623 if (TheCall->getNumArgs() > ExpectedNumArgs) 5624 return Diag(TheCall->getEndLoc(), 5625 diag::err_typecheck_call_too_many_args_at_most) 5626 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5627 << TheCall->getSourceRange(); 5628 5629 // Check the third argument is a compile time constant 5630 llvm::APSInt Value; 5631 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5632 return Diag(TheCall->getBeginLoc(), 5633 diag::err_vsx_builtin_nonconstant_argument) 5634 << 3 /* argument index */ << TheCall->getDirectCallee() 5635 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5636 TheCall->getArg(2)->getEndLoc()); 5637 5638 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5639 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5640 5641 // Check the type of argument 1 and argument 2 are vectors. 5642 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5643 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5644 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5645 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5646 << TheCall->getDirectCallee() 5647 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5648 TheCall->getArg(1)->getEndLoc()); 5649 } 5650 5651 // Check the first two arguments are the same type. 5652 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5653 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5654 << TheCall->getDirectCallee() 5655 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5656 TheCall->getArg(1)->getEndLoc()); 5657 } 5658 5659 // When default clang type checking is turned off and the customized type 5660 // checking is used, the returning type of the function must be explicitly 5661 // set. Otherwise it is _Bool by default. 5662 TheCall->setType(Arg1Ty); 5663 5664 return false; 5665 } 5666 5667 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5668 // This is declared to take (...), so we have to check everything. 5669 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5670 if (TheCall->getNumArgs() < 2) 5671 return ExprError(Diag(TheCall->getEndLoc(), 5672 diag::err_typecheck_call_too_few_args_at_least) 5673 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5674 << TheCall->getSourceRange()); 5675 5676 // Determine which of the following types of shufflevector we're checking: 5677 // 1) unary, vector mask: (lhs, mask) 5678 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5679 QualType resType = TheCall->getArg(0)->getType(); 5680 unsigned numElements = 0; 5681 5682 if (!TheCall->getArg(0)->isTypeDependent() && 5683 !TheCall->getArg(1)->isTypeDependent()) { 5684 QualType LHSType = TheCall->getArg(0)->getType(); 5685 QualType RHSType = TheCall->getArg(1)->getType(); 5686 5687 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5688 return ExprError( 5689 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5690 << TheCall->getDirectCallee() 5691 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5692 TheCall->getArg(1)->getEndLoc())); 5693 5694 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5695 unsigned numResElements = TheCall->getNumArgs() - 2; 5696 5697 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5698 // with mask. If so, verify that RHS is an integer vector type with the 5699 // same number of elts as lhs. 5700 if (TheCall->getNumArgs() == 2) { 5701 if (!RHSType->hasIntegerRepresentation() || 5702 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5703 return ExprError(Diag(TheCall->getBeginLoc(), 5704 diag::err_vec_builtin_incompatible_vector) 5705 << TheCall->getDirectCallee() 5706 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5707 TheCall->getArg(1)->getEndLoc())); 5708 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5709 return ExprError(Diag(TheCall->getBeginLoc(), 5710 diag::err_vec_builtin_incompatible_vector) 5711 << TheCall->getDirectCallee() 5712 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5713 TheCall->getArg(1)->getEndLoc())); 5714 } else if (numElements != numResElements) { 5715 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5716 resType = Context.getVectorType(eltType, numResElements, 5717 VectorType::GenericVector); 5718 } 5719 } 5720 5721 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5722 if (TheCall->getArg(i)->isTypeDependent() || 5723 TheCall->getArg(i)->isValueDependent()) 5724 continue; 5725 5726 llvm::APSInt Result(32); 5727 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5728 return ExprError(Diag(TheCall->getBeginLoc(), 5729 diag::err_shufflevector_nonconstant_argument) 5730 << TheCall->getArg(i)->getSourceRange()); 5731 5732 // Allow -1 which will be translated to undef in the IR. 5733 if (Result.isSigned() && Result.isAllOnesValue()) 5734 continue; 5735 5736 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5737 return ExprError(Diag(TheCall->getBeginLoc(), 5738 diag::err_shufflevector_argument_too_large) 5739 << TheCall->getArg(i)->getSourceRange()); 5740 } 5741 5742 SmallVector<Expr*, 32> exprs; 5743 5744 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5745 exprs.push_back(TheCall->getArg(i)); 5746 TheCall->setArg(i, nullptr); 5747 } 5748 5749 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5750 TheCall->getCallee()->getBeginLoc(), 5751 TheCall->getRParenLoc()); 5752 } 5753 5754 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5755 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5756 SourceLocation BuiltinLoc, 5757 SourceLocation RParenLoc) { 5758 ExprValueKind VK = VK_RValue; 5759 ExprObjectKind OK = OK_Ordinary; 5760 QualType DstTy = TInfo->getType(); 5761 QualType SrcTy = E->getType(); 5762 5763 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5764 return ExprError(Diag(BuiltinLoc, 5765 diag::err_convertvector_non_vector) 5766 << E->getSourceRange()); 5767 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5768 return ExprError(Diag(BuiltinLoc, 5769 diag::err_convertvector_non_vector_type)); 5770 5771 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5772 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5773 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5774 if (SrcElts != DstElts) 5775 return ExprError(Diag(BuiltinLoc, 5776 diag::err_convertvector_incompatible_vector) 5777 << E->getSourceRange()); 5778 } 5779 5780 return new (Context) 5781 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5782 } 5783 5784 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5785 // This is declared to take (const void*, ...) and can take two 5786 // optional constant int args. 5787 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5788 unsigned NumArgs = TheCall->getNumArgs(); 5789 5790 if (NumArgs > 3) 5791 return Diag(TheCall->getEndLoc(), 5792 diag::err_typecheck_call_too_many_args_at_most) 5793 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5794 5795 // Argument 0 is checked for us and the remaining arguments must be 5796 // constant integers. 5797 for (unsigned i = 1; i != NumArgs; ++i) 5798 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5799 return true; 5800 5801 return false; 5802 } 5803 5804 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5805 // __assume does not evaluate its arguments, and should warn if its argument 5806 // has side effects. 5807 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5808 Expr *Arg = TheCall->getArg(0); 5809 if (Arg->isInstantiationDependent()) return false; 5810 5811 if (Arg->HasSideEffects(Context)) 5812 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5813 << Arg->getSourceRange() 5814 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5815 5816 return false; 5817 } 5818 5819 /// Handle __builtin_alloca_with_align. This is declared 5820 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5821 /// than 8. 5822 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5823 // The alignment must be a constant integer. 5824 Expr *Arg = TheCall->getArg(1); 5825 5826 // We can't check the value of a dependent argument. 5827 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5828 if (const auto *UE = 5829 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5830 if (UE->getKind() == UETT_AlignOf || 5831 UE->getKind() == UETT_PreferredAlignOf) 5832 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5833 << Arg->getSourceRange(); 5834 5835 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5836 5837 if (!Result.isPowerOf2()) 5838 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5839 << Arg->getSourceRange(); 5840 5841 if (Result < Context.getCharWidth()) 5842 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5843 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5844 5845 if (Result > std::numeric_limits<int32_t>::max()) 5846 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5847 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5848 } 5849 5850 return false; 5851 } 5852 5853 /// Handle __builtin_assume_aligned. This is declared 5854 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5855 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5856 unsigned NumArgs = TheCall->getNumArgs(); 5857 5858 if (NumArgs > 3) 5859 return Diag(TheCall->getEndLoc(), 5860 diag::err_typecheck_call_too_many_args_at_most) 5861 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5862 5863 // The alignment must be a constant integer. 5864 Expr *Arg = TheCall->getArg(1); 5865 5866 // We can't check the value of a dependent argument. 5867 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5868 llvm::APSInt Result; 5869 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5870 return true; 5871 5872 if (!Result.isPowerOf2()) 5873 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5874 << Arg->getSourceRange(); 5875 5876 if (Result > Sema::MaximumAlignment) 5877 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5878 << Arg->getSourceRange() << Sema::MaximumAlignment; 5879 } 5880 5881 if (NumArgs > 2) { 5882 ExprResult Arg(TheCall->getArg(2)); 5883 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5884 Context.getSizeType(), false); 5885 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5886 if (Arg.isInvalid()) return true; 5887 TheCall->setArg(2, Arg.get()); 5888 } 5889 5890 return false; 5891 } 5892 5893 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5894 unsigned BuiltinID = 5895 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5896 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5897 5898 unsigned NumArgs = TheCall->getNumArgs(); 5899 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5900 if (NumArgs < NumRequiredArgs) { 5901 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5902 << 0 /* function call */ << NumRequiredArgs << NumArgs 5903 << TheCall->getSourceRange(); 5904 } 5905 if (NumArgs >= NumRequiredArgs + 0x100) { 5906 return Diag(TheCall->getEndLoc(), 5907 diag::err_typecheck_call_too_many_args_at_most) 5908 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5909 << TheCall->getSourceRange(); 5910 } 5911 unsigned i = 0; 5912 5913 // For formatting call, check buffer arg. 5914 if (!IsSizeCall) { 5915 ExprResult Arg(TheCall->getArg(i)); 5916 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5917 Context, Context.VoidPtrTy, false); 5918 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5919 if (Arg.isInvalid()) 5920 return true; 5921 TheCall->setArg(i, Arg.get()); 5922 i++; 5923 } 5924 5925 // Check string literal arg. 5926 unsigned FormatIdx = i; 5927 { 5928 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5929 if (Arg.isInvalid()) 5930 return true; 5931 TheCall->setArg(i, Arg.get()); 5932 i++; 5933 } 5934 5935 // Make sure variadic args are scalar. 5936 unsigned FirstDataArg = i; 5937 while (i < NumArgs) { 5938 ExprResult Arg = DefaultVariadicArgumentPromotion( 5939 TheCall->getArg(i), VariadicFunction, nullptr); 5940 if (Arg.isInvalid()) 5941 return true; 5942 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5943 if (ArgSize.getQuantity() >= 0x100) { 5944 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5945 << i << (int)ArgSize.getQuantity() << 0xff 5946 << TheCall->getSourceRange(); 5947 } 5948 TheCall->setArg(i, Arg.get()); 5949 i++; 5950 } 5951 5952 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5953 // call to avoid duplicate diagnostics. 5954 if (!IsSizeCall) { 5955 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5956 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5957 bool Success = CheckFormatArguments( 5958 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5959 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5960 CheckedVarArgs); 5961 if (!Success) 5962 return true; 5963 } 5964 5965 if (IsSizeCall) { 5966 TheCall->setType(Context.getSizeType()); 5967 } else { 5968 TheCall->setType(Context.VoidPtrTy); 5969 } 5970 return false; 5971 } 5972 5973 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5974 /// TheCall is a constant expression. 5975 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5976 llvm::APSInt &Result) { 5977 Expr *Arg = TheCall->getArg(ArgNum); 5978 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5979 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5980 5981 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5982 5983 if (!Arg->isIntegerConstantExpr(Result, Context)) 5984 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5985 << FDecl->getDeclName() << Arg->getSourceRange(); 5986 5987 return false; 5988 } 5989 5990 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5991 /// TheCall is a constant expression in the range [Low, High]. 5992 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5993 int Low, int High, bool RangeIsError) { 5994 if (isConstantEvaluated()) 5995 return false; 5996 llvm::APSInt Result; 5997 5998 // We can't check the value of a dependent argument. 5999 Expr *Arg = TheCall->getArg(ArgNum); 6000 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6001 return false; 6002 6003 // Check constant-ness first. 6004 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6005 return true; 6006 6007 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6008 if (RangeIsError) 6009 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6010 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6011 else 6012 // Defer the warning until we know if the code will be emitted so that 6013 // dead code can ignore this. 6014 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6015 PDiag(diag::warn_argument_invalid_range) 6016 << Result.toString(10) << Low << High 6017 << Arg->getSourceRange()); 6018 } 6019 6020 return false; 6021 } 6022 6023 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6024 /// TheCall is a constant expression is a multiple of Num.. 6025 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6026 unsigned Num) { 6027 llvm::APSInt Result; 6028 6029 // We can't check the value of a dependent argument. 6030 Expr *Arg = TheCall->getArg(ArgNum); 6031 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6032 return false; 6033 6034 // Check constant-ness first. 6035 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6036 return true; 6037 6038 if (Result.getSExtValue() % Num != 0) 6039 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6040 << Num << Arg->getSourceRange(); 6041 6042 return false; 6043 } 6044 6045 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6046 /// constant expression representing a power of 2. 6047 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6048 llvm::APSInt Result; 6049 6050 // We can't check the value of a dependent argument. 6051 Expr *Arg = TheCall->getArg(ArgNum); 6052 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6053 return false; 6054 6055 // Check constant-ness first. 6056 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6057 return true; 6058 6059 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6060 // and only if x is a power of 2. 6061 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6062 return false; 6063 6064 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6065 << Arg->getSourceRange(); 6066 } 6067 6068 static bool IsShiftedByte(llvm::APSInt Value) { 6069 if (Value.isNegative()) 6070 return false; 6071 6072 // Check if it's a shifted byte, by shifting it down 6073 while (true) { 6074 // If the value fits in the bottom byte, the check passes. 6075 if (Value < 0x100) 6076 return true; 6077 6078 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6079 // fails. 6080 if ((Value & 0xFF) != 0) 6081 return false; 6082 6083 // If the bottom 8 bits are all 0, but something above that is nonzero, 6084 // then shifting the value right by 8 bits won't affect whether it's a 6085 // shifted byte or not. So do that, and go round again. 6086 Value >>= 8; 6087 } 6088 } 6089 6090 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6091 /// a constant expression representing an arbitrary byte value shifted left by 6092 /// a multiple of 8 bits. 6093 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6094 unsigned ArgBits) { 6095 llvm::APSInt Result; 6096 6097 // We can't check the value of a dependent argument. 6098 Expr *Arg = TheCall->getArg(ArgNum); 6099 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6100 return false; 6101 6102 // Check constant-ness first. 6103 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6104 return true; 6105 6106 // Truncate to the given size. 6107 Result = Result.getLoBits(ArgBits); 6108 Result.setIsUnsigned(true); 6109 6110 if (IsShiftedByte(Result)) 6111 return false; 6112 6113 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6114 << Arg->getSourceRange(); 6115 } 6116 6117 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6118 /// TheCall is a constant expression representing either a shifted byte value, 6119 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6120 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6121 /// Arm MVE intrinsics. 6122 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6123 int ArgNum, 6124 unsigned ArgBits) { 6125 llvm::APSInt Result; 6126 6127 // We can't check the value of a dependent argument. 6128 Expr *Arg = TheCall->getArg(ArgNum); 6129 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6130 return false; 6131 6132 // Check constant-ness first. 6133 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6134 return true; 6135 6136 // Truncate to the given size. 6137 Result = Result.getLoBits(ArgBits); 6138 Result.setIsUnsigned(true); 6139 6140 // Check to see if it's in either of the required forms. 6141 if (IsShiftedByte(Result) || 6142 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6143 return false; 6144 6145 return Diag(TheCall->getBeginLoc(), 6146 diag::err_argument_not_shifted_byte_or_xxff) 6147 << Arg->getSourceRange(); 6148 } 6149 6150 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6151 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6152 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6153 if (checkArgCount(*this, TheCall, 2)) 6154 return true; 6155 Expr *Arg0 = TheCall->getArg(0); 6156 Expr *Arg1 = TheCall->getArg(1); 6157 6158 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6159 if (FirstArg.isInvalid()) 6160 return true; 6161 QualType FirstArgType = FirstArg.get()->getType(); 6162 if (!FirstArgType->isAnyPointerType()) 6163 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6164 << "first" << FirstArgType << Arg0->getSourceRange(); 6165 TheCall->setArg(0, FirstArg.get()); 6166 6167 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6168 if (SecArg.isInvalid()) 6169 return true; 6170 QualType SecArgType = SecArg.get()->getType(); 6171 if (!SecArgType->isIntegerType()) 6172 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6173 << "second" << SecArgType << Arg1->getSourceRange(); 6174 6175 // Derive the return type from the pointer argument. 6176 TheCall->setType(FirstArgType); 6177 return false; 6178 } 6179 6180 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6181 if (checkArgCount(*this, TheCall, 2)) 6182 return true; 6183 6184 Expr *Arg0 = TheCall->getArg(0); 6185 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6186 if (FirstArg.isInvalid()) 6187 return true; 6188 QualType FirstArgType = FirstArg.get()->getType(); 6189 if (!FirstArgType->isAnyPointerType()) 6190 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6191 << "first" << FirstArgType << Arg0->getSourceRange(); 6192 TheCall->setArg(0, FirstArg.get()); 6193 6194 // Derive the return type from the pointer argument. 6195 TheCall->setType(FirstArgType); 6196 6197 // Second arg must be an constant in range [0,15] 6198 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6199 } 6200 6201 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6202 if (checkArgCount(*this, TheCall, 2)) 6203 return true; 6204 Expr *Arg0 = TheCall->getArg(0); 6205 Expr *Arg1 = TheCall->getArg(1); 6206 6207 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6208 if (FirstArg.isInvalid()) 6209 return true; 6210 QualType FirstArgType = FirstArg.get()->getType(); 6211 if (!FirstArgType->isAnyPointerType()) 6212 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6213 << "first" << FirstArgType << Arg0->getSourceRange(); 6214 6215 QualType SecArgType = Arg1->getType(); 6216 if (!SecArgType->isIntegerType()) 6217 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6218 << "second" << SecArgType << Arg1->getSourceRange(); 6219 TheCall->setType(Context.IntTy); 6220 return false; 6221 } 6222 6223 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6224 BuiltinID == AArch64::BI__builtin_arm_stg) { 6225 if (checkArgCount(*this, TheCall, 1)) 6226 return true; 6227 Expr *Arg0 = TheCall->getArg(0); 6228 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6229 if (FirstArg.isInvalid()) 6230 return true; 6231 6232 QualType FirstArgType = FirstArg.get()->getType(); 6233 if (!FirstArgType->isAnyPointerType()) 6234 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6235 << "first" << FirstArgType << Arg0->getSourceRange(); 6236 TheCall->setArg(0, FirstArg.get()); 6237 6238 // Derive the return type from the pointer argument. 6239 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6240 TheCall->setType(FirstArgType); 6241 return false; 6242 } 6243 6244 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6245 Expr *ArgA = TheCall->getArg(0); 6246 Expr *ArgB = TheCall->getArg(1); 6247 6248 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6249 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6250 6251 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6252 return true; 6253 6254 QualType ArgTypeA = ArgExprA.get()->getType(); 6255 QualType ArgTypeB = ArgExprB.get()->getType(); 6256 6257 auto isNull = [&] (Expr *E) -> bool { 6258 return E->isNullPointerConstant( 6259 Context, Expr::NPC_ValueDependentIsNotNull); }; 6260 6261 // argument should be either a pointer or null 6262 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6263 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6264 << "first" << ArgTypeA << ArgA->getSourceRange(); 6265 6266 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6267 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6268 << "second" << ArgTypeB << ArgB->getSourceRange(); 6269 6270 // Ensure Pointee types are compatible 6271 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6272 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6273 QualType pointeeA = ArgTypeA->getPointeeType(); 6274 QualType pointeeB = ArgTypeB->getPointeeType(); 6275 if (!Context.typesAreCompatible( 6276 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6277 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6278 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6279 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6280 << ArgB->getSourceRange(); 6281 } 6282 } 6283 6284 // at least one argument should be pointer type 6285 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6286 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6287 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6288 6289 if (isNull(ArgA)) // adopt type of the other pointer 6290 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6291 6292 if (isNull(ArgB)) 6293 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6294 6295 TheCall->setArg(0, ArgExprA.get()); 6296 TheCall->setArg(1, ArgExprB.get()); 6297 TheCall->setType(Context.LongLongTy); 6298 return false; 6299 } 6300 assert(false && "Unhandled ARM MTE intrinsic"); 6301 return true; 6302 } 6303 6304 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6305 /// TheCall is an ARM/AArch64 special register string literal. 6306 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6307 int ArgNum, unsigned ExpectedFieldNum, 6308 bool AllowName) { 6309 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6310 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6311 BuiltinID == ARM::BI__builtin_arm_rsr || 6312 BuiltinID == ARM::BI__builtin_arm_rsrp || 6313 BuiltinID == ARM::BI__builtin_arm_wsr || 6314 BuiltinID == ARM::BI__builtin_arm_wsrp; 6315 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6316 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6317 BuiltinID == AArch64::BI__builtin_arm_rsr || 6318 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6319 BuiltinID == AArch64::BI__builtin_arm_wsr || 6320 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6321 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6322 6323 // We can't check the value of a dependent argument. 6324 Expr *Arg = TheCall->getArg(ArgNum); 6325 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6326 return false; 6327 6328 // Check if the argument is a string literal. 6329 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6330 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6331 << Arg->getSourceRange(); 6332 6333 // Check the type of special register given. 6334 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6335 SmallVector<StringRef, 6> Fields; 6336 Reg.split(Fields, ":"); 6337 6338 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6339 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6340 << Arg->getSourceRange(); 6341 6342 // If the string is the name of a register then we cannot check that it is 6343 // valid here but if the string is of one the forms described in ACLE then we 6344 // can check that the supplied fields are integers and within the valid 6345 // ranges. 6346 if (Fields.size() > 1) { 6347 bool FiveFields = Fields.size() == 5; 6348 6349 bool ValidString = true; 6350 if (IsARMBuiltin) { 6351 ValidString &= Fields[0].startswith_lower("cp") || 6352 Fields[0].startswith_lower("p"); 6353 if (ValidString) 6354 Fields[0] = 6355 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6356 6357 ValidString &= Fields[2].startswith_lower("c"); 6358 if (ValidString) 6359 Fields[2] = Fields[2].drop_front(1); 6360 6361 if (FiveFields) { 6362 ValidString &= Fields[3].startswith_lower("c"); 6363 if (ValidString) 6364 Fields[3] = Fields[3].drop_front(1); 6365 } 6366 } 6367 6368 SmallVector<int, 5> Ranges; 6369 if (FiveFields) 6370 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6371 else 6372 Ranges.append({15, 7, 15}); 6373 6374 for (unsigned i=0; i<Fields.size(); ++i) { 6375 int IntField; 6376 ValidString &= !Fields[i].getAsInteger(10, IntField); 6377 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6378 } 6379 6380 if (!ValidString) 6381 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6382 << Arg->getSourceRange(); 6383 } else if (IsAArch64Builtin && Fields.size() == 1) { 6384 // If the register name is one of those that appear in the condition below 6385 // and the special register builtin being used is one of the write builtins, 6386 // then we require that the argument provided for writing to the register 6387 // is an integer constant expression. This is because it will be lowered to 6388 // an MSR (immediate) instruction, so we need to know the immediate at 6389 // compile time. 6390 if (TheCall->getNumArgs() != 2) 6391 return false; 6392 6393 std::string RegLower = Reg.lower(); 6394 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6395 RegLower != "pan" && RegLower != "uao") 6396 return false; 6397 6398 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6399 } 6400 6401 return false; 6402 } 6403 6404 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6405 /// This checks that the target supports __builtin_longjmp and 6406 /// that val is a constant 1. 6407 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6408 if (!Context.getTargetInfo().hasSjLjLowering()) 6409 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6410 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6411 6412 Expr *Arg = TheCall->getArg(1); 6413 llvm::APSInt Result; 6414 6415 // TODO: This is less than ideal. Overload this to take a value. 6416 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6417 return true; 6418 6419 if (Result != 1) 6420 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6421 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6422 6423 return false; 6424 } 6425 6426 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6427 /// This checks that the target supports __builtin_setjmp. 6428 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6429 if (!Context.getTargetInfo().hasSjLjLowering()) 6430 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6431 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6432 return false; 6433 } 6434 6435 namespace { 6436 6437 class UncoveredArgHandler { 6438 enum { Unknown = -1, AllCovered = -2 }; 6439 6440 signed FirstUncoveredArg = Unknown; 6441 SmallVector<const Expr *, 4> DiagnosticExprs; 6442 6443 public: 6444 UncoveredArgHandler() = default; 6445 6446 bool hasUncoveredArg() const { 6447 return (FirstUncoveredArg >= 0); 6448 } 6449 6450 unsigned getUncoveredArg() const { 6451 assert(hasUncoveredArg() && "no uncovered argument"); 6452 return FirstUncoveredArg; 6453 } 6454 6455 void setAllCovered() { 6456 // A string has been found with all arguments covered, so clear out 6457 // the diagnostics. 6458 DiagnosticExprs.clear(); 6459 FirstUncoveredArg = AllCovered; 6460 } 6461 6462 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6463 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6464 6465 // Don't update if a previous string covers all arguments. 6466 if (FirstUncoveredArg == AllCovered) 6467 return; 6468 6469 // UncoveredArgHandler tracks the highest uncovered argument index 6470 // and with it all the strings that match this index. 6471 if (NewFirstUncoveredArg == FirstUncoveredArg) 6472 DiagnosticExprs.push_back(StrExpr); 6473 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6474 DiagnosticExprs.clear(); 6475 DiagnosticExprs.push_back(StrExpr); 6476 FirstUncoveredArg = NewFirstUncoveredArg; 6477 } 6478 } 6479 6480 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6481 }; 6482 6483 enum StringLiteralCheckType { 6484 SLCT_NotALiteral, 6485 SLCT_UncheckedLiteral, 6486 SLCT_CheckedLiteral 6487 }; 6488 6489 } // namespace 6490 6491 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6492 BinaryOperatorKind BinOpKind, 6493 bool AddendIsRight) { 6494 unsigned BitWidth = Offset.getBitWidth(); 6495 unsigned AddendBitWidth = Addend.getBitWidth(); 6496 // There might be negative interim results. 6497 if (Addend.isUnsigned()) { 6498 Addend = Addend.zext(++AddendBitWidth); 6499 Addend.setIsSigned(true); 6500 } 6501 // Adjust the bit width of the APSInts. 6502 if (AddendBitWidth > BitWidth) { 6503 Offset = Offset.sext(AddendBitWidth); 6504 BitWidth = AddendBitWidth; 6505 } else if (BitWidth > AddendBitWidth) { 6506 Addend = Addend.sext(BitWidth); 6507 } 6508 6509 bool Ov = false; 6510 llvm::APSInt ResOffset = Offset; 6511 if (BinOpKind == BO_Add) 6512 ResOffset = Offset.sadd_ov(Addend, Ov); 6513 else { 6514 assert(AddendIsRight && BinOpKind == BO_Sub && 6515 "operator must be add or sub with addend on the right"); 6516 ResOffset = Offset.ssub_ov(Addend, Ov); 6517 } 6518 6519 // We add an offset to a pointer here so we should support an offset as big as 6520 // possible. 6521 if (Ov) { 6522 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6523 "index (intermediate) result too big"); 6524 Offset = Offset.sext(2 * BitWidth); 6525 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6526 return; 6527 } 6528 6529 Offset = ResOffset; 6530 } 6531 6532 namespace { 6533 6534 // This is a wrapper class around StringLiteral to support offsetted string 6535 // literals as format strings. It takes the offset into account when returning 6536 // the string and its length or the source locations to display notes correctly. 6537 class FormatStringLiteral { 6538 const StringLiteral *FExpr; 6539 int64_t Offset; 6540 6541 public: 6542 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6543 : FExpr(fexpr), Offset(Offset) {} 6544 6545 StringRef getString() const { 6546 return FExpr->getString().drop_front(Offset); 6547 } 6548 6549 unsigned getByteLength() const { 6550 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6551 } 6552 6553 unsigned getLength() const { return FExpr->getLength() - Offset; } 6554 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6555 6556 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6557 6558 QualType getType() const { return FExpr->getType(); } 6559 6560 bool isAscii() const { return FExpr->isAscii(); } 6561 bool isWide() const { return FExpr->isWide(); } 6562 bool isUTF8() const { return FExpr->isUTF8(); } 6563 bool isUTF16() const { return FExpr->isUTF16(); } 6564 bool isUTF32() const { return FExpr->isUTF32(); } 6565 bool isPascal() const { return FExpr->isPascal(); } 6566 6567 SourceLocation getLocationOfByte( 6568 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6569 const TargetInfo &Target, unsigned *StartToken = nullptr, 6570 unsigned *StartTokenByteOffset = nullptr) const { 6571 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6572 StartToken, StartTokenByteOffset); 6573 } 6574 6575 SourceLocation getBeginLoc() const LLVM_READONLY { 6576 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6577 } 6578 6579 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6580 }; 6581 6582 } // namespace 6583 6584 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6585 const Expr *OrigFormatExpr, 6586 ArrayRef<const Expr *> Args, 6587 bool HasVAListArg, unsigned format_idx, 6588 unsigned firstDataArg, 6589 Sema::FormatStringType Type, 6590 bool inFunctionCall, 6591 Sema::VariadicCallType CallType, 6592 llvm::SmallBitVector &CheckedVarArgs, 6593 UncoveredArgHandler &UncoveredArg, 6594 bool IgnoreStringsWithoutSpecifiers); 6595 6596 // Determine if an expression is a string literal or constant string. 6597 // If this function returns false on the arguments to a function expecting a 6598 // format string, we will usually need to emit a warning. 6599 // True string literals are then checked by CheckFormatString. 6600 static StringLiteralCheckType 6601 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6602 bool HasVAListArg, unsigned format_idx, 6603 unsigned firstDataArg, Sema::FormatStringType Type, 6604 Sema::VariadicCallType CallType, bool InFunctionCall, 6605 llvm::SmallBitVector &CheckedVarArgs, 6606 UncoveredArgHandler &UncoveredArg, 6607 llvm::APSInt Offset, 6608 bool IgnoreStringsWithoutSpecifiers = false) { 6609 if (S.isConstantEvaluated()) 6610 return SLCT_NotALiteral; 6611 tryAgain: 6612 assert(Offset.isSigned() && "invalid offset"); 6613 6614 if (E->isTypeDependent() || E->isValueDependent()) 6615 return SLCT_NotALiteral; 6616 6617 E = E->IgnoreParenCasts(); 6618 6619 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6620 // Technically -Wformat-nonliteral does not warn about this case. 6621 // The behavior of printf and friends in this case is implementation 6622 // dependent. Ideally if the format string cannot be null then 6623 // it should have a 'nonnull' attribute in the function prototype. 6624 return SLCT_UncheckedLiteral; 6625 6626 switch (E->getStmtClass()) { 6627 case Stmt::BinaryConditionalOperatorClass: 6628 case Stmt::ConditionalOperatorClass: { 6629 // The expression is a literal if both sub-expressions were, and it was 6630 // completely checked only if both sub-expressions were checked. 6631 const AbstractConditionalOperator *C = 6632 cast<AbstractConditionalOperator>(E); 6633 6634 // Determine whether it is necessary to check both sub-expressions, for 6635 // example, because the condition expression is a constant that can be 6636 // evaluated at compile time. 6637 bool CheckLeft = true, CheckRight = true; 6638 6639 bool Cond; 6640 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6641 S.isConstantEvaluated())) { 6642 if (Cond) 6643 CheckRight = false; 6644 else 6645 CheckLeft = false; 6646 } 6647 6648 // We need to maintain the offsets for the right and the left hand side 6649 // separately to check if every possible indexed expression is a valid 6650 // string literal. They might have different offsets for different string 6651 // literals in the end. 6652 StringLiteralCheckType Left; 6653 if (!CheckLeft) 6654 Left = SLCT_UncheckedLiteral; 6655 else { 6656 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6657 HasVAListArg, format_idx, firstDataArg, 6658 Type, CallType, InFunctionCall, 6659 CheckedVarArgs, UncoveredArg, Offset, 6660 IgnoreStringsWithoutSpecifiers); 6661 if (Left == SLCT_NotALiteral || !CheckRight) { 6662 return Left; 6663 } 6664 } 6665 6666 StringLiteralCheckType Right = checkFormatStringExpr( 6667 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6668 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6669 IgnoreStringsWithoutSpecifiers); 6670 6671 return (CheckLeft && Left < Right) ? Left : Right; 6672 } 6673 6674 case Stmt::ImplicitCastExprClass: 6675 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6676 goto tryAgain; 6677 6678 case Stmt::OpaqueValueExprClass: 6679 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6680 E = src; 6681 goto tryAgain; 6682 } 6683 return SLCT_NotALiteral; 6684 6685 case Stmt::PredefinedExprClass: 6686 // While __func__, etc., are technically not string literals, they 6687 // cannot contain format specifiers and thus are not a security 6688 // liability. 6689 return SLCT_UncheckedLiteral; 6690 6691 case Stmt::DeclRefExprClass: { 6692 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6693 6694 // As an exception, do not flag errors for variables binding to 6695 // const string literals. 6696 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6697 bool isConstant = false; 6698 QualType T = DR->getType(); 6699 6700 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6701 isConstant = AT->getElementType().isConstant(S.Context); 6702 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6703 isConstant = T.isConstant(S.Context) && 6704 PT->getPointeeType().isConstant(S.Context); 6705 } else if (T->isObjCObjectPointerType()) { 6706 // In ObjC, there is usually no "const ObjectPointer" type, 6707 // so don't check if the pointee type is constant. 6708 isConstant = T.isConstant(S.Context); 6709 } 6710 6711 if (isConstant) { 6712 if (const Expr *Init = VD->getAnyInitializer()) { 6713 // Look through initializers like const char c[] = { "foo" } 6714 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6715 if (InitList->isStringLiteralInit()) 6716 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6717 } 6718 return checkFormatStringExpr(S, Init, Args, 6719 HasVAListArg, format_idx, 6720 firstDataArg, Type, CallType, 6721 /*InFunctionCall*/ false, CheckedVarArgs, 6722 UncoveredArg, Offset); 6723 } 6724 } 6725 6726 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6727 // special check to see if the format string is a function parameter 6728 // of the function calling the printf function. If the function 6729 // has an attribute indicating it is a printf-like function, then we 6730 // should suppress warnings concerning non-literals being used in a call 6731 // to a vprintf function. For example: 6732 // 6733 // void 6734 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6735 // va_list ap; 6736 // va_start(ap, fmt); 6737 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6738 // ... 6739 // } 6740 if (HasVAListArg) { 6741 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6742 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6743 int PVIndex = PV->getFunctionScopeIndex() + 1; 6744 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6745 // adjust for implicit parameter 6746 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6747 if (MD->isInstance()) 6748 ++PVIndex; 6749 // We also check if the formats are compatible. 6750 // We can't pass a 'scanf' string to a 'printf' function. 6751 if (PVIndex == PVFormat->getFormatIdx() && 6752 Type == S.GetFormatStringType(PVFormat)) 6753 return SLCT_UncheckedLiteral; 6754 } 6755 } 6756 } 6757 } 6758 } 6759 6760 return SLCT_NotALiteral; 6761 } 6762 6763 case Stmt::CallExprClass: 6764 case Stmt::CXXMemberCallExprClass: { 6765 const CallExpr *CE = cast<CallExpr>(E); 6766 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6767 bool IsFirst = true; 6768 StringLiteralCheckType CommonResult; 6769 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6770 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6771 StringLiteralCheckType Result = checkFormatStringExpr( 6772 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6773 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6774 IgnoreStringsWithoutSpecifiers); 6775 if (IsFirst) { 6776 CommonResult = Result; 6777 IsFirst = false; 6778 } 6779 } 6780 if (!IsFirst) 6781 return CommonResult; 6782 6783 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6784 unsigned BuiltinID = FD->getBuiltinID(); 6785 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6786 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6787 const Expr *Arg = CE->getArg(0); 6788 return checkFormatStringExpr(S, Arg, Args, 6789 HasVAListArg, format_idx, 6790 firstDataArg, Type, CallType, 6791 InFunctionCall, CheckedVarArgs, 6792 UncoveredArg, Offset, 6793 IgnoreStringsWithoutSpecifiers); 6794 } 6795 } 6796 } 6797 6798 return SLCT_NotALiteral; 6799 } 6800 case Stmt::ObjCMessageExprClass: { 6801 const auto *ME = cast<ObjCMessageExpr>(E); 6802 if (const auto *MD = ME->getMethodDecl()) { 6803 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6804 // As a special case heuristic, if we're using the method -[NSBundle 6805 // localizedStringForKey:value:table:], ignore any key strings that lack 6806 // format specifiers. The idea is that if the key doesn't have any 6807 // format specifiers then its probably just a key to map to the 6808 // localized strings. If it does have format specifiers though, then its 6809 // likely that the text of the key is the format string in the 6810 // programmer's language, and should be checked. 6811 const ObjCInterfaceDecl *IFace; 6812 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6813 IFace->getIdentifier()->isStr("NSBundle") && 6814 MD->getSelector().isKeywordSelector( 6815 {"localizedStringForKey", "value", "table"})) { 6816 IgnoreStringsWithoutSpecifiers = true; 6817 } 6818 6819 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6820 return checkFormatStringExpr( 6821 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6822 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6823 IgnoreStringsWithoutSpecifiers); 6824 } 6825 } 6826 6827 return SLCT_NotALiteral; 6828 } 6829 case Stmt::ObjCStringLiteralClass: 6830 case Stmt::StringLiteralClass: { 6831 const StringLiteral *StrE = nullptr; 6832 6833 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6834 StrE = ObjCFExpr->getString(); 6835 else 6836 StrE = cast<StringLiteral>(E); 6837 6838 if (StrE) { 6839 if (Offset.isNegative() || Offset > StrE->getLength()) { 6840 // TODO: It would be better to have an explicit warning for out of 6841 // bounds literals. 6842 return SLCT_NotALiteral; 6843 } 6844 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6845 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6846 firstDataArg, Type, InFunctionCall, CallType, 6847 CheckedVarArgs, UncoveredArg, 6848 IgnoreStringsWithoutSpecifiers); 6849 return SLCT_CheckedLiteral; 6850 } 6851 6852 return SLCT_NotALiteral; 6853 } 6854 case Stmt::BinaryOperatorClass: { 6855 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6856 6857 // A string literal + an int offset is still a string literal. 6858 if (BinOp->isAdditiveOp()) { 6859 Expr::EvalResult LResult, RResult; 6860 6861 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6862 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6863 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6864 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6865 6866 if (LIsInt != RIsInt) { 6867 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6868 6869 if (LIsInt) { 6870 if (BinOpKind == BO_Add) { 6871 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6872 E = BinOp->getRHS(); 6873 goto tryAgain; 6874 } 6875 } else { 6876 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6877 E = BinOp->getLHS(); 6878 goto tryAgain; 6879 } 6880 } 6881 } 6882 6883 return SLCT_NotALiteral; 6884 } 6885 case Stmt::UnaryOperatorClass: { 6886 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6887 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6888 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6889 Expr::EvalResult IndexResult; 6890 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6891 Expr::SE_NoSideEffects, 6892 S.isConstantEvaluated())) { 6893 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6894 /*RHS is int*/ true); 6895 E = ASE->getBase(); 6896 goto tryAgain; 6897 } 6898 } 6899 6900 return SLCT_NotALiteral; 6901 } 6902 6903 default: 6904 return SLCT_NotALiteral; 6905 } 6906 } 6907 6908 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6909 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6910 .Case("scanf", FST_Scanf) 6911 .Cases("printf", "printf0", FST_Printf) 6912 .Cases("NSString", "CFString", FST_NSString) 6913 .Case("strftime", FST_Strftime) 6914 .Case("strfmon", FST_Strfmon) 6915 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6916 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6917 .Case("os_trace", FST_OSLog) 6918 .Case("os_log", FST_OSLog) 6919 .Default(FST_Unknown); 6920 } 6921 6922 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6923 /// functions) for correct use of format strings. 6924 /// Returns true if a format string has been fully checked. 6925 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6926 ArrayRef<const Expr *> Args, 6927 bool IsCXXMember, 6928 VariadicCallType CallType, 6929 SourceLocation Loc, SourceRange Range, 6930 llvm::SmallBitVector &CheckedVarArgs) { 6931 FormatStringInfo FSI; 6932 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6933 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6934 FSI.FirstDataArg, GetFormatStringType(Format), 6935 CallType, Loc, Range, CheckedVarArgs); 6936 return false; 6937 } 6938 6939 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6940 bool HasVAListArg, unsigned format_idx, 6941 unsigned firstDataArg, FormatStringType Type, 6942 VariadicCallType CallType, 6943 SourceLocation Loc, SourceRange Range, 6944 llvm::SmallBitVector &CheckedVarArgs) { 6945 // CHECK: printf/scanf-like function is called with no format string. 6946 if (format_idx >= Args.size()) { 6947 Diag(Loc, diag::warn_missing_format_string) << Range; 6948 return false; 6949 } 6950 6951 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6952 6953 // CHECK: format string is not a string literal. 6954 // 6955 // Dynamically generated format strings are difficult to 6956 // automatically vet at compile time. Requiring that format strings 6957 // are string literals: (1) permits the checking of format strings by 6958 // the compiler and thereby (2) can practically remove the source of 6959 // many format string exploits. 6960 6961 // Format string can be either ObjC string (e.g. @"%d") or 6962 // C string (e.g. "%d") 6963 // ObjC string uses the same format specifiers as C string, so we can use 6964 // the same format string checking logic for both ObjC and C strings. 6965 UncoveredArgHandler UncoveredArg; 6966 StringLiteralCheckType CT = 6967 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6968 format_idx, firstDataArg, Type, CallType, 6969 /*IsFunctionCall*/ true, CheckedVarArgs, 6970 UncoveredArg, 6971 /*no string offset*/ llvm::APSInt(64, false) = 0); 6972 6973 // Generate a diagnostic where an uncovered argument is detected. 6974 if (UncoveredArg.hasUncoveredArg()) { 6975 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6976 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6977 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6978 } 6979 6980 if (CT != SLCT_NotALiteral) 6981 // Literal format string found, check done! 6982 return CT == SLCT_CheckedLiteral; 6983 6984 // Strftime is particular as it always uses a single 'time' argument, 6985 // so it is safe to pass a non-literal string. 6986 if (Type == FST_Strftime) 6987 return false; 6988 6989 // Do not emit diag when the string param is a macro expansion and the 6990 // format is either NSString or CFString. This is a hack to prevent 6991 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6992 // which are usually used in place of NS and CF string literals. 6993 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6994 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6995 return false; 6996 6997 // If there are no arguments specified, warn with -Wformat-security, otherwise 6998 // warn only with -Wformat-nonliteral. 6999 if (Args.size() == firstDataArg) { 7000 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7001 << OrigFormatExpr->getSourceRange(); 7002 switch (Type) { 7003 default: 7004 break; 7005 case FST_Kprintf: 7006 case FST_FreeBSDKPrintf: 7007 case FST_Printf: 7008 Diag(FormatLoc, diag::note_format_security_fixit) 7009 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7010 break; 7011 case FST_NSString: 7012 Diag(FormatLoc, diag::note_format_security_fixit) 7013 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7014 break; 7015 } 7016 } else { 7017 Diag(FormatLoc, diag::warn_format_nonliteral) 7018 << OrigFormatExpr->getSourceRange(); 7019 } 7020 return false; 7021 } 7022 7023 namespace { 7024 7025 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7026 protected: 7027 Sema &S; 7028 const FormatStringLiteral *FExpr; 7029 const Expr *OrigFormatExpr; 7030 const Sema::FormatStringType FSType; 7031 const unsigned FirstDataArg; 7032 const unsigned NumDataArgs; 7033 const char *Beg; // Start of format string. 7034 const bool HasVAListArg; 7035 ArrayRef<const Expr *> Args; 7036 unsigned FormatIdx; 7037 llvm::SmallBitVector CoveredArgs; 7038 bool usesPositionalArgs = false; 7039 bool atFirstArg = true; 7040 bool inFunctionCall; 7041 Sema::VariadicCallType CallType; 7042 llvm::SmallBitVector &CheckedVarArgs; 7043 UncoveredArgHandler &UncoveredArg; 7044 7045 public: 7046 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7047 const Expr *origFormatExpr, 7048 const Sema::FormatStringType type, unsigned firstDataArg, 7049 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7050 ArrayRef<const Expr *> Args, unsigned formatIdx, 7051 bool inFunctionCall, Sema::VariadicCallType callType, 7052 llvm::SmallBitVector &CheckedVarArgs, 7053 UncoveredArgHandler &UncoveredArg) 7054 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7055 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7056 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7057 inFunctionCall(inFunctionCall), CallType(callType), 7058 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7059 CoveredArgs.resize(numDataArgs); 7060 CoveredArgs.reset(); 7061 } 7062 7063 void DoneProcessing(); 7064 7065 void HandleIncompleteSpecifier(const char *startSpecifier, 7066 unsigned specifierLen) override; 7067 7068 void HandleInvalidLengthModifier( 7069 const analyze_format_string::FormatSpecifier &FS, 7070 const analyze_format_string::ConversionSpecifier &CS, 7071 const char *startSpecifier, unsigned specifierLen, 7072 unsigned DiagID); 7073 7074 void HandleNonStandardLengthModifier( 7075 const analyze_format_string::FormatSpecifier &FS, 7076 const char *startSpecifier, unsigned specifierLen); 7077 7078 void HandleNonStandardConversionSpecifier( 7079 const analyze_format_string::ConversionSpecifier &CS, 7080 const char *startSpecifier, unsigned specifierLen); 7081 7082 void HandlePosition(const char *startPos, unsigned posLen) override; 7083 7084 void HandleInvalidPosition(const char *startSpecifier, 7085 unsigned specifierLen, 7086 analyze_format_string::PositionContext p) override; 7087 7088 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7089 7090 void HandleNullChar(const char *nullCharacter) override; 7091 7092 template <typename Range> 7093 static void 7094 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7095 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7096 bool IsStringLocation, Range StringRange, 7097 ArrayRef<FixItHint> Fixit = None); 7098 7099 protected: 7100 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7101 const char *startSpec, 7102 unsigned specifierLen, 7103 const char *csStart, unsigned csLen); 7104 7105 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7106 const char *startSpec, 7107 unsigned specifierLen); 7108 7109 SourceRange getFormatStringRange(); 7110 CharSourceRange getSpecifierRange(const char *startSpecifier, 7111 unsigned specifierLen); 7112 SourceLocation getLocationOfByte(const char *x); 7113 7114 const Expr *getDataArg(unsigned i) const; 7115 7116 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7117 const analyze_format_string::ConversionSpecifier &CS, 7118 const char *startSpecifier, unsigned specifierLen, 7119 unsigned argIndex); 7120 7121 template <typename Range> 7122 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7123 bool IsStringLocation, Range StringRange, 7124 ArrayRef<FixItHint> Fixit = None); 7125 }; 7126 7127 } // namespace 7128 7129 SourceRange CheckFormatHandler::getFormatStringRange() { 7130 return OrigFormatExpr->getSourceRange(); 7131 } 7132 7133 CharSourceRange CheckFormatHandler:: 7134 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7135 SourceLocation Start = getLocationOfByte(startSpecifier); 7136 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7137 7138 // Advance the end SourceLocation by one due to half-open ranges. 7139 End = End.getLocWithOffset(1); 7140 7141 return CharSourceRange::getCharRange(Start, End); 7142 } 7143 7144 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7145 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7146 S.getLangOpts(), S.Context.getTargetInfo()); 7147 } 7148 7149 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7150 unsigned specifierLen){ 7151 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7152 getLocationOfByte(startSpecifier), 7153 /*IsStringLocation*/true, 7154 getSpecifierRange(startSpecifier, specifierLen)); 7155 } 7156 7157 void CheckFormatHandler::HandleInvalidLengthModifier( 7158 const analyze_format_string::FormatSpecifier &FS, 7159 const analyze_format_string::ConversionSpecifier &CS, 7160 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7161 using namespace analyze_format_string; 7162 7163 const LengthModifier &LM = FS.getLengthModifier(); 7164 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7165 7166 // See if we know how to fix this length modifier. 7167 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7168 if (FixedLM) { 7169 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7170 getLocationOfByte(LM.getStart()), 7171 /*IsStringLocation*/true, 7172 getSpecifierRange(startSpecifier, specifierLen)); 7173 7174 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7175 << FixedLM->toString() 7176 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7177 7178 } else { 7179 FixItHint Hint; 7180 if (DiagID == diag::warn_format_nonsensical_length) 7181 Hint = FixItHint::CreateRemoval(LMRange); 7182 7183 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7184 getLocationOfByte(LM.getStart()), 7185 /*IsStringLocation*/true, 7186 getSpecifierRange(startSpecifier, specifierLen), 7187 Hint); 7188 } 7189 } 7190 7191 void CheckFormatHandler::HandleNonStandardLengthModifier( 7192 const analyze_format_string::FormatSpecifier &FS, 7193 const char *startSpecifier, unsigned specifierLen) { 7194 using namespace analyze_format_string; 7195 7196 const LengthModifier &LM = FS.getLengthModifier(); 7197 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7198 7199 // See if we know how to fix this length modifier. 7200 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7201 if (FixedLM) { 7202 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7203 << LM.toString() << 0, 7204 getLocationOfByte(LM.getStart()), 7205 /*IsStringLocation*/true, 7206 getSpecifierRange(startSpecifier, specifierLen)); 7207 7208 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7209 << FixedLM->toString() 7210 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7211 7212 } else { 7213 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7214 << LM.toString() << 0, 7215 getLocationOfByte(LM.getStart()), 7216 /*IsStringLocation*/true, 7217 getSpecifierRange(startSpecifier, specifierLen)); 7218 } 7219 } 7220 7221 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7222 const analyze_format_string::ConversionSpecifier &CS, 7223 const char *startSpecifier, unsigned specifierLen) { 7224 using namespace analyze_format_string; 7225 7226 // See if we know how to fix this conversion specifier. 7227 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7228 if (FixedCS) { 7229 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7230 << CS.toString() << /*conversion specifier*/1, 7231 getLocationOfByte(CS.getStart()), 7232 /*IsStringLocation*/true, 7233 getSpecifierRange(startSpecifier, specifierLen)); 7234 7235 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7236 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7237 << FixedCS->toString() 7238 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7239 } else { 7240 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7241 << CS.toString() << /*conversion specifier*/1, 7242 getLocationOfByte(CS.getStart()), 7243 /*IsStringLocation*/true, 7244 getSpecifierRange(startSpecifier, specifierLen)); 7245 } 7246 } 7247 7248 void CheckFormatHandler::HandlePosition(const char *startPos, 7249 unsigned posLen) { 7250 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7251 getLocationOfByte(startPos), 7252 /*IsStringLocation*/true, 7253 getSpecifierRange(startPos, posLen)); 7254 } 7255 7256 void 7257 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7258 analyze_format_string::PositionContext p) { 7259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7260 << (unsigned) p, 7261 getLocationOfByte(startPos), /*IsStringLocation*/true, 7262 getSpecifierRange(startPos, posLen)); 7263 } 7264 7265 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7266 unsigned posLen) { 7267 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7268 getLocationOfByte(startPos), 7269 /*IsStringLocation*/true, 7270 getSpecifierRange(startPos, posLen)); 7271 } 7272 7273 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7274 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7275 // The presence of a null character is likely an error. 7276 EmitFormatDiagnostic( 7277 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7278 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7279 getFormatStringRange()); 7280 } 7281 } 7282 7283 // Note that this may return NULL if there was an error parsing or building 7284 // one of the argument expressions. 7285 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7286 return Args[FirstDataArg + i]; 7287 } 7288 7289 void CheckFormatHandler::DoneProcessing() { 7290 // Does the number of data arguments exceed the number of 7291 // format conversions in the format string? 7292 if (!HasVAListArg) { 7293 // Find any arguments that weren't covered. 7294 CoveredArgs.flip(); 7295 signed notCoveredArg = CoveredArgs.find_first(); 7296 if (notCoveredArg >= 0) { 7297 assert((unsigned)notCoveredArg < NumDataArgs); 7298 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7299 } else { 7300 UncoveredArg.setAllCovered(); 7301 } 7302 } 7303 } 7304 7305 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7306 const Expr *ArgExpr) { 7307 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7308 "Invalid state"); 7309 7310 if (!ArgExpr) 7311 return; 7312 7313 SourceLocation Loc = ArgExpr->getBeginLoc(); 7314 7315 if (S.getSourceManager().isInSystemMacro(Loc)) 7316 return; 7317 7318 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7319 for (auto E : DiagnosticExprs) 7320 PDiag << E->getSourceRange(); 7321 7322 CheckFormatHandler::EmitFormatDiagnostic( 7323 S, IsFunctionCall, DiagnosticExprs[0], 7324 PDiag, Loc, /*IsStringLocation*/false, 7325 DiagnosticExprs[0]->getSourceRange()); 7326 } 7327 7328 bool 7329 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7330 SourceLocation Loc, 7331 const char *startSpec, 7332 unsigned specifierLen, 7333 const char *csStart, 7334 unsigned csLen) { 7335 bool keepGoing = true; 7336 if (argIndex < NumDataArgs) { 7337 // Consider the argument coverered, even though the specifier doesn't 7338 // make sense. 7339 CoveredArgs.set(argIndex); 7340 } 7341 else { 7342 // If argIndex exceeds the number of data arguments we 7343 // don't issue a warning because that is just a cascade of warnings (and 7344 // they may have intended '%%' anyway). We don't want to continue processing 7345 // the format string after this point, however, as we will like just get 7346 // gibberish when trying to match arguments. 7347 keepGoing = false; 7348 } 7349 7350 StringRef Specifier(csStart, csLen); 7351 7352 // If the specifier in non-printable, it could be the first byte of a UTF-8 7353 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7354 // hex value. 7355 std::string CodePointStr; 7356 if (!llvm::sys::locale::isPrint(*csStart)) { 7357 llvm::UTF32 CodePoint; 7358 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7359 const llvm::UTF8 *E = 7360 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7361 llvm::ConversionResult Result = 7362 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7363 7364 if (Result != llvm::conversionOK) { 7365 unsigned char FirstChar = *csStart; 7366 CodePoint = (llvm::UTF32)FirstChar; 7367 } 7368 7369 llvm::raw_string_ostream OS(CodePointStr); 7370 if (CodePoint < 256) 7371 OS << "\\x" << llvm::format("%02x", CodePoint); 7372 else if (CodePoint <= 0xFFFF) 7373 OS << "\\u" << llvm::format("%04x", CodePoint); 7374 else 7375 OS << "\\U" << llvm::format("%08x", CodePoint); 7376 OS.flush(); 7377 Specifier = CodePointStr; 7378 } 7379 7380 EmitFormatDiagnostic( 7381 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7382 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7383 7384 return keepGoing; 7385 } 7386 7387 void 7388 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7389 const char *startSpec, 7390 unsigned specifierLen) { 7391 EmitFormatDiagnostic( 7392 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7393 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7394 } 7395 7396 bool 7397 CheckFormatHandler::CheckNumArgs( 7398 const analyze_format_string::FormatSpecifier &FS, 7399 const analyze_format_string::ConversionSpecifier &CS, 7400 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7401 7402 if (argIndex >= NumDataArgs) { 7403 PartialDiagnostic PDiag = FS.usesPositionalArg() 7404 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7405 << (argIndex+1) << NumDataArgs) 7406 : S.PDiag(diag::warn_printf_insufficient_data_args); 7407 EmitFormatDiagnostic( 7408 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7409 getSpecifierRange(startSpecifier, specifierLen)); 7410 7411 // Since more arguments than conversion tokens are given, by extension 7412 // all arguments are covered, so mark this as so. 7413 UncoveredArg.setAllCovered(); 7414 return false; 7415 } 7416 return true; 7417 } 7418 7419 template<typename Range> 7420 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7421 SourceLocation Loc, 7422 bool IsStringLocation, 7423 Range StringRange, 7424 ArrayRef<FixItHint> FixIt) { 7425 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7426 Loc, IsStringLocation, StringRange, FixIt); 7427 } 7428 7429 /// If the format string is not within the function call, emit a note 7430 /// so that the function call and string are in diagnostic messages. 7431 /// 7432 /// \param InFunctionCall if true, the format string is within the function 7433 /// call and only one diagnostic message will be produced. Otherwise, an 7434 /// extra note will be emitted pointing to location of the format string. 7435 /// 7436 /// \param ArgumentExpr the expression that is passed as the format string 7437 /// argument in the function call. Used for getting locations when two 7438 /// diagnostics are emitted. 7439 /// 7440 /// \param PDiag the callee should already have provided any strings for the 7441 /// diagnostic message. This function only adds locations and fixits 7442 /// to diagnostics. 7443 /// 7444 /// \param Loc primary location for diagnostic. If two diagnostics are 7445 /// required, one will be at Loc and a new SourceLocation will be created for 7446 /// the other one. 7447 /// 7448 /// \param IsStringLocation if true, Loc points to the format string should be 7449 /// used for the note. Otherwise, Loc points to the argument list and will 7450 /// be used with PDiag. 7451 /// 7452 /// \param StringRange some or all of the string to highlight. This is 7453 /// templated so it can accept either a CharSourceRange or a SourceRange. 7454 /// 7455 /// \param FixIt optional fix it hint for the format string. 7456 template <typename Range> 7457 void CheckFormatHandler::EmitFormatDiagnostic( 7458 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7459 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7460 Range StringRange, ArrayRef<FixItHint> FixIt) { 7461 if (InFunctionCall) { 7462 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7463 D << StringRange; 7464 D << FixIt; 7465 } else { 7466 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7467 << ArgumentExpr->getSourceRange(); 7468 7469 const Sema::SemaDiagnosticBuilder &Note = 7470 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7471 diag::note_format_string_defined); 7472 7473 Note << StringRange; 7474 Note << FixIt; 7475 } 7476 } 7477 7478 //===--- CHECK: Printf format string checking ------------------------------===// 7479 7480 namespace { 7481 7482 class CheckPrintfHandler : public CheckFormatHandler { 7483 public: 7484 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7485 const Expr *origFormatExpr, 7486 const Sema::FormatStringType type, unsigned firstDataArg, 7487 unsigned numDataArgs, bool isObjC, const char *beg, 7488 bool hasVAListArg, ArrayRef<const Expr *> Args, 7489 unsigned formatIdx, bool inFunctionCall, 7490 Sema::VariadicCallType CallType, 7491 llvm::SmallBitVector &CheckedVarArgs, 7492 UncoveredArgHandler &UncoveredArg) 7493 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7494 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7495 inFunctionCall, CallType, CheckedVarArgs, 7496 UncoveredArg) {} 7497 7498 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7499 7500 /// Returns true if '%@' specifiers are allowed in the format string. 7501 bool allowsObjCArg() const { 7502 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7503 FSType == Sema::FST_OSTrace; 7504 } 7505 7506 bool HandleInvalidPrintfConversionSpecifier( 7507 const analyze_printf::PrintfSpecifier &FS, 7508 const char *startSpecifier, 7509 unsigned specifierLen) override; 7510 7511 void handleInvalidMaskType(StringRef MaskType) override; 7512 7513 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7514 const char *startSpecifier, 7515 unsigned specifierLen) override; 7516 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7517 const char *StartSpecifier, 7518 unsigned SpecifierLen, 7519 const Expr *E); 7520 7521 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7522 const char *startSpecifier, unsigned specifierLen); 7523 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7524 const analyze_printf::OptionalAmount &Amt, 7525 unsigned type, 7526 const char *startSpecifier, unsigned specifierLen); 7527 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7528 const analyze_printf::OptionalFlag &flag, 7529 const char *startSpecifier, unsigned specifierLen); 7530 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7531 const analyze_printf::OptionalFlag &ignoredFlag, 7532 const analyze_printf::OptionalFlag &flag, 7533 const char *startSpecifier, unsigned specifierLen); 7534 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7535 const Expr *E); 7536 7537 void HandleEmptyObjCModifierFlag(const char *startFlag, 7538 unsigned flagLen) override; 7539 7540 void HandleInvalidObjCModifierFlag(const char *startFlag, 7541 unsigned flagLen) override; 7542 7543 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7544 const char *flagsEnd, 7545 const char *conversionPosition) 7546 override; 7547 }; 7548 7549 } // namespace 7550 7551 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7552 const analyze_printf::PrintfSpecifier &FS, 7553 const char *startSpecifier, 7554 unsigned specifierLen) { 7555 const analyze_printf::PrintfConversionSpecifier &CS = 7556 FS.getConversionSpecifier(); 7557 7558 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7559 getLocationOfByte(CS.getStart()), 7560 startSpecifier, specifierLen, 7561 CS.getStart(), CS.getLength()); 7562 } 7563 7564 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7565 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7566 } 7567 7568 bool CheckPrintfHandler::HandleAmount( 7569 const analyze_format_string::OptionalAmount &Amt, 7570 unsigned k, const char *startSpecifier, 7571 unsigned specifierLen) { 7572 if (Amt.hasDataArgument()) { 7573 if (!HasVAListArg) { 7574 unsigned argIndex = Amt.getArgIndex(); 7575 if (argIndex >= NumDataArgs) { 7576 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7577 << k, 7578 getLocationOfByte(Amt.getStart()), 7579 /*IsStringLocation*/true, 7580 getSpecifierRange(startSpecifier, specifierLen)); 7581 // Don't do any more checking. We will just emit 7582 // spurious errors. 7583 return false; 7584 } 7585 7586 // Type check the data argument. It should be an 'int'. 7587 // Although not in conformance with C99, we also allow the argument to be 7588 // an 'unsigned int' as that is a reasonably safe case. GCC also 7589 // doesn't emit a warning for that case. 7590 CoveredArgs.set(argIndex); 7591 const Expr *Arg = getDataArg(argIndex); 7592 if (!Arg) 7593 return false; 7594 7595 QualType T = Arg->getType(); 7596 7597 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7598 assert(AT.isValid()); 7599 7600 if (!AT.matchesType(S.Context, T)) { 7601 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7602 << k << AT.getRepresentativeTypeName(S.Context) 7603 << T << Arg->getSourceRange(), 7604 getLocationOfByte(Amt.getStart()), 7605 /*IsStringLocation*/true, 7606 getSpecifierRange(startSpecifier, specifierLen)); 7607 // Don't do any more checking. We will just emit 7608 // spurious errors. 7609 return false; 7610 } 7611 } 7612 } 7613 return true; 7614 } 7615 7616 void CheckPrintfHandler::HandleInvalidAmount( 7617 const analyze_printf::PrintfSpecifier &FS, 7618 const analyze_printf::OptionalAmount &Amt, 7619 unsigned type, 7620 const char *startSpecifier, 7621 unsigned specifierLen) { 7622 const analyze_printf::PrintfConversionSpecifier &CS = 7623 FS.getConversionSpecifier(); 7624 7625 FixItHint fixit = 7626 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7627 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7628 Amt.getConstantLength())) 7629 : FixItHint(); 7630 7631 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7632 << type << CS.toString(), 7633 getLocationOfByte(Amt.getStart()), 7634 /*IsStringLocation*/true, 7635 getSpecifierRange(startSpecifier, specifierLen), 7636 fixit); 7637 } 7638 7639 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7640 const analyze_printf::OptionalFlag &flag, 7641 const char *startSpecifier, 7642 unsigned specifierLen) { 7643 // Warn about pointless flag with a fixit removal. 7644 const analyze_printf::PrintfConversionSpecifier &CS = 7645 FS.getConversionSpecifier(); 7646 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7647 << flag.toString() << CS.toString(), 7648 getLocationOfByte(flag.getPosition()), 7649 /*IsStringLocation*/true, 7650 getSpecifierRange(startSpecifier, specifierLen), 7651 FixItHint::CreateRemoval( 7652 getSpecifierRange(flag.getPosition(), 1))); 7653 } 7654 7655 void CheckPrintfHandler::HandleIgnoredFlag( 7656 const analyze_printf::PrintfSpecifier &FS, 7657 const analyze_printf::OptionalFlag &ignoredFlag, 7658 const analyze_printf::OptionalFlag &flag, 7659 const char *startSpecifier, 7660 unsigned specifierLen) { 7661 // Warn about ignored flag with a fixit removal. 7662 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7663 << ignoredFlag.toString() << flag.toString(), 7664 getLocationOfByte(ignoredFlag.getPosition()), 7665 /*IsStringLocation*/true, 7666 getSpecifierRange(startSpecifier, specifierLen), 7667 FixItHint::CreateRemoval( 7668 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7669 } 7670 7671 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7672 unsigned flagLen) { 7673 // Warn about an empty flag. 7674 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7675 getLocationOfByte(startFlag), 7676 /*IsStringLocation*/true, 7677 getSpecifierRange(startFlag, flagLen)); 7678 } 7679 7680 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7681 unsigned flagLen) { 7682 // Warn about an invalid flag. 7683 auto Range = getSpecifierRange(startFlag, flagLen); 7684 StringRef flag(startFlag, flagLen); 7685 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7686 getLocationOfByte(startFlag), 7687 /*IsStringLocation*/true, 7688 Range, FixItHint::CreateRemoval(Range)); 7689 } 7690 7691 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7692 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7693 // Warn about using '[...]' without a '@' conversion. 7694 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7695 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7696 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7697 getLocationOfByte(conversionPosition), 7698 /*IsStringLocation*/true, 7699 Range, FixItHint::CreateRemoval(Range)); 7700 } 7701 7702 // Determines if the specified is a C++ class or struct containing 7703 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7704 // "c_str()"). 7705 template<typename MemberKind> 7706 static llvm::SmallPtrSet<MemberKind*, 1> 7707 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7708 const RecordType *RT = Ty->getAs<RecordType>(); 7709 llvm::SmallPtrSet<MemberKind*, 1> Results; 7710 7711 if (!RT) 7712 return Results; 7713 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7714 if (!RD || !RD->getDefinition()) 7715 return Results; 7716 7717 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7718 Sema::LookupMemberName); 7719 R.suppressDiagnostics(); 7720 7721 // We just need to include all members of the right kind turned up by the 7722 // filter, at this point. 7723 if (S.LookupQualifiedName(R, RT->getDecl())) 7724 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7725 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7726 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7727 Results.insert(FK); 7728 } 7729 return Results; 7730 } 7731 7732 /// Check if we could call '.c_str()' on an object. 7733 /// 7734 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7735 /// allow the call, or if it would be ambiguous). 7736 bool Sema::hasCStrMethod(const Expr *E) { 7737 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7738 7739 MethodSet Results = 7740 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7741 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7742 MI != ME; ++MI) 7743 if ((*MI)->getMinRequiredArguments() == 0) 7744 return true; 7745 return false; 7746 } 7747 7748 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7749 // better diagnostic if so. AT is assumed to be valid. 7750 // Returns true when a c_str() conversion method is found. 7751 bool CheckPrintfHandler::checkForCStrMembers( 7752 const analyze_printf::ArgType &AT, const Expr *E) { 7753 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7754 7755 MethodSet Results = 7756 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7757 7758 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7759 MI != ME; ++MI) { 7760 const CXXMethodDecl *Method = *MI; 7761 if (Method->getMinRequiredArguments() == 0 && 7762 AT.matchesType(S.Context, Method->getReturnType())) { 7763 // FIXME: Suggest parens if the expression needs them. 7764 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7765 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7766 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7767 return true; 7768 } 7769 } 7770 7771 return false; 7772 } 7773 7774 bool 7775 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7776 &FS, 7777 const char *startSpecifier, 7778 unsigned specifierLen) { 7779 using namespace analyze_format_string; 7780 using namespace analyze_printf; 7781 7782 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7783 7784 if (FS.consumesDataArgument()) { 7785 if (atFirstArg) { 7786 atFirstArg = false; 7787 usesPositionalArgs = FS.usesPositionalArg(); 7788 } 7789 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7790 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7791 startSpecifier, specifierLen); 7792 return false; 7793 } 7794 } 7795 7796 // First check if the field width, precision, and conversion specifier 7797 // have matching data arguments. 7798 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7799 startSpecifier, specifierLen)) { 7800 return false; 7801 } 7802 7803 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7804 startSpecifier, specifierLen)) { 7805 return false; 7806 } 7807 7808 if (!CS.consumesDataArgument()) { 7809 // FIXME: Technically specifying a precision or field width here 7810 // makes no sense. Worth issuing a warning at some point. 7811 return true; 7812 } 7813 7814 // Consume the argument. 7815 unsigned argIndex = FS.getArgIndex(); 7816 if (argIndex < NumDataArgs) { 7817 // The check to see if the argIndex is valid will come later. 7818 // We set the bit here because we may exit early from this 7819 // function if we encounter some other error. 7820 CoveredArgs.set(argIndex); 7821 } 7822 7823 // FreeBSD kernel extensions. 7824 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7825 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7826 // We need at least two arguments. 7827 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7828 return false; 7829 7830 // Claim the second argument. 7831 CoveredArgs.set(argIndex + 1); 7832 7833 // Type check the first argument (int for %b, pointer for %D) 7834 const Expr *Ex = getDataArg(argIndex); 7835 const analyze_printf::ArgType &AT = 7836 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7837 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7838 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7839 EmitFormatDiagnostic( 7840 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7841 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7842 << false << Ex->getSourceRange(), 7843 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7844 getSpecifierRange(startSpecifier, specifierLen)); 7845 7846 // Type check the second argument (char * for both %b and %D) 7847 Ex = getDataArg(argIndex + 1); 7848 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7849 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7850 EmitFormatDiagnostic( 7851 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7852 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7853 << false << Ex->getSourceRange(), 7854 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7855 getSpecifierRange(startSpecifier, specifierLen)); 7856 7857 return true; 7858 } 7859 7860 // Check for using an Objective-C specific conversion specifier 7861 // in a non-ObjC literal. 7862 if (!allowsObjCArg() && CS.isObjCArg()) { 7863 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7864 specifierLen); 7865 } 7866 7867 // %P can only be used with os_log. 7868 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7869 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7870 specifierLen); 7871 } 7872 7873 // %n is not allowed with os_log. 7874 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7875 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7876 getLocationOfByte(CS.getStart()), 7877 /*IsStringLocation*/ false, 7878 getSpecifierRange(startSpecifier, specifierLen)); 7879 7880 return true; 7881 } 7882 7883 // Only scalars are allowed for os_trace. 7884 if (FSType == Sema::FST_OSTrace && 7885 (CS.getKind() == ConversionSpecifier::PArg || 7886 CS.getKind() == ConversionSpecifier::sArg || 7887 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7888 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7889 specifierLen); 7890 } 7891 7892 // Check for use of public/private annotation outside of os_log(). 7893 if (FSType != Sema::FST_OSLog) { 7894 if (FS.isPublic().isSet()) { 7895 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7896 << "public", 7897 getLocationOfByte(FS.isPublic().getPosition()), 7898 /*IsStringLocation*/ false, 7899 getSpecifierRange(startSpecifier, specifierLen)); 7900 } 7901 if (FS.isPrivate().isSet()) { 7902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7903 << "private", 7904 getLocationOfByte(FS.isPrivate().getPosition()), 7905 /*IsStringLocation*/ false, 7906 getSpecifierRange(startSpecifier, specifierLen)); 7907 } 7908 } 7909 7910 // Check for invalid use of field width 7911 if (!FS.hasValidFieldWidth()) { 7912 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7913 startSpecifier, specifierLen); 7914 } 7915 7916 // Check for invalid use of precision 7917 if (!FS.hasValidPrecision()) { 7918 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7919 startSpecifier, specifierLen); 7920 } 7921 7922 // Precision is mandatory for %P specifier. 7923 if (CS.getKind() == ConversionSpecifier::PArg && 7924 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7925 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7926 getLocationOfByte(startSpecifier), 7927 /*IsStringLocation*/ false, 7928 getSpecifierRange(startSpecifier, specifierLen)); 7929 } 7930 7931 // Check each flag does not conflict with any other component. 7932 if (!FS.hasValidThousandsGroupingPrefix()) 7933 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7934 if (!FS.hasValidLeadingZeros()) 7935 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7936 if (!FS.hasValidPlusPrefix()) 7937 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7938 if (!FS.hasValidSpacePrefix()) 7939 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7940 if (!FS.hasValidAlternativeForm()) 7941 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7942 if (!FS.hasValidLeftJustified()) 7943 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7944 7945 // Check that flags are not ignored by another flag 7946 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7947 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7948 startSpecifier, specifierLen); 7949 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7950 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7951 startSpecifier, specifierLen); 7952 7953 // Check the length modifier is valid with the given conversion specifier. 7954 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7955 S.getLangOpts())) 7956 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7957 diag::warn_format_nonsensical_length); 7958 else if (!FS.hasStandardLengthModifier()) 7959 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7960 else if (!FS.hasStandardLengthConversionCombination()) 7961 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7962 diag::warn_format_non_standard_conversion_spec); 7963 7964 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7965 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7966 7967 // The remaining checks depend on the data arguments. 7968 if (HasVAListArg) 7969 return true; 7970 7971 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7972 return false; 7973 7974 const Expr *Arg = getDataArg(argIndex); 7975 if (!Arg) 7976 return true; 7977 7978 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7979 } 7980 7981 static bool requiresParensToAddCast(const Expr *E) { 7982 // FIXME: We should have a general way to reason about operator 7983 // precedence and whether parens are actually needed here. 7984 // Take care of a few common cases where they aren't. 7985 const Expr *Inside = E->IgnoreImpCasts(); 7986 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7987 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7988 7989 switch (Inside->getStmtClass()) { 7990 case Stmt::ArraySubscriptExprClass: 7991 case Stmt::CallExprClass: 7992 case Stmt::CharacterLiteralClass: 7993 case Stmt::CXXBoolLiteralExprClass: 7994 case Stmt::DeclRefExprClass: 7995 case Stmt::FloatingLiteralClass: 7996 case Stmt::IntegerLiteralClass: 7997 case Stmt::MemberExprClass: 7998 case Stmt::ObjCArrayLiteralClass: 7999 case Stmt::ObjCBoolLiteralExprClass: 8000 case Stmt::ObjCBoxedExprClass: 8001 case Stmt::ObjCDictionaryLiteralClass: 8002 case Stmt::ObjCEncodeExprClass: 8003 case Stmt::ObjCIvarRefExprClass: 8004 case Stmt::ObjCMessageExprClass: 8005 case Stmt::ObjCPropertyRefExprClass: 8006 case Stmt::ObjCStringLiteralClass: 8007 case Stmt::ObjCSubscriptRefExprClass: 8008 case Stmt::ParenExprClass: 8009 case Stmt::StringLiteralClass: 8010 case Stmt::UnaryOperatorClass: 8011 return false; 8012 default: 8013 return true; 8014 } 8015 } 8016 8017 static std::pair<QualType, StringRef> 8018 shouldNotPrintDirectly(const ASTContext &Context, 8019 QualType IntendedTy, 8020 const Expr *E) { 8021 // Use a 'while' to peel off layers of typedefs. 8022 QualType TyTy = IntendedTy; 8023 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8024 StringRef Name = UserTy->getDecl()->getName(); 8025 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8026 .Case("CFIndex", Context.getNSIntegerType()) 8027 .Case("NSInteger", Context.getNSIntegerType()) 8028 .Case("NSUInteger", Context.getNSUIntegerType()) 8029 .Case("SInt32", Context.IntTy) 8030 .Case("UInt32", Context.UnsignedIntTy) 8031 .Default(QualType()); 8032 8033 if (!CastTy.isNull()) 8034 return std::make_pair(CastTy, Name); 8035 8036 TyTy = UserTy->desugar(); 8037 } 8038 8039 // Strip parens if necessary. 8040 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8041 return shouldNotPrintDirectly(Context, 8042 PE->getSubExpr()->getType(), 8043 PE->getSubExpr()); 8044 8045 // If this is a conditional expression, then its result type is constructed 8046 // via usual arithmetic conversions and thus there might be no necessary 8047 // typedef sugar there. Recurse to operands to check for NSInteger & 8048 // Co. usage condition. 8049 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8050 QualType TrueTy, FalseTy; 8051 StringRef TrueName, FalseName; 8052 8053 std::tie(TrueTy, TrueName) = 8054 shouldNotPrintDirectly(Context, 8055 CO->getTrueExpr()->getType(), 8056 CO->getTrueExpr()); 8057 std::tie(FalseTy, FalseName) = 8058 shouldNotPrintDirectly(Context, 8059 CO->getFalseExpr()->getType(), 8060 CO->getFalseExpr()); 8061 8062 if (TrueTy == FalseTy) 8063 return std::make_pair(TrueTy, TrueName); 8064 else if (TrueTy.isNull()) 8065 return std::make_pair(FalseTy, FalseName); 8066 else if (FalseTy.isNull()) 8067 return std::make_pair(TrueTy, TrueName); 8068 } 8069 8070 return std::make_pair(QualType(), StringRef()); 8071 } 8072 8073 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8074 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8075 /// type do not count. 8076 static bool 8077 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8078 QualType From = ICE->getSubExpr()->getType(); 8079 QualType To = ICE->getType(); 8080 // It's an integer promotion if the destination type is the promoted 8081 // source type. 8082 if (ICE->getCastKind() == CK_IntegralCast && 8083 From->isPromotableIntegerType() && 8084 S.Context.getPromotedIntegerType(From) == To) 8085 return true; 8086 // Look through vector types, since we do default argument promotion for 8087 // those in OpenCL. 8088 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8089 From = VecTy->getElementType(); 8090 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8091 To = VecTy->getElementType(); 8092 // It's a floating promotion if the source type is a lower rank. 8093 return ICE->getCastKind() == CK_FloatingCast && 8094 S.Context.getFloatingTypeOrder(From, To) < 0; 8095 } 8096 8097 bool 8098 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8099 const char *StartSpecifier, 8100 unsigned SpecifierLen, 8101 const Expr *E) { 8102 using namespace analyze_format_string; 8103 using namespace analyze_printf; 8104 8105 // Now type check the data expression that matches the 8106 // format specifier. 8107 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8108 if (!AT.isValid()) 8109 return true; 8110 8111 QualType ExprTy = E->getType(); 8112 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8113 ExprTy = TET->getUnderlyingExpr()->getType(); 8114 } 8115 8116 // Diagnose attempts to print a boolean value as a character. Unlike other 8117 // -Wformat diagnostics, this is fine from a type perspective, but it still 8118 // doesn't make sense. 8119 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8120 E->isKnownToHaveBooleanValue()) { 8121 const CharSourceRange &CSR = 8122 getSpecifierRange(StartSpecifier, SpecifierLen); 8123 SmallString<4> FSString; 8124 llvm::raw_svector_ostream os(FSString); 8125 FS.toString(os); 8126 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8127 << FSString, 8128 E->getExprLoc(), false, CSR); 8129 return true; 8130 } 8131 8132 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8133 if (Match == analyze_printf::ArgType::Match) 8134 return true; 8135 8136 // Look through argument promotions for our error message's reported type. 8137 // This includes the integral and floating promotions, but excludes array 8138 // and function pointer decay (seeing that an argument intended to be a 8139 // string has type 'char [6]' is probably more confusing than 'char *') and 8140 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8141 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8142 if (isArithmeticArgumentPromotion(S, ICE)) { 8143 E = ICE->getSubExpr(); 8144 ExprTy = E->getType(); 8145 8146 // Check if we didn't match because of an implicit cast from a 'char' 8147 // or 'short' to an 'int'. This is done because printf is a varargs 8148 // function. 8149 if (ICE->getType() == S.Context.IntTy || 8150 ICE->getType() == S.Context.UnsignedIntTy) { 8151 // All further checking is done on the subexpression 8152 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8153 AT.matchesType(S.Context, ExprTy); 8154 if (ImplicitMatch == analyze_printf::ArgType::Match) 8155 return true; 8156 if (ImplicitMatch == ArgType::NoMatchPedantic || 8157 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8158 Match = ImplicitMatch; 8159 } 8160 } 8161 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8162 // Special case for 'a', which has type 'int' in C. 8163 // Note, however, that we do /not/ want to treat multibyte constants like 8164 // 'MooV' as characters! This form is deprecated but still exists. 8165 if (ExprTy == S.Context.IntTy) 8166 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8167 ExprTy = S.Context.CharTy; 8168 } 8169 8170 // Look through enums to their underlying type. 8171 bool IsEnum = false; 8172 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8173 ExprTy = EnumTy->getDecl()->getIntegerType(); 8174 IsEnum = true; 8175 } 8176 8177 // %C in an Objective-C context prints a unichar, not a wchar_t. 8178 // If the argument is an integer of some kind, believe the %C and suggest 8179 // a cast instead of changing the conversion specifier. 8180 QualType IntendedTy = ExprTy; 8181 if (isObjCContext() && 8182 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8183 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8184 !ExprTy->isCharType()) { 8185 // 'unichar' is defined as a typedef of unsigned short, but we should 8186 // prefer using the typedef if it is visible. 8187 IntendedTy = S.Context.UnsignedShortTy; 8188 8189 // While we are here, check if the value is an IntegerLiteral that happens 8190 // to be within the valid range. 8191 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8192 const llvm::APInt &V = IL->getValue(); 8193 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8194 return true; 8195 } 8196 8197 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8198 Sema::LookupOrdinaryName); 8199 if (S.LookupName(Result, S.getCurScope())) { 8200 NamedDecl *ND = Result.getFoundDecl(); 8201 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8202 if (TD->getUnderlyingType() == IntendedTy) 8203 IntendedTy = S.Context.getTypedefType(TD); 8204 } 8205 } 8206 } 8207 8208 // Special-case some of Darwin's platform-independence types by suggesting 8209 // casts to primitive types that are known to be large enough. 8210 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8211 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8212 QualType CastTy; 8213 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8214 if (!CastTy.isNull()) { 8215 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8216 // (long in ASTContext). Only complain to pedants. 8217 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8218 (AT.isSizeT() || AT.isPtrdiffT()) && 8219 AT.matchesType(S.Context, CastTy)) 8220 Match = ArgType::NoMatchPedantic; 8221 IntendedTy = CastTy; 8222 ShouldNotPrintDirectly = true; 8223 } 8224 } 8225 8226 // We may be able to offer a FixItHint if it is a supported type. 8227 PrintfSpecifier fixedFS = FS; 8228 bool Success = 8229 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8230 8231 if (Success) { 8232 // Get the fix string from the fixed format specifier 8233 SmallString<16> buf; 8234 llvm::raw_svector_ostream os(buf); 8235 fixedFS.toString(os); 8236 8237 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8238 8239 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8240 unsigned Diag; 8241 switch (Match) { 8242 case ArgType::Match: llvm_unreachable("expected non-matching"); 8243 case ArgType::NoMatchPedantic: 8244 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8245 break; 8246 case ArgType::NoMatchTypeConfusion: 8247 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8248 break; 8249 case ArgType::NoMatch: 8250 Diag = diag::warn_format_conversion_argument_type_mismatch; 8251 break; 8252 } 8253 8254 // In this case, the specifier is wrong and should be changed to match 8255 // the argument. 8256 EmitFormatDiagnostic(S.PDiag(Diag) 8257 << AT.getRepresentativeTypeName(S.Context) 8258 << IntendedTy << IsEnum << E->getSourceRange(), 8259 E->getBeginLoc(), 8260 /*IsStringLocation*/ false, SpecRange, 8261 FixItHint::CreateReplacement(SpecRange, os.str())); 8262 } else { 8263 // The canonical type for formatting this value is different from the 8264 // actual type of the expression. (This occurs, for example, with Darwin's 8265 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8266 // should be printed as 'long' for 64-bit compatibility.) 8267 // Rather than emitting a normal format/argument mismatch, we want to 8268 // add a cast to the recommended type (and correct the format string 8269 // if necessary). 8270 SmallString<16> CastBuf; 8271 llvm::raw_svector_ostream CastFix(CastBuf); 8272 CastFix << "("; 8273 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8274 CastFix << ")"; 8275 8276 SmallVector<FixItHint,4> Hints; 8277 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8278 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8279 8280 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8281 // If there's already a cast present, just replace it. 8282 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8283 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8284 8285 } else if (!requiresParensToAddCast(E)) { 8286 // If the expression has high enough precedence, 8287 // just write the C-style cast. 8288 Hints.push_back( 8289 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8290 } else { 8291 // Otherwise, add parens around the expression as well as the cast. 8292 CastFix << "("; 8293 Hints.push_back( 8294 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8295 8296 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8297 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8298 } 8299 8300 if (ShouldNotPrintDirectly) { 8301 // The expression has a type that should not be printed directly. 8302 // We extract the name from the typedef because we don't want to show 8303 // the underlying type in the diagnostic. 8304 StringRef Name; 8305 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8306 Name = TypedefTy->getDecl()->getName(); 8307 else 8308 Name = CastTyName; 8309 unsigned Diag = Match == ArgType::NoMatchPedantic 8310 ? diag::warn_format_argument_needs_cast_pedantic 8311 : diag::warn_format_argument_needs_cast; 8312 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8313 << E->getSourceRange(), 8314 E->getBeginLoc(), /*IsStringLocation=*/false, 8315 SpecRange, Hints); 8316 } else { 8317 // In this case, the expression could be printed using a different 8318 // specifier, but we've decided that the specifier is probably correct 8319 // and we should cast instead. Just use the normal warning message. 8320 EmitFormatDiagnostic( 8321 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8322 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8323 << E->getSourceRange(), 8324 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8325 } 8326 } 8327 } else { 8328 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8329 SpecifierLen); 8330 // Since the warning for passing non-POD types to variadic functions 8331 // was deferred until now, we emit a warning for non-POD 8332 // arguments here. 8333 switch (S.isValidVarArgType(ExprTy)) { 8334 case Sema::VAK_Valid: 8335 case Sema::VAK_ValidInCXX11: { 8336 unsigned Diag; 8337 switch (Match) { 8338 case ArgType::Match: llvm_unreachable("expected non-matching"); 8339 case ArgType::NoMatchPedantic: 8340 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8341 break; 8342 case ArgType::NoMatchTypeConfusion: 8343 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8344 break; 8345 case ArgType::NoMatch: 8346 Diag = diag::warn_format_conversion_argument_type_mismatch; 8347 break; 8348 } 8349 8350 EmitFormatDiagnostic( 8351 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8352 << IsEnum << CSR << E->getSourceRange(), 8353 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8354 break; 8355 } 8356 case Sema::VAK_Undefined: 8357 case Sema::VAK_MSVCUndefined: 8358 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8359 << S.getLangOpts().CPlusPlus11 << ExprTy 8360 << CallType 8361 << AT.getRepresentativeTypeName(S.Context) << CSR 8362 << E->getSourceRange(), 8363 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8364 checkForCStrMembers(AT, E); 8365 break; 8366 8367 case Sema::VAK_Invalid: 8368 if (ExprTy->isObjCObjectType()) 8369 EmitFormatDiagnostic( 8370 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8371 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8372 << AT.getRepresentativeTypeName(S.Context) << CSR 8373 << E->getSourceRange(), 8374 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8375 else 8376 // FIXME: If this is an initializer list, suggest removing the braces 8377 // or inserting a cast to the target type. 8378 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8379 << isa<InitListExpr>(E) << ExprTy << CallType 8380 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8381 break; 8382 } 8383 8384 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8385 "format string specifier index out of range"); 8386 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8387 } 8388 8389 return true; 8390 } 8391 8392 //===--- CHECK: Scanf format string checking ------------------------------===// 8393 8394 namespace { 8395 8396 class CheckScanfHandler : public CheckFormatHandler { 8397 public: 8398 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8399 const Expr *origFormatExpr, Sema::FormatStringType type, 8400 unsigned firstDataArg, unsigned numDataArgs, 8401 const char *beg, bool hasVAListArg, 8402 ArrayRef<const Expr *> Args, unsigned formatIdx, 8403 bool inFunctionCall, Sema::VariadicCallType CallType, 8404 llvm::SmallBitVector &CheckedVarArgs, 8405 UncoveredArgHandler &UncoveredArg) 8406 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8407 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8408 inFunctionCall, CallType, CheckedVarArgs, 8409 UncoveredArg) {} 8410 8411 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8412 const char *startSpecifier, 8413 unsigned specifierLen) override; 8414 8415 bool HandleInvalidScanfConversionSpecifier( 8416 const analyze_scanf::ScanfSpecifier &FS, 8417 const char *startSpecifier, 8418 unsigned specifierLen) override; 8419 8420 void HandleIncompleteScanList(const char *start, const char *end) override; 8421 }; 8422 8423 } // namespace 8424 8425 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8426 const char *end) { 8427 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8428 getLocationOfByte(end), /*IsStringLocation*/true, 8429 getSpecifierRange(start, end - start)); 8430 } 8431 8432 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8433 const analyze_scanf::ScanfSpecifier &FS, 8434 const char *startSpecifier, 8435 unsigned specifierLen) { 8436 const analyze_scanf::ScanfConversionSpecifier &CS = 8437 FS.getConversionSpecifier(); 8438 8439 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8440 getLocationOfByte(CS.getStart()), 8441 startSpecifier, specifierLen, 8442 CS.getStart(), CS.getLength()); 8443 } 8444 8445 bool CheckScanfHandler::HandleScanfSpecifier( 8446 const analyze_scanf::ScanfSpecifier &FS, 8447 const char *startSpecifier, 8448 unsigned specifierLen) { 8449 using namespace analyze_scanf; 8450 using namespace analyze_format_string; 8451 8452 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8453 8454 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8455 // be used to decide if we are using positional arguments consistently. 8456 if (FS.consumesDataArgument()) { 8457 if (atFirstArg) { 8458 atFirstArg = false; 8459 usesPositionalArgs = FS.usesPositionalArg(); 8460 } 8461 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8462 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8463 startSpecifier, specifierLen); 8464 return false; 8465 } 8466 } 8467 8468 // Check if the field with is non-zero. 8469 const OptionalAmount &Amt = FS.getFieldWidth(); 8470 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8471 if (Amt.getConstantAmount() == 0) { 8472 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8473 Amt.getConstantLength()); 8474 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8475 getLocationOfByte(Amt.getStart()), 8476 /*IsStringLocation*/true, R, 8477 FixItHint::CreateRemoval(R)); 8478 } 8479 } 8480 8481 if (!FS.consumesDataArgument()) { 8482 // FIXME: Technically specifying a precision or field width here 8483 // makes no sense. Worth issuing a warning at some point. 8484 return true; 8485 } 8486 8487 // Consume the argument. 8488 unsigned argIndex = FS.getArgIndex(); 8489 if (argIndex < NumDataArgs) { 8490 // The check to see if the argIndex is valid will come later. 8491 // We set the bit here because we may exit early from this 8492 // function if we encounter some other error. 8493 CoveredArgs.set(argIndex); 8494 } 8495 8496 // Check the length modifier is valid with the given conversion specifier. 8497 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8498 S.getLangOpts())) 8499 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8500 diag::warn_format_nonsensical_length); 8501 else if (!FS.hasStandardLengthModifier()) 8502 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8503 else if (!FS.hasStandardLengthConversionCombination()) 8504 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8505 diag::warn_format_non_standard_conversion_spec); 8506 8507 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8508 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8509 8510 // The remaining checks depend on the data arguments. 8511 if (HasVAListArg) 8512 return true; 8513 8514 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8515 return false; 8516 8517 // Check that the argument type matches the format specifier. 8518 const Expr *Ex = getDataArg(argIndex); 8519 if (!Ex) 8520 return true; 8521 8522 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8523 8524 if (!AT.isValid()) { 8525 return true; 8526 } 8527 8528 analyze_format_string::ArgType::MatchKind Match = 8529 AT.matchesType(S.Context, Ex->getType()); 8530 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8531 if (Match == analyze_format_string::ArgType::Match) 8532 return true; 8533 8534 ScanfSpecifier fixedFS = FS; 8535 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8536 S.getLangOpts(), S.Context); 8537 8538 unsigned Diag = 8539 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8540 : diag::warn_format_conversion_argument_type_mismatch; 8541 8542 if (Success) { 8543 // Get the fix string from the fixed format specifier. 8544 SmallString<128> buf; 8545 llvm::raw_svector_ostream os(buf); 8546 fixedFS.toString(os); 8547 8548 EmitFormatDiagnostic( 8549 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8550 << Ex->getType() << false << Ex->getSourceRange(), 8551 Ex->getBeginLoc(), 8552 /*IsStringLocation*/ false, 8553 getSpecifierRange(startSpecifier, specifierLen), 8554 FixItHint::CreateReplacement( 8555 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8556 } else { 8557 EmitFormatDiagnostic(S.PDiag(Diag) 8558 << AT.getRepresentativeTypeName(S.Context) 8559 << Ex->getType() << false << Ex->getSourceRange(), 8560 Ex->getBeginLoc(), 8561 /*IsStringLocation*/ false, 8562 getSpecifierRange(startSpecifier, specifierLen)); 8563 } 8564 8565 return true; 8566 } 8567 8568 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8569 const Expr *OrigFormatExpr, 8570 ArrayRef<const Expr *> Args, 8571 bool HasVAListArg, unsigned format_idx, 8572 unsigned firstDataArg, 8573 Sema::FormatStringType Type, 8574 bool inFunctionCall, 8575 Sema::VariadicCallType CallType, 8576 llvm::SmallBitVector &CheckedVarArgs, 8577 UncoveredArgHandler &UncoveredArg, 8578 bool IgnoreStringsWithoutSpecifiers) { 8579 // CHECK: is the format string a wide literal? 8580 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8581 CheckFormatHandler::EmitFormatDiagnostic( 8582 S, inFunctionCall, Args[format_idx], 8583 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8584 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8585 return; 8586 } 8587 8588 // Str - The format string. NOTE: this is NOT null-terminated! 8589 StringRef StrRef = FExpr->getString(); 8590 const char *Str = StrRef.data(); 8591 // Account for cases where the string literal is truncated in a declaration. 8592 const ConstantArrayType *T = 8593 S.Context.getAsConstantArrayType(FExpr->getType()); 8594 assert(T && "String literal not of constant array type!"); 8595 size_t TypeSize = T->getSize().getZExtValue(); 8596 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8597 const unsigned numDataArgs = Args.size() - firstDataArg; 8598 8599 if (IgnoreStringsWithoutSpecifiers && 8600 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8601 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8602 return; 8603 8604 // Emit a warning if the string literal is truncated and does not contain an 8605 // embedded null character. 8606 if (TypeSize <= StrRef.size() && 8607 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8608 CheckFormatHandler::EmitFormatDiagnostic( 8609 S, inFunctionCall, Args[format_idx], 8610 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8611 FExpr->getBeginLoc(), 8612 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8613 return; 8614 } 8615 8616 // CHECK: empty format string? 8617 if (StrLen == 0 && numDataArgs > 0) { 8618 CheckFormatHandler::EmitFormatDiagnostic( 8619 S, inFunctionCall, Args[format_idx], 8620 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8621 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8622 return; 8623 } 8624 8625 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8626 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8627 Type == Sema::FST_OSTrace) { 8628 CheckPrintfHandler H( 8629 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8630 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8631 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8632 CheckedVarArgs, UncoveredArg); 8633 8634 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8635 S.getLangOpts(), 8636 S.Context.getTargetInfo(), 8637 Type == Sema::FST_FreeBSDKPrintf)) 8638 H.DoneProcessing(); 8639 } else if (Type == Sema::FST_Scanf) { 8640 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8641 numDataArgs, Str, HasVAListArg, Args, format_idx, 8642 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8643 8644 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8645 S.getLangOpts(), 8646 S.Context.getTargetInfo())) 8647 H.DoneProcessing(); 8648 } // TODO: handle other formats 8649 } 8650 8651 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8652 // Str - The format string. NOTE: this is NOT null-terminated! 8653 StringRef StrRef = FExpr->getString(); 8654 const char *Str = StrRef.data(); 8655 // Account for cases where the string literal is truncated in a declaration. 8656 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8657 assert(T && "String literal not of constant array type!"); 8658 size_t TypeSize = T->getSize().getZExtValue(); 8659 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8660 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8661 getLangOpts(), 8662 Context.getTargetInfo()); 8663 } 8664 8665 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8666 8667 // Returns the related absolute value function that is larger, of 0 if one 8668 // does not exist. 8669 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8670 switch (AbsFunction) { 8671 default: 8672 return 0; 8673 8674 case Builtin::BI__builtin_abs: 8675 return Builtin::BI__builtin_labs; 8676 case Builtin::BI__builtin_labs: 8677 return Builtin::BI__builtin_llabs; 8678 case Builtin::BI__builtin_llabs: 8679 return 0; 8680 8681 case Builtin::BI__builtin_fabsf: 8682 return Builtin::BI__builtin_fabs; 8683 case Builtin::BI__builtin_fabs: 8684 return Builtin::BI__builtin_fabsl; 8685 case Builtin::BI__builtin_fabsl: 8686 return 0; 8687 8688 case Builtin::BI__builtin_cabsf: 8689 return Builtin::BI__builtin_cabs; 8690 case Builtin::BI__builtin_cabs: 8691 return Builtin::BI__builtin_cabsl; 8692 case Builtin::BI__builtin_cabsl: 8693 return 0; 8694 8695 case Builtin::BIabs: 8696 return Builtin::BIlabs; 8697 case Builtin::BIlabs: 8698 return Builtin::BIllabs; 8699 case Builtin::BIllabs: 8700 return 0; 8701 8702 case Builtin::BIfabsf: 8703 return Builtin::BIfabs; 8704 case Builtin::BIfabs: 8705 return Builtin::BIfabsl; 8706 case Builtin::BIfabsl: 8707 return 0; 8708 8709 case Builtin::BIcabsf: 8710 return Builtin::BIcabs; 8711 case Builtin::BIcabs: 8712 return Builtin::BIcabsl; 8713 case Builtin::BIcabsl: 8714 return 0; 8715 } 8716 } 8717 8718 // Returns the argument type of the absolute value function. 8719 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8720 unsigned AbsType) { 8721 if (AbsType == 0) 8722 return QualType(); 8723 8724 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8725 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8726 if (Error != ASTContext::GE_None) 8727 return QualType(); 8728 8729 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8730 if (!FT) 8731 return QualType(); 8732 8733 if (FT->getNumParams() != 1) 8734 return QualType(); 8735 8736 return FT->getParamType(0); 8737 } 8738 8739 // Returns the best absolute value function, or zero, based on type and 8740 // current absolute value function. 8741 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8742 unsigned AbsFunctionKind) { 8743 unsigned BestKind = 0; 8744 uint64_t ArgSize = Context.getTypeSize(ArgType); 8745 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8746 Kind = getLargerAbsoluteValueFunction(Kind)) { 8747 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8748 if (Context.getTypeSize(ParamType) >= ArgSize) { 8749 if (BestKind == 0) 8750 BestKind = Kind; 8751 else if (Context.hasSameType(ParamType, ArgType)) { 8752 BestKind = Kind; 8753 break; 8754 } 8755 } 8756 } 8757 return BestKind; 8758 } 8759 8760 enum AbsoluteValueKind { 8761 AVK_Integer, 8762 AVK_Floating, 8763 AVK_Complex 8764 }; 8765 8766 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8767 if (T->isIntegralOrEnumerationType()) 8768 return AVK_Integer; 8769 if (T->isRealFloatingType()) 8770 return AVK_Floating; 8771 if (T->isAnyComplexType()) 8772 return AVK_Complex; 8773 8774 llvm_unreachable("Type not integer, floating, or complex"); 8775 } 8776 8777 // Changes the absolute value function to a different type. Preserves whether 8778 // the function is a builtin. 8779 static unsigned changeAbsFunction(unsigned AbsKind, 8780 AbsoluteValueKind ValueKind) { 8781 switch (ValueKind) { 8782 case AVK_Integer: 8783 switch (AbsKind) { 8784 default: 8785 return 0; 8786 case Builtin::BI__builtin_fabsf: 8787 case Builtin::BI__builtin_fabs: 8788 case Builtin::BI__builtin_fabsl: 8789 case Builtin::BI__builtin_cabsf: 8790 case Builtin::BI__builtin_cabs: 8791 case Builtin::BI__builtin_cabsl: 8792 return Builtin::BI__builtin_abs; 8793 case Builtin::BIfabsf: 8794 case Builtin::BIfabs: 8795 case Builtin::BIfabsl: 8796 case Builtin::BIcabsf: 8797 case Builtin::BIcabs: 8798 case Builtin::BIcabsl: 8799 return Builtin::BIabs; 8800 } 8801 case AVK_Floating: 8802 switch (AbsKind) { 8803 default: 8804 return 0; 8805 case Builtin::BI__builtin_abs: 8806 case Builtin::BI__builtin_labs: 8807 case Builtin::BI__builtin_llabs: 8808 case Builtin::BI__builtin_cabsf: 8809 case Builtin::BI__builtin_cabs: 8810 case Builtin::BI__builtin_cabsl: 8811 return Builtin::BI__builtin_fabsf; 8812 case Builtin::BIabs: 8813 case Builtin::BIlabs: 8814 case Builtin::BIllabs: 8815 case Builtin::BIcabsf: 8816 case Builtin::BIcabs: 8817 case Builtin::BIcabsl: 8818 return Builtin::BIfabsf; 8819 } 8820 case AVK_Complex: 8821 switch (AbsKind) { 8822 default: 8823 return 0; 8824 case Builtin::BI__builtin_abs: 8825 case Builtin::BI__builtin_labs: 8826 case Builtin::BI__builtin_llabs: 8827 case Builtin::BI__builtin_fabsf: 8828 case Builtin::BI__builtin_fabs: 8829 case Builtin::BI__builtin_fabsl: 8830 return Builtin::BI__builtin_cabsf; 8831 case Builtin::BIabs: 8832 case Builtin::BIlabs: 8833 case Builtin::BIllabs: 8834 case Builtin::BIfabsf: 8835 case Builtin::BIfabs: 8836 case Builtin::BIfabsl: 8837 return Builtin::BIcabsf; 8838 } 8839 } 8840 llvm_unreachable("Unable to convert function"); 8841 } 8842 8843 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8844 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8845 if (!FnInfo) 8846 return 0; 8847 8848 switch (FDecl->getBuiltinID()) { 8849 default: 8850 return 0; 8851 case Builtin::BI__builtin_abs: 8852 case Builtin::BI__builtin_fabs: 8853 case Builtin::BI__builtin_fabsf: 8854 case Builtin::BI__builtin_fabsl: 8855 case Builtin::BI__builtin_labs: 8856 case Builtin::BI__builtin_llabs: 8857 case Builtin::BI__builtin_cabs: 8858 case Builtin::BI__builtin_cabsf: 8859 case Builtin::BI__builtin_cabsl: 8860 case Builtin::BIabs: 8861 case Builtin::BIlabs: 8862 case Builtin::BIllabs: 8863 case Builtin::BIfabs: 8864 case Builtin::BIfabsf: 8865 case Builtin::BIfabsl: 8866 case Builtin::BIcabs: 8867 case Builtin::BIcabsf: 8868 case Builtin::BIcabsl: 8869 return FDecl->getBuiltinID(); 8870 } 8871 llvm_unreachable("Unknown Builtin type"); 8872 } 8873 8874 // If the replacement is valid, emit a note with replacement function. 8875 // Additionally, suggest including the proper header if not already included. 8876 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8877 unsigned AbsKind, QualType ArgType) { 8878 bool EmitHeaderHint = true; 8879 const char *HeaderName = nullptr; 8880 const char *FunctionName = nullptr; 8881 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8882 FunctionName = "std::abs"; 8883 if (ArgType->isIntegralOrEnumerationType()) { 8884 HeaderName = "cstdlib"; 8885 } else if (ArgType->isRealFloatingType()) { 8886 HeaderName = "cmath"; 8887 } else { 8888 llvm_unreachable("Invalid Type"); 8889 } 8890 8891 // Lookup all std::abs 8892 if (NamespaceDecl *Std = S.getStdNamespace()) { 8893 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8894 R.suppressDiagnostics(); 8895 S.LookupQualifiedName(R, Std); 8896 8897 for (const auto *I : R) { 8898 const FunctionDecl *FDecl = nullptr; 8899 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8900 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8901 } else { 8902 FDecl = dyn_cast<FunctionDecl>(I); 8903 } 8904 if (!FDecl) 8905 continue; 8906 8907 // Found std::abs(), check that they are the right ones. 8908 if (FDecl->getNumParams() != 1) 8909 continue; 8910 8911 // Check that the parameter type can handle the argument. 8912 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8913 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8914 S.Context.getTypeSize(ArgType) <= 8915 S.Context.getTypeSize(ParamType)) { 8916 // Found a function, don't need the header hint. 8917 EmitHeaderHint = false; 8918 break; 8919 } 8920 } 8921 } 8922 } else { 8923 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8924 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8925 8926 if (HeaderName) { 8927 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8928 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8929 R.suppressDiagnostics(); 8930 S.LookupName(R, S.getCurScope()); 8931 8932 if (R.isSingleResult()) { 8933 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8934 if (FD && FD->getBuiltinID() == AbsKind) { 8935 EmitHeaderHint = false; 8936 } else { 8937 return; 8938 } 8939 } else if (!R.empty()) { 8940 return; 8941 } 8942 } 8943 } 8944 8945 S.Diag(Loc, diag::note_replace_abs_function) 8946 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8947 8948 if (!HeaderName) 8949 return; 8950 8951 if (!EmitHeaderHint) 8952 return; 8953 8954 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8955 << FunctionName; 8956 } 8957 8958 template <std::size_t StrLen> 8959 static bool IsStdFunction(const FunctionDecl *FDecl, 8960 const char (&Str)[StrLen]) { 8961 if (!FDecl) 8962 return false; 8963 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8964 return false; 8965 if (!FDecl->isInStdNamespace()) 8966 return false; 8967 8968 return true; 8969 } 8970 8971 // Warn when using the wrong abs() function. 8972 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8973 const FunctionDecl *FDecl) { 8974 if (Call->getNumArgs() != 1) 8975 return; 8976 8977 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8978 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8979 if (AbsKind == 0 && !IsStdAbs) 8980 return; 8981 8982 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8983 QualType ParamType = Call->getArg(0)->getType(); 8984 8985 // Unsigned types cannot be negative. Suggest removing the absolute value 8986 // function call. 8987 if (ArgType->isUnsignedIntegerType()) { 8988 const char *FunctionName = 8989 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8990 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8991 Diag(Call->getExprLoc(), diag::note_remove_abs) 8992 << FunctionName 8993 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8994 return; 8995 } 8996 8997 // Taking the absolute value of a pointer is very suspicious, they probably 8998 // wanted to index into an array, dereference a pointer, call a function, etc. 8999 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9000 unsigned DiagType = 0; 9001 if (ArgType->isFunctionType()) 9002 DiagType = 1; 9003 else if (ArgType->isArrayType()) 9004 DiagType = 2; 9005 9006 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9007 return; 9008 } 9009 9010 // std::abs has overloads which prevent most of the absolute value problems 9011 // from occurring. 9012 if (IsStdAbs) 9013 return; 9014 9015 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9016 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9017 9018 // The argument and parameter are the same kind. Check if they are the right 9019 // size. 9020 if (ArgValueKind == ParamValueKind) { 9021 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9022 return; 9023 9024 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9025 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9026 << FDecl << ArgType << ParamType; 9027 9028 if (NewAbsKind == 0) 9029 return; 9030 9031 emitReplacement(*this, Call->getExprLoc(), 9032 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9033 return; 9034 } 9035 9036 // ArgValueKind != ParamValueKind 9037 // The wrong type of absolute value function was used. Attempt to find the 9038 // proper one. 9039 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9040 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9041 if (NewAbsKind == 0) 9042 return; 9043 9044 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9045 << FDecl << ParamValueKind << ArgValueKind; 9046 9047 emitReplacement(*this, Call->getExprLoc(), 9048 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9049 } 9050 9051 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9052 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9053 const FunctionDecl *FDecl) { 9054 if (!Call || !FDecl) return; 9055 9056 // Ignore template specializations and macros. 9057 if (inTemplateInstantiation()) return; 9058 if (Call->getExprLoc().isMacroID()) return; 9059 9060 // Only care about the one template argument, two function parameter std::max 9061 if (Call->getNumArgs() != 2) return; 9062 if (!IsStdFunction(FDecl, "max")) return; 9063 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9064 if (!ArgList) return; 9065 if (ArgList->size() != 1) return; 9066 9067 // Check that template type argument is unsigned integer. 9068 const auto& TA = ArgList->get(0); 9069 if (TA.getKind() != TemplateArgument::Type) return; 9070 QualType ArgType = TA.getAsType(); 9071 if (!ArgType->isUnsignedIntegerType()) return; 9072 9073 // See if either argument is a literal zero. 9074 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9075 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9076 if (!MTE) return false; 9077 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9078 if (!Num) return false; 9079 if (Num->getValue() != 0) return false; 9080 return true; 9081 }; 9082 9083 const Expr *FirstArg = Call->getArg(0); 9084 const Expr *SecondArg = Call->getArg(1); 9085 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9086 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9087 9088 // Only warn when exactly one argument is zero. 9089 if (IsFirstArgZero == IsSecondArgZero) return; 9090 9091 SourceRange FirstRange = FirstArg->getSourceRange(); 9092 SourceRange SecondRange = SecondArg->getSourceRange(); 9093 9094 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9095 9096 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9097 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9098 9099 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9100 SourceRange RemovalRange; 9101 if (IsFirstArgZero) { 9102 RemovalRange = SourceRange(FirstRange.getBegin(), 9103 SecondRange.getBegin().getLocWithOffset(-1)); 9104 } else { 9105 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9106 SecondRange.getEnd()); 9107 } 9108 9109 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9110 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9111 << FixItHint::CreateRemoval(RemovalRange); 9112 } 9113 9114 //===--- CHECK: Standard memory functions ---------------------------------===// 9115 9116 /// Takes the expression passed to the size_t parameter of functions 9117 /// such as memcmp, strncat, etc and warns if it's a comparison. 9118 /// 9119 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9120 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9121 IdentifierInfo *FnName, 9122 SourceLocation FnLoc, 9123 SourceLocation RParenLoc) { 9124 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9125 if (!Size) 9126 return false; 9127 9128 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9129 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9130 return false; 9131 9132 SourceRange SizeRange = Size->getSourceRange(); 9133 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9134 << SizeRange << FnName; 9135 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9136 << FnName 9137 << FixItHint::CreateInsertion( 9138 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9139 << FixItHint::CreateRemoval(RParenLoc); 9140 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9141 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9142 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9143 ")"); 9144 9145 return true; 9146 } 9147 9148 /// Determine whether the given type is or contains a dynamic class type 9149 /// (e.g., whether it has a vtable). 9150 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9151 bool &IsContained) { 9152 // Look through array types while ignoring qualifiers. 9153 const Type *Ty = T->getBaseElementTypeUnsafe(); 9154 IsContained = false; 9155 9156 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9157 RD = RD ? RD->getDefinition() : nullptr; 9158 if (!RD || RD->isInvalidDecl()) 9159 return nullptr; 9160 9161 if (RD->isDynamicClass()) 9162 return RD; 9163 9164 // Check all the fields. If any bases were dynamic, the class is dynamic. 9165 // It's impossible for a class to transitively contain itself by value, so 9166 // infinite recursion is impossible. 9167 for (auto *FD : RD->fields()) { 9168 bool SubContained; 9169 if (const CXXRecordDecl *ContainedRD = 9170 getContainedDynamicClass(FD->getType(), SubContained)) { 9171 IsContained = true; 9172 return ContainedRD; 9173 } 9174 } 9175 9176 return nullptr; 9177 } 9178 9179 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9180 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9181 if (Unary->getKind() == UETT_SizeOf) 9182 return Unary; 9183 return nullptr; 9184 } 9185 9186 /// If E is a sizeof expression, returns its argument expression, 9187 /// otherwise returns NULL. 9188 static const Expr *getSizeOfExprArg(const Expr *E) { 9189 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9190 if (!SizeOf->isArgumentType()) 9191 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9192 return nullptr; 9193 } 9194 9195 /// If E is a sizeof expression, returns its argument type. 9196 static QualType getSizeOfArgType(const Expr *E) { 9197 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9198 return SizeOf->getTypeOfArgument(); 9199 return QualType(); 9200 } 9201 9202 namespace { 9203 9204 struct SearchNonTrivialToInitializeField 9205 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9206 using Super = 9207 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9208 9209 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9210 9211 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9212 SourceLocation SL) { 9213 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9214 asDerived().visitArray(PDIK, AT, SL); 9215 return; 9216 } 9217 9218 Super::visitWithKind(PDIK, FT, SL); 9219 } 9220 9221 void visitARCStrong(QualType FT, SourceLocation SL) { 9222 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9223 } 9224 void visitARCWeak(QualType FT, SourceLocation SL) { 9225 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9226 } 9227 void visitStruct(QualType FT, SourceLocation SL) { 9228 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9229 visit(FD->getType(), FD->getLocation()); 9230 } 9231 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9232 const ArrayType *AT, SourceLocation SL) { 9233 visit(getContext().getBaseElementType(AT), SL); 9234 } 9235 void visitTrivial(QualType FT, SourceLocation SL) {} 9236 9237 static void diag(QualType RT, const Expr *E, Sema &S) { 9238 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9239 } 9240 9241 ASTContext &getContext() { return S.getASTContext(); } 9242 9243 const Expr *E; 9244 Sema &S; 9245 }; 9246 9247 struct SearchNonTrivialToCopyField 9248 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9249 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9250 9251 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9252 9253 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9254 SourceLocation SL) { 9255 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9256 asDerived().visitArray(PCK, AT, SL); 9257 return; 9258 } 9259 9260 Super::visitWithKind(PCK, FT, SL); 9261 } 9262 9263 void visitARCStrong(QualType FT, SourceLocation SL) { 9264 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9265 } 9266 void visitARCWeak(QualType FT, SourceLocation SL) { 9267 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9268 } 9269 void visitStruct(QualType FT, SourceLocation SL) { 9270 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9271 visit(FD->getType(), FD->getLocation()); 9272 } 9273 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9274 SourceLocation SL) { 9275 visit(getContext().getBaseElementType(AT), SL); 9276 } 9277 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9278 SourceLocation SL) {} 9279 void visitTrivial(QualType FT, SourceLocation SL) {} 9280 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9281 9282 static void diag(QualType RT, const Expr *E, Sema &S) { 9283 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9284 } 9285 9286 ASTContext &getContext() { return S.getASTContext(); } 9287 9288 const Expr *E; 9289 Sema &S; 9290 }; 9291 9292 } 9293 9294 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9295 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9296 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9297 9298 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9299 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9300 return false; 9301 9302 return doesExprLikelyComputeSize(BO->getLHS()) || 9303 doesExprLikelyComputeSize(BO->getRHS()); 9304 } 9305 9306 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9307 } 9308 9309 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9310 /// 9311 /// \code 9312 /// #define MACRO 0 9313 /// foo(MACRO); 9314 /// foo(0); 9315 /// \endcode 9316 /// 9317 /// This should return true for the first call to foo, but not for the second 9318 /// (regardless of whether foo is a macro or function). 9319 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9320 SourceLocation CallLoc, 9321 SourceLocation ArgLoc) { 9322 if (!CallLoc.isMacroID()) 9323 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9324 9325 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9326 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9327 } 9328 9329 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9330 /// last two arguments transposed. 9331 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9332 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9333 return; 9334 9335 const Expr *SizeArg = 9336 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9337 9338 auto isLiteralZero = [](const Expr *E) { 9339 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9340 }; 9341 9342 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9343 SourceLocation CallLoc = Call->getRParenLoc(); 9344 SourceManager &SM = S.getSourceManager(); 9345 if (isLiteralZero(SizeArg) && 9346 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9347 9348 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9349 9350 // Some platforms #define bzero to __builtin_memset. See if this is the 9351 // case, and if so, emit a better diagnostic. 9352 if (BId == Builtin::BIbzero || 9353 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9354 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9355 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9356 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9357 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9358 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9359 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9360 } 9361 return; 9362 } 9363 9364 // If the second argument to a memset is a sizeof expression and the third 9365 // isn't, this is also likely an error. This should catch 9366 // 'memset(buf, sizeof(buf), 0xff)'. 9367 if (BId == Builtin::BImemset && 9368 doesExprLikelyComputeSize(Call->getArg(1)) && 9369 !doesExprLikelyComputeSize(Call->getArg(2))) { 9370 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9371 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9372 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9373 return; 9374 } 9375 } 9376 9377 /// Check for dangerous or invalid arguments to memset(). 9378 /// 9379 /// This issues warnings on known problematic, dangerous or unspecified 9380 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9381 /// function calls. 9382 /// 9383 /// \param Call The call expression to diagnose. 9384 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9385 unsigned BId, 9386 IdentifierInfo *FnName) { 9387 assert(BId != 0); 9388 9389 // It is possible to have a non-standard definition of memset. Validate 9390 // we have enough arguments, and if not, abort further checking. 9391 unsigned ExpectedNumArgs = 9392 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9393 if (Call->getNumArgs() < ExpectedNumArgs) 9394 return; 9395 9396 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9397 BId == Builtin::BIstrndup ? 1 : 2); 9398 unsigned LenArg = 9399 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9400 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9401 9402 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9403 Call->getBeginLoc(), Call->getRParenLoc())) 9404 return; 9405 9406 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9407 CheckMemaccessSize(*this, BId, Call); 9408 9409 // We have special checking when the length is a sizeof expression. 9410 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9411 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9412 llvm::FoldingSetNodeID SizeOfArgID; 9413 9414 // Although widely used, 'bzero' is not a standard function. Be more strict 9415 // with the argument types before allowing diagnostics and only allow the 9416 // form bzero(ptr, sizeof(...)). 9417 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9418 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9419 return; 9420 9421 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9422 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9423 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9424 9425 QualType DestTy = Dest->getType(); 9426 QualType PointeeTy; 9427 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9428 PointeeTy = DestPtrTy->getPointeeType(); 9429 9430 // Never warn about void type pointers. This can be used to suppress 9431 // false positives. 9432 if (PointeeTy->isVoidType()) 9433 continue; 9434 9435 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9436 // actually comparing the expressions for equality. Because computing the 9437 // expression IDs can be expensive, we only do this if the diagnostic is 9438 // enabled. 9439 if (SizeOfArg && 9440 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9441 SizeOfArg->getExprLoc())) { 9442 // We only compute IDs for expressions if the warning is enabled, and 9443 // cache the sizeof arg's ID. 9444 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9445 SizeOfArg->Profile(SizeOfArgID, Context, true); 9446 llvm::FoldingSetNodeID DestID; 9447 Dest->Profile(DestID, Context, true); 9448 if (DestID == SizeOfArgID) { 9449 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9450 // over sizeof(src) as well. 9451 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9452 StringRef ReadableName = FnName->getName(); 9453 9454 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9455 if (UnaryOp->getOpcode() == UO_AddrOf) 9456 ActionIdx = 1; // If its an address-of operator, just remove it. 9457 if (!PointeeTy->isIncompleteType() && 9458 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9459 ActionIdx = 2; // If the pointee's size is sizeof(char), 9460 // suggest an explicit length. 9461 9462 // If the function is defined as a builtin macro, do not show macro 9463 // expansion. 9464 SourceLocation SL = SizeOfArg->getExprLoc(); 9465 SourceRange DSR = Dest->getSourceRange(); 9466 SourceRange SSR = SizeOfArg->getSourceRange(); 9467 SourceManager &SM = getSourceManager(); 9468 9469 if (SM.isMacroArgExpansion(SL)) { 9470 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9471 SL = SM.getSpellingLoc(SL); 9472 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9473 SM.getSpellingLoc(DSR.getEnd())); 9474 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9475 SM.getSpellingLoc(SSR.getEnd())); 9476 } 9477 9478 DiagRuntimeBehavior(SL, SizeOfArg, 9479 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9480 << ReadableName 9481 << PointeeTy 9482 << DestTy 9483 << DSR 9484 << SSR); 9485 DiagRuntimeBehavior(SL, SizeOfArg, 9486 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9487 << ActionIdx 9488 << SSR); 9489 9490 break; 9491 } 9492 } 9493 9494 // Also check for cases where the sizeof argument is the exact same 9495 // type as the memory argument, and where it points to a user-defined 9496 // record type. 9497 if (SizeOfArgTy != QualType()) { 9498 if (PointeeTy->isRecordType() && 9499 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9500 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9501 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9502 << FnName << SizeOfArgTy << ArgIdx 9503 << PointeeTy << Dest->getSourceRange() 9504 << LenExpr->getSourceRange()); 9505 break; 9506 } 9507 } 9508 } else if (DestTy->isArrayType()) { 9509 PointeeTy = DestTy; 9510 } 9511 9512 if (PointeeTy == QualType()) 9513 continue; 9514 9515 // Always complain about dynamic classes. 9516 bool IsContained; 9517 if (const CXXRecordDecl *ContainedRD = 9518 getContainedDynamicClass(PointeeTy, IsContained)) { 9519 9520 unsigned OperationType = 0; 9521 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9522 // "overwritten" if we're warning about the destination for any call 9523 // but memcmp; otherwise a verb appropriate to the call. 9524 if (ArgIdx != 0 || IsCmp) { 9525 if (BId == Builtin::BImemcpy) 9526 OperationType = 1; 9527 else if(BId == Builtin::BImemmove) 9528 OperationType = 2; 9529 else if (IsCmp) 9530 OperationType = 3; 9531 } 9532 9533 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9534 PDiag(diag::warn_dyn_class_memaccess) 9535 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9536 << IsContained << ContainedRD << OperationType 9537 << Call->getCallee()->getSourceRange()); 9538 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9539 BId != Builtin::BImemset) 9540 DiagRuntimeBehavior( 9541 Dest->getExprLoc(), Dest, 9542 PDiag(diag::warn_arc_object_memaccess) 9543 << ArgIdx << FnName << PointeeTy 9544 << Call->getCallee()->getSourceRange()); 9545 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9546 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9547 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9548 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9549 PDiag(diag::warn_cstruct_memaccess) 9550 << ArgIdx << FnName << PointeeTy << 0); 9551 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9552 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9553 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9554 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9555 PDiag(diag::warn_cstruct_memaccess) 9556 << ArgIdx << FnName << PointeeTy << 1); 9557 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9558 } else { 9559 continue; 9560 } 9561 } else 9562 continue; 9563 9564 DiagRuntimeBehavior( 9565 Dest->getExprLoc(), Dest, 9566 PDiag(diag::note_bad_memaccess_silence) 9567 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9568 break; 9569 } 9570 } 9571 9572 // A little helper routine: ignore addition and subtraction of integer literals. 9573 // This intentionally does not ignore all integer constant expressions because 9574 // we don't want to remove sizeof(). 9575 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9576 Ex = Ex->IgnoreParenCasts(); 9577 9578 while (true) { 9579 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9580 if (!BO || !BO->isAdditiveOp()) 9581 break; 9582 9583 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9584 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9585 9586 if (isa<IntegerLiteral>(RHS)) 9587 Ex = LHS; 9588 else if (isa<IntegerLiteral>(LHS)) 9589 Ex = RHS; 9590 else 9591 break; 9592 } 9593 9594 return Ex; 9595 } 9596 9597 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9598 ASTContext &Context) { 9599 // Only handle constant-sized or VLAs, but not flexible members. 9600 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9601 // Only issue the FIXIT for arrays of size > 1. 9602 if (CAT->getSize().getSExtValue() <= 1) 9603 return false; 9604 } else if (!Ty->isVariableArrayType()) { 9605 return false; 9606 } 9607 return true; 9608 } 9609 9610 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9611 // be the size of the source, instead of the destination. 9612 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9613 IdentifierInfo *FnName) { 9614 9615 // Don't crash if the user has the wrong number of arguments 9616 unsigned NumArgs = Call->getNumArgs(); 9617 if ((NumArgs != 3) && (NumArgs != 4)) 9618 return; 9619 9620 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9621 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9622 const Expr *CompareWithSrc = nullptr; 9623 9624 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9625 Call->getBeginLoc(), Call->getRParenLoc())) 9626 return; 9627 9628 // Look for 'strlcpy(dst, x, sizeof(x))' 9629 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9630 CompareWithSrc = Ex; 9631 else { 9632 // Look for 'strlcpy(dst, x, strlen(x))' 9633 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9634 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9635 SizeCall->getNumArgs() == 1) 9636 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9637 } 9638 } 9639 9640 if (!CompareWithSrc) 9641 return; 9642 9643 // Determine if the argument to sizeof/strlen is equal to the source 9644 // argument. In principle there's all kinds of things you could do 9645 // here, for instance creating an == expression and evaluating it with 9646 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9647 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9648 if (!SrcArgDRE) 9649 return; 9650 9651 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9652 if (!CompareWithSrcDRE || 9653 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9654 return; 9655 9656 const Expr *OriginalSizeArg = Call->getArg(2); 9657 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9658 << OriginalSizeArg->getSourceRange() << FnName; 9659 9660 // Output a FIXIT hint if the destination is an array (rather than a 9661 // pointer to an array). This could be enhanced to handle some 9662 // pointers if we know the actual size, like if DstArg is 'array+2' 9663 // we could say 'sizeof(array)-2'. 9664 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9665 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9666 return; 9667 9668 SmallString<128> sizeString; 9669 llvm::raw_svector_ostream OS(sizeString); 9670 OS << "sizeof("; 9671 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9672 OS << ")"; 9673 9674 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9675 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9676 OS.str()); 9677 } 9678 9679 /// Check if two expressions refer to the same declaration. 9680 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9681 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9682 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9683 return D1->getDecl() == D2->getDecl(); 9684 return false; 9685 } 9686 9687 static const Expr *getStrlenExprArg(const Expr *E) { 9688 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9689 const FunctionDecl *FD = CE->getDirectCallee(); 9690 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9691 return nullptr; 9692 return CE->getArg(0)->IgnoreParenCasts(); 9693 } 9694 return nullptr; 9695 } 9696 9697 // Warn on anti-patterns as the 'size' argument to strncat. 9698 // The correct size argument should look like following: 9699 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9700 void Sema::CheckStrncatArguments(const CallExpr *CE, 9701 IdentifierInfo *FnName) { 9702 // Don't crash if the user has the wrong number of arguments. 9703 if (CE->getNumArgs() < 3) 9704 return; 9705 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9706 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9707 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9708 9709 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9710 CE->getRParenLoc())) 9711 return; 9712 9713 // Identify common expressions, which are wrongly used as the size argument 9714 // to strncat and may lead to buffer overflows. 9715 unsigned PatternType = 0; 9716 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9717 // - sizeof(dst) 9718 if (referToTheSameDecl(SizeOfArg, DstArg)) 9719 PatternType = 1; 9720 // - sizeof(src) 9721 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9722 PatternType = 2; 9723 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9724 if (BE->getOpcode() == BO_Sub) { 9725 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9726 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9727 // - sizeof(dst) - strlen(dst) 9728 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9729 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9730 PatternType = 1; 9731 // - sizeof(src) - (anything) 9732 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9733 PatternType = 2; 9734 } 9735 } 9736 9737 if (PatternType == 0) 9738 return; 9739 9740 // Generate the diagnostic. 9741 SourceLocation SL = LenArg->getBeginLoc(); 9742 SourceRange SR = LenArg->getSourceRange(); 9743 SourceManager &SM = getSourceManager(); 9744 9745 // If the function is defined as a builtin macro, do not show macro expansion. 9746 if (SM.isMacroArgExpansion(SL)) { 9747 SL = SM.getSpellingLoc(SL); 9748 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9749 SM.getSpellingLoc(SR.getEnd())); 9750 } 9751 9752 // Check if the destination is an array (rather than a pointer to an array). 9753 QualType DstTy = DstArg->getType(); 9754 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9755 Context); 9756 if (!isKnownSizeArray) { 9757 if (PatternType == 1) 9758 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9759 else 9760 Diag(SL, diag::warn_strncat_src_size) << SR; 9761 return; 9762 } 9763 9764 if (PatternType == 1) 9765 Diag(SL, diag::warn_strncat_large_size) << SR; 9766 else 9767 Diag(SL, diag::warn_strncat_src_size) << SR; 9768 9769 SmallString<128> sizeString; 9770 llvm::raw_svector_ostream OS(sizeString); 9771 OS << "sizeof("; 9772 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9773 OS << ") - "; 9774 OS << "strlen("; 9775 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9776 OS << ") - 1"; 9777 9778 Diag(SL, diag::note_strncat_wrong_size) 9779 << FixItHint::CreateReplacement(SR, OS.str()); 9780 } 9781 9782 void 9783 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9784 SourceLocation ReturnLoc, 9785 bool isObjCMethod, 9786 const AttrVec *Attrs, 9787 const FunctionDecl *FD) { 9788 // Check if the return value is null but should not be. 9789 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9790 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9791 CheckNonNullExpr(*this, RetValExp)) 9792 Diag(ReturnLoc, diag::warn_null_ret) 9793 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9794 9795 // C++11 [basic.stc.dynamic.allocation]p4: 9796 // If an allocation function declared with a non-throwing 9797 // exception-specification fails to allocate storage, it shall return 9798 // a null pointer. Any other allocation function that fails to allocate 9799 // storage shall indicate failure only by throwing an exception [...] 9800 if (FD) { 9801 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9802 if (Op == OO_New || Op == OO_Array_New) { 9803 const FunctionProtoType *Proto 9804 = FD->getType()->castAs<FunctionProtoType>(); 9805 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9806 CheckNonNullExpr(*this, RetValExp)) 9807 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9808 << FD << getLangOpts().CPlusPlus11; 9809 } 9810 } 9811 } 9812 9813 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9814 9815 /// Check for comparisons of floating point operands using != and ==. 9816 /// Issue a warning if these are no self-comparisons, as they are not likely 9817 /// to do what the programmer intended. 9818 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9819 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9820 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9821 9822 // Special case: check for x == x (which is OK). 9823 // Do not emit warnings for such cases. 9824 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9825 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9826 if (DRL->getDecl() == DRR->getDecl()) 9827 return; 9828 9829 // Special case: check for comparisons against literals that can be exactly 9830 // represented by APFloat. In such cases, do not emit a warning. This 9831 // is a heuristic: often comparison against such literals are used to 9832 // detect if a value in a variable has not changed. This clearly can 9833 // lead to false negatives. 9834 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9835 if (FLL->isExact()) 9836 return; 9837 } else 9838 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9839 if (FLR->isExact()) 9840 return; 9841 9842 // Check for comparisons with builtin types. 9843 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9844 if (CL->getBuiltinCallee()) 9845 return; 9846 9847 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9848 if (CR->getBuiltinCallee()) 9849 return; 9850 9851 // Emit the diagnostic. 9852 Diag(Loc, diag::warn_floatingpoint_eq) 9853 << LHS->getSourceRange() << RHS->getSourceRange(); 9854 } 9855 9856 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9857 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9858 9859 namespace { 9860 9861 /// Structure recording the 'active' range of an integer-valued 9862 /// expression. 9863 struct IntRange { 9864 /// The number of bits active in the int. 9865 unsigned Width; 9866 9867 /// True if the int is known not to have negative values. 9868 bool NonNegative; 9869 9870 IntRange(unsigned Width, bool NonNegative) 9871 : Width(Width), NonNegative(NonNegative) {} 9872 9873 /// Returns the range of the bool type. 9874 static IntRange forBoolType() { 9875 return IntRange(1, true); 9876 } 9877 9878 /// Returns the range of an opaque value of the given integral type. 9879 static IntRange forValueOfType(ASTContext &C, QualType T) { 9880 return forValueOfCanonicalType(C, 9881 T->getCanonicalTypeInternal().getTypePtr()); 9882 } 9883 9884 /// Returns the range of an opaque value of a canonical integral type. 9885 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9886 assert(T->isCanonicalUnqualified()); 9887 9888 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9889 T = VT->getElementType().getTypePtr(); 9890 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9891 T = CT->getElementType().getTypePtr(); 9892 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9893 T = AT->getValueType().getTypePtr(); 9894 9895 if (!C.getLangOpts().CPlusPlus) { 9896 // For enum types in C code, use the underlying datatype. 9897 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9898 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9899 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9900 // For enum types in C++, use the known bit width of the enumerators. 9901 EnumDecl *Enum = ET->getDecl(); 9902 // In C++11, enums can have a fixed underlying type. Use this type to 9903 // compute the range. 9904 if (Enum->isFixed()) { 9905 return IntRange(C.getIntWidth(QualType(T, 0)), 9906 !ET->isSignedIntegerOrEnumerationType()); 9907 } 9908 9909 unsigned NumPositive = Enum->getNumPositiveBits(); 9910 unsigned NumNegative = Enum->getNumNegativeBits(); 9911 9912 if (NumNegative == 0) 9913 return IntRange(NumPositive, true/*NonNegative*/); 9914 else 9915 return IntRange(std::max(NumPositive + 1, NumNegative), 9916 false/*NonNegative*/); 9917 } 9918 9919 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9920 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9921 9922 const BuiltinType *BT = cast<BuiltinType>(T); 9923 assert(BT->isInteger()); 9924 9925 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9926 } 9927 9928 /// Returns the "target" range of a canonical integral type, i.e. 9929 /// the range of values expressible in the type. 9930 /// 9931 /// This matches forValueOfCanonicalType except that enums have the 9932 /// full range of their type, not the range of their enumerators. 9933 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9934 assert(T->isCanonicalUnqualified()); 9935 9936 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9937 T = VT->getElementType().getTypePtr(); 9938 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9939 T = CT->getElementType().getTypePtr(); 9940 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9941 T = AT->getValueType().getTypePtr(); 9942 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9943 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9944 9945 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9946 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9947 9948 const BuiltinType *BT = cast<BuiltinType>(T); 9949 assert(BT->isInteger()); 9950 9951 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9952 } 9953 9954 /// Returns the supremum of two ranges: i.e. their conservative merge. 9955 static IntRange join(IntRange L, IntRange R) { 9956 return IntRange(std::max(L.Width, R.Width), 9957 L.NonNegative && R.NonNegative); 9958 } 9959 9960 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9961 static IntRange meet(IntRange L, IntRange R) { 9962 return IntRange(std::min(L.Width, R.Width), 9963 L.NonNegative || R.NonNegative); 9964 } 9965 }; 9966 9967 } // namespace 9968 9969 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9970 unsigned MaxWidth) { 9971 if (value.isSigned() && value.isNegative()) 9972 return IntRange(value.getMinSignedBits(), false); 9973 9974 if (value.getBitWidth() > MaxWidth) 9975 value = value.trunc(MaxWidth); 9976 9977 // isNonNegative() just checks the sign bit without considering 9978 // signedness. 9979 return IntRange(value.getActiveBits(), true); 9980 } 9981 9982 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9983 unsigned MaxWidth) { 9984 if (result.isInt()) 9985 return GetValueRange(C, result.getInt(), MaxWidth); 9986 9987 if (result.isVector()) { 9988 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9989 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9990 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9991 R = IntRange::join(R, El); 9992 } 9993 return R; 9994 } 9995 9996 if (result.isComplexInt()) { 9997 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9998 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9999 return IntRange::join(R, I); 10000 } 10001 10002 // This can happen with lossless casts to intptr_t of "based" lvalues. 10003 // Assume it might use arbitrary bits. 10004 // FIXME: The only reason we need to pass the type in here is to get 10005 // the sign right on this one case. It would be nice if APValue 10006 // preserved this. 10007 assert(result.isLValue() || result.isAddrLabelDiff()); 10008 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10009 } 10010 10011 static QualType GetExprType(const Expr *E) { 10012 QualType Ty = E->getType(); 10013 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10014 Ty = AtomicRHS->getValueType(); 10015 return Ty; 10016 } 10017 10018 /// Pseudo-evaluate the given integer expression, estimating the 10019 /// range of values it might take. 10020 /// 10021 /// \param MaxWidth - the width to which the value will be truncated 10022 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10023 bool InConstantContext) { 10024 E = E->IgnoreParens(); 10025 10026 // Try a full evaluation first. 10027 Expr::EvalResult result; 10028 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10029 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10030 10031 // I think we only want to look through implicit casts here; if the 10032 // user has an explicit widening cast, we should treat the value as 10033 // being of the new, wider type. 10034 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10035 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10036 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10037 10038 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10039 10040 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10041 CE->getCastKind() == CK_BooleanToSignedIntegral; 10042 10043 // Assume that non-integer casts can span the full range of the type. 10044 if (!isIntegerCast) 10045 return OutputTypeRange; 10046 10047 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10048 std::min(MaxWidth, OutputTypeRange.Width), 10049 InConstantContext); 10050 10051 // Bail out if the subexpr's range is as wide as the cast type. 10052 if (SubRange.Width >= OutputTypeRange.Width) 10053 return OutputTypeRange; 10054 10055 // Otherwise, we take the smaller width, and we're non-negative if 10056 // either the output type or the subexpr is. 10057 return IntRange(SubRange.Width, 10058 SubRange.NonNegative || OutputTypeRange.NonNegative); 10059 } 10060 10061 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10062 // If we can fold the condition, just take that operand. 10063 bool CondResult; 10064 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10065 return GetExprRange(C, 10066 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10067 MaxWidth, InConstantContext); 10068 10069 // Otherwise, conservatively merge. 10070 IntRange L = 10071 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10072 IntRange R = 10073 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10074 return IntRange::join(L, R); 10075 } 10076 10077 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10078 switch (BO->getOpcode()) { 10079 case BO_Cmp: 10080 llvm_unreachable("builtin <=> should have class type"); 10081 10082 // Boolean-valued operations are single-bit and positive. 10083 case BO_LAnd: 10084 case BO_LOr: 10085 case BO_LT: 10086 case BO_GT: 10087 case BO_LE: 10088 case BO_GE: 10089 case BO_EQ: 10090 case BO_NE: 10091 return IntRange::forBoolType(); 10092 10093 // The type of the assignments is the type of the LHS, so the RHS 10094 // is not necessarily the same type. 10095 case BO_MulAssign: 10096 case BO_DivAssign: 10097 case BO_RemAssign: 10098 case BO_AddAssign: 10099 case BO_SubAssign: 10100 case BO_XorAssign: 10101 case BO_OrAssign: 10102 // TODO: bitfields? 10103 return IntRange::forValueOfType(C, GetExprType(E)); 10104 10105 // Simple assignments just pass through the RHS, which will have 10106 // been coerced to the LHS type. 10107 case BO_Assign: 10108 // TODO: bitfields? 10109 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10110 10111 // Operations with opaque sources are black-listed. 10112 case BO_PtrMemD: 10113 case BO_PtrMemI: 10114 return IntRange::forValueOfType(C, GetExprType(E)); 10115 10116 // Bitwise-and uses the *infinum* of the two source ranges. 10117 case BO_And: 10118 case BO_AndAssign: 10119 return IntRange::meet( 10120 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10121 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10122 10123 // Left shift gets black-listed based on a judgement call. 10124 case BO_Shl: 10125 // ...except that we want to treat '1 << (blah)' as logically 10126 // positive. It's an important idiom. 10127 if (IntegerLiteral *I 10128 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10129 if (I->getValue() == 1) { 10130 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10131 return IntRange(R.Width, /*NonNegative*/ true); 10132 } 10133 } 10134 LLVM_FALLTHROUGH; 10135 10136 case BO_ShlAssign: 10137 return IntRange::forValueOfType(C, GetExprType(E)); 10138 10139 // Right shift by a constant can narrow its left argument. 10140 case BO_Shr: 10141 case BO_ShrAssign: { 10142 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10143 10144 // If the shift amount is a positive constant, drop the width by 10145 // that much. 10146 llvm::APSInt shift; 10147 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10148 shift.isNonNegative()) { 10149 unsigned zext = shift.getZExtValue(); 10150 if (zext >= L.Width) 10151 L.Width = (L.NonNegative ? 0 : 1); 10152 else 10153 L.Width -= zext; 10154 } 10155 10156 return L; 10157 } 10158 10159 // Comma acts as its right operand. 10160 case BO_Comma: 10161 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10162 10163 // Black-list pointer subtractions. 10164 case BO_Sub: 10165 if (BO->getLHS()->getType()->isPointerType()) 10166 return IntRange::forValueOfType(C, GetExprType(E)); 10167 break; 10168 10169 // The width of a division result is mostly determined by the size 10170 // of the LHS. 10171 case BO_Div: { 10172 // Don't 'pre-truncate' the operands. 10173 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10174 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10175 10176 // If the divisor is constant, use that. 10177 llvm::APSInt divisor; 10178 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10179 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10180 if (log2 >= L.Width) 10181 L.Width = (L.NonNegative ? 0 : 1); 10182 else 10183 L.Width = std::min(L.Width - log2, MaxWidth); 10184 return L; 10185 } 10186 10187 // Otherwise, just use the LHS's width. 10188 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10189 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10190 } 10191 10192 // The result of a remainder can't be larger than the result of 10193 // either side. 10194 case BO_Rem: { 10195 // Don't 'pre-truncate' the operands. 10196 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10197 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10198 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10199 10200 IntRange meet = IntRange::meet(L, R); 10201 meet.Width = std::min(meet.Width, MaxWidth); 10202 return meet; 10203 } 10204 10205 // The default behavior is okay for these. 10206 case BO_Mul: 10207 case BO_Add: 10208 case BO_Xor: 10209 case BO_Or: 10210 break; 10211 } 10212 10213 // The default case is to treat the operation as if it were closed 10214 // on the narrowest type that encompasses both operands. 10215 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10216 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10217 return IntRange::join(L, R); 10218 } 10219 10220 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10221 switch (UO->getOpcode()) { 10222 // Boolean-valued operations are white-listed. 10223 case UO_LNot: 10224 return IntRange::forBoolType(); 10225 10226 // Operations with opaque sources are black-listed. 10227 case UO_Deref: 10228 case UO_AddrOf: // should be impossible 10229 return IntRange::forValueOfType(C, GetExprType(E)); 10230 10231 default: 10232 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10233 } 10234 } 10235 10236 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10237 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10238 10239 if (const auto *BitField = E->getSourceBitField()) 10240 return IntRange(BitField->getBitWidthValue(C), 10241 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10242 10243 return IntRange::forValueOfType(C, GetExprType(E)); 10244 } 10245 10246 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10247 bool InConstantContext) { 10248 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10249 } 10250 10251 /// Checks whether the given value, which currently has the given 10252 /// source semantics, has the same value when coerced through the 10253 /// target semantics. 10254 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10255 const llvm::fltSemantics &Src, 10256 const llvm::fltSemantics &Tgt) { 10257 llvm::APFloat truncated = value; 10258 10259 bool ignored; 10260 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10261 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10262 10263 return truncated.bitwiseIsEqual(value); 10264 } 10265 10266 /// Checks whether the given value, which currently has the given 10267 /// source semantics, has the same value when coerced through the 10268 /// target semantics. 10269 /// 10270 /// The value might be a vector of floats (or a complex number). 10271 static bool IsSameFloatAfterCast(const APValue &value, 10272 const llvm::fltSemantics &Src, 10273 const llvm::fltSemantics &Tgt) { 10274 if (value.isFloat()) 10275 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10276 10277 if (value.isVector()) { 10278 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10279 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10280 return false; 10281 return true; 10282 } 10283 10284 assert(value.isComplexFloat()); 10285 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10286 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10287 } 10288 10289 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10290 bool IsListInit = false); 10291 10292 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10293 // Suppress cases where we are comparing against an enum constant. 10294 if (const DeclRefExpr *DR = 10295 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10296 if (isa<EnumConstantDecl>(DR->getDecl())) 10297 return true; 10298 10299 // Suppress cases where the value is expanded from a macro, unless that macro 10300 // is how a language represents a boolean literal. This is the case in both C 10301 // and Objective-C. 10302 SourceLocation BeginLoc = E->getBeginLoc(); 10303 if (BeginLoc.isMacroID()) { 10304 StringRef MacroName = Lexer::getImmediateMacroName( 10305 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10306 return MacroName != "YES" && MacroName != "NO" && 10307 MacroName != "true" && MacroName != "false"; 10308 } 10309 10310 return false; 10311 } 10312 10313 static bool isKnownToHaveUnsignedValue(Expr *E) { 10314 return E->getType()->isIntegerType() && 10315 (!E->getType()->isSignedIntegerType() || 10316 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10317 } 10318 10319 namespace { 10320 /// The promoted range of values of a type. In general this has the 10321 /// following structure: 10322 /// 10323 /// |-----------| . . . |-----------| 10324 /// ^ ^ ^ ^ 10325 /// Min HoleMin HoleMax Max 10326 /// 10327 /// ... where there is only a hole if a signed type is promoted to unsigned 10328 /// (in which case Min and Max are the smallest and largest representable 10329 /// values). 10330 struct PromotedRange { 10331 // Min, or HoleMax if there is a hole. 10332 llvm::APSInt PromotedMin; 10333 // Max, or HoleMin if there is a hole. 10334 llvm::APSInt PromotedMax; 10335 10336 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10337 if (R.Width == 0) 10338 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10339 else if (R.Width >= BitWidth && !Unsigned) { 10340 // Promotion made the type *narrower*. This happens when promoting 10341 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10342 // Treat all values of 'signed int' as being in range for now. 10343 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10344 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10345 } else { 10346 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10347 .extOrTrunc(BitWidth); 10348 PromotedMin.setIsUnsigned(Unsigned); 10349 10350 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10351 .extOrTrunc(BitWidth); 10352 PromotedMax.setIsUnsigned(Unsigned); 10353 } 10354 } 10355 10356 // Determine whether this range is contiguous (has no hole). 10357 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10358 10359 // Where a constant value is within the range. 10360 enum ComparisonResult { 10361 LT = 0x1, 10362 LE = 0x2, 10363 GT = 0x4, 10364 GE = 0x8, 10365 EQ = 0x10, 10366 NE = 0x20, 10367 InRangeFlag = 0x40, 10368 10369 Less = LE | LT | NE, 10370 Min = LE | InRangeFlag, 10371 InRange = InRangeFlag, 10372 Max = GE | InRangeFlag, 10373 Greater = GE | GT | NE, 10374 10375 OnlyValue = LE | GE | EQ | InRangeFlag, 10376 InHole = NE 10377 }; 10378 10379 ComparisonResult compare(const llvm::APSInt &Value) const { 10380 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10381 Value.isUnsigned() == PromotedMin.isUnsigned()); 10382 if (!isContiguous()) { 10383 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10384 if (Value.isMinValue()) return Min; 10385 if (Value.isMaxValue()) return Max; 10386 if (Value >= PromotedMin) return InRange; 10387 if (Value <= PromotedMax) return InRange; 10388 return InHole; 10389 } 10390 10391 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10392 case -1: return Less; 10393 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10394 case 1: 10395 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10396 case -1: return InRange; 10397 case 0: return Max; 10398 case 1: return Greater; 10399 } 10400 } 10401 10402 llvm_unreachable("impossible compare result"); 10403 } 10404 10405 static llvm::Optional<StringRef> 10406 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10407 if (Op == BO_Cmp) { 10408 ComparisonResult LTFlag = LT, GTFlag = GT; 10409 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10410 10411 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10412 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10413 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10414 return llvm::None; 10415 } 10416 10417 ComparisonResult TrueFlag, FalseFlag; 10418 if (Op == BO_EQ) { 10419 TrueFlag = EQ; 10420 FalseFlag = NE; 10421 } else if (Op == BO_NE) { 10422 TrueFlag = NE; 10423 FalseFlag = EQ; 10424 } else { 10425 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10426 TrueFlag = LT; 10427 FalseFlag = GE; 10428 } else { 10429 TrueFlag = GT; 10430 FalseFlag = LE; 10431 } 10432 if (Op == BO_GE || Op == BO_LE) 10433 std::swap(TrueFlag, FalseFlag); 10434 } 10435 if (R & TrueFlag) 10436 return StringRef("true"); 10437 if (R & FalseFlag) 10438 return StringRef("false"); 10439 return llvm::None; 10440 } 10441 }; 10442 } 10443 10444 static bool HasEnumType(Expr *E) { 10445 // Strip off implicit integral promotions. 10446 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10447 if (ICE->getCastKind() != CK_IntegralCast && 10448 ICE->getCastKind() != CK_NoOp) 10449 break; 10450 E = ICE->getSubExpr(); 10451 } 10452 10453 return E->getType()->isEnumeralType(); 10454 } 10455 10456 static int classifyConstantValue(Expr *Constant) { 10457 // The values of this enumeration are used in the diagnostics 10458 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10459 enum ConstantValueKind { 10460 Miscellaneous = 0, 10461 LiteralTrue, 10462 LiteralFalse 10463 }; 10464 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10465 return BL->getValue() ? ConstantValueKind::LiteralTrue 10466 : ConstantValueKind::LiteralFalse; 10467 return ConstantValueKind::Miscellaneous; 10468 } 10469 10470 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10471 Expr *Constant, Expr *Other, 10472 const llvm::APSInt &Value, 10473 bool RhsConstant) { 10474 if (S.inTemplateInstantiation()) 10475 return false; 10476 10477 Expr *OriginalOther = Other; 10478 10479 Constant = Constant->IgnoreParenImpCasts(); 10480 Other = Other->IgnoreParenImpCasts(); 10481 10482 // Suppress warnings on tautological comparisons between values of the same 10483 // enumeration type. There are only two ways we could warn on this: 10484 // - If the constant is outside the range of representable values of 10485 // the enumeration. In such a case, we should warn about the cast 10486 // to enumeration type, not about the comparison. 10487 // - If the constant is the maximum / minimum in-range value. For an 10488 // enumeratin type, such comparisons can be meaningful and useful. 10489 if (Constant->getType()->isEnumeralType() && 10490 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10491 return false; 10492 10493 // TODO: Investigate using GetExprRange() to get tighter bounds 10494 // on the bit ranges. 10495 QualType OtherT = Other->getType(); 10496 if (const auto *AT = OtherT->getAs<AtomicType>()) 10497 OtherT = AT->getValueType(); 10498 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10499 10500 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10501 // (Namely, macOS). 10502 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10503 S.NSAPIObj->isObjCBOOLType(OtherT) && 10504 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10505 10506 // Whether we're treating Other as being a bool because of the form of 10507 // expression despite it having another type (typically 'int' in C). 10508 bool OtherIsBooleanDespiteType = 10509 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10510 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10511 OtherRange = IntRange::forBoolType(); 10512 10513 // Determine the promoted range of the other type and see if a comparison of 10514 // the constant against that range is tautological. 10515 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10516 Value.isUnsigned()); 10517 auto Cmp = OtherPromotedRange.compare(Value); 10518 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10519 if (!Result) 10520 return false; 10521 10522 // Suppress the diagnostic for an in-range comparison if the constant comes 10523 // from a macro or enumerator. We don't want to diagnose 10524 // 10525 // some_long_value <= INT_MAX 10526 // 10527 // when sizeof(int) == sizeof(long). 10528 bool InRange = Cmp & PromotedRange::InRangeFlag; 10529 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10530 return false; 10531 10532 // If this is a comparison to an enum constant, include that 10533 // constant in the diagnostic. 10534 const EnumConstantDecl *ED = nullptr; 10535 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10536 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10537 10538 // Should be enough for uint128 (39 decimal digits) 10539 SmallString<64> PrettySourceValue; 10540 llvm::raw_svector_ostream OS(PrettySourceValue); 10541 if (ED) { 10542 OS << '\'' << *ED << "' (" << Value << ")"; 10543 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10544 Constant->IgnoreParenImpCasts())) { 10545 OS << (BL->getValue() ? "YES" : "NO"); 10546 } else { 10547 OS << Value; 10548 } 10549 10550 if (IsObjCSignedCharBool) { 10551 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10552 S.PDiag(diag::warn_tautological_compare_objc_bool) 10553 << OS.str() << *Result); 10554 return true; 10555 } 10556 10557 // FIXME: We use a somewhat different formatting for the in-range cases and 10558 // cases involving boolean values for historical reasons. We should pick a 10559 // consistent way of presenting these diagnostics. 10560 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10561 10562 S.DiagRuntimeBehavior( 10563 E->getOperatorLoc(), E, 10564 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10565 : diag::warn_tautological_bool_compare) 10566 << OS.str() << classifyConstantValue(Constant) << OtherT 10567 << OtherIsBooleanDespiteType << *Result 10568 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10569 } else { 10570 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10571 ? (HasEnumType(OriginalOther) 10572 ? diag::warn_unsigned_enum_always_true_comparison 10573 : diag::warn_unsigned_always_true_comparison) 10574 : diag::warn_tautological_constant_compare; 10575 10576 S.Diag(E->getOperatorLoc(), Diag) 10577 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10578 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10579 } 10580 10581 return true; 10582 } 10583 10584 /// Analyze the operands of the given comparison. Implements the 10585 /// fallback case from AnalyzeComparison. 10586 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10587 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10588 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10589 } 10590 10591 /// Implements -Wsign-compare. 10592 /// 10593 /// \param E the binary operator to check for warnings 10594 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10595 // The type the comparison is being performed in. 10596 QualType T = E->getLHS()->getType(); 10597 10598 // Only analyze comparison operators where both sides have been converted to 10599 // the same type. 10600 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10601 return AnalyzeImpConvsInComparison(S, E); 10602 10603 // Don't analyze value-dependent comparisons directly. 10604 if (E->isValueDependent()) 10605 return AnalyzeImpConvsInComparison(S, E); 10606 10607 Expr *LHS = E->getLHS(); 10608 Expr *RHS = E->getRHS(); 10609 10610 if (T->isIntegralType(S.Context)) { 10611 llvm::APSInt RHSValue; 10612 llvm::APSInt LHSValue; 10613 10614 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10615 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10616 10617 // We don't care about expressions whose result is a constant. 10618 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10619 return AnalyzeImpConvsInComparison(S, E); 10620 10621 // We only care about expressions where just one side is literal 10622 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10623 // Is the constant on the RHS or LHS? 10624 const bool RhsConstant = IsRHSIntegralLiteral; 10625 Expr *Const = RhsConstant ? RHS : LHS; 10626 Expr *Other = RhsConstant ? LHS : RHS; 10627 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10628 10629 // Check whether an integer constant comparison results in a value 10630 // of 'true' or 'false'. 10631 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10632 return AnalyzeImpConvsInComparison(S, E); 10633 } 10634 } 10635 10636 if (!T->hasUnsignedIntegerRepresentation()) { 10637 // We don't do anything special if this isn't an unsigned integral 10638 // comparison: we're only interested in integral comparisons, and 10639 // signed comparisons only happen in cases we don't care to warn about. 10640 return AnalyzeImpConvsInComparison(S, E); 10641 } 10642 10643 LHS = LHS->IgnoreParenImpCasts(); 10644 RHS = RHS->IgnoreParenImpCasts(); 10645 10646 if (!S.getLangOpts().CPlusPlus) { 10647 // Avoid warning about comparison of integers with different signs when 10648 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10649 // the type of `E`. 10650 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10651 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10652 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10653 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10654 } 10655 10656 // Check to see if one of the (unmodified) operands is of different 10657 // signedness. 10658 Expr *signedOperand, *unsignedOperand; 10659 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10660 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10661 "unsigned comparison between two signed integer expressions?"); 10662 signedOperand = LHS; 10663 unsignedOperand = RHS; 10664 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10665 signedOperand = RHS; 10666 unsignedOperand = LHS; 10667 } else { 10668 return AnalyzeImpConvsInComparison(S, E); 10669 } 10670 10671 // Otherwise, calculate the effective range of the signed operand. 10672 IntRange signedRange = 10673 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10674 10675 // Go ahead and analyze implicit conversions in the operands. Note 10676 // that we skip the implicit conversions on both sides. 10677 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10678 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10679 10680 // If the signed range is non-negative, -Wsign-compare won't fire. 10681 if (signedRange.NonNegative) 10682 return; 10683 10684 // For (in)equality comparisons, if the unsigned operand is a 10685 // constant which cannot collide with a overflowed signed operand, 10686 // then reinterpreting the signed operand as unsigned will not 10687 // change the result of the comparison. 10688 if (E->isEqualityOp()) { 10689 unsigned comparisonWidth = S.Context.getIntWidth(T); 10690 IntRange unsignedRange = 10691 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10692 10693 // We should never be unable to prove that the unsigned operand is 10694 // non-negative. 10695 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10696 10697 if (unsignedRange.Width < comparisonWidth) 10698 return; 10699 } 10700 10701 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10702 S.PDiag(diag::warn_mixed_sign_comparison) 10703 << LHS->getType() << RHS->getType() 10704 << LHS->getSourceRange() << RHS->getSourceRange()); 10705 } 10706 10707 /// Analyzes an attempt to assign the given value to a bitfield. 10708 /// 10709 /// Returns true if there was something fishy about the attempt. 10710 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10711 SourceLocation InitLoc) { 10712 assert(Bitfield->isBitField()); 10713 if (Bitfield->isInvalidDecl()) 10714 return false; 10715 10716 // White-list bool bitfields. 10717 QualType BitfieldType = Bitfield->getType(); 10718 if (BitfieldType->isBooleanType()) 10719 return false; 10720 10721 if (BitfieldType->isEnumeralType()) { 10722 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10723 // If the underlying enum type was not explicitly specified as an unsigned 10724 // type and the enum contain only positive values, MSVC++ will cause an 10725 // inconsistency by storing this as a signed type. 10726 if (S.getLangOpts().CPlusPlus11 && 10727 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10728 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10729 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10730 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10731 << BitfieldEnumDecl->getNameAsString(); 10732 } 10733 } 10734 10735 if (Bitfield->getType()->isBooleanType()) 10736 return false; 10737 10738 // Ignore value- or type-dependent expressions. 10739 if (Bitfield->getBitWidth()->isValueDependent() || 10740 Bitfield->getBitWidth()->isTypeDependent() || 10741 Init->isValueDependent() || 10742 Init->isTypeDependent()) 10743 return false; 10744 10745 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10746 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10747 10748 Expr::EvalResult Result; 10749 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10750 Expr::SE_AllowSideEffects)) { 10751 // The RHS is not constant. If the RHS has an enum type, make sure the 10752 // bitfield is wide enough to hold all the values of the enum without 10753 // truncation. 10754 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10755 EnumDecl *ED = EnumTy->getDecl(); 10756 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10757 10758 // Enum types are implicitly signed on Windows, so check if there are any 10759 // negative enumerators to see if the enum was intended to be signed or 10760 // not. 10761 bool SignedEnum = ED->getNumNegativeBits() > 0; 10762 10763 // Check for surprising sign changes when assigning enum values to a 10764 // bitfield of different signedness. If the bitfield is signed and we 10765 // have exactly the right number of bits to store this unsigned enum, 10766 // suggest changing the enum to an unsigned type. This typically happens 10767 // on Windows where unfixed enums always use an underlying type of 'int'. 10768 unsigned DiagID = 0; 10769 if (SignedEnum && !SignedBitfield) { 10770 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10771 } else if (SignedBitfield && !SignedEnum && 10772 ED->getNumPositiveBits() == FieldWidth) { 10773 DiagID = diag::warn_signed_bitfield_enum_conversion; 10774 } 10775 10776 if (DiagID) { 10777 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10778 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10779 SourceRange TypeRange = 10780 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10781 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10782 << SignedEnum << TypeRange; 10783 } 10784 10785 // Compute the required bitwidth. If the enum has negative values, we need 10786 // one more bit than the normal number of positive bits to represent the 10787 // sign bit. 10788 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10789 ED->getNumNegativeBits()) 10790 : ED->getNumPositiveBits(); 10791 10792 // Check the bitwidth. 10793 if (BitsNeeded > FieldWidth) { 10794 Expr *WidthExpr = Bitfield->getBitWidth(); 10795 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10796 << Bitfield << ED; 10797 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10798 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10799 } 10800 } 10801 10802 return false; 10803 } 10804 10805 llvm::APSInt Value = Result.Val.getInt(); 10806 10807 unsigned OriginalWidth = Value.getBitWidth(); 10808 10809 if (!Value.isSigned() || Value.isNegative()) 10810 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10811 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10812 OriginalWidth = Value.getMinSignedBits(); 10813 10814 if (OriginalWidth <= FieldWidth) 10815 return false; 10816 10817 // Compute the value which the bitfield will contain. 10818 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10819 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10820 10821 // Check whether the stored value is equal to the original value. 10822 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10823 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10824 return false; 10825 10826 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10827 // therefore don't strictly fit into a signed bitfield of width 1. 10828 if (FieldWidth == 1 && Value == 1) 10829 return false; 10830 10831 std::string PrettyValue = Value.toString(10); 10832 std::string PrettyTrunc = TruncatedValue.toString(10); 10833 10834 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10835 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10836 << Init->getSourceRange(); 10837 10838 return true; 10839 } 10840 10841 /// Analyze the given simple or compound assignment for warning-worthy 10842 /// operations. 10843 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10844 // Just recurse on the LHS. 10845 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10846 10847 // We want to recurse on the RHS as normal unless we're assigning to 10848 // a bitfield. 10849 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10850 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10851 E->getOperatorLoc())) { 10852 // Recurse, ignoring any implicit conversions on the RHS. 10853 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10854 E->getOperatorLoc()); 10855 } 10856 } 10857 10858 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10859 10860 // Diagnose implicitly sequentially-consistent atomic assignment. 10861 if (E->getLHS()->getType()->isAtomicType()) 10862 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10863 } 10864 10865 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10866 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10867 SourceLocation CContext, unsigned diag, 10868 bool pruneControlFlow = false) { 10869 if (pruneControlFlow) { 10870 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10871 S.PDiag(diag) 10872 << SourceType << T << E->getSourceRange() 10873 << SourceRange(CContext)); 10874 return; 10875 } 10876 S.Diag(E->getExprLoc(), diag) 10877 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10878 } 10879 10880 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10881 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10882 SourceLocation CContext, 10883 unsigned diag, bool pruneControlFlow = false) { 10884 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10885 } 10886 10887 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10888 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10889 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10890 } 10891 10892 static void adornObjCBoolConversionDiagWithTernaryFixit( 10893 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10894 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10895 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10896 Ignored = OVE->getSourceExpr(); 10897 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10898 isa<BinaryOperator>(Ignored) || 10899 isa<CXXOperatorCallExpr>(Ignored); 10900 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10901 if (NeedsParens) 10902 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10903 << FixItHint::CreateInsertion(EndLoc, ")"); 10904 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10905 } 10906 10907 /// Diagnose an implicit cast from a floating point value to an integer value. 10908 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10909 SourceLocation CContext) { 10910 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10911 const bool PruneWarnings = S.inTemplateInstantiation(); 10912 10913 Expr *InnerE = E->IgnoreParenImpCasts(); 10914 // We also want to warn on, e.g., "int i = -1.234" 10915 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10916 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10917 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10918 10919 const bool IsLiteral = 10920 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10921 10922 llvm::APFloat Value(0.0); 10923 bool IsConstant = 10924 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10925 if (!IsConstant) { 10926 if (isObjCSignedCharBool(S, T)) { 10927 return adornObjCBoolConversionDiagWithTernaryFixit( 10928 S, E, 10929 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10930 << E->getType()); 10931 } 10932 10933 return DiagnoseImpCast(S, E, T, CContext, 10934 diag::warn_impcast_float_integer, PruneWarnings); 10935 } 10936 10937 bool isExact = false; 10938 10939 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10940 T->hasUnsignedIntegerRepresentation()); 10941 llvm::APFloat::opStatus Result = Value.convertToInteger( 10942 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10943 10944 // FIXME: Force the precision of the source value down so we don't print 10945 // digits which are usually useless (we don't really care here if we 10946 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10947 // would automatically print the shortest representation, but it's a bit 10948 // tricky to implement. 10949 SmallString<16> PrettySourceValue; 10950 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10951 precision = (precision * 59 + 195) / 196; 10952 Value.toString(PrettySourceValue, precision); 10953 10954 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10955 return adornObjCBoolConversionDiagWithTernaryFixit( 10956 S, E, 10957 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10958 << PrettySourceValue); 10959 } 10960 10961 if (Result == llvm::APFloat::opOK && isExact) { 10962 if (IsLiteral) return; 10963 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10964 PruneWarnings); 10965 } 10966 10967 // Conversion of a floating-point value to a non-bool integer where the 10968 // integral part cannot be represented by the integer type is undefined. 10969 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10970 return DiagnoseImpCast( 10971 S, E, T, CContext, 10972 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10973 : diag::warn_impcast_float_to_integer_out_of_range, 10974 PruneWarnings); 10975 10976 unsigned DiagID = 0; 10977 if (IsLiteral) { 10978 // Warn on floating point literal to integer. 10979 DiagID = diag::warn_impcast_literal_float_to_integer; 10980 } else if (IntegerValue == 0) { 10981 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10982 return DiagnoseImpCast(S, E, T, CContext, 10983 diag::warn_impcast_float_integer, PruneWarnings); 10984 } 10985 // Warn on non-zero to zero conversion. 10986 DiagID = diag::warn_impcast_float_to_integer_zero; 10987 } else { 10988 if (IntegerValue.isUnsigned()) { 10989 if (!IntegerValue.isMaxValue()) { 10990 return DiagnoseImpCast(S, E, T, CContext, 10991 diag::warn_impcast_float_integer, PruneWarnings); 10992 } 10993 } else { // IntegerValue.isSigned() 10994 if (!IntegerValue.isMaxSignedValue() && 10995 !IntegerValue.isMinSignedValue()) { 10996 return DiagnoseImpCast(S, E, T, CContext, 10997 diag::warn_impcast_float_integer, PruneWarnings); 10998 } 10999 } 11000 // Warn on evaluatable floating point expression to integer conversion. 11001 DiagID = diag::warn_impcast_float_to_integer; 11002 } 11003 11004 SmallString<16> PrettyTargetValue; 11005 if (IsBool) 11006 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11007 else 11008 IntegerValue.toString(PrettyTargetValue); 11009 11010 if (PruneWarnings) { 11011 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11012 S.PDiag(DiagID) 11013 << E->getType() << T.getUnqualifiedType() 11014 << PrettySourceValue << PrettyTargetValue 11015 << E->getSourceRange() << SourceRange(CContext)); 11016 } else { 11017 S.Diag(E->getExprLoc(), DiagID) 11018 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11019 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11020 } 11021 } 11022 11023 /// Analyze the given compound assignment for the possible losing of 11024 /// floating-point precision. 11025 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11026 assert(isa<CompoundAssignOperator>(E) && 11027 "Must be compound assignment operation"); 11028 // Recurse on the LHS and RHS in here 11029 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11030 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11031 11032 if (E->getLHS()->getType()->isAtomicType()) 11033 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11034 11035 // Now check the outermost expression 11036 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11037 const auto *RBT = cast<CompoundAssignOperator>(E) 11038 ->getComputationResultType() 11039 ->getAs<BuiltinType>(); 11040 11041 // The below checks assume source is floating point. 11042 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11043 11044 // If source is floating point but target is an integer. 11045 if (ResultBT->isInteger()) 11046 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11047 E->getExprLoc(), diag::warn_impcast_float_integer); 11048 11049 if (!ResultBT->isFloatingPoint()) 11050 return; 11051 11052 // If both source and target are floating points, warn about losing precision. 11053 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11054 QualType(ResultBT, 0), QualType(RBT, 0)); 11055 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11056 // warn about dropping FP rank. 11057 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11058 diag::warn_impcast_float_result_precision); 11059 } 11060 11061 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11062 IntRange Range) { 11063 if (!Range.Width) return "0"; 11064 11065 llvm::APSInt ValueInRange = Value; 11066 ValueInRange.setIsSigned(!Range.NonNegative); 11067 ValueInRange = ValueInRange.trunc(Range.Width); 11068 return ValueInRange.toString(10); 11069 } 11070 11071 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11072 if (!isa<ImplicitCastExpr>(Ex)) 11073 return false; 11074 11075 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11076 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11077 const Type *Source = 11078 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11079 if (Target->isDependentType()) 11080 return false; 11081 11082 const BuiltinType *FloatCandidateBT = 11083 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11084 const Type *BoolCandidateType = ToBool ? Target : Source; 11085 11086 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11087 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11088 } 11089 11090 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11091 SourceLocation CC) { 11092 unsigned NumArgs = TheCall->getNumArgs(); 11093 for (unsigned i = 0; i < NumArgs; ++i) { 11094 Expr *CurrA = TheCall->getArg(i); 11095 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11096 continue; 11097 11098 bool IsSwapped = ((i > 0) && 11099 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11100 IsSwapped |= ((i < (NumArgs - 1)) && 11101 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11102 if (IsSwapped) { 11103 // Warn on this floating-point to bool conversion. 11104 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11105 CurrA->getType(), CC, 11106 diag::warn_impcast_floating_point_to_bool); 11107 } 11108 } 11109 } 11110 11111 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11112 SourceLocation CC) { 11113 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11114 E->getExprLoc())) 11115 return; 11116 11117 // Don't warn on functions which have return type nullptr_t. 11118 if (isa<CallExpr>(E)) 11119 return; 11120 11121 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11122 const Expr::NullPointerConstantKind NullKind = 11123 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11124 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11125 return; 11126 11127 // Return if target type is a safe conversion. 11128 if (T->isAnyPointerType() || T->isBlockPointerType() || 11129 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11130 return; 11131 11132 SourceLocation Loc = E->getSourceRange().getBegin(); 11133 11134 // Venture through the macro stacks to get to the source of macro arguments. 11135 // The new location is a better location than the complete location that was 11136 // passed in. 11137 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11138 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11139 11140 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11141 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11142 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11143 Loc, S.SourceMgr, S.getLangOpts()); 11144 if (MacroName == "NULL") 11145 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11146 } 11147 11148 // Only warn if the null and context location are in the same macro expansion. 11149 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11150 return; 11151 11152 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11153 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11154 << FixItHint::CreateReplacement(Loc, 11155 S.getFixItZeroLiteralForType(T, Loc)); 11156 } 11157 11158 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11159 ObjCArrayLiteral *ArrayLiteral); 11160 11161 static void 11162 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11163 ObjCDictionaryLiteral *DictionaryLiteral); 11164 11165 /// Check a single element within a collection literal against the 11166 /// target element type. 11167 static void checkObjCCollectionLiteralElement(Sema &S, 11168 QualType TargetElementType, 11169 Expr *Element, 11170 unsigned ElementKind) { 11171 // Skip a bitcast to 'id' or qualified 'id'. 11172 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11173 if (ICE->getCastKind() == CK_BitCast && 11174 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11175 Element = ICE->getSubExpr(); 11176 } 11177 11178 QualType ElementType = Element->getType(); 11179 ExprResult ElementResult(Element); 11180 if (ElementType->getAs<ObjCObjectPointerType>() && 11181 S.CheckSingleAssignmentConstraints(TargetElementType, 11182 ElementResult, 11183 false, false) 11184 != Sema::Compatible) { 11185 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11186 << ElementType << ElementKind << TargetElementType 11187 << Element->getSourceRange(); 11188 } 11189 11190 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11191 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11192 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11193 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11194 } 11195 11196 /// Check an Objective-C array literal being converted to the given 11197 /// target type. 11198 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11199 ObjCArrayLiteral *ArrayLiteral) { 11200 if (!S.NSArrayDecl) 11201 return; 11202 11203 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11204 if (!TargetObjCPtr) 11205 return; 11206 11207 if (TargetObjCPtr->isUnspecialized() || 11208 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11209 != S.NSArrayDecl->getCanonicalDecl()) 11210 return; 11211 11212 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11213 if (TypeArgs.size() != 1) 11214 return; 11215 11216 QualType TargetElementType = TypeArgs[0]; 11217 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11218 checkObjCCollectionLiteralElement(S, TargetElementType, 11219 ArrayLiteral->getElement(I), 11220 0); 11221 } 11222 } 11223 11224 /// Check an Objective-C dictionary literal being converted to the given 11225 /// target type. 11226 static void 11227 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11228 ObjCDictionaryLiteral *DictionaryLiteral) { 11229 if (!S.NSDictionaryDecl) 11230 return; 11231 11232 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11233 if (!TargetObjCPtr) 11234 return; 11235 11236 if (TargetObjCPtr->isUnspecialized() || 11237 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11238 != S.NSDictionaryDecl->getCanonicalDecl()) 11239 return; 11240 11241 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11242 if (TypeArgs.size() != 2) 11243 return; 11244 11245 QualType TargetKeyType = TypeArgs[0]; 11246 QualType TargetObjectType = TypeArgs[1]; 11247 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11248 auto Element = DictionaryLiteral->getKeyValueElement(I); 11249 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11250 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11251 } 11252 } 11253 11254 // Helper function to filter out cases for constant width constant conversion. 11255 // Don't warn on char array initialization or for non-decimal values. 11256 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11257 SourceLocation CC) { 11258 // If initializing from a constant, and the constant starts with '0', 11259 // then it is a binary, octal, or hexadecimal. Allow these constants 11260 // to fill all the bits, even if there is a sign change. 11261 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11262 const char FirstLiteralCharacter = 11263 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11264 if (FirstLiteralCharacter == '0') 11265 return false; 11266 } 11267 11268 // If the CC location points to a '{', and the type is char, then assume 11269 // assume it is an array initialization. 11270 if (CC.isValid() && T->isCharType()) { 11271 const char FirstContextCharacter = 11272 S.getSourceManager().getCharacterData(CC)[0]; 11273 if (FirstContextCharacter == '{') 11274 return false; 11275 } 11276 11277 return true; 11278 } 11279 11280 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11281 const auto *IL = dyn_cast<IntegerLiteral>(E); 11282 if (!IL) { 11283 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11284 if (UO->getOpcode() == UO_Minus) 11285 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11286 } 11287 } 11288 11289 return IL; 11290 } 11291 11292 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11293 E = E->IgnoreParenImpCasts(); 11294 SourceLocation ExprLoc = E->getExprLoc(); 11295 11296 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11297 BinaryOperator::Opcode Opc = BO->getOpcode(); 11298 Expr::EvalResult Result; 11299 // Do not diagnose unsigned shifts. 11300 if (Opc == BO_Shl) { 11301 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11302 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11303 if (LHS && LHS->getValue() == 0) 11304 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11305 else if (!E->isValueDependent() && LHS && RHS && 11306 RHS->getValue().isNonNegative() && 11307 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11308 S.Diag(ExprLoc, diag::warn_left_shift_always) 11309 << (Result.Val.getInt() != 0); 11310 else if (E->getType()->isSignedIntegerType()) 11311 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11312 } 11313 } 11314 11315 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11316 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11317 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11318 if (!LHS || !RHS) 11319 return; 11320 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11321 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11322 // Do not diagnose common idioms. 11323 return; 11324 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11325 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11326 } 11327 } 11328 11329 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11330 SourceLocation CC, 11331 bool *ICContext = nullptr, 11332 bool IsListInit = false) { 11333 if (E->isTypeDependent() || E->isValueDependent()) return; 11334 11335 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11336 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11337 if (Source == Target) return; 11338 if (Target->isDependentType()) return; 11339 11340 // If the conversion context location is invalid don't complain. We also 11341 // don't want to emit a warning if the issue occurs from the expansion of 11342 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11343 // delay this check as long as possible. Once we detect we are in that 11344 // scenario, we just return. 11345 if (CC.isInvalid()) 11346 return; 11347 11348 if (Source->isAtomicType()) 11349 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11350 11351 // Diagnose implicit casts to bool. 11352 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11353 if (isa<StringLiteral>(E)) 11354 // Warn on string literal to bool. Checks for string literals in logical 11355 // and expressions, for instance, assert(0 && "error here"), are 11356 // prevented by a check in AnalyzeImplicitConversions(). 11357 return DiagnoseImpCast(S, E, T, CC, 11358 diag::warn_impcast_string_literal_to_bool); 11359 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11360 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11361 // This covers the literal expressions that evaluate to Objective-C 11362 // objects. 11363 return DiagnoseImpCast(S, E, T, CC, 11364 diag::warn_impcast_objective_c_literal_to_bool); 11365 } 11366 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11367 // Warn on pointer to bool conversion that is always true. 11368 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11369 SourceRange(CC)); 11370 } 11371 } 11372 11373 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11374 // is a typedef for signed char (macOS), then that constant value has to be 1 11375 // or 0. 11376 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11377 Expr::EvalResult Result; 11378 if (E->EvaluateAsInt(Result, S.getASTContext(), 11379 Expr::SE_AllowSideEffects)) { 11380 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11381 adornObjCBoolConversionDiagWithTernaryFixit( 11382 S, E, 11383 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11384 << Result.Val.getInt().toString(10)); 11385 } 11386 return; 11387 } 11388 } 11389 11390 // Check implicit casts from Objective-C collection literals to specialized 11391 // collection types, e.g., NSArray<NSString *> *. 11392 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11393 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11394 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11395 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11396 11397 // Strip vector types. 11398 if (isa<VectorType>(Source)) { 11399 if (!isa<VectorType>(Target)) { 11400 if (S.SourceMgr.isInSystemMacro(CC)) 11401 return; 11402 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11403 } 11404 11405 // If the vector cast is cast between two vectors of the same size, it is 11406 // a bitcast, not a conversion. 11407 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11408 return; 11409 11410 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11411 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11412 } 11413 if (auto VecTy = dyn_cast<VectorType>(Target)) 11414 Target = VecTy->getElementType().getTypePtr(); 11415 11416 // Strip complex types. 11417 if (isa<ComplexType>(Source)) { 11418 if (!isa<ComplexType>(Target)) { 11419 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11420 return; 11421 11422 return DiagnoseImpCast(S, E, T, CC, 11423 S.getLangOpts().CPlusPlus 11424 ? diag::err_impcast_complex_scalar 11425 : diag::warn_impcast_complex_scalar); 11426 } 11427 11428 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11429 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11430 } 11431 11432 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11433 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11434 11435 // If the source is floating point... 11436 if (SourceBT && SourceBT->isFloatingPoint()) { 11437 // ...and the target is floating point... 11438 if (TargetBT && TargetBT->isFloatingPoint()) { 11439 // ...then warn if we're dropping FP rank. 11440 11441 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11442 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11443 if (Order > 0) { 11444 // Don't warn about float constants that are precisely 11445 // representable in the target type. 11446 Expr::EvalResult result; 11447 if (E->EvaluateAsRValue(result, S.Context)) { 11448 // Value might be a float, a float vector, or a float complex. 11449 if (IsSameFloatAfterCast(result.Val, 11450 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11451 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11452 return; 11453 } 11454 11455 if (S.SourceMgr.isInSystemMacro(CC)) 11456 return; 11457 11458 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11459 } 11460 // ... or possibly if we're increasing rank, too 11461 else if (Order < 0) { 11462 if (S.SourceMgr.isInSystemMacro(CC)) 11463 return; 11464 11465 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11466 } 11467 return; 11468 } 11469 11470 // If the target is integral, always warn. 11471 if (TargetBT && TargetBT->isInteger()) { 11472 if (S.SourceMgr.isInSystemMacro(CC)) 11473 return; 11474 11475 DiagnoseFloatingImpCast(S, E, T, CC); 11476 } 11477 11478 // Detect the case where a call result is converted from floating-point to 11479 // to bool, and the final argument to the call is converted from bool, to 11480 // discover this typo: 11481 // 11482 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11483 // 11484 // FIXME: This is an incredibly special case; is there some more general 11485 // way to detect this class of misplaced-parentheses bug? 11486 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11487 // Check last argument of function call to see if it is an 11488 // implicit cast from a type matching the type the result 11489 // is being cast to. 11490 CallExpr *CEx = cast<CallExpr>(E); 11491 if (unsigned NumArgs = CEx->getNumArgs()) { 11492 Expr *LastA = CEx->getArg(NumArgs - 1); 11493 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11494 if (isa<ImplicitCastExpr>(LastA) && 11495 InnerE->getType()->isBooleanType()) { 11496 // Warn on this floating-point to bool conversion 11497 DiagnoseImpCast(S, E, T, CC, 11498 diag::warn_impcast_floating_point_to_bool); 11499 } 11500 } 11501 } 11502 return; 11503 } 11504 11505 // Valid casts involving fixed point types should be accounted for here. 11506 if (Source->isFixedPointType()) { 11507 if (Target->isUnsaturatedFixedPointType()) { 11508 Expr::EvalResult Result; 11509 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11510 S.isConstantEvaluated())) { 11511 APFixedPoint Value = Result.Val.getFixedPoint(); 11512 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11513 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11514 if (Value > MaxVal || Value < MinVal) { 11515 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11516 S.PDiag(diag::warn_impcast_fixed_point_range) 11517 << Value.toString() << T 11518 << E->getSourceRange() 11519 << clang::SourceRange(CC)); 11520 return; 11521 } 11522 } 11523 } else if (Target->isIntegerType()) { 11524 Expr::EvalResult Result; 11525 if (!S.isConstantEvaluated() && 11526 E->EvaluateAsFixedPoint(Result, S.Context, 11527 Expr::SE_AllowSideEffects)) { 11528 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11529 11530 bool Overflowed; 11531 llvm::APSInt IntResult = FXResult.convertToInt( 11532 S.Context.getIntWidth(T), 11533 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11534 11535 if (Overflowed) { 11536 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11537 S.PDiag(diag::warn_impcast_fixed_point_range) 11538 << FXResult.toString() << T 11539 << E->getSourceRange() 11540 << clang::SourceRange(CC)); 11541 return; 11542 } 11543 } 11544 } 11545 } else if (Target->isUnsaturatedFixedPointType()) { 11546 if (Source->isIntegerType()) { 11547 Expr::EvalResult Result; 11548 if (!S.isConstantEvaluated() && 11549 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11550 llvm::APSInt Value = Result.Val.getInt(); 11551 11552 bool Overflowed; 11553 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11554 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11555 11556 if (Overflowed) { 11557 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11558 S.PDiag(diag::warn_impcast_fixed_point_range) 11559 << Value.toString(/*Radix=*/10) << T 11560 << E->getSourceRange() 11561 << clang::SourceRange(CC)); 11562 return; 11563 } 11564 } 11565 } 11566 } 11567 11568 // If we are casting an integer type to a floating point type without 11569 // initialization-list syntax, we might lose accuracy if the floating 11570 // point type has a narrower significand than the integer type. 11571 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11572 TargetBT->isFloatingType() && !IsListInit) { 11573 // Determine the number of precision bits in the source integer type. 11574 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11575 unsigned int SourcePrecision = SourceRange.Width; 11576 11577 // Determine the number of precision bits in the 11578 // target floating point type. 11579 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11580 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11581 11582 if (SourcePrecision > 0 && TargetPrecision > 0 && 11583 SourcePrecision > TargetPrecision) { 11584 11585 llvm::APSInt SourceInt; 11586 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11587 // If the source integer is a constant, convert it to the target 11588 // floating point type. Issue a warning if the value changes 11589 // during the whole conversion. 11590 llvm::APFloat TargetFloatValue( 11591 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11592 llvm::APFloat::opStatus ConversionStatus = 11593 TargetFloatValue.convertFromAPInt( 11594 SourceInt, SourceBT->isSignedInteger(), 11595 llvm::APFloat::rmNearestTiesToEven); 11596 11597 if (ConversionStatus != llvm::APFloat::opOK) { 11598 std::string PrettySourceValue = SourceInt.toString(10); 11599 SmallString<32> PrettyTargetValue; 11600 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11601 11602 S.DiagRuntimeBehavior( 11603 E->getExprLoc(), E, 11604 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11605 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11606 << E->getSourceRange() << clang::SourceRange(CC)); 11607 } 11608 } else { 11609 // Otherwise, the implicit conversion may lose precision. 11610 DiagnoseImpCast(S, E, T, CC, 11611 diag::warn_impcast_integer_float_precision); 11612 } 11613 } 11614 } 11615 11616 DiagnoseNullConversion(S, E, T, CC); 11617 11618 S.DiscardMisalignedMemberAddress(Target, E); 11619 11620 if (Target->isBooleanType()) 11621 DiagnoseIntInBoolContext(S, E); 11622 11623 if (!Source->isIntegerType() || !Target->isIntegerType()) 11624 return; 11625 11626 // TODO: remove this early return once the false positives for constant->bool 11627 // in templates, macros, etc, are reduced or removed. 11628 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11629 return; 11630 11631 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11632 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11633 return adornObjCBoolConversionDiagWithTernaryFixit( 11634 S, E, 11635 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11636 << E->getType()); 11637 } 11638 11639 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11640 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11641 11642 if (SourceRange.Width > TargetRange.Width) { 11643 // If the source is a constant, use a default-on diagnostic. 11644 // TODO: this should happen for bitfield stores, too. 11645 Expr::EvalResult Result; 11646 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11647 S.isConstantEvaluated())) { 11648 llvm::APSInt Value(32); 11649 Value = Result.Val.getInt(); 11650 11651 if (S.SourceMgr.isInSystemMacro(CC)) 11652 return; 11653 11654 std::string PrettySourceValue = Value.toString(10); 11655 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11656 11657 S.DiagRuntimeBehavior( 11658 E->getExprLoc(), E, 11659 S.PDiag(diag::warn_impcast_integer_precision_constant) 11660 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11661 << E->getSourceRange() << clang::SourceRange(CC)); 11662 return; 11663 } 11664 11665 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11666 if (S.SourceMgr.isInSystemMacro(CC)) 11667 return; 11668 11669 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11670 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11671 /* pruneControlFlow */ true); 11672 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11673 } 11674 11675 if (TargetRange.Width > SourceRange.Width) { 11676 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11677 if (UO->getOpcode() == UO_Minus) 11678 if (Source->isUnsignedIntegerType()) { 11679 if (Target->isUnsignedIntegerType()) 11680 return DiagnoseImpCast(S, E, T, CC, 11681 diag::warn_impcast_high_order_zero_bits); 11682 if (Target->isSignedIntegerType()) 11683 return DiagnoseImpCast(S, E, T, CC, 11684 diag::warn_impcast_nonnegative_result); 11685 } 11686 } 11687 11688 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11689 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11690 // Warn when doing a signed to signed conversion, warn if the positive 11691 // source value is exactly the width of the target type, which will 11692 // cause a negative value to be stored. 11693 11694 Expr::EvalResult Result; 11695 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11696 !S.SourceMgr.isInSystemMacro(CC)) { 11697 llvm::APSInt Value = Result.Val.getInt(); 11698 if (isSameWidthConstantConversion(S, E, T, CC)) { 11699 std::string PrettySourceValue = Value.toString(10); 11700 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11701 11702 S.DiagRuntimeBehavior( 11703 E->getExprLoc(), E, 11704 S.PDiag(diag::warn_impcast_integer_precision_constant) 11705 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11706 << E->getSourceRange() << clang::SourceRange(CC)); 11707 return; 11708 } 11709 } 11710 11711 // Fall through for non-constants to give a sign conversion warning. 11712 } 11713 11714 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11715 (!TargetRange.NonNegative && SourceRange.NonNegative && 11716 SourceRange.Width == TargetRange.Width)) { 11717 if (S.SourceMgr.isInSystemMacro(CC)) 11718 return; 11719 11720 unsigned DiagID = diag::warn_impcast_integer_sign; 11721 11722 // Traditionally, gcc has warned about this under -Wsign-compare. 11723 // We also want to warn about it in -Wconversion. 11724 // So if -Wconversion is off, use a completely identical diagnostic 11725 // in the sign-compare group. 11726 // The conditional-checking code will 11727 if (ICContext) { 11728 DiagID = diag::warn_impcast_integer_sign_conditional; 11729 *ICContext = true; 11730 } 11731 11732 return DiagnoseImpCast(S, E, T, CC, DiagID); 11733 } 11734 11735 // Diagnose conversions between different enumeration types. 11736 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11737 // type, to give us better diagnostics. 11738 QualType SourceType = E->getType(); 11739 if (!S.getLangOpts().CPlusPlus) { 11740 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11741 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11742 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11743 SourceType = S.Context.getTypeDeclType(Enum); 11744 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11745 } 11746 } 11747 11748 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11749 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11750 if (SourceEnum->getDecl()->hasNameForLinkage() && 11751 TargetEnum->getDecl()->hasNameForLinkage() && 11752 SourceEnum != TargetEnum) { 11753 if (S.SourceMgr.isInSystemMacro(CC)) 11754 return; 11755 11756 return DiagnoseImpCast(S, E, SourceType, T, CC, 11757 diag::warn_impcast_different_enum_types); 11758 } 11759 } 11760 11761 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11762 SourceLocation CC, QualType T); 11763 11764 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11765 SourceLocation CC, bool &ICContext) { 11766 E = E->IgnoreParenImpCasts(); 11767 11768 if (isa<ConditionalOperator>(E)) 11769 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11770 11771 AnalyzeImplicitConversions(S, E, CC); 11772 if (E->getType() != T) 11773 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11774 } 11775 11776 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11777 SourceLocation CC, QualType T) { 11778 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11779 11780 bool Suspicious = false; 11781 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11782 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11783 11784 if (T->isBooleanType()) 11785 DiagnoseIntInBoolContext(S, E); 11786 11787 // If -Wconversion would have warned about either of the candidates 11788 // for a signedness conversion to the context type... 11789 if (!Suspicious) return; 11790 11791 // ...but it's currently ignored... 11792 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11793 return; 11794 11795 // ...then check whether it would have warned about either of the 11796 // candidates for a signedness conversion to the condition type. 11797 if (E->getType() == T) return; 11798 11799 Suspicious = false; 11800 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11801 E->getType(), CC, &Suspicious); 11802 if (!Suspicious) 11803 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11804 E->getType(), CC, &Suspicious); 11805 } 11806 11807 /// Check conversion of given expression to boolean. 11808 /// Input argument E is a logical expression. 11809 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11810 if (S.getLangOpts().Bool) 11811 return; 11812 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11813 return; 11814 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11815 } 11816 11817 namespace { 11818 struct AnalyzeImplicitConversionsWorkItem { 11819 Expr *E; 11820 SourceLocation CC; 11821 bool IsListInit; 11822 }; 11823 } 11824 11825 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11826 /// that should be visited are added to WorkList. 11827 static void AnalyzeImplicitConversions( 11828 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11829 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11830 Expr *OrigE = Item.E; 11831 SourceLocation CC = Item.CC; 11832 11833 QualType T = OrigE->getType(); 11834 Expr *E = OrigE->IgnoreParenImpCasts(); 11835 11836 // Propagate whether we are in a C++ list initialization expression. 11837 // If so, we do not issue warnings for implicit int-float conversion 11838 // precision loss, because C++11 narrowing already handles it. 11839 bool IsListInit = Item.IsListInit || 11840 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11841 11842 if (E->isTypeDependent() || E->isValueDependent()) 11843 return; 11844 11845 Expr *SourceExpr = E; 11846 // Examine, but don't traverse into the source expression of an 11847 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11848 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11849 // evaluate it in the context of checking the specific conversion to T though. 11850 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11851 if (auto *Src = OVE->getSourceExpr()) 11852 SourceExpr = Src; 11853 11854 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11855 if (UO->getOpcode() == UO_Not && 11856 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11857 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11858 << OrigE->getSourceRange() << T->isBooleanType() 11859 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11860 11861 // For conditional operators, we analyze the arguments as if they 11862 // were being fed directly into the output. 11863 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11864 CheckConditionalOperator(S, CO, CC, T); 11865 return; 11866 } 11867 11868 // Check implicit argument conversions for function calls. 11869 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11870 CheckImplicitArgumentConversions(S, Call, CC); 11871 11872 // Go ahead and check any implicit conversions we might have skipped. 11873 // The non-canonical typecheck is just an optimization; 11874 // CheckImplicitConversion will filter out dead implicit conversions. 11875 if (SourceExpr->getType() != T) 11876 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11877 11878 // Now continue drilling into this expression. 11879 11880 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11881 // The bound subexpressions in a PseudoObjectExpr are not reachable 11882 // as transitive children. 11883 // FIXME: Use a more uniform representation for this. 11884 for (auto *SE : POE->semantics()) 11885 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11886 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11887 } 11888 11889 // Skip past explicit casts. 11890 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11891 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11892 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11893 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11894 WorkList.push_back({E, CC, IsListInit}); 11895 return; 11896 } 11897 11898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11899 // Do a somewhat different check with comparison operators. 11900 if (BO->isComparisonOp()) 11901 return AnalyzeComparison(S, BO); 11902 11903 // And with simple assignments. 11904 if (BO->getOpcode() == BO_Assign) 11905 return AnalyzeAssignment(S, BO); 11906 // And with compound assignments. 11907 if (BO->isAssignmentOp()) 11908 return AnalyzeCompoundAssignment(S, BO); 11909 } 11910 11911 // These break the otherwise-useful invariant below. Fortunately, 11912 // we don't really need to recurse into them, because any internal 11913 // expressions should have been analyzed already when they were 11914 // built into statements. 11915 if (isa<StmtExpr>(E)) return; 11916 11917 // Don't descend into unevaluated contexts. 11918 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11919 11920 // Now just recurse over the expression's children. 11921 CC = E->getExprLoc(); 11922 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11923 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11924 for (Stmt *SubStmt : E->children()) { 11925 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11926 if (!ChildExpr) 11927 continue; 11928 11929 if (IsLogicalAndOperator && 11930 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11931 // Ignore checking string literals that are in logical and operators. 11932 // This is a common pattern for asserts. 11933 continue; 11934 WorkList.push_back({ChildExpr, CC, IsListInit}); 11935 } 11936 11937 if (BO && BO->isLogicalOp()) { 11938 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11939 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11940 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11941 11942 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11943 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11944 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11945 } 11946 11947 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11948 if (U->getOpcode() == UO_LNot) { 11949 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11950 } else if (U->getOpcode() != UO_AddrOf) { 11951 if (U->getSubExpr()->getType()->isAtomicType()) 11952 S.Diag(U->getSubExpr()->getBeginLoc(), 11953 diag::warn_atomic_implicit_seq_cst); 11954 } 11955 } 11956 } 11957 11958 /// AnalyzeImplicitConversions - Find and report any interesting 11959 /// implicit conversions in the given expression. There are a couple 11960 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11961 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11962 bool IsListInit/*= false*/) { 11963 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 11964 WorkList.push_back({OrigE, CC, IsListInit}); 11965 while (!WorkList.empty()) 11966 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 11967 } 11968 11969 /// Diagnose integer type and any valid implicit conversion to it. 11970 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11971 // Taking into account implicit conversions, 11972 // allow any integer. 11973 if (!E->getType()->isIntegerType()) { 11974 S.Diag(E->getBeginLoc(), 11975 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11976 return true; 11977 } 11978 // Potentially emit standard warnings for implicit conversions if enabled 11979 // using -Wconversion. 11980 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11981 return false; 11982 } 11983 11984 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11985 // Returns true when emitting a warning about taking the address of a reference. 11986 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11987 const PartialDiagnostic &PD) { 11988 E = E->IgnoreParenImpCasts(); 11989 11990 const FunctionDecl *FD = nullptr; 11991 11992 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11993 if (!DRE->getDecl()->getType()->isReferenceType()) 11994 return false; 11995 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11996 if (!M->getMemberDecl()->getType()->isReferenceType()) 11997 return false; 11998 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11999 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12000 return false; 12001 FD = Call->getDirectCallee(); 12002 } else { 12003 return false; 12004 } 12005 12006 SemaRef.Diag(E->getExprLoc(), PD); 12007 12008 // If possible, point to location of function. 12009 if (FD) { 12010 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12011 } 12012 12013 return true; 12014 } 12015 12016 // Returns true if the SourceLocation is expanded from any macro body. 12017 // Returns false if the SourceLocation is invalid, is from not in a macro 12018 // expansion, or is from expanded from a top-level macro argument. 12019 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12020 if (Loc.isInvalid()) 12021 return false; 12022 12023 while (Loc.isMacroID()) { 12024 if (SM.isMacroBodyExpansion(Loc)) 12025 return true; 12026 Loc = SM.getImmediateMacroCallerLoc(Loc); 12027 } 12028 12029 return false; 12030 } 12031 12032 /// Diagnose pointers that are always non-null. 12033 /// \param E the expression containing the pointer 12034 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12035 /// compared to a null pointer 12036 /// \param IsEqual True when the comparison is equal to a null pointer 12037 /// \param Range Extra SourceRange to highlight in the diagnostic 12038 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12039 Expr::NullPointerConstantKind NullKind, 12040 bool IsEqual, SourceRange Range) { 12041 if (!E) 12042 return; 12043 12044 // Don't warn inside macros. 12045 if (E->getExprLoc().isMacroID()) { 12046 const SourceManager &SM = getSourceManager(); 12047 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12048 IsInAnyMacroBody(SM, Range.getBegin())) 12049 return; 12050 } 12051 E = E->IgnoreImpCasts(); 12052 12053 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12054 12055 if (isa<CXXThisExpr>(E)) { 12056 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12057 : diag::warn_this_bool_conversion; 12058 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12059 return; 12060 } 12061 12062 bool IsAddressOf = false; 12063 12064 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12065 if (UO->getOpcode() != UO_AddrOf) 12066 return; 12067 IsAddressOf = true; 12068 E = UO->getSubExpr(); 12069 } 12070 12071 if (IsAddressOf) { 12072 unsigned DiagID = IsCompare 12073 ? diag::warn_address_of_reference_null_compare 12074 : diag::warn_address_of_reference_bool_conversion; 12075 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12076 << IsEqual; 12077 if (CheckForReference(*this, E, PD)) { 12078 return; 12079 } 12080 } 12081 12082 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12083 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12084 std::string Str; 12085 llvm::raw_string_ostream S(Str); 12086 E->printPretty(S, nullptr, getPrintingPolicy()); 12087 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12088 : diag::warn_cast_nonnull_to_bool; 12089 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12090 << E->getSourceRange() << Range << IsEqual; 12091 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12092 }; 12093 12094 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12095 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12096 if (auto *Callee = Call->getDirectCallee()) { 12097 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12098 ComplainAboutNonnullParamOrCall(A); 12099 return; 12100 } 12101 } 12102 } 12103 12104 // Expect to find a single Decl. Skip anything more complicated. 12105 ValueDecl *D = nullptr; 12106 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12107 D = R->getDecl(); 12108 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12109 D = M->getMemberDecl(); 12110 } 12111 12112 // Weak Decls can be null. 12113 if (!D || D->isWeak()) 12114 return; 12115 12116 // Check for parameter decl with nonnull attribute 12117 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12118 if (getCurFunction() && 12119 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12120 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12121 ComplainAboutNonnullParamOrCall(A); 12122 return; 12123 } 12124 12125 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12126 // Skip function template not specialized yet. 12127 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12128 return; 12129 auto ParamIter = llvm::find(FD->parameters(), PV); 12130 assert(ParamIter != FD->param_end()); 12131 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12132 12133 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12134 if (!NonNull->args_size()) { 12135 ComplainAboutNonnullParamOrCall(NonNull); 12136 return; 12137 } 12138 12139 for (const ParamIdx &ArgNo : NonNull->args()) { 12140 if (ArgNo.getASTIndex() == ParamNo) { 12141 ComplainAboutNonnullParamOrCall(NonNull); 12142 return; 12143 } 12144 } 12145 } 12146 } 12147 } 12148 } 12149 12150 QualType T = D->getType(); 12151 const bool IsArray = T->isArrayType(); 12152 const bool IsFunction = T->isFunctionType(); 12153 12154 // Address of function is used to silence the function warning. 12155 if (IsAddressOf && IsFunction) { 12156 return; 12157 } 12158 12159 // Found nothing. 12160 if (!IsAddressOf && !IsFunction && !IsArray) 12161 return; 12162 12163 // Pretty print the expression for the diagnostic. 12164 std::string Str; 12165 llvm::raw_string_ostream S(Str); 12166 E->printPretty(S, nullptr, getPrintingPolicy()); 12167 12168 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12169 : diag::warn_impcast_pointer_to_bool; 12170 enum { 12171 AddressOf, 12172 FunctionPointer, 12173 ArrayPointer 12174 } DiagType; 12175 if (IsAddressOf) 12176 DiagType = AddressOf; 12177 else if (IsFunction) 12178 DiagType = FunctionPointer; 12179 else if (IsArray) 12180 DiagType = ArrayPointer; 12181 else 12182 llvm_unreachable("Could not determine diagnostic."); 12183 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12184 << Range << IsEqual; 12185 12186 if (!IsFunction) 12187 return; 12188 12189 // Suggest '&' to silence the function warning. 12190 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12191 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12192 12193 // Check to see if '()' fixit should be emitted. 12194 QualType ReturnType; 12195 UnresolvedSet<4> NonTemplateOverloads; 12196 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12197 if (ReturnType.isNull()) 12198 return; 12199 12200 if (IsCompare) { 12201 // There are two cases here. If there is null constant, the only suggest 12202 // for a pointer return type. If the null is 0, then suggest if the return 12203 // type is a pointer or an integer type. 12204 if (!ReturnType->isPointerType()) { 12205 if (NullKind == Expr::NPCK_ZeroExpression || 12206 NullKind == Expr::NPCK_ZeroLiteral) { 12207 if (!ReturnType->isIntegerType()) 12208 return; 12209 } else { 12210 return; 12211 } 12212 } 12213 } else { // !IsCompare 12214 // For function to bool, only suggest if the function pointer has bool 12215 // return type. 12216 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12217 return; 12218 } 12219 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12220 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12221 } 12222 12223 /// Diagnoses "dangerous" implicit conversions within the given 12224 /// expression (which is a full expression). Implements -Wconversion 12225 /// and -Wsign-compare. 12226 /// 12227 /// \param CC the "context" location of the implicit conversion, i.e. 12228 /// the most location of the syntactic entity requiring the implicit 12229 /// conversion 12230 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12231 // Don't diagnose in unevaluated contexts. 12232 if (isUnevaluatedContext()) 12233 return; 12234 12235 // Don't diagnose for value- or type-dependent expressions. 12236 if (E->isTypeDependent() || E->isValueDependent()) 12237 return; 12238 12239 // Check for array bounds violations in cases where the check isn't triggered 12240 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12241 // ArraySubscriptExpr is on the RHS of a variable initialization. 12242 CheckArrayAccess(E); 12243 12244 // This is not the right CC for (e.g.) a variable initialization. 12245 AnalyzeImplicitConversions(*this, E, CC); 12246 } 12247 12248 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12249 /// Input argument E is a logical expression. 12250 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12251 ::CheckBoolLikeConversion(*this, E, CC); 12252 } 12253 12254 /// Diagnose when expression is an integer constant expression and its evaluation 12255 /// results in integer overflow 12256 void Sema::CheckForIntOverflow (Expr *E) { 12257 // Use a work list to deal with nested struct initializers. 12258 SmallVector<Expr *, 2> Exprs(1, E); 12259 12260 do { 12261 Expr *OriginalE = Exprs.pop_back_val(); 12262 Expr *E = OriginalE->IgnoreParenCasts(); 12263 12264 if (isa<BinaryOperator>(E)) { 12265 E->EvaluateForOverflow(Context); 12266 continue; 12267 } 12268 12269 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12270 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12271 else if (isa<ObjCBoxedExpr>(OriginalE)) 12272 E->EvaluateForOverflow(Context); 12273 else if (auto Call = dyn_cast<CallExpr>(E)) 12274 Exprs.append(Call->arg_begin(), Call->arg_end()); 12275 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12276 Exprs.append(Message->arg_begin(), Message->arg_end()); 12277 } while (!Exprs.empty()); 12278 } 12279 12280 namespace { 12281 12282 /// Visitor for expressions which looks for unsequenced operations on the 12283 /// same object. 12284 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12285 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12286 12287 /// A tree of sequenced regions within an expression. Two regions are 12288 /// unsequenced if one is an ancestor or a descendent of the other. When we 12289 /// finish processing an expression with sequencing, such as a comma 12290 /// expression, we fold its tree nodes into its parent, since they are 12291 /// unsequenced with respect to nodes we will visit later. 12292 class SequenceTree { 12293 struct Value { 12294 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12295 unsigned Parent : 31; 12296 unsigned Merged : 1; 12297 }; 12298 SmallVector<Value, 8> Values; 12299 12300 public: 12301 /// A region within an expression which may be sequenced with respect 12302 /// to some other region. 12303 class Seq { 12304 friend class SequenceTree; 12305 12306 unsigned Index; 12307 12308 explicit Seq(unsigned N) : Index(N) {} 12309 12310 public: 12311 Seq() : Index(0) {} 12312 }; 12313 12314 SequenceTree() { Values.push_back(Value(0)); } 12315 Seq root() const { return Seq(0); } 12316 12317 /// Create a new sequence of operations, which is an unsequenced 12318 /// subset of \p Parent. This sequence of operations is sequenced with 12319 /// respect to other children of \p Parent. 12320 Seq allocate(Seq Parent) { 12321 Values.push_back(Value(Parent.Index)); 12322 return Seq(Values.size() - 1); 12323 } 12324 12325 /// Merge a sequence of operations into its parent. 12326 void merge(Seq S) { 12327 Values[S.Index].Merged = true; 12328 } 12329 12330 /// Determine whether two operations are unsequenced. This operation 12331 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12332 /// should have been merged into its parent as appropriate. 12333 bool isUnsequenced(Seq Cur, Seq Old) { 12334 unsigned C = representative(Cur.Index); 12335 unsigned Target = representative(Old.Index); 12336 while (C >= Target) { 12337 if (C == Target) 12338 return true; 12339 C = Values[C].Parent; 12340 } 12341 return false; 12342 } 12343 12344 private: 12345 /// Pick a representative for a sequence. 12346 unsigned representative(unsigned K) { 12347 if (Values[K].Merged) 12348 // Perform path compression as we go. 12349 return Values[K].Parent = representative(Values[K].Parent); 12350 return K; 12351 } 12352 }; 12353 12354 /// An object for which we can track unsequenced uses. 12355 using Object = const NamedDecl *; 12356 12357 /// Different flavors of object usage which we track. We only track the 12358 /// least-sequenced usage of each kind. 12359 enum UsageKind { 12360 /// A read of an object. Multiple unsequenced reads are OK. 12361 UK_Use, 12362 12363 /// A modification of an object which is sequenced before the value 12364 /// computation of the expression, such as ++n in C++. 12365 UK_ModAsValue, 12366 12367 /// A modification of an object which is not sequenced before the value 12368 /// computation of the expression, such as n++. 12369 UK_ModAsSideEffect, 12370 12371 UK_Count = UK_ModAsSideEffect + 1 12372 }; 12373 12374 /// Bundle together a sequencing region and the expression corresponding 12375 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12376 struct Usage { 12377 const Expr *UsageExpr; 12378 SequenceTree::Seq Seq; 12379 12380 Usage() : UsageExpr(nullptr), Seq() {} 12381 }; 12382 12383 struct UsageInfo { 12384 Usage Uses[UK_Count]; 12385 12386 /// Have we issued a diagnostic for this object already? 12387 bool Diagnosed; 12388 12389 UsageInfo() : Uses(), Diagnosed(false) {} 12390 }; 12391 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12392 12393 Sema &SemaRef; 12394 12395 /// Sequenced regions within the expression. 12396 SequenceTree Tree; 12397 12398 /// Declaration modifications and references which we have seen. 12399 UsageInfoMap UsageMap; 12400 12401 /// The region we are currently within. 12402 SequenceTree::Seq Region; 12403 12404 /// Filled in with declarations which were modified as a side-effect 12405 /// (that is, post-increment operations). 12406 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12407 12408 /// Expressions to check later. We defer checking these to reduce 12409 /// stack usage. 12410 SmallVectorImpl<const Expr *> &WorkList; 12411 12412 /// RAII object wrapping the visitation of a sequenced subexpression of an 12413 /// expression. At the end of this process, the side-effects of the evaluation 12414 /// become sequenced with respect to the value computation of the result, so 12415 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12416 /// UK_ModAsValue. 12417 struct SequencedSubexpression { 12418 SequencedSubexpression(SequenceChecker &Self) 12419 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12420 Self.ModAsSideEffect = &ModAsSideEffect; 12421 } 12422 12423 ~SequencedSubexpression() { 12424 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12425 // Add a new usage with usage kind UK_ModAsValue, and then restore 12426 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12427 // the previous one was empty). 12428 UsageInfo &UI = Self.UsageMap[M.first]; 12429 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12430 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12431 SideEffectUsage = M.second; 12432 } 12433 Self.ModAsSideEffect = OldModAsSideEffect; 12434 } 12435 12436 SequenceChecker &Self; 12437 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12438 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12439 }; 12440 12441 /// RAII object wrapping the visitation of a subexpression which we might 12442 /// choose to evaluate as a constant. If any subexpression is evaluated and 12443 /// found to be non-constant, this allows us to suppress the evaluation of 12444 /// the outer expression. 12445 class EvaluationTracker { 12446 public: 12447 EvaluationTracker(SequenceChecker &Self) 12448 : Self(Self), Prev(Self.EvalTracker) { 12449 Self.EvalTracker = this; 12450 } 12451 12452 ~EvaluationTracker() { 12453 Self.EvalTracker = Prev; 12454 if (Prev) 12455 Prev->EvalOK &= EvalOK; 12456 } 12457 12458 bool evaluate(const Expr *E, bool &Result) { 12459 if (!EvalOK || E->isValueDependent()) 12460 return false; 12461 EvalOK = E->EvaluateAsBooleanCondition( 12462 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12463 return EvalOK; 12464 } 12465 12466 private: 12467 SequenceChecker &Self; 12468 EvaluationTracker *Prev; 12469 bool EvalOK = true; 12470 } *EvalTracker = nullptr; 12471 12472 /// Find the object which is produced by the specified expression, 12473 /// if any. 12474 Object getObject(const Expr *E, bool Mod) const { 12475 E = E->IgnoreParenCasts(); 12476 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12477 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12478 return getObject(UO->getSubExpr(), Mod); 12479 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12480 if (BO->getOpcode() == BO_Comma) 12481 return getObject(BO->getRHS(), Mod); 12482 if (Mod && BO->isAssignmentOp()) 12483 return getObject(BO->getLHS(), Mod); 12484 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12485 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12486 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12487 return ME->getMemberDecl(); 12488 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12489 // FIXME: If this is a reference, map through to its value. 12490 return DRE->getDecl(); 12491 return nullptr; 12492 } 12493 12494 /// Note that an object \p O was modified or used by an expression 12495 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12496 /// the object \p O as obtained via the \p UsageMap. 12497 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12498 // Get the old usage for the given object and usage kind. 12499 Usage &U = UI.Uses[UK]; 12500 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12501 // If we have a modification as side effect and are in a sequenced 12502 // subexpression, save the old Usage so that we can restore it later 12503 // in SequencedSubexpression::~SequencedSubexpression. 12504 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12505 ModAsSideEffect->push_back(std::make_pair(O, U)); 12506 // Then record the new usage with the current sequencing region. 12507 U.UsageExpr = UsageExpr; 12508 U.Seq = Region; 12509 } 12510 } 12511 12512 /// Check whether a modification or use of an object \p O in an expression 12513 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12514 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12515 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12516 /// usage and false we are checking for a mod-use unsequenced usage. 12517 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12518 UsageKind OtherKind, bool IsModMod) { 12519 if (UI.Diagnosed) 12520 return; 12521 12522 const Usage &U = UI.Uses[OtherKind]; 12523 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12524 return; 12525 12526 const Expr *Mod = U.UsageExpr; 12527 const Expr *ModOrUse = UsageExpr; 12528 if (OtherKind == UK_Use) 12529 std::swap(Mod, ModOrUse); 12530 12531 SemaRef.DiagRuntimeBehavior( 12532 Mod->getExprLoc(), {Mod, ModOrUse}, 12533 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12534 : diag::warn_unsequenced_mod_use) 12535 << O << SourceRange(ModOrUse->getExprLoc())); 12536 UI.Diagnosed = true; 12537 } 12538 12539 // A note on note{Pre, Post}{Use, Mod}: 12540 // 12541 // (It helps to follow the algorithm with an expression such as 12542 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12543 // operations before C++17 and both are well-defined in C++17). 12544 // 12545 // When visiting a node which uses/modify an object we first call notePreUse 12546 // or notePreMod before visiting its sub-expression(s). At this point the 12547 // children of the current node have not yet been visited and so the eventual 12548 // uses/modifications resulting from the children of the current node have not 12549 // been recorded yet. 12550 // 12551 // We then visit the children of the current node. After that notePostUse or 12552 // notePostMod is called. These will 1) detect an unsequenced modification 12553 // as side effect (as in "k++ + k") and 2) add a new usage with the 12554 // appropriate usage kind. 12555 // 12556 // We also have to be careful that some operation sequences modification as 12557 // side effect as well (for example: || or ,). To account for this we wrap 12558 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12559 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12560 // which record usages which are modifications as side effect, and then 12561 // downgrade them (or more accurately restore the previous usage which was a 12562 // modification as side effect) when exiting the scope of the sequenced 12563 // subexpression. 12564 12565 void notePreUse(Object O, const Expr *UseExpr) { 12566 UsageInfo &UI = UsageMap[O]; 12567 // Uses conflict with other modifications. 12568 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12569 } 12570 12571 void notePostUse(Object O, const Expr *UseExpr) { 12572 UsageInfo &UI = UsageMap[O]; 12573 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12574 /*IsModMod=*/false); 12575 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12576 } 12577 12578 void notePreMod(Object O, const Expr *ModExpr) { 12579 UsageInfo &UI = UsageMap[O]; 12580 // Modifications conflict with other modifications and with uses. 12581 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12582 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12583 } 12584 12585 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12586 UsageInfo &UI = UsageMap[O]; 12587 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12588 /*IsModMod=*/true); 12589 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12590 } 12591 12592 public: 12593 SequenceChecker(Sema &S, const Expr *E, 12594 SmallVectorImpl<const Expr *> &WorkList) 12595 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12596 Visit(E); 12597 // Silence a -Wunused-private-field since WorkList is now unused. 12598 // TODO: Evaluate if it can be used, and if not remove it. 12599 (void)this->WorkList; 12600 } 12601 12602 void VisitStmt(const Stmt *S) { 12603 // Skip all statements which aren't expressions for now. 12604 } 12605 12606 void VisitExpr(const Expr *E) { 12607 // By default, just recurse to evaluated subexpressions. 12608 Base::VisitStmt(E); 12609 } 12610 12611 void VisitCastExpr(const CastExpr *E) { 12612 Object O = Object(); 12613 if (E->getCastKind() == CK_LValueToRValue) 12614 O = getObject(E->getSubExpr(), false); 12615 12616 if (O) 12617 notePreUse(O, E); 12618 VisitExpr(E); 12619 if (O) 12620 notePostUse(O, E); 12621 } 12622 12623 void VisitSequencedExpressions(const Expr *SequencedBefore, 12624 const Expr *SequencedAfter) { 12625 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12626 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12627 SequenceTree::Seq OldRegion = Region; 12628 12629 { 12630 SequencedSubexpression SeqBefore(*this); 12631 Region = BeforeRegion; 12632 Visit(SequencedBefore); 12633 } 12634 12635 Region = AfterRegion; 12636 Visit(SequencedAfter); 12637 12638 Region = OldRegion; 12639 12640 Tree.merge(BeforeRegion); 12641 Tree.merge(AfterRegion); 12642 } 12643 12644 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12645 // C++17 [expr.sub]p1: 12646 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12647 // expression E1 is sequenced before the expression E2. 12648 if (SemaRef.getLangOpts().CPlusPlus17) 12649 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12650 else { 12651 Visit(ASE->getLHS()); 12652 Visit(ASE->getRHS()); 12653 } 12654 } 12655 12656 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12657 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12658 void VisitBinPtrMem(const BinaryOperator *BO) { 12659 // C++17 [expr.mptr.oper]p4: 12660 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12661 // the expression E1 is sequenced before the expression E2. 12662 if (SemaRef.getLangOpts().CPlusPlus17) 12663 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12664 else { 12665 Visit(BO->getLHS()); 12666 Visit(BO->getRHS()); 12667 } 12668 } 12669 12670 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12671 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12672 void VisitBinShlShr(const BinaryOperator *BO) { 12673 // C++17 [expr.shift]p4: 12674 // The expression E1 is sequenced before the expression E2. 12675 if (SemaRef.getLangOpts().CPlusPlus17) 12676 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12677 else { 12678 Visit(BO->getLHS()); 12679 Visit(BO->getRHS()); 12680 } 12681 } 12682 12683 void VisitBinComma(const BinaryOperator *BO) { 12684 // C++11 [expr.comma]p1: 12685 // Every value computation and side effect associated with the left 12686 // expression is sequenced before every value computation and side 12687 // effect associated with the right expression. 12688 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12689 } 12690 12691 void VisitBinAssign(const BinaryOperator *BO) { 12692 SequenceTree::Seq RHSRegion; 12693 SequenceTree::Seq LHSRegion; 12694 if (SemaRef.getLangOpts().CPlusPlus17) { 12695 RHSRegion = Tree.allocate(Region); 12696 LHSRegion = Tree.allocate(Region); 12697 } else { 12698 RHSRegion = Region; 12699 LHSRegion = Region; 12700 } 12701 SequenceTree::Seq OldRegion = Region; 12702 12703 // C++11 [expr.ass]p1: 12704 // [...] the assignment is sequenced after the value computation 12705 // of the right and left operands, [...] 12706 // 12707 // so check it before inspecting the operands and update the 12708 // map afterwards. 12709 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12710 if (O) 12711 notePreMod(O, BO); 12712 12713 if (SemaRef.getLangOpts().CPlusPlus17) { 12714 // C++17 [expr.ass]p1: 12715 // [...] The right operand is sequenced before the left operand. [...] 12716 { 12717 SequencedSubexpression SeqBefore(*this); 12718 Region = RHSRegion; 12719 Visit(BO->getRHS()); 12720 } 12721 12722 Region = LHSRegion; 12723 Visit(BO->getLHS()); 12724 12725 if (O && isa<CompoundAssignOperator>(BO)) 12726 notePostUse(O, BO); 12727 12728 } else { 12729 // C++11 does not specify any sequencing between the LHS and RHS. 12730 Region = LHSRegion; 12731 Visit(BO->getLHS()); 12732 12733 if (O && isa<CompoundAssignOperator>(BO)) 12734 notePostUse(O, BO); 12735 12736 Region = RHSRegion; 12737 Visit(BO->getRHS()); 12738 } 12739 12740 // C++11 [expr.ass]p1: 12741 // the assignment is sequenced [...] before the value computation of the 12742 // assignment expression. 12743 // C11 6.5.16/3 has no such rule. 12744 Region = OldRegion; 12745 if (O) 12746 notePostMod(O, BO, 12747 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12748 : UK_ModAsSideEffect); 12749 if (SemaRef.getLangOpts().CPlusPlus17) { 12750 Tree.merge(RHSRegion); 12751 Tree.merge(LHSRegion); 12752 } 12753 } 12754 12755 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12756 VisitBinAssign(CAO); 12757 } 12758 12759 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12760 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12761 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12762 Object O = getObject(UO->getSubExpr(), true); 12763 if (!O) 12764 return VisitExpr(UO); 12765 12766 notePreMod(O, UO); 12767 Visit(UO->getSubExpr()); 12768 // C++11 [expr.pre.incr]p1: 12769 // the expression ++x is equivalent to x+=1 12770 notePostMod(O, UO, 12771 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12772 : UK_ModAsSideEffect); 12773 } 12774 12775 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12776 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12777 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12778 Object O = getObject(UO->getSubExpr(), true); 12779 if (!O) 12780 return VisitExpr(UO); 12781 12782 notePreMod(O, UO); 12783 Visit(UO->getSubExpr()); 12784 notePostMod(O, UO, UK_ModAsSideEffect); 12785 } 12786 12787 void VisitBinLOr(const BinaryOperator *BO) { 12788 // C++11 [expr.log.or]p2: 12789 // If the second expression is evaluated, every value computation and 12790 // side effect associated with the first expression is sequenced before 12791 // every value computation and side effect associated with the 12792 // second expression. 12793 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12794 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12795 SequenceTree::Seq OldRegion = Region; 12796 12797 EvaluationTracker Eval(*this); 12798 { 12799 SequencedSubexpression Sequenced(*this); 12800 Region = LHSRegion; 12801 Visit(BO->getLHS()); 12802 } 12803 12804 // C++11 [expr.log.or]p1: 12805 // [...] the second operand is not evaluated if the first operand 12806 // evaluates to true. 12807 bool EvalResult = false; 12808 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12809 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12810 if (ShouldVisitRHS) { 12811 Region = RHSRegion; 12812 Visit(BO->getRHS()); 12813 } 12814 12815 Region = OldRegion; 12816 Tree.merge(LHSRegion); 12817 Tree.merge(RHSRegion); 12818 } 12819 12820 void VisitBinLAnd(const BinaryOperator *BO) { 12821 // C++11 [expr.log.and]p2: 12822 // If the second expression is evaluated, every value computation and 12823 // side effect associated with the first expression is sequenced before 12824 // every value computation and side effect associated with the 12825 // second expression. 12826 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12827 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12828 SequenceTree::Seq OldRegion = Region; 12829 12830 EvaluationTracker Eval(*this); 12831 { 12832 SequencedSubexpression Sequenced(*this); 12833 Region = LHSRegion; 12834 Visit(BO->getLHS()); 12835 } 12836 12837 // C++11 [expr.log.and]p1: 12838 // [...] the second operand is not evaluated if the first operand is false. 12839 bool EvalResult = false; 12840 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12841 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12842 if (ShouldVisitRHS) { 12843 Region = RHSRegion; 12844 Visit(BO->getRHS()); 12845 } 12846 12847 Region = OldRegion; 12848 Tree.merge(LHSRegion); 12849 Tree.merge(RHSRegion); 12850 } 12851 12852 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12853 // C++11 [expr.cond]p1: 12854 // [...] Every value computation and side effect associated with the first 12855 // expression is sequenced before every value computation and side effect 12856 // associated with the second or third expression. 12857 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12858 12859 // No sequencing is specified between the true and false expression. 12860 // However since exactly one of both is going to be evaluated we can 12861 // consider them to be sequenced. This is needed to avoid warning on 12862 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12863 // both the true and false expressions because we can't evaluate x. 12864 // This will still allow us to detect an expression like (pre C++17) 12865 // "(x ? y += 1 : y += 2) = y". 12866 // 12867 // We don't wrap the visitation of the true and false expression with 12868 // SequencedSubexpression because we don't want to downgrade modifications 12869 // as side effect in the true and false expressions after the visition 12870 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12871 // not warn between the two "y++", but we should warn between the "y++" 12872 // and the "y". 12873 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12874 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12875 SequenceTree::Seq OldRegion = Region; 12876 12877 EvaluationTracker Eval(*this); 12878 { 12879 SequencedSubexpression Sequenced(*this); 12880 Region = ConditionRegion; 12881 Visit(CO->getCond()); 12882 } 12883 12884 // C++11 [expr.cond]p1: 12885 // [...] The first expression is contextually converted to bool (Clause 4). 12886 // It is evaluated and if it is true, the result of the conditional 12887 // expression is the value of the second expression, otherwise that of the 12888 // third expression. Only one of the second and third expressions is 12889 // evaluated. [...] 12890 bool EvalResult = false; 12891 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12892 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12893 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12894 if (ShouldVisitTrueExpr) { 12895 Region = TrueRegion; 12896 Visit(CO->getTrueExpr()); 12897 } 12898 if (ShouldVisitFalseExpr) { 12899 Region = FalseRegion; 12900 Visit(CO->getFalseExpr()); 12901 } 12902 12903 Region = OldRegion; 12904 Tree.merge(ConditionRegion); 12905 Tree.merge(TrueRegion); 12906 Tree.merge(FalseRegion); 12907 } 12908 12909 void VisitCallExpr(const CallExpr *CE) { 12910 // C++11 [intro.execution]p15: 12911 // When calling a function [...], every value computation and side effect 12912 // associated with any argument expression, or with the postfix expression 12913 // designating the called function, is sequenced before execution of every 12914 // expression or statement in the body of the function [and thus before 12915 // the value computation of its result]. 12916 SequencedSubexpression Sequenced(*this); 12917 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12918 [&] { Base::VisitCallExpr(CE); }); 12919 12920 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12921 } 12922 12923 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12924 // This is a call, so all subexpressions are sequenced before the result. 12925 SequencedSubexpression Sequenced(*this); 12926 12927 if (!CCE->isListInitialization()) 12928 return VisitExpr(CCE); 12929 12930 // In C++11, list initializations are sequenced. 12931 SmallVector<SequenceTree::Seq, 32> Elts; 12932 SequenceTree::Seq Parent = Region; 12933 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12934 E = CCE->arg_end(); 12935 I != E; ++I) { 12936 Region = Tree.allocate(Parent); 12937 Elts.push_back(Region); 12938 Visit(*I); 12939 } 12940 12941 // Forget that the initializers are sequenced. 12942 Region = Parent; 12943 for (unsigned I = 0; I < Elts.size(); ++I) 12944 Tree.merge(Elts[I]); 12945 } 12946 12947 void VisitInitListExpr(const InitListExpr *ILE) { 12948 if (!SemaRef.getLangOpts().CPlusPlus11) 12949 return VisitExpr(ILE); 12950 12951 // In C++11, list initializations are sequenced. 12952 SmallVector<SequenceTree::Seq, 32> Elts; 12953 SequenceTree::Seq Parent = Region; 12954 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12955 const Expr *E = ILE->getInit(I); 12956 if (!E) 12957 continue; 12958 Region = Tree.allocate(Parent); 12959 Elts.push_back(Region); 12960 Visit(E); 12961 } 12962 12963 // Forget that the initializers are sequenced. 12964 Region = Parent; 12965 for (unsigned I = 0; I < Elts.size(); ++I) 12966 Tree.merge(Elts[I]); 12967 } 12968 }; 12969 12970 } // namespace 12971 12972 void Sema::CheckUnsequencedOperations(const Expr *E) { 12973 SmallVector<const Expr *, 8> WorkList; 12974 WorkList.push_back(E); 12975 while (!WorkList.empty()) { 12976 const Expr *Item = WorkList.pop_back_val(); 12977 SequenceChecker(*this, Item, WorkList); 12978 } 12979 } 12980 12981 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12982 bool IsConstexpr) { 12983 llvm::SaveAndRestore<bool> ConstantContext( 12984 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12985 CheckImplicitConversions(E, CheckLoc); 12986 if (!E->isInstantiationDependent()) 12987 CheckUnsequencedOperations(E); 12988 if (!IsConstexpr && !E->isValueDependent()) 12989 CheckForIntOverflow(E); 12990 DiagnoseMisalignedMembers(); 12991 } 12992 12993 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12994 FieldDecl *BitField, 12995 Expr *Init) { 12996 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12997 } 12998 12999 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13000 SourceLocation Loc) { 13001 if (!PType->isVariablyModifiedType()) 13002 return; 13003 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13004 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13005 return; 13006 } 13007 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13008 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13009 return; 13010 } 13011 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13012 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13013 return; 13014 } 13015 13016 const ArrayType *AT = S.Context.getAsArrayType(PType); 13017 if (!AT) 13018 return; 13019 13020 if (AT->getSizeModifier() != ArrayType::Star) { 13021 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13022 return; 13023 } 13024 13025 S.Diag(Loc, diag::err_array_star_in_function_definition); 13026 } 13027 13028 /// CheckParmsForFunctionDef - Check that the parameters of the given 13029 /// function are appropriate for the definition of a function. This 13030 /// takes care of any checks that cannot be performed on the 13031 /// declaration itself, e.g., that the types of each of the function 13032 /// parameters are complete. 13033 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13034 bool CheckParameterNames) { 13035 bool HasInvalidParm = false; 13036 for (ParmVarDecl *Param : Parameters) { 13037 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13038 // function declarator that is part of a function definition of 13039 // that function shall not have incomplete type. 13040 // 13041 // This is also C++ [dcl.fct]p6. 13042 if (!Param->isInvalidDecl() && 13043 RequireCompleteType(Param->getLocation(), Param->getType(), 13044 diag::err_typecheck_decl_incomplete_type)) { 13045 Param->setInvalidDecl(); 13046 HasInvalidParm = true; 13047 } 13048 13049 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13050 // declaration of each parameter shall include an identifier. 13051 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13052 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13053 // Diagnose this as an extension in C17 and earlier. 13054 if (!getLangOpts().C2x) 13055 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13056 } 13057 13058 // C99 6.7.5.3p12: 13059 // If the function declarator is not part of a definition of that 13060 // function, parameters may have incomplete type and may use the [*] 13061 // notation in their sequences of declarator specifiers to specify 13062 // variable length array types. 13063 QualType PType = Param->getOriginalType(); 13064 // FIXME: This diagnostic should point the '[*]' if source-location 13065 // information is added for it. 13066 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13067 13068 // If the parameter is a c++ class type and it has to be destructed in the 13069 // callee function, declare the destructor so that it can be called by the 13070 // callee function. Do not perform any direct access check on the dtor here. 13071 if (!Param->isInvalidDecl()) { 13072 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13073 if (!ClassDecl->isInvalidDecl() && 13074 !ClassDecl->hasIrrelevantDestructor() && 13075 !ClassDecl->isDependentContext() && 13076 ClassDecl->isParamDestroyedInCallee()) { 13077 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13078 MarkFunctionReferenced(Param->getLocation(), Destructor); 13079 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13080 } 13081 } 13082 } 13083 13084 // Parameters with the pass_object_size attribute only need to be marked 13085 // constant at function definitions. Because we lack information about 13086 // whether we're on a declaration or definition when we're instantiating the 13087 // attribute, we need to check for constness here. 13088 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13089 if (!Param->getType().isConstQualified()) 13090 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13091 << Attr->getSpelling() << 1; 13092 13093 // Check for parameter names shadowing fields from the class. 13094 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13095 // The owning context for the parameter should be the function, but we 13096 // want to see if this function's declaration context is a record. 13097 DeclContext *DC = Param->getDeclContext(); 13098 if (DC && DC->isFunctionOrMethod()) { 13099 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13100 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13101 RD, /*DeclIsField*/ false); 13102 } 13103 } 13104 } 13105 13106 return HasInvalidParm; 13107 } 13108 13109 Optional<std::pair<CharUnits, CharUnits>> 13110 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13111 13112 /// Compute the alignment and offset of the base class object given the 13113 /// derived-to-base cast expression and the alignment and offset of the derived 13114 /// class object. 13115 static std::pair<CharUnits, CharUnits> 13116 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13117 CharUnits BaseAlignment, CharUnits Offset, 13118 ASTContext &Ctx) { 13119 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13120 ++PathI) { 13121 const CXXBaseSpecifier *Base = *PathI; 13122 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13123 if (Base->isVirtual()) { 13124 // The complete object may have a lower alignment than the non-virtual 13125 // alignment of the base, in which case the base may be misaligned. Choose 13126 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13127 // conservative lower bound of the complete object alignment. 13128 CharUnits NonVirtualAlignment = 13129 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13130 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13131 Offset = CharUnits::Zero(); 13132 } else { 13133 const ASTRecordLayout &RL = 13134 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13135 Offset += RL.getBaseClassOffset(BaseDecl); 13136 } 13137 DerivedType = Base->getType(); 13138 } 13139 13140 return std::make_pair(BaseAlignment, Offset); 13141 } 13142 13143 /// Compute the alignment and offset of a binary additive operator. 13144 static Optional<std::pair<CharUnits, CharUnits>> 13145 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13146 bool IsSub, ASTContext &Ctx) { 13147 QualType PointeeType = PtrE->getType()->getPointeeType(); 13148 13149 if (!PointeeType->isConstantSizeType()) 13150 return llvm::None; 13151 13152 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13153 13154 if (!P) 13155 return llvm::None; 13156 13157 llvm::APSInt IdxRes; 13158 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13159 if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) { 13160 CharUnits Offset = EltSize * IdxRes.getExtValue(); 13161 if (IsSub) 13162 Offset = -Offset; 13163 return std::make_pair(P->first, P->second + Offset); 13164 } 13165 13166 // If the integer expression isn't a constant expression, compute the lower 13167 // bound of the alignment using the alignment and offset of the pointer 13168 // expression and the element size. 13169 return std::make_pair( 13170 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13171 CharUnits::Zero()); 13172 } 13173 13174 /// This helper function takes an lvalue expression and returns the alignment of 13175 /// a VarDecl and a constant offset from the VarDecl. 13176 Optional<std::pair<CharUnits, CharUnits>> 13177 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13178 E = E->IgnoreParens(); 13179 switch (E->getStmtClass()) { 13180 default: 13181 break; 13182 case Stmt::CStyleCastExprClass: 13183 case Stmt::CXXStaticCastExprClass: 13184 case Stmt::ImplicitCastExprClass: { 13185 auto *CE = cast<CastExpr>(E); 13186 const Expr *From = CE->getSubExpr(); 13187 switch (CE->getCastKind()) { 13188 default: 13189 break; 13190 case CK_NoOp: 13191 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13192 case CK_UncheckedDerivedToBase: 13193 case CK_DerivedToBase: { 13194 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13195 if (!P) 13196 break; 13197 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13198 P->second, Ctx); 13199 } 13200 } 13201 break; 13202 } 13203 case Stmt::ArraySubscriptExprClass: { 13204 auto *ASE = cast<ArraySubscriptExpr>(E); 13205 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13206 false, Ctx); 13207 } 13208 case Stmt::DeclRefExprClass: { 13209 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13210 // FIXME: If VD is captured by copy or is an escaping __block variable, 13211 // use the alignment of VD's type. 13212 if (!VD->getType()->isReferenceType()) 13213 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13214 if (VD->hasInit()) 13215 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13216 } 13217 break; 13218 } 13219 case Stmt::MemberExprClass: { 13220 auto *ME = cast<MemberExpr>(E); 13221 if (ME->isArrow()) 13222 break; 13223 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13224 if (!FD || FD->getType()->isReferenceType()) 13225 break; 13226 auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13227 if (!P) 13228 break; 13229 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13230 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13231 return std::make_pair(P->first, 13232 P->second + CharUnits::fromQuantity(Offset)); 13233 } 13234 case Stmt::UnaryOperatorClass: { 13235 auto *UO = cast<UnaryOperator>(E); 13236 switch (UO->getOpcode()) { 13237 default: 13238 break; 13239 case UO_Deref: 13240 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13241 } 13242 break; 13243 } 13244 case Stmt::BinaryOperatorClass: { 13245 auto *BO = cast<BinaryOperator>(E); 13246 auto Opcode = BO->getOpcode(); 13247 switch (Opcode) { 13248 default: 13249 break; 13250 case BO_Comma: 13251 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13252 } 13253 break; 13254 } 13255 } 13256 return llvm::None; 13257 } 13258 13259 /// This helper function takes a pointer expression and returns the alignment of 13260 /// a VarDecl and a constant offset from the VarDecl. 13261 Optional<std::pair<CharUnits, CharUnits>> 13262 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13263 E = E->IgnoreParens(); 13264 switch (E->getStmtClass()) { 13265 default: 13266 break; 13267 case Stmt::CStyleCastExprClass: 13268 case Stmt::CXXStaticCastExprClass: 13269 case Stmt::ImplicitCastExprClass: { 13270 auto *CE = cast<CastExpr>(E); 13271 const Expr *From = CE->getSubExpr(); 13272 switch (CE->getCastKind()) { 13273 default: 13274 break; 13275 case CK_NoOp: 13276 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13277 case CK_ArrayToPointerDecay: 13278 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13279 case CK_UncheckedDerivedToBase: 13280 case CK_DerivedToBase: { 13281 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13282 if (!P) 13283 break; 13284 return getDerivedToBaseAlignmentAndOffset( 13285 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13286 } 13287 } 13288 break; 13289 } 13290 case Stmt::UnaryOperatorClass: { 13291 auto *UO = cast<UnaryOperator>(E); 13292 if (UO->getOpcode() == UO_AddrOf) 13293 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13294 break; 13295 } 13296 case Stmt::BinaryOperatorClass: { 13297 auto *BO = cast<BinaryOperator>(E); 13298 auto Opcode = BO->getOpcode(); 13299 switch (Opcode) { 13300 default: 13301 break; 13302 case BO_Add: 13303 case BO_Sub: { 13304 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13305 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13306 std::swap(LHS, RHS); 13307 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13308 Ctx); 13309 } 13310 case BO_Comma: 13311 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13312 } 13313 break; 13314 } 13315 } 13316 return llvm::None; 13317 } 13318 13319 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13320 // See if we can compute the alignment of a VarDecl and an offset from it. 13321 Optional<std::pair<CharUnits, CharUnits>> P = 13322 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13323 13324 if (P) 13325 return P->first.alignmentAtOffset(P->second); 13326 13327 // If that failed, return the type's alignment. 13328 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13329 } 13330 13331 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13332 /// pointer cast increases the alignment requirements. 13333 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13334 // This is actually a lot of work to potentially be doing on every 13335 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13336 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13337 return; 13338 13339 // Ignore dependent types. 13340 if (T->isDependentType() || Op->getType()->isDependentType()) 13341 return; 13342 13343 // Require that the destination be a pointer type. 13344 const PointerType *DestPtr = T->getAs<PointerType>(); 13345 if (!DestPtr) return; 13346 13347 // If the destination has alignment 1, we're done. 13348 QualType DestPointee = DestPtr->getPointeeType(); 13349 if (DestPointee->isIncompleteType()) return; 13350 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13351 if (DestAlign.isOne()) return; 13352 13353 // Require that the source be a pointer type. 13354 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13355 if (!SrcPtr) return; 13356 QualType SrcPointee = SrcPtr->getPointeeType(); 13357 13358 // Whitelist casts from cv void*. We already implicitly 13359 // whitelisted casts to cv void*, since they have alignment 1. 13360 // Also whitelist casts involving incomplete types, which implicitly 13361 // includes 'void'. 13362 if (SrcPointee->isIncompleteType()) return; 13363 13364 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13365 13366 if (SrcAlign >= DestAlign) return; 13367 13368 Diag(TRange.getBegin(), diag::warn_cast_align) 13369 << Op->getType() << T 13370 << static_cast<unsigned>(SrcAlign.getQuantity()) 13371 << static_cast<unsigned>(DestAlign.getQuantity()) 13372 << TRange << Op->getSourceRange(); 13373 } 13374 13375 /// Check whether this array fits the idiom of a size-one tail padded 13376 /// array member of a struct. 13377 /// 13378 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13379 /// commonly used to emulate flexible arrays in C89 code. 13380 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13381 const NamedDecl *ND) { 13382 if (Size != 1 || !ND) return false; 13383 13384 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13385 if (!FD) return false; 13386 13387 // Don't consider sizes resulting from macro expansions or template argument 13388 // substitution to form C89 tail-padded arrays. 13389 13390 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13391 while (TInfo) { 13392 TypeLoc TL = TInfo->getTypeLoc(); 13393 // Look through typedefs. 13394 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13395 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13396 TInfo = TDL->getTypeSourceInfo(); 13397 continue; 13398 } 13399 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13400 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13401 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13402 return false; 13403 } 13404 break; 13405 } 13406 13407 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13408 if (!RD) return false; 13409 if (RD->isUnion()) return false; 13410 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13411 if (!CRD->isStandardLayout()) return false; 13412 } 13413 13414 // See if this is the last field decl in the record. 13415 const Decl *D = FD; 13416 while ((D = D->getNextDeclInContext())) 13417 if (isa<FieldDecl>(D)) 13418 return false; 13419 return true; 13420 } 13421 13422 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13423 const ArraySubscriptExpr *ASE, 13424 bool AllowOnePastEnd, bool IndexNegated) { 13425 // Already diagnosed by the constant evaluator. 13426 if (isConstantEvaluated()) 13427 return; 13428 13429 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13430 if (IndexExpr->isValueDependent()) 13431 return; 13432 13433 const Type *EffectiveType = 13434 BaseExpr->getType()->getPointeeOrArrayElementType(); 13435 BaseExpr = BaseExpr->IgnoreParenCasts(); 13436 const ConstantArrayType *ArrayTy = 13437 Context.getAsConstantArrayType(BaseExpr->getType()); 13438 13439 if (!ArrayTy) 13440 return; 13441 13442 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13443 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13444 return; 13445 13446 Expr::EvalResult Result; 13447 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13448 return; 13449 13450 llvm::APSInt index = Result.Val.getInt(); 13451 if (IndexNegated) 13452 index = -index; 13453 13454 const NamedDecl *ND = nullptr; 13455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13456 ND = DRE->getDecl(); 13457 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13458 ND = ME->getMemberDecl(); 13459 13460 if (index.isUnsigned() || !index.isNegative()) { 13461 // It is possible that the type of the base expression after 13462 // IgnoreParenCasts is incomplete, even though the type of the base 13463 // expression before IgnoreParenCasts is complete (see PR39746 for an 13464 // example). In this case we have no information about whether the array 13465 // access exceeds the array bounds. However we can still diagnose an array 13466 // access which precedes the array bounds. 13467 if (BaseType->isIncompleteType()) 13468 return; 13469 13470 llvm::APInt size = ArrayTy->getSize(); 13471 if (!size.isStrictlyPositive()) 13472 return; 13473 13474 if (BaseType != EffectiveType) { 13475 // Make sure we're comparing apples to apples when comparing index to size 13476 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13477 uint64_t array_typesize = Context.getTypeSize(BaseType); 13478 // Handle ptrarith_typesize being zero, such as when casting to void* 13479 if (!ptrarith_typesize) ptrarith_typesize = 1; 13480 if (ptrarith_typesize != array_typesize) { 13481 // There's a cast to a different size type involved 13482 uint64_t ratio = array_typesize / ptrarith_typesize; 13483 // TODO: Be smarter about handling cases where array_typesize is not a 13484 // multiple of ptrarith_typesize 13485 if (ptrarith_typesize * ratio == array_typesize) 13486 size *= llvm::APInt(size.getBitWidth(), ratio); 13487 } 13488 } 13489 13490 if (size.getBitWidth() > index.getBitWidth()) 13491 index = index.zext(size.getBitWidth()); 13492 else if (size.getBitWidth() < index.getBitWidth()) 13493 size = size.zext(index.getBitWidth()); 13494 13495 // For array subscripting the index must be less than size, but for pointer 13496 // arithmetic also allow the index (offset) to be equal to size since 13497 // computing the next address after the end of the array is legal and 13498 // commonly done e.g. in C++ iterators and range-based for loops. 13499 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13500 return; 13501 13502 // Also don't warn for arrays of size 1 which are members of some 13503 // structure. These are often used to approximate flexible arrays in C89 13504 // code. 13505 if (IsTailPaddedMemberArray(*this, size, ND)) 13506 return; 13507 13508 // Suppress the warning if the subscript expression (as identified by the 13509 // ']' location) and the index expression are both from macro expansions 13510 // within a system header. 13511 if (ASE) { 13512 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13513 ASE->getRBracketLoc()); 13514 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13515 SourceLocation IndexLoc = 13516 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13517 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13518 return; 13519 } 13520 } 13521 13522 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13523 if (ASE) 13524 DiagID = diag::warn_array_index_exceeds_bounds; 13525 13526 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13527 PDiag(DiagID) << index.toString(10, true) 13528 << size.toString(10, true) 13529 << (unsigned)size.getLimitedValue(~0U) 13530 << IndexExpr->getSourceRange()); 13531 } else { 13532 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13533 if (!ASE) { 13534 DiagID = diag::warn_ptr_arith_precedes_bounds; 13535 if (index.isNegative()) index = -index; 13536 } 13537 13538 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13539 PDiag(DiagID) << index.toString(10, true) 13540 << IndexExpr->getSourceRange()); 13541 } 13542 13543 if (!ND) { 13544 // Try harder to find a NamedDecl to point at in the note. 13545 while (const ArraySubscriptExpr *ASE = 13546 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13547 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13549 ND = DRE->getDecl(); 13550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13551 ND = ME->getMemberDecl(); 13552 } 13553 13554 if (ND) 13555 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13556 PDiag(diag::note_array_declared_here) 13557 << ND->getDeclName()); 13558 } 13559 13560 void Sema::CheckArrayAccess(const Expr *expr) { 13561 int AllowOnePastEnd = 0; 13562 while (expr) { 13563 expr = expr->IgnoreParenImpCasts(); 13564 switch (expr->getStmtClass()) { 13565 case Stmt::ArraySubscriptExprClass: { 13566 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13567 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13568 AllowOnePastEnd > 0); 13569 expr = ASE->getBase(); 13570 break; 13571 } 13572 case Stmt::MemberExprClass: { 13573 expr = cast<MemberExpr>(expr)->getBase(); 13574 break; 13575 } 13576 case Stmt::OMPArraySectionExprClass: { 13577 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13578 if (ASE->getLowerBound()) 13579 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13580 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13581 return; 13582 } 13583 case Stmt::UnaryOperatorClass: { 13584 // Only unwrap the * and & unary operators 13585 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13586 expr = UO->getSubExpr(); 13587 switch (UO->getOpcode()) { 13588 case UO_AddrOf: 13589 AllowOnePastEnd++; 13590 break; 13591 case UO_Deref: 13592 AllowOnePastEnd--; 13593 break; 13594 default: 13595 return; 13596 } 13597 break; 13598 } 13599 case Stmt::ConditionalOperatorClass: { 13600 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13601 if (const Expr *lhs = cond->getLHS()) 13602 CheckArrayAccess(lhs); 13603 if (const Expr *rhs = cond->getRHS()) 13604 CheckArrayAccess(rhs); 13605 return; 13606 } 13607 case Stmt::CXXOperatorCallExprClass: { 13608 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13609 for (const auto *Arg : OCE->arguments()) 13610 CheckArrayAccess(Arg); 13611 return; 13612 } 13613 default: 13614 return; 13615 } 13616 } 13617 } 13618 13619 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13620 13621 namespace { 13622 13623 struct RetainCycleOwner { 13624 VarDecl *Variable = nullptr; 13625 SourceRange Range; 13626 SourceLocation Loc; 13627 bool Indirect = false; 13628 13629 RetainCycleOwner() = default; 13630 13631 void setLocsFrom(Expr *e) { 13632 Loc = e->getExprLoc(); 13633 Range = e->getSourceRange(); 13634 } 13635 }; 13636 13637 } // namespace 13638 13639 /// Consider whether capturing the given variable can possibly lead to 13640 /// a retain cycle. 13641 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13642 // In ARC, it's captured strongly iff the variable has __strong 13643 // lifetime. In MRR, it's captured strongly if the variable is 13644 // __block and has an appropriate type. 13645 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13646 return false; 13647 13648 owner.Variable = var; 13649 if (ref) 13650 owner.setLocsFrom(ref); 13651 return true; 13652 } 13653 13654 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13655 while (true) { 13656 e = e->IgnoreParens(); 13657 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13658 switch (cast->getCastKind()) { 13659 case CK_BitCast: 13660 case CK_LValueBitCast: 13661 case CK_LValueToRValue: 13662 case CK_ARCReclaimReturnedObject: 13663 e = cast->getSubExpr(); 13664 continue; 13665 13666 default: 13667 return false; 13668 } 13669 } 13670 13671 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13672 ObjCIvarDecl *ivar = ref->getDecl(); 13673 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13674 return false; 13675 13676 // Try to find a retain cycle in the base. 13677 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13678 return false; 13679 13680 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13681 owner.Indirect = true; 13682 return true; 13683 } 13684 13685 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13686 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13687 if (!var) return false; 13688 return considerVariable(var, ref, owner); 13689 } 13690 13691 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13692 if (member->isArrow()) return false; 13693 13694 // Don't count this as an indirect ownership. 13695 e = member->getBase(); 13696 continue; 13697 } 13698 13699 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13700 // Only pay attention to pseudo-objects on property references. 13701 ObjCPropertyRefExpr *pre 13702 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13703 ->IgnoreParens()); 13704 if (!pre) return false; 13705 if (pre->isImplicitProperty()) return false; 13706 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13707 if (!property->isRetaining() && 13708 !(property->getPropertyIvarDecl() && 13709 property->getPropertyIvarDecl()->getType() 13710 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13711 return false; 13712 13713 owner.Indirect = true; 13714 if (pre->isSuperReceiver()) { 13715 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13716 if (!owner.Variable) 13717 return false; 13718 owner.Loc = pre->getLocation(); 13719 owner.Range = pre->getSourceRange(); 13720 return true; 13721 } 13722 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13723 ->getSourceExpr()); 13724 continue; 13725 } 13726 13727 // Array ivars? 13728 13729 return false; 13730 } 13731 } 13732 13733 namespace { 13734 13735 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13736 ASTContext &Context; 13737 VarDecl *Variable; 13738 Expr *Capturer = nullptr; 13739 bool VarWillBeReased = false; 13740 13741 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13742 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13743 Context(Context), Variable(variable) {} 13744 13745 void VisitDeclRefExpr(DeclRefExpr *ref) { 13746 if (ref->getDecl() == Variable && !Capturer) 13747 Capturer = ref; 13748 } 13749 13750 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13751 if (Capturer) return; 13752 Visit(ref->getBase()); 13753 if (Capturer && ref->isFreeIvar()) 13754 Capturer = ref; 13755 } 13756 13757 void VisitBlockExpr(BlockExpr *block) { 13758 // Look inside nested blocks 13759 if (block->getBlockDecl()->capturesVariable(Variable)) 13760 Visit(block->getBlockDecl()->getBody()); 13761 } 13762 13763 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13764 if (Capturer) return; 13765 if (OVE->getSourceExpr()) 13766 Visit(OVE->getSourceExpr()); 13767 } 13768 13769 void VisitBinaryOperator(BinaryOperator *BinOp) { 13770 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13771 return; 13772 Expr *LHS = BinOp->getLHS(); 13773 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13774 if (DRE->getDecl() != Variable) 13775 return; 13776 if (Expr *RHS = BinOp->getRHS()) { 13777 RHS = RHS->IgnoreParenCasts(); 13778 llvm::APSInt Value; 13779 VarWillBeReased = 13780 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13781 } 13782 } 13783 } 13784 }; 13785 13786 } // namespace 13787 13788 /// Check whether the given argument is a block which captures a 13789 /// variable. 13790 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13791 assert(owner.Variable && owner.Loc.isValid()); 13792 13793 e = e->IgnoreParenCasts(); 13794 13795 // Look through [^{...} copy] and Block_copy(^{...}). 13796 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13797 Selector Cmd = ME->getSelector(); 13798 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13799 e = ME->getInstanceReceiver(); 13800 if (!e) 13801 return nullptr; 13802 e = e->IgnoreParenCasts(); 13803 } 13804 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13805 if (CE->getNumArgs() == 1) { 13806 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13807 if (Fn) { 13808 const IdentifierInfo *FnI = Fn->getIdentifier(); 13809 if (FnI && FnI->isStr("_Block_copy")) { 13810 e = CE->getArg(0)->IgnoreParenCasts(); 13811 } 13812 } 13813 } 13814 } 13815 13816 BlockExpr *block = dyn_cast<BlockExpr>(e); 13817 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13818 return nullptr; 13819 13820 FindCaptureVisitor visitor(S.Context, owner.Variable); 13821 visitor.Visit(block->getBlockDecl()->getBody()); 13822 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13823 } 13824 13825 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13826 RetainCycleOwner &owner) { 13827 assert(capturer); 13828 assert(owner.Variable && owner.Loc.isValid()); 13829 13830 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13831 << owner.Variable << capturer->getSourceRange(); 13832 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13833 << owner.Indirect << owner.Range; 13834 } 13835 13836 /// Check for a keyword selector that starts with the word 'add' or 13837 /// 'set'. 13838 static bool isSetterLikeSelector(Selector sel) { 13839 if (sel.isUnarySelector()) return false; 13840 13841 StringRef str = sel.getNameForSlot(0); 13842 while (!str.empty() && str.front() == '_') str = str.substr(1); 13843 if (str.startswith("set")) 13844 str = str.substr(3); 13845 else if (str.startswith("add")) { 13846 // Specially whitelist 'addOperationWithBlock:'. 13847 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13848 return false; 13849 str = str.substr(3); 13850 } 13851 else 13852 return false; 13853 13854 if (str.empty()) return true; 13855 return !isLowercase(str.front()); 13856 } 13857 13858 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13859 ObjCMessageExpr *Message) { 13860 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13861 Message->getReceiverInterface(), 13862 NSAPI::ClassId_NSMutableArray); 13863 if (!IsMutableArray) { 13864 return None; 13865 } 13866 13867 Selector Sel = Message->getSelector(); 13868 13869 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13870 S.NSAPIObj->getNSArrayMethodKind(Sel); 13871 if (!MKOpt) { 13872 return None; 13873 } 13874 13875 NSAPI::NSArrayMethodKind MK = *MKOpt; 13876 13877 switch (MK) { 13878 case NSAPI::NSMutableArr_addObject: 13879 case NSAPI::NSMutableArr_insertObjectAtIndex: 13880 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13881 return 0; 13882 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13883 return 1; 13884 13885 default: 13886 return None; 13887 } 13888 13889 return None; 13890 } 13891 13892 static 13893 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13894 ObjCMessageExpr *Message) { 13895 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13896 Message->getReceiverInterface(), 13897 NSAPI::ClassId_NSMutableDictionary); 13898 if (!IsMutableDictionary) { 13899 return None; 13900 } 13901 13902 Selector Sel = Message->getSelector(); 13903 13904 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13905 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13906 if (!MKOpt) { 13907 return None; 13908 } 13909 13910 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13911 13912 switch (MK) { 13913 case NSAPI::NSMutableDict_setObjectForKey: 13914 case NSAPI::NSMutableDict_setValueForKey: 13915 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13916 return 0; 13917 13918 default: 13919 return None; 13920 } 13921 13922 return None; 13923 } 13924 13925 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13926 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13927 Message->getReceiverInterface(), 13928 NSAPI::ClassId_NSMutableSet); 13929 13930 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13931 Message->getReceiverInterface(), 13932 NSAPI::ClassId_NSMutableOrderedSet); 13933 if (!IsMutableSet && !IsMutableOrderedSet) { 13934 return None; 13935 } 13936 13937 Selector Sel = Message->getSelector(); 13938 13939 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13940 if (!MKOpt) { 13941 return None; 13942 } 13943 13944 NSAPI::NSSetMethodKind MK = *MKOpt; 13945 13946 switch (MK) { 13947 case NSAPI::NSMutableSet_addObject: 13948 case NSAPI::NSOrderedSet_setObjectAtIndex: 13949 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13950 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13951 return 0; 13952 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13953 return 1; 13954 } 13955 13956 return None; 13957 } 13958 13959 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13960 if (!Message->isInstanceMessage()) { 13961 return; 13962 } 13963 13964 Optional<int> ArgOpt; 13965 13966 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13967 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13968 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13969 return; 13970 } 13971 13972 int ArgIndex = *ArgOpt; 13973 13974 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13975 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13976 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13977 } 13978 13979 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13980 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13981 if (ArgRE->isObjCSelfExpr()) { 13982 Diag(Message->getSourceRange().getBegin(), 13983 diag::warn_objc_circular_container) 13984 << ArgRE->getDecl() << StringRef("'super'"); 13985 } 13986 } 13987 } else { 13988 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13989 13990 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13991 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13992 } 13993 13994 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13995 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13996 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13997 ValueDecl *Decl = ReceiverRE->getDecl(); 13998 Diag(Message->getSourceRange().getBegin(), 13999 diag::warn_objc_circular_container) 14000 << Decl << Decl; 14001 if (!ArgRE->isObjCSelfExpr()) { 14002 Diag(Decl->getLocation(), 14003 diag::note_objc_circular_container_declared_here) 14004 << Decl; 14005 } 14006 } 14007 } 14008 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14009 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14010 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14011 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14012 Diag(Message->getSourceRange().getBegin(), 14013 diag::warn_objc_circular_container) 14014 << Decl << Decl; 14015 Diag(Decl->getLocation(), 14016 diag::note_objc_circular_container_declared_here) 14017 << Decl; 14018 } 14019 } 14020 } 14021 } 14022 } 14023 14024 /// Check a message send to see if it's likely to cause a retain cycle. 14025 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14026 // Only check instance methods whose selector looks like a setter. 14027 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14028 return; 14029 14030 // Try to find a variable that the receiver is strongly owned by. 14031 RetainCycleOwner owner; 14032 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14033 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14034 return; 14035 } else { 14036 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14037 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14038 owner.Loc = msg->getSuperLoc(); 14039 owner.Range = msg->getSuperLoc(); 14040 } 14041 14042 // Check whether the receiver is captured by any of the arguments. 14043 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14044 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14045 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14046 // noescape blocks should not be retained by the method. 14047 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14048 continue; 14049 return diagnoseRetainCycle(*this, capturer, owner); 14050 } 14051 } 14052 } 14053 14054 /// Check a property assign to see if it's likely to cause a retain cycle. 14055 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14056 RetainCycleOwner owner; 14057 if (!findRetainCycleOwner(*this, receiver, owner)) 14058 return; 14059 14060 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14061 diagnoseRetainCycle(*this, capturer, owner); 14062 } 14063 14064 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14065 RetainCycleOwner Owner; 14066 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14067 return; 14068 14069 // Because we don't have an expression for the variable, we have to set the 14070 // location explicitly here. 14071 Owner.Loc = Var->getLocation(); 14072 Owner.Range = Var->getSourceRange(); 14073 14074 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14075 diagnoseRetainCycle(*this, Capturer, Owner); 14076 } 14077 14078 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14079 Expr *RHS, bool isProperty) { 14080 // Check if RHS is an Objective-C object literal, which also can get 14081 // immediately zapped in a weak reference. Note that we explicitly 14082 // allow ObjCStringLiterals, since those are designed to never really die. 14083 RHS = RHS->IgnoreParenImpCasts(); 14084 14085 // This enum needs to match with the 'select' in 14086 // warn_objc_arc_literal_assign (off-by-1). 14087 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14088 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14089 return false; 14090 14091 S.Diag(Loc, diag::warn_arc_literal_assign) 14092 << (unsigned) Kind 14093 << (isProperty ? 0 : 1) 14094 << RHS->getSourceRange(); 14095 14096 return true; 14097 } 14098 14099 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14100 Qualifiers::ObjCLifetime LT, 14101 Expr *RHS, bool isProperty) { 14102 // Strip off any implicit cast added to get to the one ARC-specific. 14103 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14104 if (cast->getCastKind() == CK_ARCConsumeObject) { 14105 S.Diag(Loc, diag::warn_arc_retained_assign) 14106 << (LT == Qualifiers::OCL_ExplicitNone) 14107 << (isProperty ? 0 : 1) 14108 << RHS->getSourceRange(); 14109 return true; 14110 } 14111 RHS = cast->getSubExpr(); 14112 } 14113 14114 if (LT == Qualifiers::OCL_Weak && 14115 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14116 return true; 14117 14118 return false; 14119 } 14120 14121 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14122 QualType LHS, Expr *RHS) { 14123 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14124 14125 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14126 return false; 14127 14128 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14129 return true; 14130 14131 return false; 14132 } 14133 14134 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14135 Expr *LHS, Expr *RHS) { 14136 QualType LHSType; 14137 // PropertyRef on LHS type need be directly obtained from 14138 // its declaration as it has a PseudoType. 14139 ObjCPropertyRefExpr *PRE 14140 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14141 if (PRE && !PRE->isImplicitProperty()) { 14142 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14143 if (PD) 14144 LHSType = PD->getType(); 14145 } 14146 14147 if (LHSType.isNull()) 14148 LHSType = LHS->getType(); 14149 14150 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14151 14152 if (LT == Qualifiers::OCL_Weak) { 14153 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14154 getCurFunction()->markSafeWeakUse(LHS); 14155 } 14156 14157 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14158 return; 14159 14160 // FIXME. Check for other life times. 14161 if (LT != Qualifiers::OCL_None) 14162 return; 14163 14164 if (PRE) { 14165 if (PRE->isImplicitProperty()) 14166 return; 14167 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14168 if (!PD) 14169 return; 14170 14171 unsigned Attributes = PD->getPropertyAttributes(); 14172 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14173 // when 'assign' attribute was not explicitly specified 14174 // by user, ignore it and rely on property type itself 14175 // for lifetime info. 14176 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14177 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14178 LHSType->isObjCRetainableType()) 14179 return; 14180 14181 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14182 if (cast->getCastKind() == CK_ARCConsumeObject) { 14183 Diag(Loc, diag::warn_arc_retained_property_assign) 14184 << RHS->getSourceRange(); 14185 return; 14186 } 14187 RHS = cast->getSubExpr(); 14188 } 14189 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14190 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14191 return; 14192 } 14193 } 14194 } 14195 14196 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14197 14198 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14199 SourceLocation StmtLoc, 14200 const NullStmt *Body) { 14201 // Do not warn if the body is a macro that expands to nothing, e.g: 14202 // 14203 // #define CALL(x) 14204 // if (condition) 14205 // CALL(0); 14206 if (Body->hasLeadingEmptyMacro()) 14207 return false; 14208 14209 // Get line numbers of statement and body. 14210 bool StmtLineInvalid; 14211 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14212 &StmtLineInvalid); 14213 if (StmtLineInvalid) 14214 return false; 14215 14216 bool BodyLineInvalid; 14217 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14218 &BodyLineInvalid); 14219 if (BodyLineInvalid) 14220 return false; 14221 14222 // Warn if null statement and body are on the same line. 14223 if (StmtLine != BodyLine) 14224 return false; 14225 14226 return true; 14227 } 14228 14229 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14230 const Stmt *Body, 14231 unsigned DiagID) { 14232 // Since this is a syntactic check, don't emit diagnostic for template 14233 // instantiations, this just adds noise. 14234 if (CurrentInstantiationScope) 14235 return; 14236 14237 // The body should be a null statement. 14238 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14239 if (!NBody) 14240 return; 14241 14242 // Do the usual checks. 14243 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14244 return; 14245 14246 Diag(NBody->getSemiLoc(), DiagID); 14247 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14248 } 14249 14250 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14251 const Stmt *PossibleBody) { 14252 assert(!CurrentInstantiationScope); // Ensured by caller 14253 14254 SourceLocation StmtLoc; 14255 const Stmt *Body; 14256 unsigned DiagID; 14257 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14258 StmtLoc = FS->getRParenLoc(); 14259 Body = FS->getBody(); 14260 DiagID = diag::warn_empty_for_body; 14261 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14262 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14263 Body = WS->getBody(); 14264 DiagID = diag::warn_empty_while_body; 14265 } else 14266 return; // Neither `for' nor `while'. 14267 14268 // The body should be a null statement. 14269 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14270 if (!NBody) 14271 return; 14272 14273 // Skip expensive checks if diagnostic is disabled. 14274 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14275 return; 14276 14277 // Do the usual checks. 14278 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14279 return; 14280 14281 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14282 // noise level low, emit diagnostics only if for/while is followed by a 14283 // CompoundStmt, e.g.: 14284 // for (int i = 0; i < n; i++); 14285 // { 14286 // a(i); 14287 // } 14288 // or if for/while is followed by a statement with more indentation 14289 // than for/while itself: 14290 // for (int i = 0; i < n; i++); 14291 // a(i); 14292 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14293 if (!ProbableTypo) { 14294 bool BodyColInvalid; 14295 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14296 PossibleBody->getBeginLoc(), &BodyColInvalid); 14297 if (BodyColInvalid) 14298 return; 14299 14300 bool StmtColInvalid; 14301 unsigned StmtCol = 14302 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14303 if (StmtColInvalid) 14304 return; 14305 14306 if (BodyCol > StmtCol) 14307 ProbableTypo = true; 14308 } 14309 14310 if (ProbableTypo) { 14311 Diag(NBody->getSemiLoc(), DiagID); 14312 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14313 } 14314 } 14315 14316 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14317 14318 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14319 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14320 SourceLocation OpLoc) { 14321 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14322 return; 14323 14324 if (inTemplateInstantiation()) 14325 return; 14326 14327 // Strip parens and casts away. 14328 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14329 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14330 14331 // Check for a call expression 14332 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14333 if (!CE || CE->getNumArgs() != 1) 14334 return; 14335 14336 // Check for a call to std::move 14337 if (!CE->isCallToStdMove()) 14338 return; 14339 14340 // Get argument from std::move 14341 RHSExpr = CE->getArg(0); 14342 14343 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14344 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14345 14346 // Two DeclRefExpr's, check that the decls are the same. 14347 if (LHSDeclRef && RHSDeclRef) { 14348 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14349 return; 14350 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14351 RHSDeclRef->getDecl()->getCanonicalDecl()) 14352 return; 14353 14354 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14355 << LHSExpr->getSourceRange() 14356 << RHSExpr->getSourceRange(); 14357 return; 14358 } 14359 14360 // Member variables require a different approach to check for self moves. 14361 // MemberExpr's are the same if every nested MemberExpr refers to the same 14362 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14363 // the base Expr's are CXXThisExpr's. 14364 const Expr *LHSBase = LHSExpr; 14365 const Expr *RHSBase = RHSExpr; 14366 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14367 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14368 if (!LHSME || !RHSME) 14369 return; 14370 14371 while (LHSME && RHSME) { 14372 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14373 RHSME->getMemberDecl()->getCanonicalDecl()) 14374 return; 14375 14376 LHSBase = LHSME->getBase(); 14377 RHSBase = RHSME->getBase(); 14378 LHSME = dyn_cast<MemberExpr>(LHSBase); 14379 RHSME = dyn_cast<MemberExpr>(RHSBase); 14380 } 14381 14382 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14383 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14384 if (LHSDeclRef && RHSDeclRef) { 14385 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14386 return; 14387 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14388 RHSDeclRef->getDecl()->getCanonicalDecl()) 14389 return; 14390 14391 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14392 << LHSExpr->getSourceRange() 14393 << RHSExpr->getSourceRange(); 14394 return; 14395 } 14396 14397 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14398 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14399 << LHSExpr->getSourceRange() 14400 << RHSExpr->getSourceRange(); 14401 } 14402 14403 //===--- Layout compatibility ----------------------------------------------// 14404 14405 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14406 14407 /// Check if two enumeration types are layout-compatible. 14408 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14409 // C++11 [dcl.enum] p8: 14410 // Two enumeration types are layout-compatible if they have the same 14411 // underlying type. 14412 return ED1->isComplete() && ED2->isComplete() && 14413 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14414 } 14415 14416 /// Check if two fields are layout-compatible. 14417 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14418 FieldDecl *Field2) { 14419 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14420 return false; 14421 14422 if (Field1->isBitField() != Field2->isBitField()) 14423 return false; 14424 14425 if (Field1->isBitField()) { 14426 // Make sure that the bit-fields are the same length. 14427 unsigned Bits1 = Field1->getBitWidthValue(C); 14428 unsigned Bits2 = Field2->getBitWidthValue(C); 14429 14430 if (Bits1 != Bits2) 14431 return false; 14432 } 14433 14434 return true; 14435 } 14436 14437 /// Check if two standard-layout structs are layout-compatible. 14438 /// (C++11 [class.mem] p17) 14439 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14440 RecordDecl *RD2) { 14441 // If both records are C++ classes, check that base classes match. 14442 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14443 // If one of records is a CXXRecordDecl we are in C++ mode, 14444 // thus the other one is a CXXRecordDecl, too. 14445 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14446 // Check number of base classes. 14447 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14448 return false; 14449 14450 // Check the base classes. 14451 for (CXXRecordDecl::base_class_const_iterator 14452 Base1 = D1CXX->bases_begin(), 14453 BaseEnd1 = D1CXX->bases_end(), 14454 Base2 = D2CXX->bases_begin(); 14455 Base1 != BaseEnd1; 14456 ++Base1, ++Base2) { 14457 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14458 return false; 14459 } 14460 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14461 // If only RD2 is a C++ class, it should have zero base classes. 14462 if (D2CXX->getNumBases() > 0) 14463 return false; 14464 } 14465 14466 // Check the fields. 14467 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14468 Field2End = RD2->field_end(), 14469 Field1 = RD1->field_begin(), 14470 Field1End = RD1->field_end(); 14471 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14472 if (!isLayoutCompatible(C, *Field1, *Field2)) 14473 return false; 14474 } 14475 if (Field1 != Field1End || Field2 != Field2End) 14476 return false; 14477 14478 return true; 14479 } 14480 14481 /// Check if two standard-layout unions are layout-compatible. 14482 /// (C++11 [class.mem] p18) 14483 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14484 RecordDecl *RD2) { 14485 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14486 for (auto *Field2 : RD2->fields()) 14487 UnmatchedFields.insert(Field2); 14488 14489 for (auto *Field1 : RD1->fields()) { 14490 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14491 I = UnmatchedFields.begin(), 14492 E = UnmatchedFields.end(); 14493 14494 for ( ; I != E; ++I) { 14495 if (isLayoutCompatible(C, Field1, *I)) { 14496 bool Result = UnmatchedFields.erase(*I); 14497 (void) Result; 14498 assert(Result); 14499 break; 14500 } 14501 } 14502 if (I == E) 14503 return false; 14504 } 14505 14506 return UnmatchedFields.empty(); 14507 } 14508 14509 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14510 RecordDecl *RD2) { 14511 if (RD1->isUnion() != RD2->isUnion()) 14512 return false; 14513 14514 if (RD1->isUnion()) 14515 return isLayoutCompatibleUnion(C, RD1, RD2); 14516 else 14517 return isLayoutCompatibleStruct(C, RD1, RD2); 14518 } 14519 14520 /// Check if two types are layout-compatible in C++11 sense. 14521 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14522 if (T1.isNull() || T2.isNull()) 14523 return false; 14524 14525 // C++11 [basic.types] p11: 14526 // If two types T1 and T2 are the same type, then T1 and T2 are 14527 // layout-compatible types. 14528 if (C.hasSameType(T1, T2)) 14529 return true; 14530 14531 T1 = T1.getCanonicalType().getUnqualifiedType(); 14532 T2 = T2.getCanonicalType().getUnqualifiedType(); 14533 14534 const Type::TypeClass TC1 = T1->getTypeClass(); 14535 const Type::TypeClass TC2 = T2->getTypeClass(); 14536 14537 if (TC1 != TC2) 14538 return false; 14539 14540 if (TC1 == Type::Enum) { 14541 return isLayoutCompatible(C, 14542 cast<EnumType>(T1)->getDecl(), 14543 cast<EnumType>(T2)->getDecl()); 14544 } else if (TC1 == Type::Record) { 14545 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14546 return false; 14547 14548 return isLayoutCompatible(C, 14549 cast<RecordType>(T1)->getDecl(), 14550 cast<RecordType>(T2)->getDecl()); 14551 } 14552 14553 return false; 14554 } 14555 14556 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14557 14558 /// Given a type tag expression find the type tag itself. 14559 /// 14560 /// \param TypeExpr Type tag expression, as it appears in user's code. 14561 /// 14562 /// \param VD Declaration of an identifier that appears in a type tag. 14563 /// 14564 /// \param MagicValue Type tag magic value. 14565 /// 14566 /// \param isConstantEvaluated wether the evalaution should be performed in 14567 14568 /// constant context. 14569 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14570 const ValueDecl **VD, uint64_t *MagicValue, 14571 bool isConstantEvaluated) { 14572 while(true) { 14573 if (!TypeExpr) 14574 return false; 14575 14576 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14577 14578 switch (TypeExpr->getStmtClass()) { 14579 case Stmt::UnaryOperatorClass: { 14580 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14581 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14582 TypeExpr = UO->getSubExpr(); 14583 continue; 14584 } 14585 return false; 14586 } 14587 14588 case Stmt::DeclRefExprClass: { 14589 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14590 *VD = DRE->getDecl(); 14591 return true; 14592 } 14593 14594 case Stmt::IntegerLiteralClass: { 14595 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14596 llvm::APInt MagicValueAPInt = IL->getValue(); 14597 if (MagicValueAPInt.getActiveBits() <= 64) { 14598 *MagicValue = MagicValueAPInt.getZExtValue(); 14599 return true; 14600 } else 14601 return false; 14602 } 14603 14604 case Stmt::BinaryConditionalOperatorClass: 14605 case Stmt::ConditionalOperatorClass: { 14606 const AbstractConditionalOperator *ACO = 14607 cast<AbstractConditionalOperator>(TypeExpr); 14608 bool Result; 14609 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14610 isConstantEvaluated)) { 14611 if (Result) 14612 TypeExpr = ACO->getTrueExpr(); 14613 else 14614 TypeExpr = ACO->getFalseExpr(); 14615 continue; 14616 } 14617 return false; 14618 } 14619 14620 case Stmt::BinaryOperatorClass: { 14621 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14622 if (BO->getOpcode() == BO_Comma) { 14623 TypeExpr = BO->getRHS(); 14624 continue; 14625 } 14626 return false; 14627 } 14628 14629 default: 14630 return false; 14631 } 14632 } 14633 } 14634 14635 /// Retrieve the C type corresponding to type tag TypeExpr. 14636 /// 14637 /// \param TypeExpr Expression that specifies a type tag. 14638 /// 14639 /// \param MagicValues Registered magic values. 14640 /// 14641 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14642 /// kind. 14643 /// 14644 /// \param TypeInfo Information about the corresponding C type. 14645 /// 14646 /// \param isConstantEvaluated wether the evalaution should be performed in 14647 /// constant context. 14648 /// 14649 /// \returns true if the corresponding C type was found. 14650 static bool GetMatchingCType( 14651 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14652 const ASTContext &Ctx, 14653 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14654 *MagicValues, 14655 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14656 bool isConstantEvaluated) { 14657 FoundWrongKind = false; 14658 14659 // Variable declaration that has type_tag_for_datatype attribute. 14660 const ValueDecl *VD = nullptr; 14661 14662 uint64_t MagicValue; 14663 14664 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14665 return false; 14666 14667 if (VD) { 14668 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14669 if (I->getArgumentKind() != ArgumentKind) { 14670 FoundWrongKind = true; 14671 return false; 14672 } 14673 TypeInfo.Type = I->getMatchingCType(); 14674 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14675 TypeInfo.MustBeNull = I->getMustBeNull(); 14676 return true; 14677 } 14678 return false; 14679 } 14680 14681 if (!MagicValues) 14682 return false; 14683 14684 llvm::DenseMap<Sema::TypeTagMagicValue, 14685 Sema::TypeTagData>::const_iterator I = 14686 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14687 if (I == MagicValues->end()) 14688 return false; 14689 14690 TypeInfo = I->second; 14691 return true; 14692 } 14693 14694 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14695 uint64_t MagicValue, QualType Type, 14696 bool LayoutCompatible, 14697 bool MustBeNull) { 14698 if (!TypeTagForDatatypeMagicValues) 14699 TypeTagForDatatypeMagicValues.reset( 14700 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14701 14702 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14703 (*TypeTagForDatatypeMagicValues)[Magic] = 14704 TypeTagData(Type, LayoutCompatible, MustBeNull); 14705 } 14706 14707 static bool IsSameCharType(QualType T1, QualType T2) { 14708 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14709 if (!BT1) 14710 return false; 14711 14712 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14713 if (!BT2) 14714 return false; 14715 14716 BuiltinType::Kind T1Kind = BT1->getKind(); 14717 BuiltinType::Kind T2Kind = BT2->getKind(); 14718 14719 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14720 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14721 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14722 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14723 } 14724 14725 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14726 const ArrayRef<const Expr *> ExprArgs, 14727 SourceLocation CallSiteLoc) { 14728 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14729 bool IsPointerAttr = Attr->getIsPointer(); 14730 14731 // Retrieve the argument representing the 'type_tag'. 14732 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14733 if (TypeTagIdxAST >= ExprArgs.size()) { 14734 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14735 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14736 return; 14737 } 14738 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14739 bool FoundWrongKind; 14740 TypeTagData TypeInfo; 14741 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14742 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14743 TypeInfo, isConstantEvaluated())) { 14744 if (FoundWrongKind) 14745 Diag(TypeTagExpr->getExprLoc(), 14746 diag::warn_type_tag_for_datatype_wrong_kind) 14747 << TypeTagExpr->getSourceRange(); 14748 return; 14749 } 14750 14751 // Retrieve the argument representing the 'arg_idx'. 14752 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14753 if (ArgumentIdxAST >= ExprArgs.size()) { 14754 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14755 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14756 return; 14757 } 14758 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14759 if (IsPointerAttr) { 14760 // Skip implicit cast of pointer to `void *' (as a function argument). 14761 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14762 if (ICE->getType()->isVoidPointerType() && 14763 ICE->getCastKind() == CK_BitCast) 14764 ArgumentExpr = ICE->getSubExpr(); 14765 } 14766 QualType ArgumentType = ArgumentExpr->getType(); 14767 14768 // Passing a `void*' pointer shouldn't trigger a warning. 14769 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14770 return; 14771 14772 if (TypeInfo.MustBeNull) { 14773 // Type tag with matching void type requires a null pointer. 14774 if (!ArgumentExpr->isNullPointerConstant(Context, 14775 Expr::NPC_ValueDependentIsNotNull)) { 14776 Diag(ArgumentExpr->getExprLoc(), 14777 diag::warn_type_safety_null_pointer_required) 14778 << ArgumentKind->getName() 14779 << ArgumentExpr->getSourceRange() 14780 << TypeTagExpr->getSourceRange(); 14781 } 14782 return; 14783 } 14784 14785 QualType RequiredType = TypeInfo.Type; 14786 if (IsPointerAttr) 14787 RequiredType = Context.getPointerType(RequiredType); 14788 14789 bool mismatch = false; 14790 if (!TypeInfo.LayoutCompatible) { 14791 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14792 14793 // C++11 [basic.fundamental] p1: 14794 // Plain char, signed char, and unsigned char are three distinct types. 14795 // 14796 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14797 // char' depending on the current char signedness mode. 14798 if (mismatch) 14799 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14800 RequiredType->getPointeeType())) || 14801 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14802 mismatch = false; 14803 } else 14804 if (IsPointerAttr) 14805 mismatch = !isLayoutCompatible(Context, 14806 ArgumentType->getPointeeType(), 14807 RequiredType->getPointeeType()); 14808 else 14809 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14810 14811 if (mismatch) 14812 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14813 << ArgumentType << ArgumentKind 14814 << TypeInfo.LayoutCompatible << RequiredType 14815 << ArgumentExpr->getSourceRange() 14816 << TypeTagExpr->getSourceRange(); 14817 } 14818 14819 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14820 CharUnits Alignment) { 14821 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14822 } 14823 14824 void Sema::DiagnoseMisalignedMembers() { 14825 for (MisalignedMember &m : MisalignedMembers) { 14826 const NamedDecl *ND = m.RD; 14827 if (ND->getName().empty()) { 14828 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14829 ND = TD; 14830 } 14831 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14832 << m.MD << ND << m.E->getSourceRange(); 14833 } 14834 MisalignedMembers.clear(); 14835 } 14836 14837 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14838 E = E->IgnoreParens(); 14839 if (!T->isPointerType() && !T->isIntegerType()) 14840 return; 14841 if (isa<UnaryOperator>(E) && 14842 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14843 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14844 if (isa<MemberExpr>(Op)) { 14845 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14846 if (MA != MisalignedMembers.end() && 14847 (T->isIntegerType() || 14848 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14849 Context.getTypeAlignInChars( 14850 T->getPointeeType()) <= MA->Alignment)))) 14851 MisalignedMembers.erase(MA); 14852 } 14853 } 14854 } 14855 14856 void Sema::RefersToMemberWithReducedAlignment( 14857 Expr *E, 14858 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14859 Action) { 14860 const auto *ME = dyn_cast<MemberExpr>(E); 14861 if (!ME) 14862 return; 14863 14864 // No need to check expressions with an __unaligned-qualified type. 14865 if (E->getType().getQualifiers().hasUnaligned()) 14866 return; 14867 14868 // For a chain of MemberExpr like "a.b.c.d" this list 14869 // will keep FieldDecl's like [d, c, b]. 14870 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14871 const MemberExpr *TopME = nullptr; 14872 bool AnyIsPacked = false; 14873 do { 14874 QualType BaseType = ME->getBase()->getType(); 14875 if (BaseType->isDependentType()) 14876 return; 14877 if (ME->isArrow()) 14878 BaseType = BaseType->getPointeeType(); 14879 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14880 if (RD->isInvalidDecl()) 14881 return; 14882 14883 ValueDecl *MD = ME->getMemberDecl(); 14884 auto *FD = dyn_cast<FieldDecl>(MD); 14885 // We do not care about non-data members. 14886 if (!FD || FD->isInvalidDecl()) 14887 return; 14888 14889 AnyIsPacked = 14890 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14891 ReverseMemberChain.push_back(FD); 14892 14893 TopME = ME; 14894 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14895 } while (ME); 14896 assert(TopME && "We did not compute a topmost MemberExpr!"); 14897 14898 // Not the scope of this diagnostic. 14899 if (!AnyIsPacked) 14900 return; 14901 14902 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14903 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14904 // TODO: The innermost base of the member expression may be too complicated. 14905 // For now, just disregard these cases. This is left for future 14906 // improvement. 14907 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14908 return; 14909 14910 // Alignment expected by the whole expression. 14911 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14912 14913 // No need to do anything else with this case. 14914 if (ExpectedAlignment.isOne()) 14915 return; 14916 14917 // Synthesize offset of the whole access. 14918 CharUnits Offset; 14919 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14920 I++) { 14921 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14922 } 14923 14924 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14925 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14926 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14927 14928 // The base expression of the innermost MemberExpr may give 14929 // stronger guarantees than the class containing the member. 14930 if (DRE && !TopME->isArrow()) { 14931 const ValueDecl *VD = DRE->getDecl(); 14932 if (!VD->getType()->isReferenceType()) 14933 CompleteObjectAlignment = 14934 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14935 } 14936 14937 // Check if the synthesized offset fulfills the alignment. 14938 if (Offset % ExpectedAlignment != 0 || 14939 // It may fulfill the offset it but the effective alignment may still be 14940 // lower than the expected expression alignment. 14941 CompleteObjectAlignment < ExpectedAlignment) { 14942 // If this happens, we want to determine a sensible culprit of this. 14943 // Intuitively, watching the chain of member expressions from right to 14944 // left, we start with the required alignment (as required by the field 14945 // type) but some packed attribute in that chain has reduced the alignment. 14946 // It may happen that another packed structure increases it again. But if 14947 // we are here such increase has not been enough. So pointing the first 14948 // FieldDecl that either is packed or else its RecordDecl is, 14949 // seems reasonable. 14950 FieldDecl *FD = nullptr; 14951 CharUnits Alignment; 14952 for (FieldDecl *FDI : ReverseMemberChain) { 14953 if (FDI->hasAttr<PackedAttr>() || 14954 FDI->getParent()->hasAttr<PackedAttr>()) { 14955 FD = FDI; 14956 Alignment = std::min( 14957 Context.getTypeAlignInChars(FD->getType()), 14958 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14959 break; 14960 } 14961 } 14962 assert(FD && "We did not find a packed FieldDecl!"); 14963 Action(E, FD->getParent(), FD, Alignment); 14964 } 14965 } 14966 14967 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14968 using namespace std::placeholders; 14969 14970 RefersToMemberWithReducedAlignment( 14971 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14972 _2, _3, _4)); 14973 } 14974